]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm-project/clang/lib/Sema/SemaDeclCXX.cpp
Merge ^/vendor/lldb/dist up to its last change, and resolve conflicts.
[FreeBSD/FreeBSD.git] / contrib / llvm-project / clang / lib / Sema / SemaDeclCXX.cpp
1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for C++ declarations.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTLambda.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/ComparisonCategories.h"
20 #include "clang/AST/EvaluatedExprVisitor.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/RecordLayout.h"
23 #include "clang/AST/RecursiveASTVisitor.h"
24 #include "clang/AST/StmtVisitor.h"
25 #include "clang/AST/TypeLoc.h"
26 #include "clang/AST/TypeOrdering.h"
27 #include "clang/Basic/AttributeCommonInfo.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   case EST_NoThrow:
197     return;
198   // If we're still at noexcept(true) and there's a throw() callee,
199   // change to that specification.
200   case EST_DynamicNone:
201     if (ComputedEST == EST_BasicNoexcept)
202       ComputedEST = EST_DynamicNone;
203     return;
204   case EST_DependentNoexcept:
205     llvm_unreachable(
206         "should not generate implicit declarations for dependent cases");
207   case EST_Dynamic:
208     break;
209   }
210   assert(EST == EST_Dynamic && "EST case not considered earlier.");
211   assert(ComputedEST != EST_None &&
212          "Shouldn't collect exceptions when throw-all is guaranteed.");
213   ComputedEST = EST_Dynamic;
214   // Record the exceptions in this function's exception specification.
215   for (const auto &E : Proto->exceptions())
216     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
217       Exceptions.push_back(E);
218 }
219
220 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
221   if (!E || ComputedEST == EST_MSAny)
222     return;
223
224   // FIXME:
225   //
226   // C++0x [except.spec]p14:
227   //   [An] implicit exception-specification specifies the type-id T if and
228   // only if T is allowed by the exception-specification of a function directly
229   // invoked by f's implicit definition; f shall allow all exceptions if any
230   // function it directly invokes allows all exceptions, and f shall allow no
231   // exceptions if every function it directly invokes allows no exceptions.
232   //
233   // Note in particular that if an implicit exception-specification is generated
234   // for a function containing a throw-expression, that specification can still
235   // be noexcept(true).
236   //
237   // Note also that 'directly invoked' is not defined in the standard, and there
238   // is no indication that we should only consider potentially-evaluated calls.
239   //
240   // Ultimately we should implement the intent of the standard: the exception
241   // specification should be the set of exceptions which can be thrown by the
242   // implicit definition. For now, we assume that any non-nothrow expression can
243   // throw any exception.
244
245   if (Self->canThrow(E))
246     ComputedEST = EST_None;
247 }
248
249 bool
250 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
251                               SourceLocation EqualLoc) {
252   if (RequireCompleteType(Param->getLocation(), Param->getType(),
253                           diag::err_typecheck_decl_incomplete_type)) {
254     Param->setInvalidDecl();
255     return true;
256   }
257
258   // C++ [dcl.fct.default]p5
259   //   A default argument expression is implicitly converted (clause
260   //   4) to the parameter type. The default argument expression has
261   //   the same semantic constraints as the initializer expression in
262   //   a declaration of a variable of the parameter type, using the
263   //   copy-initialization semantics (8.5).
264   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
265                                                                     Param);
266   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
267                                                            EqualLoc);
268   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
269   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
270   if (Result.isInvalid())
271     return true;
272   Arg = Result.getAs<Expr>();
273
274   CheckCompletedExpr(Arg, EqualLoc);
275   Arg = MaybeCreateExprWithCleanups(Arg);
276
277   // Okay: add the default argument to the parameter
278   Param->setDefaultArg(Arg);
279
280   // We have already instantiated this parameter; provide each of the
281   // instantiations with the uninstantiated default argument.
282   UnparsedDefaultArgInstantiationsMap::iterator InstPos
283     = UnparsedDefaultArgInstantiations.find(Param);
284   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
285     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
286       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
287
288     // We're done tracking this parameter's instantiations.
289     UnparsedDefaultArgInstantiations.erase(InstPos);
290   }
291
292   return false;
293 }
294
295 /// ActOnParamDefaultArgument - Check whether the default argument
296 /// provided for a function parameter is well-formed. If so, attach it
297 /// to the parameter declaration.
298 void
299 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
300                                 Expr *DefaultArg) {
301   if (!param || !DefaultArg)
302     return;
303
304   ParmVarDecl *Param = cast<ParmVarDecl>(param);
305   UnparsedDefaultArgLocs.erase(Param);
306
307   // Default arguments are only permitted in C++
308   if (!getLangOpts().CPlusPlus) {
309     Diag(EqualLoc, diag::err_param_default_argument)
310       << DefaultArg->getSourceRange();
311     Param->setInvalidDecl();
312     return;
313   }
314
315   // Check for unexpanded parameter packs.
316   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
317     Param->setInvalidDecl();
318     return;
319   }
320
321   // C++11 [dcl.fct.default]p3
322   //   A default argument expression [...] shall not be specified for a
323   //   parameter pack.
324   if (Param->isParameterPack()) {
325     Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
326         << DefaultArg->getSourceRange();
327     return;
328   }
329
330   // Check that the default argument is well-formed
331   CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
332   if (DefaultArgChecker.Visit(DefaultArg)) {
333     Param->setInvalidDecl();
334     return;
335   }
336
337   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
338 }
339
340 /// ActOnParamUnparsedDefaultArgument - We've seen a default
341 /// argument for a function parameter, but we can't parse it yet
342 /// because we're inside a class definition. Note that this default
343 /// argument will be parsed later.
344 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
345                                              SourceLocation EqualLoc,
346                                              SourceLocation ArgLoc) {
347   if (!param)
348     return;
349
350   ParmVarDecl *Param = cast<ParmVarDecl>(param);
351   Param->setUnparsedDefaultArg();
352   UnparsedDefaultArgLocs[Param] = ArgLoc;
353 }
354
355 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
356 /// the default argument for the parameter param failed.
357 void Sema::ActOnParamDefaultArgumentError(Decl *param,
358                                           SourceLocation EqualLoc) {
359   if (!param)
360     return;
361
362   ParmVarDecl *Param = cast<ParmVarDecl>(param);
363   Param->setInvalidDecl();
364   UnparsedDefaultArgLocs.erase(Param);
365   Param->setDefaultArg(new(Context)
366                        OpaqueValueExpr(EqualLoc,
367                                        Param->getType().getNonReferenceType(),
368                                        VK_RValue));
369 }
370
371 /// CheckExtraCXXDefaultArguments - Check for any extra default
372 /// arguments in the declarator, which is not a function declaration
373 /// or definition and therefore is not permitted to have default
374 /// arguments. This routine should be invoked for every declarator
375 /// that is not a function declaration or definition.
376 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
377   // C++ [dcl.fct.default]p3
378   //   A default argument expression shall be specified only in the
379   //   parameter-declaration-clause of a function declaration or in a
380   //   template-parameter (14.1). It shall not be specified for a
381   //   parameter pack. If it is specified in a
382   //   parameter-declaration-clause, it shall not occur within a
383   //   declarator or abstract-declarator of a parameter-declaration.
384   bool MightBeFunction = D.isFunctionDeclarationContext();
385   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
386     DeclaratorChunk &chunk = D.getTypeObject(i);
387     if (chunk.Kind == DeclaratorChunk::Function) {
388       if (MightBeFunction) {
389         // This is a function declaration. It can have default arguments, but
390         // keep looking in case its return type is a function type with default
391         // arguments.
392         MightBeFunction = false;
393         continue;
394       }
395       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
396            ++argIdx) {
397         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
398         if (Param->hasUnparsedDefaultArg()) {
399           std::unique_ptr<CachedTokens> Toks =
400               std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
401           SourceRange SR;
402           if (Toks->size() > 1)
403             SR = SourceRange((*Toks)[1].getLocation(),
404                              Toks->back().getLocation());
405           else
406             SR = UnparsedDefaultArgLocs[Param];
407           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
408             << SR;
409         } else if (Param->getDefaultArg()) {
410           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
411             << Param->getDefaultArg()->getSourceRange();
412           Param->setDefaultArg(nullptr);
413         }
414       }
415     } else if (chunk.Kind != DeclaratorChunk::Paren) {
416       MightBeFunction = false;
417     }
418   }
419 }
420
421 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
422   for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
423     const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
424     if (!PVD->hasDefaultArg())
425       return false;
426     if (!PVD->hasInheritedDefaultArg())
427       return true;
428   }
429   return false;
430 }
431
432 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
433 /// function, once we already know that they have the same
434 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
435 /// error, false otherwise.
436 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
437                                 Scope *S) {
438   bool Invalid = false;
439
440   // The declaration context corresponding to the scope is the semantic
441   // parent, unless this is a local function declaration, in which case
442   // it is that surrounding function.
443   DeclContext *ScopeDC = New->isLocalExternDecl()
444                              ? New->getLexicalDeclContext()
445                              : New->getDeclContext();
446
447   // Find the previous declaration for the purpose of default arguments.
448   FunctionDecl *PrevForDefaultArgs = Old;
449   for (/**/; PrevForDefaultArgs;
450        // Don't bother looking back past the latest decl if this is a local
451        // extern declaration; nothing else could work.
452        PrevForDefaultArgs = New->isLocalExternDecl()
453                                 ? nullptr
454                                 : PrevForDefaultArgs->getPreviousDecl()) {
455     // Ignore hidden declarations.
456     if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
457       continue;
458
459     if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
460         !New->isCXXClassMember()) {
461       // Ignore default arguments of old decl if they are not in
462       // the same scope and this is not an out-of-line definition of
463       // a member function.
464       continue;
465     }
466
467     if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
468       // If only one of these is a local function declaration, then they are
469       // declared in different scopes, even though isDeclInScope may think
470       // they're in the same scope. (If both are local, the scope check is
471       // sufficient, and if neither is local, then they are in the same scope.)
472       continue;
473     }
474
475     // We found the right previous declaration.
476     break;
477   }
478
479   // C++ [dcl.fct.default]p4:
480   //   For non-template functions, default arguments can be added in
481   //   later declarations of a function in the same
482   //   scope. Declarations in different scopes have completely
483   //   distinct sets of default arguments. That is, declarations in
484   //   inner scopes do not acquire default arguments from
485   //   declarations in outer scopes, and vice versa. In a given
486   //   function declaration, all parameters subsequent to a
487   //   parameter with a default argument shall have default
488   //   arguments supplied in this or previous declarations. A
489   //   default argument shall not be redefined by a later
490   //   declaration (not even to the same value).
491   //
492   // C++ [dcl.fct.default]p6:
493   //   Except for member functions of class templates, the default arguments
494   //   in a member function definition that appears outside of the class
495   //   definition are added to the set of default arguments provided by the
496   //   member function declaration in the class definition.
497   for (unsigned p = 0, NumParams = PrevForDefaultArgs
498                                        ? PrevForDefaultArgs->getNumParams()
499                                        : 0;
500        p < NumParams; ++p) {
501     ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
502     ParmVarDecl *NewParam = New->getParamDecl(p);
503
504     bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
505     bool NewParamHasDfl = NewParam->hasDefaultArg();
506
507     if (OldParamHasDfl && NewParamHasDfl) {
508       unsigned DiagDefaultParamID =
509         diag::err_param_default_argument_redefinition;
510
511       // MSVC accepts that default parameters be redefined for member functions
512       // of template class. The new default parameter's value is ignored.
513       Invalid = true;
514       if (getLangOpts().MicrosoftExt) {
515         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
516         if (MD && MD->getParent()->getDescribedClassTemplate()) {
517           // Merge the old default argument into the new parameter.
518           NewParam->setHasInheritedDefaultArg();
519           if (OldParam->hasUninstantiatedDefaultArg())
520             NewParam->setUninstantiatedDefaultArg(
521                                       OldParam->getUninstantiatedDefaultArg());
522           else
523             NewParam->setDefaultArg(OldParam->getInit());
524           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
525           Invalid = false;
526         }
527       }
528
529       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
530       // hint here. Alternatively, we could walk the type-source information
531       // for NewParam to find the last source location in the type... but it
532       // isn't worth the effort right now. This is the kind of test case that
533       // is hard to get right:
534       //   int f(int);
535       //   void g(int (*fp)(int) = f);
536       //   void g(int (*fp)(int) = &f);
537       Diag(NewParam->getLocation(), DiagDefaultParamID)
538         << NewParam->getDefaultArgRange();
539
540       // Look for the function declaration where the default argument was
541       // actually written, which may be a declaration prior to Old.
542       for (auto Older = PrevForDefaultArgs;
543            OldParam->hasInheritedDefaultArg(); /**/) {
544         Older = Older->getPreviousDecl();
545         OldParam = Older->getParamDecl(p);
546       }
547
548       Diag(OldParam->getLocation(), diag::note_previous_definition)
549         << OldParam->getDefaultArgRange();
550     } else if (OldParamHasDfl) {
551       // Merge the old default argument into the new parameter unless the new
552       // function is a friend declaration in a template class. In the latter
553       // case the default arguments will be inherited when the friend
554       // declaration will be instantiated.
555       if (New->getFriendObjectKind() == Decl::FOK_None ||
556           !New->getLexicalDeclContext()->isDependentContext()) {
557         // It's important to use getInit() here;  getDefaultArg()
558         // strips off any top-level ExprWithCleanups.
559         NewParam->setHasInheritedDefaultArg();
560         if (OldParam->hasUnparsedDefaultArg())
561           NewParam->setUnparsedDefaultArg();
562         else if (OldParam->hasUninstantiatedDefaultArg())
563           NewParam->setUninstantiatedDefaultArg(
564                                        OldParam->getUninstantiatedDefaultArg());
565         else
566           NewParam->setDefaultArg(OldParam->getInit());
567       }
568     } else if (NewParamHasDfl) {
569       if (New->getDescribedFunctionTemplate()) {
570         // Paragraph 4, quoted above, only applies to non-template functions.
571         Diag(NewParam->getLocation(),
572              diag::err_param_default_argument_template_redecl)
573           << NewParam->getDefaultArgRange();
574         Diag(PrevForDefaultArgs->getLocation(),
575              diag::note_template_prev_declaration)
576             << false;
577       } else if (New->getTemplateSpecializationKind()
578                    != TSK_ImplicitInstantiation &&
579                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
580         // C++ [temp.expr.spec]p21:
581         //   Default function arguments shall not be specified in a declaration
582         //   or a definition for one of the following explicit specializations:
583         //     - the explicit specialization of a function template;
584         //     - the explicit specialization of a member function template;
585         //     - the explicit specialization of a member function of a class
586         //       template where the class template specialization to which the
587         //       member function specialization belongs is implicitly
588         //       instantiated.
589         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
590           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
591           << New->getDeclName()
592           << NewParam->getDefaultArgRange();
593       } else if (New->getDeclContext()->isDependentContext()) {
594         // C++ [dcl.fct.default]p6 (DR217):
595         //   Default arguments for a member function of a class template shall
596         //   be specified on the initial declaration of the member function
597         //   within the class template.
598         //
599         // Reading the tea leaves a bit in DR217 and its reference to DR205
600         // leads me to the conclusion that one cannot add default function
601         // arguments for an out-of-line definition of a member function of a
602         // dependent type.
603         int WhichKind = 2;
604         if (CXXRecordDecl *Record
605               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
606           if (Record->getDescribedClassTemplate())
607             WhichKind = 0;
608           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
609             WhichKind = 1;
610           else
611             WhichKind = 2;
612         }
613
614         Diag(NewParam->getLocation(),
615              diag::err_param_default_argument_member_template_redecl)
616           << WhichKind
617           << NewParam->getDefaultArgRange();
618       }
619     }
620   }
621
622   // DR1344: If a default argument is added outside a class definition and that
623   // default argument makes the function a special member function, the program
624   // is ill-formed. This can only happen for constructors.
625   if (isa<CXXConstructorDecl>(New) &&
626       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
627     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
628                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
629     if (NewSM != OldSM) {
630       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
631       assert(NewParam->hasDefaultArg());
632       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
633         << NewParam->getDefaultArgRange() << NewSM;
634       Diag(Old->getLocation(), diag::note_previous_declaration);
635     }
636   }
637
638   const FunctionDecl *Def;
639   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
640   // template has a constexpr specifier then all its declarations shall
641   // contain the constexpr specifier.
642   if (New->getConstexprKind() != Old->getConstexprKind()) {
643     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
644         << New << New->getConstexprKind() << Old->getConstexprKind();
645     Diag(Old->getLocation(), diag::note_previous_declaration);
646     Invalid = true;
647   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
648              Old->isDefined(Def) &&
649              // If a friend function is inlined but does not have 'inline'
650              // specifier, it is a definition. Do not report attribute conflict
651              // in this case, redefinition will be diagnosed later.
652              (New->isInlineSpecified() ||
653               New->getFriendObjectKind() == Decl::FOK_None)) {
654     // C++11 [dcl.fcn.spec]p4:
655     //   If the definition of a function appears in a translation unit before its
656     //   first declaration as inline, the program is ill-formed.
657     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
658     Diag(Def->getLocation(), diag::note_previous_definition);
659     Invalid = true;
660   }
661
662   // C++17 [temp.deduct.guide]p3:
663   //   Two deduction guide declarations in the same translation unit
664   //   for the same class template shall not have equivalent
665   //   parameter-declaration-clauses.
666   if (isa<CXXDeductionGuideDecl>(New) &&
667       !New->isFunctionTemplateSpecialization()) {
668     Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
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++17 [dcl.dcl]/8:
721   //   The decl-specifier-seq shall contain only the type-specifier auto
722   //   and cv-qualifiers.
723   // C++2a [dcl.dcl]/8:
724   //   If decl-specifier-seq contains any decl-specifier other than static,
725   //   thread_local, auto, or cv-qualifiers, the program is ill-formed.
726   auto &DS = D.getDeclSpec();
727   {
728     SmallVector<StringRef, 8> BadSpecifiers;
729     SmallVector<SourceLocation, 8> BadSpecifierLocs;
730     SmallVector<StringRef, 8> CPlusPlus20Specifiers;
731     SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
732     if (auto SCS = DS.getStorageClassSpec()) {
733       if (SCS == DeclSpec::SCS_static) {
734         CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
735         CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
736       } else {
737         BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
738         BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
739       }
740     }
741     if (auto TSCS = DS.getThreadStorageClassSpec()) {
742       CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
743       CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
744     }
745     if (DS.hasConstexprSpecifier()) {
746       BadSpecifiers.push_back(
747           DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
748       BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
749     }
750     if (DS.isInlineSpecified()) {
751       BadSpecifiers.push_back("inline");
752       BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
753     }
754     if (!BadSpecifiers.empty()) {
755       auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
756       Err << (int)BadSpecifiers.size()
757           << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
758       // Don't add FixItHints to remove the specifiers; we do still respect
759       // them when building the underlying variable.
760       for (auto Loc : BadSpecifierLocs)
761         Err << SourceRange(Loc, Loc);
762     } else if (!CPlusPlus20Specifiers.empty()) {
763       auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
764                          getLangOpts().CPlusPlus2a
765                              ? diag::warn_cxx17_compat_decomp_decl_spec
766                              : diag::ext_decomp_decl_spec);
767       Warn << (int)CPlusPlus20Specifiers.size()
768            << llvm::join(CPlusPlus20Specifiers.begin(),
769                          CPlusPlus20Specifiers.end(), " ");
770       for (auto Loc : CPlusPlus20SpecifierLocs)
771         Warn << SourceRange(Loc, Loc);
772     }
773     // We can't recover from it being declared as a typedef.
774     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
775       return nullptr;
776   }
777
778   // C++2a [dcl.struct.bind]p1:
779   //   A cv that includes volatile is deprecated
780   if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
781       getLangOpts().CPlusPlus2a)
782     Diag(DS.getVolatileSpecLoc(),
783          diag::warn_deprecated_volatile_structured_binding);
784
785   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
786   QualType R = TInfo->getType();
787
788   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
789                                       UPPC_DeclarationType))
790     D.setInvalidType();
791
792   // The syntax only allows a single ref-qualifier prior to the decomposition
793   // declarator. No other declarator chunks are permitted. Also check the type
794   // specifier here.
795   if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
796       D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
797       (D.getNumTypeObjects() == 1 &&
798        D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
799     Diag(Decomp.getLSquareLoc(),
800          (D.hasGroupingParens() ||
801           (D.getNumTypeObjects() &&
802            D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
803              ? diag::err_decomp_decl_parens
804              : diag::err_decomp_decl_type)
805         << R;
806
807     // In most cases, there's no actual problem with an explicitly-specified
808     // type, but a function type won't work here, and ActOnVariableDeclarator
809     // shouldn't be called for such a type.
810     if (R->isFunctionType())
811       D.setInvalidType();
812   }
813
814   // Build the BindingDecls.
815   SmallVector<BindingDecl*, 8> Bindings;
816
817   // Build the BindingDecls.
818   for (auto &B : D.getDecompositionDeclarator().bindings()) {
819     // Check for name conflicts.
820     DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
821     LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
822                           ForVisibleRedeclaration);
823     LookupName(Previous, S,
824                /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
825
826     // It's not permitted to shadow a template parameter name.
827     if (Previous.isSingleResult() &&
828         Previous.getFoundDecl()->isTemplateParameter()) {
829       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
830                                       Previous.getFoundDecl());
831       Previous.clear();
832     }
833
834     bool ConsiderLinkage = DC->isFunctionOrMethod() &&
835                            DS.getStorageClassSpec() == DeclSpec::SCS_extern;
836     FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
837                          /*AllowInlineNamespace*/false);
838     if (!Previous.empty()) {
839       auto *Old = Previous.getRepresentativeDecl();
840       Diag(B.NameLoc, diag::err_redefinition) << B.Name;
841       Diag(Old->getLocation(), diag::note_previous_definition);
842     }
843
844     auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
845     PushOnScopeChains(BD, S, true);
846     Bindings.push_back(BD);
847     ParsingInitForAutoVars.insert(BD);
848   }
849
850   // There are no prior lookup results for the variable itself, because it
851   // is unnamed.
852   DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
853                                Decomp.getLSquareLoc());
854   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
855                         ForVisibleRedeclaration);
856
857   // Build the variable that holds the non-decomposed object.
858   bool AddToScope = true;
859   NamedDecl *New =
860       ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
861                               MultiTemplateParamsArg(), AddToScope, Bindings);
862   if (AddToScope) {
863     S->AddDecl(New);
864     CurContext->addHiddenDecl(New);
865   }
866
867   if (isInOpenMPDeclareTargetContext())
868     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
869
870   return New;
871 }
872
873 static bool checkSimpleDecomposition(
874     Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
875     QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
876     llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
877   if ((int64_t)Bindings.size() != NumElems) {
878     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
879         << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
880         << (NumElems < Bindings.size());
881     return true;
882   }
883
884   unsigned I = 0;
885   for (auto *B : Bindings) {
886     SourceLocation Loc = B->getLocation();
887     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
888     if (E.isInvalid())
889       return true;
890     E = GetInit(Loc, E.get(), I++);
891     if (E.isInvalid())
892       return true;
893     B->setBinding(ElemType, E.get());
894   }
895
896   return false;
897 }
898
899 static bool checkArrayLikeDecomposition(Sema &S,
900                                         ArrayRef<BindingDecl *> Bindings,
901                                         ValueDecl *Src, QualType DecompType,
902                                         const llvm::APSInt &NumElems,
903                                         QualType ElemType) {
904   return checkSimpleDecomposition(
905       S, Bindings, Src, DecompType, NumElems, ElemType,
906       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
907         ExprResult E = S.ActOnIntegerConstant(Loc, I);
908         if (E.isInvalid())
909           return ExprError();
910         return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
911       });
912 }
913
914 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
915                                     ValueDecl *Src, QualType DecompType,
916                                     const ConstantArrayType *CAT) {
917   return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
918                                      llvm::APSInt(CAT->getSize()),
919                                      CAT->getElementType());
920 }
921
922 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
923                                      ValueDecl *Src, QualType DecompType,
924                                      const VectorType *VT) {
925   return checkArrayLikeDecomposition(
926       S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
927       S.Context.getQualifiedType(VT->getElementType(),
928                                  DecompType.getQualifiers()));
929 }
930
931 static bool checkComplexDecomposition(Sema &S,
932                                       ArrayRef<BindingDecl *> Bindings,
933                                       ValueDecl *Src, QualType DecompType,
934                                       const ComplexType *CT) {
935   return checkSimpleDecomposition(
936       S, Bindings, Src, DecompType, llvm::APSInt::get(2),
937       S.Context.getQualifiedType(CT->getElementType(),
938                                  DecompType.getQualifiers()),
939       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
940         return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
941       });
942 }
943
944 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
945                                      TemplateArgumentListInfo &Args) {
946   SmallString<128> SS;
947   llvm::raw_svector_ostream OS(SS);
948   bool First = true;
949   for (auto &Arg : Args.arguments()) {
950     if (!First)
951       OS << ", ";
952     Arg.getArgument().print(PrintingPolicy, OS);
953     First = false;
954   }
955   return OS.str();
956 }
957
958 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
959                                      SourceLocation Loc, StringRef Trait,
960                                      TemplateArgumentListInfo &Args,
961                                      unsigned DiagID) {
962   auto DiagnoseMissing = [&] {
963     if (DiagID)
964       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
965                                                Args);
966     return true;
967   };
968
969   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
970   NamespaceDecl *Std = S.getStdNamespace();
971   if (!Std)
972     return DiagnoseMissing();
973
974   // Look up the trait itself, within namespace std. We can diagnose various
975   // problems with this lookup even if we've been asked to not diagnose a
976   // missing specialization, because this can only fail if the user has been
977   // declaring their own names in namespace std or we don't support the
978   // standard library implementation in use.
979   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
980                       Loc, Sema::LookupOrdinaryName);
981   if (!S.LookupQualifiedName(Result, Std))
982     return DiagnoseMissing();
983   if (Result.isAmbiguous())
984     return true;
985
986   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
987   if (!TraitTD) {
988     Result.suppressDiagnostics();
989     NamedDecl *Found = *Result.begin();
990     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
991     S.Diag(Found->getLocation(), diag::note_declared_at);
992     return true;
993   }
994
995   // Build the template-id.
996   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
997   if (TraitTy.isNull())
998     return true;
999   if (!S.isCompleteType(Loc, TraitTy)) {
1000     if (DiagID)
1001       S.RequireCompleteType(
1002           Loc, TraitTy, DiagID,
1003           printTemplateArgs(S.Context.getPrintingPolicy(), Args));
1004     return true;
1005   }
1006
1007   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1008   assert(RD && "specialization of class template is not a class?");
1009
1010   // Look up the member of the trait type.
1011   S.LookupQualifiedName(TraitMemberLookup, RD);
1012   return TraitMemberLookup.isAmbiguous();
1013 }
1014
1015 static TemplateArgumentLoc
1016 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1017                                    uint64_t I) {
1018   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1019   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1020 }
1021
1022 static TemplateArgumentLoc
1023 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1024   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1025 }
1026
1027 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1028
1029 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1030                                llvm::APSInt &Size) {
1031   EnterExpressionEvaluationContext ContextRAII(
1032       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1033
1034   DeclarationName Value = S.PP.getIdentifierInfo("value");
1035   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1036
1037   // Form template argument list for tuple_size<T>.
1038   TemplateArgumentListInfo Args(Loc, Loc);
1039   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1040
1041   // If there's no tuple_size specialization or the lookup of 'value' is empty,
1042   // it's not tuple-like.
1043   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1044       R.empty())
1045     return IsTupleLike::NotTupleLike;
1046
1047   // If we get this far, we've committed to the tuple interpretation, but
1048   // we can still fail if there actually isn't a usable ::value.
1049
1050   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1051     LookupResult &R;
1052     TemplateArgumentListInfo &Args;
1053     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1054         : R(R), Args(Args) {}
1055     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1056       S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1057           << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1058     }
1059   } Diagnoser(R, Args);
1060
1061   ExprResult E =
1062       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1063   if (E.isInvalid())
1064     return IsTupleLike::Error;
1065
1066   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1067   if (E.isInvalid())
1068     return IsTupleLike::Error;
1069
1070   return IsTupleLike::TupleLike;
1071 }
1072
1073 /// \return std::tuple_element<I, T>::type.
1074 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1075                                         unsigned I, QualType T) {
1076   // Form template argument list for tuple_element<I, T>.
1077   TemplateArgumentListInfo Args(Loc, Loc);
1078   Args.addArgument(
1079       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1080   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1081
1082   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1083   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1084   if (lookupStdTypeTraitMember(
1085           S, R, Loc, "tuple_element", Args,
1086           diag::err_decomp_decl_std_tuple_element_not_specialized))
1087     return QualType();
1088
1089   auto *TD = R.getAsSingle<TypeDecl>();
1090   if (!TD) {
1091     R.suppressDiagnostics();
1092     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1093       << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1094     if (!R.empty())
1095       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1096     return QualType();
1097   }
1098
1099   return S.Context.getTypeDeclType(TD);
1100 }
1101
1102 namespace {
1103 struct BindingDiagnosticTrap {
1104   Sema &S;
1105   DiagnosticErrorTrap Trap;
1106   BindingDecl *BD;
1107
1108   BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1109       : S(S), Trap(S.Diags), BD(BD) {}
1110   ~BindingDiagnosticTrap() {
1111     if (Trap.hasErrorOccurred())
1112       S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1113   }
1114 };
1115 }
1116
1117 static bool checkTupleLikeDecomposition(Sema &S,
1118                                         ArrayRef<BindingDecl *> Bindings,
1119                                         VarDecl *Src, QualType DecompType,
1120                                         const llvm::APSInt &TupleSize) {
1121   if ((int64_t)Bindings.size() != TupleSize) {
1122     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1123         << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1124         << (TupleSize < Bindings.size());
1125     return true;
1126   }
1127
1128   if (Bindings.empty())
1129     return false;
1130
1131   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1132
1133   // [dcl.decomp]p3:
1134   //   The unqualified-id get is looked up in the scope of E by class member
1135   //   access lookup ...
1136   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1137   bool UseMemberGet = false;
1138   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1139     if (auto *RD = DecompType->getAsCXXRecordDecl())
1140       S.LookupQualifiedName(MemberGet, RD);
1141     if (MemberGet.isAmbiguous())
1142       return true;
1143     //   ... and if that finds at least one declaration that is a function
1144     //   template whose first template parameter is a non-type parameter ...
1145     for (NamedDecl *D : MemberGet) {
1146       if (FunctionTemplateDecl *FTD =
1147               dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1148         TemplateParameterList *TPL = FTD->getTemplateParameters();
1149         if (TPL->size() != 0 &&
1150             isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1151           //   ... the initializer is e.get<i>().
1152           UseMemberGet = true;
1153           break;
1154         }
1155       }
1156     }
1157   }
1158
1159   unsigned I = 0;
1160   for (auto *B : Bindings) {
1161     BindingDiagnosticTrap Trap(S, B);
1162     SourceLocation Loc = B->getLocation();
1163
1164     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1165     if (E.isInvalid())
1166       return true;
1167
1168     //   e is an lvalue if the type of the entity is an lvalue reference and
1169     //   an xvalue otherwise
1170     if (!Src->getType()->isLValueReferenceType())
1171       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1172                                    E.get(), nullptr, VK_XValue);
1173
1174     TemplateArgumentListInfo Args(Loc, Loc);
1175     Args.addArgument(
1176         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1177
1178     if (UseMemberGet) {
1179       //   if [lookup of member get] finds at least one declaration, the
1180       //   initializer is e.get<i-1>().
1181       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1182                                      CXXScopeSpec(), SourceLocation(), nullptr,
1183                                      MemberGet, &Args, nullptr);
1184       if (E.isInvalid())
1185         return true;
1186
1187       E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1188     } else {
1189       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1190       //   in the associated namespaces.
1191       Expr *Get = UnresolvedLookupExpr::Create(
1192           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1193           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1194           UnresolvedSetIterator(), UnresolvedSetIterator());
1195
1196       Expr *Arg = E.get();
1197       E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1198     }
1199     if (E.isInvalid())
1200       return true;
1201     Expr *Init = E.get();
1202
1203     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1204     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1205     if (T.isNull())
1206       return true;
1207
1208     //   each vi is a variable of type "reference to T" initialized with the
1209     //   initializer, where the reference is an lvalue reference if the
1210     //   initializer is an lvalue and an rvalue reference otherwise
1211     QualType RefType =
1212         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1213     if (RefType.isNull())
1214       return true;
1215     auto *RefVD = VarDecl::Create(
1216         S.Context, Src->getDeclContext(), Loc, Loc,
1217         B->getDeclName().getAsIdentifierInfo(), RefType,
1218         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1219     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1220     RefVD->setTSCSpec(Src->getTSCSpec());
1221     RefVD->setImplicit();
1222     if (Src->isInlineSpecified())
1223       RefVD->setInlineSpecified();
1224     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1225
1226     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1227     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1228     InitializationSequence Seq(S, Entity, Kind, Init);
1229     E = Seq.Perform(S, Entity, Kind, Init);
1230     if (E.isInvalid())
1231       return true;
1232     E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1233     if (E.isInvalid())
1234       return true;
1235     RefVD->setInit(E.get());
1236     if (!E.get()->isValueDependent())
1237       RefVD->checkInitIsICE();
1238
1239     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1240                                    DeclarationNameInfo(B->getDeclName(), Loc),
1241                                    RefVD);
1242     if (E.isInvalid())
1243       return true;
1244
1245     B->setBinding(T, E.get());
1246     I++;
1247   }
1248
1249   return false;
1250 }
1251
1252 /// Find the base class to decompose in a built-in decomposition of a class type.
1253 /// This base class search is, unfortunately, not quite like any other that we
1254 /// perform anywhere else in C++.
1255 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1256                                                 const CXXRecordDecl *RD,
1257                                                 CXXCastPath &BasePath) {
1258   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1259                           CXXBasePath &Path) {
1260     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1261   };
1262
1263   const CXXRecordDecl *ClassWithFields = nullptr;
1264   AccessSpecifier AS = AS_public;
1265   if (RD->hasDirectFields())
1266     // [dcl.decomp]p4:
1267     //   Otherwise, all of E's non-static data members shall be public direct
1268     //   members of E ...
1269     ClassWithFields = RD;
1270   else {
1271     //   ... or of ...
1272     CXXBasePaths Paths;
1273     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1274     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1275       // If no classes have fields, just decompose RD itself. (This will work
1276       // if and only if zero bindings were provided.)
1277       return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1278     }
1279
1280     CXXBasePath *BestPath = nullptr;
1281     for (auto &P : Paths) {
1282       if (!BestPath)
1283         BestPath = &P;
1284       else if (!S.Context.hasSameType(P.back().Base->getType(),
1285                                       BestPath->back().Base->getType())) {
1286         //   ... the same ...
1287         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1288           << false << RD << BestPath->back().Base->getType()
1289           << P.back().Base->getType();
1290         return DeclAccessPair();
1291       } else if (P.Access < BestPath->Access) {
1292         BestPath = &P;
1293       }
1294     }
1295
1296     //   ... unambiguous ...
1297     QualType BaseType = BestPath->back().Base->getType();
1298     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1299       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1300         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1301       return DeclAccessPair();
1302     }
1303
1304     //   ... [accessible, implied by other rules] base class of E.
1305     S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1306                            *BestPath, diag::err_decomp_decl_inaccessible_base);
1307     AS = BestPath->Access;
1308
1309     ClassWithFields = BaseType->getAsCXXRecordDecl();
1310     S.BuildBasePathArray(Paths, BasePath);
1311   }
1312
1313   // The above search did not check whether the selected class itself has base
1314   // classes with fields, so check that now.
1315   CXXBasePaths Paths;
1316   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1317     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1318       << (ClassWithFields == RD) << RD << ClassWithFields
1319       << Paths.front().back().Base->getType();
1320     return DeclAccessPair();
1321   }
1322
1323   return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1324 }
1325
1326 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1327                                      ValueDecl *Src, QualType DecompType,
1328                                      const CXXRecordDecl *OrigRD) {
1329   if (S.RequireCompleteType(Src->getLocation(), DecompType,
1330                             diag::err_incomplete_type))
1331     return true;
1332
1333   CXXCastPath BasePath;
1334   DeclAccessPair BasePair =
1335       findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1336   const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1337   if (!RD)
1338     return true;
1339   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1340                                                  DecompType.getQualifiers());
1341
1342   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1343     unsigned NumFields =
1344         std::count_if(RD->field_begin(), RD->field_end(),
1345                       [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1346     assert(Bindings.size() != NumFields);
1347     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1348         << DecompType << (unsigned)Bindings.size() << NumFields
1349         << (NumFields < Bindings.size());
1350     return true;
1351   };
1352
1353   //   all of E's non-static data members shall be [...] well-formed
1354   //   when named as e.name in the context of the structured binding,
1355   //   E shall not have an anonymous union member, ...
1356   unsigned I = 0;
1357   for (auto *FD : RD->fields()) {
1358     if (FD->isUnnamedBitfield())
1359       continue;
1360
1361     if (FD->isAnonymousStructOrUnion()) {
1362       S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1363         << DecompType << FD->getType()->isUnionType();
1364       S.Diag(FD->getLocation(), diag::note_declared_at);
1365       return true;
1366     }
1367
1368     // We have a real field to bind.
1369     if (I >= Bindings.size())
1370       return DiagnoseBadNumberOfBindings();
1371     auto *B = Bindings[I++];
1372     SourceLocation Loc = B->getLocation();
1373
1374     // The field must be accessible in the context of the structured binding.
1375     // We already checked that the base class is accessible.
1376     // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1377     // const_cast here.
1378     S.CheckStructuredBindingMemberAccess(
1379         Loc, const_cast<CXXRecordDecl *>(OrigRD),
1380         DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1381                                      BasePair.getAccess(), FD->getAccess())));
1382
1383     // Initialize the binding to Src.FD.
1384     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1385     if (E.isInvalid())
1386       return true;
1387     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1388                             VK_LValue, &BasePath);
1389     if (E.isInvalid())
1390       return true;
1391     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1392                                   CXXScopeSpec(), FD,
1393                                   DeclAccessPair::make(FD, FD->getAccess()),
1394                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1395     if (E.isInvalid())
1396       return true;
1397
1398     // If the type of the member is T, the referenced type is cv T, where cv is
1399     // the cv-qualification of the decomposition expression.
1400     //
1401     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1402     // 'const' to the type of the field.
1403     Qualifiers Q = DecompType.getQualifiers();
1404     if (FD->isMutable())
1405       Q.removeConst();
1406     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1407   }
1408
1409   if (I != Bindings.size())
1410     return DiagnoseBadNumberOfBindings();
1411
1412   return false;
1413 }
1414
1415 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1416   QualType DecompType = DD->getType();
1417
1418   // If the type of the decomposition is dependent, then so is the type of
1419   // each binding.
1420   if (DecompType->isDependentType()) {
1421     for (auto *B : DD->bindings())
1422       B->setType(Context.DependentTy);
1423     return;
1424   }
1425
1426   DecompType = DecompType.getNonReferenceType();
1427   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1428
1429   // C++1z [dcl.decomp]/2:
1430   //   If E is an array type [...]
1431   // As an extension, we also support decomposition of built-in complex and
1432   // vector types.
1433   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1434     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1435       DD->setInvalidDecl();
1436     return;
1437   }
1438   if (auto *VT = DecompType->getAs<VectorType>()) {
1439     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1440       DD->setInvalidDecl();
1441     return;
1442   }
1443   if (auto *CT = DecompType->getAs<ComplexType>()) {
1444     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1445       DD->setInvalidDecl();
1446     return;
1447   }
1448
1449   // C++1z [dcl.decomp]/3:
1450   //   if the expression std::tuple_size<E>::value is a well-formed integral
1451   //   constant expression, [...]
1452   llvm::APSInt TupleSize(32);
1453   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1454   case IsTupleLike::Error:
1455     DD->setInvalidDecl();
1456     return;
1457
1458   case IsTupleLike::TupleLike:
1459     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1460       DD->setInvalidDecl();
1461     return;
1462
1463   case IsTupleLike::NotTupleLike:
1464     break;
1465   }
1466
1467   // C++1z [dcl.dcl]/8:
1468   //   [E shall be of array or non-union class type]
1469   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1470   if (!RD || RD->isUnion()) {
1471     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1472         << DD << !RD << DecompType;
1473     DD->setInvalidDecl();
1474     return;
1475   }
1476
1477   // C++1z [dcl.decomp]/4:
1478   //   all of E's non-static data members shall be [...] direct members of
1479   //   E or of the same unambiguous public base class of E, ...
1480   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1481     DD->setInvalidDecl();
1482 }
1483
1484 /// Merge the exception specifications of two variable declarations.
1485 ///
1486 /// This is called when there's a redeclaration of a VarDecl. The function
1487 /// checks if the redeclaration might have an exception specification and
1488 /// validates compatibility and merges the specs if necessary.
1489 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1490   // Shortcut if exceptions are disabled.
1491   if (!getLangOpts().CXXExceptions)
1492     return;
1493
1494   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1495          "Should only be called if types are otherwise the same.");
1496
1497   QualType NewType = New->getType();
1498   QualType OldType = Old->getType();
1499
1500   // We're only interested in pointers and references to functions, as well
1501   // as pointers to member functions.
1502   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1503     NewType = R->getPointeeType();
1504     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1505   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1506     NewType = P->getPointeeType();
1507     OldType = OldType->getAs<PointerType>()->getPointeeType();
1508   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1509     NewType = M->getPointeeType();
1510     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1511   }
1512
1513   if (!NewType->isFunctionProtoType())
1514     return;
1515
1516   // There's lots of special cases for functions. For function pointers, system
1517   // libraries are hopefully not as broken so that we don't need these
1518   // workarounds.
1519   if (CheckEquivalentExceptionSpec(
1520         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1521         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1522     New->setInvalidDecl();
1523   }
1524 }
1525
1526 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1527 /// function declaration are well-formed according to C++
1528 /// [dcl.fct.default].
1529 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1530   unsigned NumParams = FD->getNumParams();
1531   unsigned p;
1532
1533   // Find first parameter with a default argument
1534   for (p = 0; p < NumParams; ++p) {
1535     ParmVarDecl *Param = FD->getParamDecl(p);
1536     if (Param->hasDefaultArg())
1537       break;
1538   }
1539
1540   // C++11 [dcl.fct.default]p4:
1541   //   In a given function declaration, each parameter subsequent to a parameter
1542   //   with a default argument shall have a default argument supplied in this or
1543   //   a previous declaration or shall be a function parameter pack. A default
1544   //   argument shall not be redefined by a later declaration (not even to the
1545   //   same value).
1546   unsigned LastMissingDefaultArg = 0;
1547   for (; p < NumParams; ++p) {
1548     ParmVarDecl *Param = FD->getParamDecl(p);
1549     if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
1550       if (Param->isInvalidDecl())
1551         /* We already complained about this parameter. */;
1552       else if (Param->getIdentifier())
1553         Diag(Param->getLocation(),
1554              diag::err_param_default_argument_missing_name)
1555           << Param->getIdentifier();
1556       else
1557         Diag(Param->getLocation(),
1558              diag::err_param_default_argument_missing);
1559
1560       LastMissingDefaultArg = p;
1561     }
1562   }
1563
1564   if (LastMissingDefaultArg > 0) {
1565     // Some default arguments were missing. Clear out all of the
1566     // default arguments up to (and including) the last missing
1567     // default argument, so that we leave the function parameters
1568     // in a semantically valid state.
1569     for (p = 0; p <= LastMissingDefaultArg; ++p) {
1570       ParmVarDecl *Param = FD->getParamDecl(p);
1571       if (Param->hasDefaultArg()) {
1572         Param->setDefaultArg(nullptr);
1573       }
1574     }
1575   }
1576 }
1577
1578 /// Check that the given type is a literal type. Issue a diagnostic if not,
1579 /// if Kind is Diagnose.
1580 /// \return \c true if a problem has been found (and optionally diagnosed).
1581 template <typename... Ts>
1582 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1583                              SourceLocation Loc, QualType T, unsigned DiagID,
1584                              Ts &&...DiagArgs) {
1585   if (T->isDependentType())
1586     return false;
1587
1588   switch (Kind) {
1589   case Sema::CheckConstexprKind::Diagnose:
1590     return SemaRef.RequireLiteralType(Loc, T, DiagID,
1591                                       std::forward<Ts>(DiagArgs)...);
1592
1593   case Sema::CheckConstexprKind::CheckValid:
1594     return !T->isLiteralType(SemaRef.Context);
1595   }
1596
1597   llvm_unreachable("unknown CheckConstexprKind");
1598 }
1599
1600 /// Determine whether a destructor cannot be constexpr due to
1601 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1602                                                const CXXDestructorDecl *DD,
1603                                                Sema::CheckConstexprKind Kind) {
1604   auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1605     const CXXRecordDecl *RD =
1606         T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1607     if (!RD || RD->hasConstexprDestructor())
1608       return true;
1609
1610     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1611       SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1612           << DD->getConstexprKind() << !FD
1613           << (FD ? FD->getDeclName() : DeclarationName()) << T;
1614       SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1615           << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1616     }
1617     return false;
1618   };
1619
1620   const CXXRecordDecl *RD = DD->getParent();
1621   for (const CXXBaseSpecifier &B : RD->bases())
1622     if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1623       return false;
1624   for (const FieldDecl *FD : RD->fields())
1625     if (!Check(FD->getLocation(), FD->getType(), FD))
1626       return false;
1627   return true;
1628 }
1629
1630 // CheckConstexprParameterTypes - Check whether a function's parameter types
1631 // are all literal types. If so, return true. If not, produce a suitable
1632 // diagnostic and return false.
1633 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1634                                          const FunctionDecl *FD,
1635                                          Sema::CheckConstexprKind Kind) {
1636   unsigned ArgIndex = 0;
1637   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
1638   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1639                                               e = FT->param_type_end();
1640        i != e; ++i, ++ArgIndex) {
1641     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1642     SourceLocation ParamLoc = PD->getLocation();
1643     if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1644                          diag::err_constexpr_non_literal_param, ArgIndex + 1,
1645                          PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1646                          FD->isConsteval()))
1647       return false;
1648   }
1649   return true;
1650 }
1651
1652 /// Get diagnostic %select index for tag kind for
1653 /// record diagnostic message.
1654 /// WARNING: Indexes apply to particular diagnostics only!
1655 ///
1656 /// \returns diagnostic %select index.
1657 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1658   switch (Tag) {
1659   case TTK_Struct: return 0;
1660   case TTK_Interface: return 1;
1661   case TTK_Class:  return 2;
1662   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1663   }
1664 }
1665
1666 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1667                                        Stmt *Body,
1668                                        Sema::CheckConstexprKind Kind);
1669
1670 // Check whether a function declaration satisfies the requirements of a
1671 // constexpr function definition or a constexpr constructor definition. If so,
1672 // return true. If not, produce appropriate diagnostics (unless asked not to by
1673 // Kind) and return false.
1674 //
1675 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1676 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1677                                             CheckConstexprKind Kind) {
1678   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1679   if (MD && MD->isInstance()) {
1680     // C++11 [dcl.constexpr]p4:
1681     //  The definition of a constexpr constructor shall satisfy the following
1682     //  constraints:
1683     //  - the class shall not have any virtual base classes;
1684     //
1685     // FIXME: This only applies to constructors and destructors, not arbitrary
1686     // member functions.
1687     const CXXRecordDecl *RD = MD->getParent();
1688     if (RD->getNumVBases()) {
1689       if (Kind == CheckConstexprKind::CheckValid)
1690         return false;
1691
1692       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1693         << isa<CXXConstructorDecl>(NewFD)
1694         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1695       for (const auto &I : RD->vbases())
1696         Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1697             << I.getSourceRange();
1698       return false;
1699     }
1700   }
1701
1702   if (!isa<CXXConstructorDecl>(NewFD)) {
1703     // C++11 [dcl.constexpr]p3:
1704     //  The definition of a constexpr function shall satisfy the following
1705     //  constraints:
1706     // - it shall not be virtual; (removed in C++20)
1707     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1708     if (Method && Method->isVirtual()) {
1709       if (getLangOpts().CPlusPlus2a) {
1710         if (Kind == CheckConstexprKind::Diagnose)
1711           Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1712       } else {
1713         if (Kind == CheckConstexprKind::CheckValid)
1714           return false;
1715
1716         Method = Method->getCanonicalDecl();
1717         Diag(Method->getLocation(), diag::err_constexpr_virtual);
1718
1719         // If it's not obvious why this function is virtual, find an overridden
1720         // function which uses the 'virtual' keyword.
1721         const CXXMethodDecl *WrittenVirtual = Method;
1722         while (!WrittenVirtual->isVirtualAsWritten())
1723           WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1724         if (WrittenVirtual != Method)
1725           Diag(WrittenVirtual->getLocation(),
1726                diag::note_overridden_virtual_function);
1727         return false;
1728       }
1729     }
1730
1731     // - its return type shall be a literal type;
1732     QualType RT = NewFD->getReturnType();
1733     if (CheckLiteralType(*this, Kind, NewFD->getLocation(), RT,
1734                          diag::err_constexpr_non_literal_return,
1735                          NewFD->isConsteval()))
1736       return false;
1737   }
1738
1739   if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1740     // A destructor can be constexpr only if the defaulted destructor could be;
1741     // we don't need to check the members and bases if we already know they all
1742     // have constexpr destructors.
1743     if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1744       if (Kind == CheckConstexprKind::CheckValid)
1745         return false;
1746       if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1747         return false;
1748     }
1749   }
1750
1751   // - each of its parameter types shall be a literal type;
1752   if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1753     return false;
1754
1755   Stmt *Body = NewFD->getBody();
1756   assert(Body &&
1757          "CheckConstexprFunctionDefinition called on function with no body");
1758   return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1759 }
1760
1761 /// Check the given declaration statement is legal within a constexpr function
1762 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1763 ///
1764 /// \return true if the body is OK (maybe only as an extension), false if we
1765 ///         have diagnosed a problem.
1766 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1767                                    DeclStmt *DS, SourceLocation &Cxx1yLoc,
1768                                    Sema::CheckConstexprKind Kind) {
1769   // C++11 [dcl.constexpr]p3 and p4:
1770   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1771   //  contain only
1772   for (const auto *DclIt : DS->decls()) {
1773     switch (DclIt->getKind()) {
1774     case Decl::StaticAssert:
1775     case Decl::Using:
1776     case Decl::UsingShadow:
1777     case Decl::UsingDirective:
1778     case Decl::UnresolvedUsingTypename:
1779     case Decl::UnresolvedUsingValue:
1780       //   - static_assert-declarations
1781       //   - using-declarations,
1782       //   - using-directives,
1783       continue;
1784
1785     case Decl::Typedef:
1786     case Decl::TypeAlias: {
1787       //   - typedef declarations and alias-declarations that do not define
1788       //     classes or enumerations,
1789       const auto *TN = cast<TypedefNameDecl>(DclIt);
1790       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1791         // Don't allow variably-modified types in constexpr functions.
1792         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1793           TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1794           SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1795             << TL.getSourceRange() << TL.getType()
1796             << isa<CXXConstructorDecl>(Dcl);
1797         }
1798         return false;
1799       }
1800       continue;
1801     }
1802
1803     case Decl::Enum:
1804     case Decl::CXXRecord:
1805       // C++1y allows types to be defined, not just declared.
1806       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1807         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1808           SemaRef.Diag(DS->getBeginLoc(),
1809                        SemaRef.getLangOpts().CPlusPlus14
1810                            ? diag::warn_cxx11_compat_constexpr_type_definition
1811                            : diag::ext_constexpr_type_definition)
1812               << isa<CXXConstructorDecl>(Dcl);
1813         } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1814           return false;
1815         }
1816       }
1817       continue;
1818
1819     case Decl::EnumConstant:
1820     case Decl::IndirectField:
1821     case Decl::ParmVar:
1822       // These can only appear with other declarations which are banned in
1823       // C++11 and permitted in C++1y, so ignore them.
1824       continue;
1825
1826     case Decl::Var:
1827     case Decl::Decomposition: {
1828       // C++1y [dcl.constexpr]p3 allows anything except:
1829       //   a definition of a variable of non-literal type or of static or
1830       //   thread storage duration or [before C++2a] for which no
1831       //   initialization is performed.
1832       const auto *VD = cast<VarDecl>(DclIt);
1833       if (VD->isThisDeclarationADefinition()) {
1834         if (VD->isStaticLocal()) {
1835           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1836             SemaRef.Diag(VD->getLocation(),
1837                          diag::err_constexpr_local_var_static)
1838               << isa<CXXConstructorDecl>(Dcl)
1839               << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1840           }
1841           return false;
1842         }
1843         if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1844                              diag::err_constexpr_local_var_non_literal_type,
1845                              isa<CXXConstructorDecl>(Dcl)))
1846           return false;
1847         if (!VD->getType()->isDependentType() &&
1848             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1849           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1850             SemaRef.Diag(
1851                 VD->getLocation(),
1852                 SemaRef.getLangOpts().CPlusPlus2a
1853                     ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1854                     : diag::ext_constexpr_local_var_no_init)
1855                 << isa<CXXConstructorDecl>(Dcl);
1856           } else if (!SemaRef.getLangOpts().CPlusPlus2a) {
1857             return false;
1858           }
1859           continue;
1860         }
1861       }
1862       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1863         SemaRef.Diag(VD->getLocation(),
1864                      SemaRef.getLangOpts().CPlusPlus14
1865                       ? diag::warn_cxx11_compat_constexpr_local_var
1866                       : diag::ext_constexpr_local_var)
1867           << isa<CXXConstructorDecl>(Dcl);
1868       } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1869         return false;
1870       }
1871       continue;
1872     }
1873
1874     case Decl::NamespaceAlias:
1875     case Decl::Function:
1876       // These are disallowed in C++11 and permitted in C++1y. Allow them
1877       // everywhere as an extension.
1878       if (!Cxx1yLoc.isValid())
1879         Cxx1yLoc = DS->getBeginLoc();
1880       continue;
1881
1882     default:
1883       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1884         SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1885             << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1886       }
1887       return false;
1888     }
1889   }
1890
1891   return true;
1892 }
1893
1894 /// Check that the given field is initialized within a constexpr constructor.
1895 ///
1896 /// \param Dcl The constexpr constructor being checked.
1897 /// \param Field The field being checked. This may be a member of an anonymous
1898 ///        struct or union nested within the class being checked.
1899 /// \param Inits All declarations, including anonymous struct/union members and
1900 ///        indirect members, for which any initialization was provided.
1901 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
1902 ///        multiple notes for different members to the same error.
1903 /// \param Kind Whether we're diagnosing a constructor as written or determining
1904 ///        whether the formal requirements are satisfied.
1905 /// \return \c false if we're checking for validity and the constructor does
1906 ///         not satisfy the requirements on a constexpr constructor.
1907 static bool CheckConstexprCtorInitializer(Sema &SemaRef,
1908                                           const FunctionDecl *Dcl,
1909                                           FieldDecl *Field,
1910                                           llvm::SmallSet<Decl*, 16> &Inits,
1911                                           bool &Diagnosed,
1912                                           Sema::CheckConstexprKind Kind) {
1913   // In C++20 onwards, there's nothing to check for validity.
1914   if (Kind == Sema::CheckConstexprKind::CheckValid &&
1915       SemaRef.getLangOpts().CPlusPlus2a)
1916     return true;
1917
1918   if (Field->isInvalidDecl())
1919     return true;
1920
1921   if (Field->isUnnamedBitfield())
1922     return true;
1923
1924   // Anonymous unions with no variant members and empty anonymous structs do not
1925   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1926   // indirect fields don't need initializing.
1927   if (Field->isAnonymousStructOrUnion() &&
1928       (Field->getType()->isUnionType()
1929            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1930            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1931     return true;
1932
1933   if (!Inits.count(Field)) {
1934     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1935       if (!Diagnosed) {
1936         SemaRef.Diag(Dcl->getLocation(),
1937                      SemaRef.getLangOpts().CPlusPlus2a
1938                          ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
1939                          : diag::ext_constexpr_ctor_missing_init);
1940         Diagnosed = true;
1941       }
1942       SemaRef.Diag(Field->getLocation(),
1943                    diag::note_constexpr_ctor_missing_init);
1944     } else if (!SemaRef.getLangOpts().CPlusPlus2a) {
1945       return false;
1946     }
1947   } else if (Field->isAnonymousStructOrUnion()) {
1948     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1949     for (auto *I : RD->fields())
1950       // If an anonymous union contains an anonymous struct of which any member
1951       // is initialized, all members must be initialized.
1952       if (!RD->isUnion() || Inits.count(I))
1953         if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
1954                                            Kind))
1955           return false;
1956   }
1957   return true;
1958 }
1959
1960 /// Check the provided statement is allowed in a constexpr function
1961 /// definition.
1962 static bool
1963 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1964                            SmallVectorImpl<SourceLocation> &ReturnStmts,
1965                            SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
1966                            Sema::CheckConstexprKind Kind) {
1967   // - its function-body shall be [...] a compound-statement that contains only
1968   switch (S->getStmtClass()) {
1969   case Stmt::NullStmtClass:
1970     //   - null statements,
1971     return true;
1972
1973   case Stmt::DeclStmtClass:
1974     //   - static_assert-declarations
1975     //   - using-declarations,
1976     //   - using-directives,
1977     //   - typedef declarations and alias-declarations that do not define
1978     //     classes or enumerations,
1979     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
1980       return false;
1981     return true;
1982
1983   case Stmt::ReturnStmtClass:
1984     //   - and exactly one return statement;
1985     if (isa<CXXConstructorDecl>(Dcl)) {
1986       // C++1y allows return statements in constexpr constructors.
1987       if (!Cxx1yLoc.isValid())
1988         Cxx1yLoc = S->getBeginLoc();
1989       return true;
1990     }
1991
1992     ReturnStmts.push_back(S->getBeginLoc());
1993     return true;
1994
1995   case Stmt::CompoundStmtClass: {
1996     // C++1y allows compound-statements.
1997     if (!Cxx1yLoc.isValid())
1998       Cxx1yLoc = S->getBeginLoc();
1999
2000     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2001     for (auto *BodyIt : CompStmt->body()) {
2002       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2003                                       Cxx1yLoc, Cxx2aLoc, Kind))
2004         return false;
2005     }
2006     return true;
2007   }
2008
2009   case Stmt::AttributedStmtClass:
2010     if (!Cxx1yLoc.isValid())
2011       Cxx1yLoc = S->getBeginLoc();
2012     return true;
2013
2014   case Stmt::IfStmtClass: {
2015     // C++1y allows if-statements.
2016     if (!Cxx1yLoc.isValid())
2017       Cxx1yLoc = S->getBeginLoc();
2018
2019     IfStmt *If = cast<IfStmt>(S);
2020     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2021                                     Cxx1yLoc, Cxx2aLoc, Kind))
2022       return false;
2023     if (If->getElse() &&
2024         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2025                                     Cxx1yLoc, Cxx2aLoc, Kind))
2026       return false;
2027     return true;
2028   }
2029
2030   case Stmt::WhileStmtClass:
2031   case Stmt::DoStmtClass:
2032   case Stmt::ForStmtClass:
2033   case Stmt::CXXForRangeStmtClass:
2034   case Stmt::ContinueStmtClass:
2035     // C++1y allows all of these. We don't allow them as extensions in C++11,
2036     // because they don't make sense without variable mutation.
2037     if (!SemaRef.getLangOpts().CPlusPlus14)
2038       break;
2039     if (!Cxx1yLoc.isValid())
2040       Cxx1yLoc = S->getBeginLoc();
2041     for (Stmt *SubStmt : S->children())
2042       if (SubStmt &&
2043           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2044                                       Cxx1yLoc, Cxx2aLoc, Kind))
2045         return false;
2046     return true;
2047
2048   case Stmt::SwitchStmtClass:
2049   case Stmt::CaseStmtClass:
2050   case Stmt::DefaultStmtClass:
2051   case Stmt::BreakStmtClass:
2052     // C++1y allows switch-statements, and since they don't need variable
2053     // mutation, we can reasonably allow them in C++11 as an extension.
2054     if (!Cxx1yLoc.isValid())
2055       Cxx1yLoc = S->getBeginLoc();
2056     for (Stmt *SubStmt : S->children())
2057       if (SubStmt &&
2058           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2059                                       Cxx1yLoc, Cxx2aLoc, Kind))
2060         return false;
2061     return true;
2062
2063   case Stmt::GCCAsmStmtClass:
2064   case Stmt::MSAsmStmtClass:
2065     // C++2a allows inline assembly statements.
2066   case Stmt::CXXTryStmtClass:
2067     if (Cxx2aLoc.isInvalid())
2068       Cxx2aLoc = S->getBeginLoc();
2069     for (Stmt *SubStmt : S->children()) {
2070       if (SubStmt &&
2071           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2072                                       Cxx1yLoc, Cxx2aLoc, Kind))
2073         return false;
2074     }
2075     return true;
2076
2077   case Stmt::CXXCatchStmtClass:
2078     // Do not bother checking the language mode (already covered by the
2079     // try block check).
2080     if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
2081                                     cast<CXXCatchStmt>(S)->getHandlerBlock(),
2082                                     ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind))
2083       return false;
2084     return true;
2085
2086   default:
2087     if (!isa<Expr>(S))
2088       break;
2089
2090     // C++1y allows expression-statements.
2091     if (!Cxx1yLoc.isValid())
2092       Cxx1yLoc = S->getBeginLoc();
2093     return true;
2094   }
2095
2096   if (Kind == Sema::CheckConstexprKind::Diagnose) {
2097     SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2098         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2099   }
2100   return false;
2101 }
2102
2103 /// Check the body for the given constexpr function declaration only contains
2104 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2105 ///
2106 /// \return true if the body is OK, false if we have found or diagnosed a
2107 /// problem.
2108 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2109                                        Stmt *Body,
2110                                        Sema::CheckConstexprKind Kind) {
2111   SmallVector<SourceLocation, 4> ReturnStmts;
2112
2113   if (isa<CXXTryStmt>(Body)) {
2114     // C++11 [dcl.constexpr]p3:
2115     //  The definition of a constexpr function shall satisfy the following
2116     //  constraints: [...]
2117     // - its function-body shall be = delete, = default, or a
2118     //   compound-statement
2119     //
2120     // C++11 [dcl.constexpr]p4:
2121     //  In the definition of a constexpr constructor, [...]
2122     // - its function-body shall not be a function-try-block;
2123     //
2124     // This restriction is lifted in C++2a, as long as inner statements also
2125     // apply the general constexpr rules.
2126     switch (Kind) {
2127     case Sema::CheckConstexprKind::CheckValid:
2128       if (!SemaRef.getLangOpts().CPlusPlus2a)
2129         return false;
2130       break;
2131
2132     case Sema::CheckConstexprKind::Diagnose:
2133       SemaRef.Diag(Body->getBeginLoc(),
2134            !SemaRef.getLangOpts().CPlusPlus2a
2135                ? diag::ext_constexpr_function_try_block_cxx2a
2136                : diag::warn_cxx17_compat_constexpr_function_try_block)
2137           << isa<CXXConstructorDecl>(Dcl);
2138       break;
2139     }
2140   }
2141
2142   // - its function-body shall be [...] a compound-statement that contains only
2143   //   [... list of cases ...]
2144   //
2145   // Note that walking the children here is enough to properly check for
2146   // CompoundStmt and CXXTryStmt body.
2147   SourceLocation Cxx1yLoc, Cxx2aLoc;
2148   for (Stmt *SubStmt : Body->children()) {
2149     if (SubStmt &&
2150         !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2151                                     Cxx1yLoc, Cxx2aLoc, Kind))
2152       return false;
2153   }
2154
2155   if (Kind == Sema::CheckConstexprKind::CheckValid) {
2156     // If this is only valid as an extension, report that we don't satisfy the
2157     // constraints of the current language.
2158     if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus2a) ||
2159         (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2160       return false;
2161   } else if (Cxx2aLoc.isValid()) {
2162     SemaRef.Diag(Cxx2aLoc,
2163          SemaRef.getLangOpts().CPlusPlus2a
2164            ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2165            : diag::ext_constexpr_body_invalid_stmt_cxx2a)
2166       << isa<CXXConstructorDecl>(Dcl);
2167   } else if (Cxx1yLoc.isValid()) {
2168     SemaRef.Diag(Cxx1yLoc,
2169          SemaRef.getLangOpts().CPlusPlus14
2170            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2171            : diag::ext_constexpr_body_invalid_stmt)
2172       << isa<CXXConstructorDecl>(Dcl);
2173   }
2174
2175   if (const CXXConstructorDecl *Constructor
2176         = dyn_cast<CXXConstructorDecl>(Dcl)) {
2177     const CXXRecordDecl *RD = Constructor->getParent();
2178     // DR1359:
2179     // - every non-variant non-static data member and base class sub-object
2180     //   shall be initialized;
2181     // DR1460:
2182     // - if the class is a union having variant members, exactly one of them
2183     //   shall be initialized;
2184     if (RD->isUnion()) {
2185       if (Constructor->getNumCtorInitializers() == 0 &&
2186           RD->hasVariantMembers()) {
2187         if (Kind == Sema::CheckConstexprKind::Diagnose) {
2188           SemaRef.Diag(
2189               Dcl->getLocation(),
2190               SemaRef.getLangOpts().CPlusPlus2a
2191                   ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2192                   : diag::ext_constexpr_union_ctor_no_init);
2193         } else if (!SemaRef.getLangOpts().CPlusPlus2a) {
2194           return false;
2195         }
2196       }
2197     } else if (!Constructor->isDependentContext() &&
2198                !Constructor->isDelegatingConstructor()) {
2199       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2200
2201       // Skip detailed checking if we have enough initializers, and we would
2202       // allow at most one initializer per member.
2203       bool AnyAnonStructUnionMembers = false;
2204       unsigned Fields = 0;
2205       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2206            E = RD->field_end(); I != E; ++I, ++Fields) {
2207         if (I->isAnonymousStructOrUnion()) {
2208           AnyAnonStructUnionMembers = true;
2209           break;
2210         }
2211       }
2212       // DR1460:
2213       // - if the class is a union-like class, but is not a union, for each of
2214       //   its anonymous union members having variant members, exactly one of
2215       //   them shall be initialized;
2216       if (AnyAnonStructUnionMembers ||
2217           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2218         // Check initialization of non-static data members. Base classes are
2219         // always initialized so do not need to be checked. Dependent bases
2220         // might not have initializers in the member initializer list.
2221         llvm::SmallSet<Decl*, 16> Inits;
2222         for (const auto *I: Constructor->inits()) {
2223           if (FieldDecl *FD = I->getMember())
2224             Inits.insert(FD);
2225           else if (IndirectFieldDecl *ID = I->getIndirectMember())
2226             Inits.insert(ID->chain_begin(), ID->chain_end());
2227         }
2228
2229         bool Diagnosed = false;
2230         for (auto *I : RD->fields())
2231           if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2232                                              Kind))
2233             return false;
2234       }
2235     }
2236   } else {
2237     if (ReturnStmts.empty()) {
2238       // C++1y doesn't require constexpr functions to contain a 'return'
2239       // statement. We still do, unless the return type might be void, because
2240       // otherwise if there's no return statement, the function cannot
2241       // be used in a core constant expression.
2242       bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2243                 (Dcl->getReturnType()->isVoidType() ||
2244                  Dcl->getReturnType()->isDependentType());
2245       switch (Kind) {
2246       case Sema::CheckConstexprKind::Diagnose:
2247         SemaRef.Diag(Dcl->getLocation(),
2248                      OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2249                         : diag::err_constexpr_body_no_return)
2250             << Dcl->isConsteval();
2251         if (!OK)
2252           return false;
2253         break;
2254
2255       case Sema::CheckConstexprKind::CheckValid:
2256         // The formal requirements don't include this rule in C++14, even
2257         // though the "must be able to produce a constant expression" rules
2258         // still imply it in some cases.
2259         if (!SemaRef.getLangOpts().CPlusPlus14)
2260           return false;
2261         break;
2262       }
2263     } else if (ReturnStmts.size() > 1) {
2264       switch (Kind) {
2265       case Sema::CheckConstexprKind::Diagnose:
2266         SemaRef.Diag(
2267             ReturnStmts.back(),
2268             SemaRef.getLangOpts().CPlusPlus14
2269                 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2270                 : diag::ext_constexpr_body_multiple_return);
2271         for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2272           SemaRef.Diag(ReturnStmts[I],
2273                        diag::note_constexpr_body_previous_return);
2274         break;
2275
2276       case Sema::CheckConstexprKind::CheckValid:
2277         if (!SemaRef.getLangOpts().CPlusPlus14)
2278           return false;
2279         break;
2280       }
2281     }
2282   }
2283
2284   // C++11 [dcl.constexpr]p5:
2285   //   if no function argument values exist such that the function invocation
2286   //   substitution would produce a constant expression, the program is
2287   //   ill-formed; no diagnostic required.
2288   // C++11 [dcl.constexpr]p3:
2289   //   - every constructor call and implicit conversion used in initializing the
2290   //     return value shall be one of those allowed in a constant expression.
2291   // C++11 [dcl.constexpr]p4:
2292   //   - every constructor involved in initializing non-static data members and
2293   //     base class sub-objects shall be a constexpr constructor.
2294   //
2295   // Note that this rule is distinct from the "requirements for a constexpr
2296   // function", so is not checked in CheckValid mode.
2297   SmallVector<PartialDiagnosticAt, 8> Diags;
2298   if (Kind == Sema::CheckConstexprKind::Diagnose &&
2299       !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2300     SemaRef.Diag(Dcl->getLocation(),
2301                  diag::ext_constexpr_function_never_constant_expr)
2302         << isa<CXXConstructorDecl>(Dcl);
2303     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2304       SemaRef.Diag(Diags[I].first, Diags[I].second);
2305     // Don't return false here: we allow this for compatibility in
2306     // system headers.
2307   }
2308
2309   return true;
2310 }
2311
2312 /// Get the class that is directly named by the current context. This is the
2313 /// class for which an unqualified-id in this scope could name a constructor
2314 /// or destructor.
2315 ///
2316 /// If the scope specifier denotes a class, this will be that class.
2317 /// If the scope specifier is empty, this will be the class whose
2318 /// member-specification we are currently within. Otherwise, there
2319 /// is no such class.
2320 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2321   assert(getLangOpts().CPlusPlus && "No class names in C!");
2322
2323   if (SS && SS->isInvalid())
2324     return nullptr;
2325
2326   if (SS && SS->isNotEmpty()) {
2327     DeclContext *DC = computeDeclContext(*SS, true);
2328     return dyn_cast_or_null<CXXRecordDecl>(DC);
2329   }
2330
2331   return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2332 }
2333
2334 /// isCurrentClassName - Determine whether the identifier II is the
2335 /// name of the class type currently being defined. In the case of
2336 /// nested classes, this will only return true if II is the name of
2337 /// the innermost class.
2338 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2339                               const CXXScopeSpec *SS) {
2340   CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2341   return CurDecl && &II == CurDecl->getIdentifier();
2342 }
2343
2344 /// Determine whether the identifier II is a typo for the name of
2345 /// the class type currently being defined. If so, update it to the identifier
2346 /// that should have been used.
2347 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2348   assert(getLangOpts().CPlusPlus && "No class names in C!");
2349
2350   if (!getLangOpts().SpellChecking)
2351     return false;
2352
2353   CXXRecordDecl *CurDecl;
2354   if (SS && SS->isSet() && !SS->isInvalid()) {
2355     DeclContext *DC = computeDeclContext(*SS, true);
2356     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2357   } else
2358     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2359
2360   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2361       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2362           < II->getLength()) {
2363     II = CurDecl->getIdentifier();
2364     return true;
2365   }
2366
2367   return false;
2368 }
2369
2370 /// Determine whether the given class is a base class of the given
2371 /// class, including looking at dependent bases.
2372 static bool findCircularInheritance(const CXXRecordDecl *Class,
2373                                     const CXXRecordDecl *Current) {
2374   SmallVector<const CXXRecordDecl*, 8> Queue;
2375
2376   Class = Class->getCanonicalDecl();
2377   while (true) {
2378     for (const auto &I : Current->bases()) {
2379       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2380       if (!Base)
2381         continue;
2382
2383       Base = Base->getDefinition();
2384       if (!Base)
2385         continue;
2386
2387       if (Base->getCanonicalDecl() == Class)
2388         return true;
2389
2390       Queue.push_back(Base);
2391     }
2392
2393     if (Queue.empty())
2394       return false;
2395
2396     Current = Queue.pop_back_val();
2397   }
2398
2399   return false;
2400 }
2401
2402 /// Check the validity of a C++ base class specifier.
2403 ///
2404 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2405 /// and returns NULL otherwise.
2406 CXXBaseSpecifier *
2407 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2408                          SourceRange SpecifierRange,
2409                          bool Virtual, AccessSpecifier Access,
2410                          TypeSourceInfo *TInfo,
2411                          SourceLocation EllipsisLoc) {
2412   QualType BaseType = TInfo->getType();
2413
2414   // C++ [class.union]p1:
2415   //   A union shall not have base classes.
2416   if (Class->isUnion()) {
2417     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2418       << SpecifierRange;
2419     return nullptr;
2420   }
2421
2422   if (EllipsisLoc.isValid() &&
2423       !TInfo->getType()->containsUnexpandedParameterPack()) {
2424     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2425       << TInfo->getTypeLoc().getSourceRange();
2426     EllipsisLoc = SourceLocation();
2427   }
2428
2429   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2430
2431   if (BaseType->isDependentType()) {
2432     // Make sure that we don't have circular inheritance among our dependent
2433     // bases. For non-dependent bases, the check for completeness below handles
2434     // this.
2435     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2436       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2437           ((BaseDecl = BaseDecl->getDefinition()) &&
2438            findCircularInheritance(Class, BaseDecl))) {
2439         Diag(BaseLoc, diag::err_circular_inheritance)
2440           << BaseType << Context.getTypeDeclType(Class);
2441
2442         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2443           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2444             << BaseType;
2445
2446         return nullptr;
2447       }
2448     }
2449
2450     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2451                                           Class->getTagKind() == TTK_Class,
2452                                           Access, TInfo, EllipsisLoc);
2453   }
2454
2455   // Base specifiers must be record types.
2456   if (!BaseType->isRecordType()) {
2457     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2458     return nullptr;
2459   }
2460
2461   // C++ [class.union]p1:
2462   //   A union shall not be used as a base class.
2463   if (BaseType->isUnionType()) {
2464     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2465     return nullptr;
2466   }
2467
2468   // For the MS ABI, propagate DLL attributes to base class templates.
2469   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2470     if (Attr *ClassAttr = getDLLAttr(Class)) {
2471       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2472               BaseType->getAsCXXRecordDecl())) {
2473         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2474                                             BaseLoc);
2475       }
2476     }
2477   }
2478
2479   // C++ [class.derived]p2:
2480   //   The class-name in a base-specifier shall not be an incompletely
2481   //   defined class.
2482   if (RequireCompleteType(BaseLoc, BaseType,
2483                           diag::err_incomplete_base_class, SpecifierRange)) {
2484     Class->setInvalidDecl();
2485     return nullptr;
2486   }
2487
2488   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2489   RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2490   assert(BaseDecl && "Record type has no declaration");
2491   BaseDecl = BaseDecl->getDefinition();
2492   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2493   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2494   assert(CXXBaseDecl && "Base type is not a C++ type");
2495
2496   // Microsoft docs say:
2497   // "If a base-class has a code_seg attribute, derived classes must have the
2498   // same attribute."
2499   const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2500   const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2501   if ((DerivedCSA || BaseCSA) &&
2502       (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2503     Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2504     Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2505       << CXXBaseDecl;
2506     return nullptr;
2507   }
2508
2509   // A class which contains a flexible array member is not suitable for use as a
2510   // base class:
2511   //   - If the layout determines that a base comes before another base,
2512   //     the flexible array member would index into the subsequent base.
2513   //   - If the layout determines that base comes before the derived class,
2514   //     the flexible array member would index into the derived class.
2515   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2516     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2517       << CXXBaseDecl->getDeclName();
2518     return nullptr;
2519   }
2520
2521   // C++ [class]p3:
2522   //   If a class is marked final and it appears as a base-type-specifier in
2523   //   base-clause, the program is ill-formed.
2524   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2525     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2526       << CXXBaseDecl->getDeclName()
2527       << FA->isSpelledAsSealed();
2528     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2529         << CXXBaseDecl->getDeclName() << FA->getRange();
2530     return nullptr;
2531   }
2532
2533   if (BaseDecl->isInvalidDecl())
2534     Class->setInvalidDecl();
2535
2536   // Create the base specifier.
2537   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2538                                         Class->getTagKind() == TTK_Class,
2539                                         Access, TInfo, EllipsisLoc);
2540 }
2541
2542 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2543 /// one entry in the base class list of a class specifier, for
2544 /// example:
2545 ///    class foo : public bar, virtual private baz {
2546 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2547 BaseResult
2548 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2549                          ParsedAttributes &Attributes,
2550                          bool Virtual, AccessSpecifier Access,
2551                          ParsedType basetype, SourceLocation BaseLoc,
2552                          SourceLocation EllipsisLoc) {
2553   if (!classdecl)
2554     return true;
2555
2556   AdjustDeclIfTemplate(classdecl);
2557   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2558   if (!Class)
2559     return true;
2560
2561   // We haven't yet attached the base specifiers.
2562   Class->setIsParsingBaseSpecifiers();
2563
2564   // We do not support any C++11 attributes on base-specifiers yet.
2565   // Diagnose any attributes we see.
2566   for (const ParsedAttr &AL : Attributes) {
2567     if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2568       continue;
2569     Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2570                           ? (unsigned)diag::warn_unknown_attribute_ignored
2571                           : (unsigned)diag::err_base_specifier_attribute)
2572         << AL;
2573   }
2574
2575   TypeSourceInfo *TInfo = nullptr;
2576   GetTypeFromParser(basetype, &TInfo);
2577
2578   if (EllipsisLoc.isInvalid() &&
2579       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2580                                       UPPC_BaseType))
2581     return true;
2582
2583   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2584                                                       Virtual, Access, TInfo,
2585                                                       EllipsisLoc))
2586     return BaseSpec;
2587   else
2588     Class->setInvalidDecl();
2589
2590   return true;
2591 }
2592
2593 /// Use small set to collect indirect bases.  As this is only used
2594 /// locally, there's no need to abstract the small size parameter.
2595 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2596
2597 /// Recursively add the bases of Type.  Don't add Type itself.
2598 static void
2599 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2600                   const QualType &Type)
2601 {
2602   // Even though the incoming type is a base, it might not be
2603   // a class -- it could be a template parm, for instance.
2604   if (auto Rec = Type->getAs<RecordType>()) {
2605     auto Decl = Rec->getAsCXXRecordDecl();
2606
2607     // Iterate over its bases.
2608     for (const auto &BaseSpec : Decl->bases()) {
2609       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2610         .getUnqualifiedType();
2611       if (Set.insert(Base).second)
2612         // If we've not already seen it, recurse.
2613         NoteIndirectBases(Context, Set, Base);
2614     }
2615   }
2616 }
2617
2618 /// Performs the actual work of attaching the given base class
2619 /// specifiers to a C++ class.
2620 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2621                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2622  if (Bases.empty())
2623     return false;
2624
2625   // Used to keep track of which base types we have already seen, so
2626   // that we can properly diagnose redundant direct base types. Note
2627   // that the key is always the unqualified canonical type of the base
2628   // class.
2629   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2630
2631   // Used to track indirect bases so we can see if a direct base is
2632   // ambiguous.
2633   IndirectBaseSet IndirectBaseTypes;
2634
2635   // Copy non-redundant base specifiers into permanent storage.
2636   unsigned NumGoodBases = 0;
2637   bool Invalid = false;
2638   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2639     QualType NewBaseType
2640       = Context.getCanonicalType(Bases[idx]->getType());
2641     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2642
2643     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2644     if (KnownBase) {
2645       // C++ [class.mi]p3:
2646       //   A class shall not be specified as a direct base class of a
2647       //   derived class more than once.
2648       Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2649           << KnownBase->getType() << Bases[idx]->getSourceRange();
2650
2651       // Delete the duplicate base class specifier; we're going to
2652       // overwrite its pointer later.
2653       Context.Deallocate(Bases[idx]);
2654
2655       Invalid = true;
2656     } else {
2657       // Okay, add this new base class.
2658       KnownBase = Bases[idx];
2659       Bases[NumGoodBases++] = Bases[idx];
2660
2661       // Note this base's direct & indirect bases, if there could be ambiguity.
2662       if (Bases.size() > 1)
2663         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2664
2665       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2666         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2667         if (Class->isInterface() &&
2668               (!RD->isInterfaceLike() ||
2669                KnownBase->getAccessSpecifier() != AS_public)) {
2670           // The Microsoft extension __interface does not permit bases that
2671           // are not themselves public interfaces.
2672           Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2673               << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2674               << RD->getSourceRange();
2675           Invalid = true;
2676         }
2677         if (RD->hasAttr<WeakAttr>())
2678           Class->addAttr(WeakAttr::CreateImplicit(Context));
2679       }
2680     }
2681   }
2682
2683   // Attach the remaining base class specifiers to the derived class.
2684   Class->setBases(Bases.data(), NumGoodBases);
2685
2686   // Check that the only base classes that are duplicate are virtual.
2687   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2688     // Check whether this direct base is inaccessible due to ambiguity.
2689     QualType BaseType = Bases[idx]->getType();
2690
2691     // Skip all dependent types in templates being used as base specifiers.
2692     // Checks below assume that the base specifier is a CXXRecord.
2693     if (BaseType->isDependentType())
2694       continue;
2695
2696     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2697       .getUnqualifiedType();
2698
2699     if (IndirectBaseTypes.count(CanonicalBase)) {
2700       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2701                          /*DetectVirtual=*/true);
2702       bool found
2703         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2704       assert(found);
2705       (void)found;
2706
2707       if (Paths.isAmbiguous(CanonicalBase))
2708         Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2709             << BaseType << getAmbiguousPathsDisplayString(Paths)
2710             << Bases[idx]->getSourceRange();
2711       else
2712         assert(Bases[idx]->isVirtual());
2713     }
2714
2715     // Delete the base class specifier, since its data has been copied
2716     // into the CXXRecordDecl.
2717     Context.Deallocate(Bases[idx]);
2718   }
2719
2720   return Invalid;
2721 }
2722
2723 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2724 /// class, after checking whether there are any duplicate base
2725 /// classes.
2726 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2727                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2728   if (!ClassDecl || Bases.empty())
2729     return;
2730
2731   AdjustDeclIfTemplate(ClassDecl);
2732   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2733 }
2734
2735 /// Determine whether the type \p Derived is a C++ class that is
2736 /// derived from the type \p Base.
2737 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2738   if (!getLangOpts().CPlusPlus)
2739     return false;
2740
2741   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2742   if (!DerivedRD)
2743     return false;
2744
2745   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2746   if (!BaseRD)
2747     return false;
2748
2749   // If either the base or the derived type is invalid, don't try to
2750   // check whether one is derived from the other.
2751   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2752     return false;
2753
2754   // FIXME: In a modules build, do we need the entire path to be visible for us
2755   // to be able to use the inheritance relationship?
2756   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2757     return false;
2758
2759   return DerivedRD->isDerivedFrom(BaseRD);
2760 }
2761
2762 /// Determine whether the type \p Derived is a C++ class that is
2763 /// derived from the type \p Base.
2764 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2765                          CXXBasePaths &Paths) {
2766   if (!getLangOpts().CPlusPlus)
2767     return false;
2768
2769   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2770   if (!DerivedRD)
2771     return false;
2772
2773   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2774   if (!BaseRD)
2775     return false;
2776
2777   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2778     return false;
2779
2780   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2781 }
2782
2783 static void BuildBasePathArray(const CXXBasePath &Path,
2784                                CXXCastPath &BasePathArray) {
2785   // We first go backward and check if we have a virtual base.
2786   // FIXME: It would be better if CXXBasePath had the base specifier for
2787   // the nearest virtual base.
2788   unsigned Start = 0;
2789   for (unsigned I = Path.size(); I != 0; --I) {
2790     if (Path[I - 1].Base->isVirtual()) {
2791       Start = I - 1;
2792       break;
2793     }
2794   }
2795
2796   // Now add all bases.
2797   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2798     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2799 }
2800
2801
2802 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2803                               CXXCastPath &BasePathArray) {
2804   assert(BasePathArray.empty() && "Base path array must be empty!");
2805   assert(Paths.isRecordingPaths() && "Must record paths!");
2806   return ::BuildBasePathArray(Paths.front(), BasePathArray);
2807 }
2808 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2809 /// conversion (where Derived and Base are class types) is
2810 /// well-formed, meaning that the conversion is unambiguous (and
2811 /// that all of the base classes are accessible). Returns true
2812 /// and emits a diagnostic if the code is ill-formed, returns false
2813 /// otherwise. Loc is the location where this routine should point to
2814 /// if there is an error, and Range is the source range to highlight
2815 /// if there is an error.
2816 ///
2817 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2818 /// diagnostic for the respective type of error will be suppressed, but the
2819 /// check for ill-formed code will still be performed.
2820 bool
2821 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2822                                    unsigned InaccessibleBaseID,
2823                                    unsigned AmbigiousBaseConvID,
2824                                    SourceLocation Loc, SourceRange Range,
2825                                    DeclarationName Name,
2826                                    CXXCastPath *BasePath,
2827                                    bool IgnoreAccess) {
2828   // First, determine whether the path from Derived to Base is
2829   // ambiguous. This is slightly more expensive than checking whether
2830   // the Derived to Base conversion exists, because here we need to
2831   // explore multiple paths to determine if there is an ambiguity.
2832   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2833                      /*DetectVirtual=*/false);
2834   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2835   if (!DerivationOkay)
2836     return true;
2837
2838   const CXXBasePath *Path = nullptr;
2839   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2840     Path = &Paths.front();
2841
2842   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2843   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2844   // user to access such bases.
2845   if (!Path && getLangOpts().MSVCCompat) {
2846     for (const CXXBasePath &PossiblePath : Paths) {
2847       if (PossiblePath.size() == 1) {
2848         Path = &PossiblePath;
2849         if (AmbigiousBaseConvID)
2850           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2851               << Base << Derived << Range;
2852         break;
2853       }
2854     }
2855   }
2856
2857   if (Path) {
2858     if (!IgnoreAccess) {
2859       // Check that the base class can be accessed.
2860       switch (
2861           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2862       case AR_inaccessible:
2863         return true;
2864       case AR_accessible:
2865       case AR_dependent:
2866       case AR_delayed:
2867         break;
2868       }
2869     }
2870
2871     // Build a base path if necessary.
2872     if (BasePath)
2873       ::BuildBasePathArray(*Path, *BasePath);
2874     return false;
2875   }
2876
2877   if (AmbigiousBaseConvID) {
2878     // We know that the derived-to-base conversion is ambiguous, and
2879     // we're going to produce a diagnostic. Perform the derived-to-base
2880     // search just one more time to compute all of the possible paths so
2881     // that we can print them out. This is more expensive than any of
2882     // the previous derived-to-base checks we've done, but at this point
2883     // performance isn't as much of an issue.
2884     Paths.clear();
2885     Paths.setRecordingPaths(true);
2886     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2887     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2888     (void)StillOkay;
2889
2890     // Build up a textual representation of the ambiguous paths, e.g.,
2891     // D -> B -> A, that will be used to illustrate the ambiguous
2892     // conversions in the diagnostic. We only print one of the paths
2893     // to each base class subobject.
2894     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2895
2896     Diag(Loc, AmbigiousBaseConvID)
2897     << Derived << Base << PathDisplayStr << Range << Name;
2898   }
2899   return true;
2900 }
2901
2902 bool
2903 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2904                                    SourceLocation Loc, SourceRange Range,
2905                                    CXXCastPath *BasePath,
2906                                    bool IgnoreAccess) {
2907   return CheckDerivedToBaseConversion(
2908       Derived, Base, diag::err_upcast_to_inaccessible_base,
2909       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2910       BasePath, IgnoreAccess);
2911 }
2912
2913
2914 /// Builds a string representing ambiguous paths from a
2915 /// specific derived class to different subobjects of the same base
2916 /// class.
2917 ///
2918 /// This function builds a string that can be used in error messages
2919 /// to show the different paths that one can take through the
2920 /// inheritance hierarchy to go from the derived class to different
2921 /// subobjects of a base class. The result looks something like this:
2922 /// @code
2923 /// struct D -> struct B -> struct A
2924 /// struct D -> struct C -> struct A
2925 /// @endcode
2926 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2927   std::string PathDisplayStr;
2928   std::set<unsigned> DisplayedPaths;
2929   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2930        Path != Paths.end(); ++Path) {
2931     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2932       // We haven't displayed a path to this particular base
2933       // class subobject yet.
2934       PathDisplayStr += "\n    ";
2935       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2936       for (CXXBasePath::const_iterator Element = Path->begin();
2937            Element != Path->end(); ++Element)
2938         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2939     }
2940   }
2941
2942   return PathDisplayStr;
2943 }
2944
2945 //===----------------------------------------------------------------------===//
2946 // C++ class member Handling
2947 //===----------------------------------------------------------------------===//
2948
2949 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2950 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
2951                                 SourceLocation ColonLoc,
2952                                 const ParsedAttributesView &Attrs) {
2953   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2954   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2955                                                   ASLoc, ColonLoc);
2956   CurContext->addHiddenDecl(ASDecl);
2957   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2958 }
2959
2960 /// CheckOverrideControl - Check C++11 override control semantics.
2961 void Sema::CheckOverrideControl(NamedDecl *D) {
2962   if (D->isInvalidDecl())
2963     return;
2964
2965   // We only care about "override" and "final" declarations.
2966   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2967     return;
2968
2969   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2970
2971   // We can't check dependent instance methods.
2972   if (MD && MD->isInstance() &&
2973       (MD->getParent()->hasAnyDependentBases() ||
2974        MD->getType()->isDependentType()))
2975     return;
2976
2977   if (MD && !MD->isVirtual()) {
2978     // If we have a non-virtual method, check if if hides a virtual method.
2979     // (In that case, it's most likely the method has the wrong type.)
2980     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2981     FindHiddenVirtualMethods(MD, OverloadedMethods);
2982
2983     if (!OverloadedMethods.empty()) {
2984       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2985         Diag(OA->getLocation(),
2986              diag::override_keyword_hides_virtual_member_function)
2987           << "override" << (OverloadedMethods.size() > 1);
2988       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2989         Diag(FA->getLocation(),
2990              diag::override_keyword_hides_virtual_member_function)
2991           << (FA->isSpelledAsSealed() ? "sealed" : "final")
2992           << (OverloadedMethods.size() > 1);
2993       }
2994       NoteHiddenVirtualMethods(MD, OverloadedMethods);
2995       MD->setInvalidDecl();
2996       return;
2997     }
2998     // Fall through into the general case diagnostic.
2999     // FIXME: We might want to attempt typo correction here.
3000   }
3001
3002   if (!MD || !MD->isVirtual()) {
3003     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3004       Diag(OA->getLocation(),
3005            diag::override_keyword_only_allowed_on_virtual_member_functions)
3006         << "override" << FixItHint::CreateRemoval(OA->getLocation());
3007       D->dropAttr<OverrideAttr>();
3008     }
3009     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3010       Diag(FA->getLocation(),
3011            diag::override_keyword_only_allowed_on_virtual_member_functions)
3012         << (FA->isSpelledAsSealed() ? "sealed" : "final")
3013         << FixItHint::CreateRemoval(FA->getLocation());
3014       D->dropAttr<FinalAttr>();
3015     }
3016     return;
3017   }
3018
3019   // C++11 [class.virtual]p5:
3020   //   If a function is marked with the virt-specifier override and
3021   //   does not override a member function of a base class, the program is
3022   //   ill-formed.
3023   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3024   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3025     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3026       << MD->getDeclName();
3027 }
3028
3029 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
3030   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3031     return;
3032   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3033   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3034     return;
3035
3036   SourceLocation Loc = MD->getLocation();
3037   SourceLocation SpellingLoc = Loc;
3038   if (getSourceManager().isMacroArgExpansion(Loc))
3039     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3040   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3041   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3042       return;
3043
3044   if (MD->size_overridden_methods() > 0) {
3045     unsigned DiagID = isa<CXXDestructorDecl>(MD)
3046                           ? diag::warn_destructor_marked_not_override_overriding
3047                           : diag::warn_function_marked_not_override_overriding;
3048     Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3049     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3050     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3051   }
3052 }
3053
3054 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3055 /// function overrides a virtual member function marked 'final', according to
3056 /// C++11 [class.virtual]p4.
3057 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3058                                                   const CXXMethodDecl *Old) {
3059   FinalAttr *FA = Old->getAttr<FinalAttr>();
3060   if (!FA)
3061     return false;
3062
3063   Diag(New->getLocation(), diag::err_final_function_overridden)
3064     << New->getDeclName()
3065     << FA->isSpelledAsSealed();
3066   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3067   return true;
3068 }
3069
3070 static bool InitializationHasSideEffects(const FieldDecl &FD) {
3071   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3072   // FIXME: Destruction of ObjC lifetime types has side-effects.
3073   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3074     return !RD->isCompleteDefinition() ||
3075            !RD->hasTrivialDefaultConstructor() ||
3076            !RD->hasTrivialDestructor();
3077   return false;
3078 }
3079
3080 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
3081   ParsedAttributesView::const_iterator Itr =
3082       llvm::find_if(list, [](const ParsedAttr &AL) {
3083         return AL.isDeclspecPropertyAttribute();
3084       });
3085   if (Itr != list.end())
3086     return &*Itr;
3087   return nullptr;
3088 }
3089
3090 // Check if there is a field shadowing.
3091 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3092                                       DeclarationName FieldName,
3093                                       const CXXRecordDecl *RD,
3094                                       bool DeclIsField) {
3095   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3096     return;
3097
3098   // To record a shadowed field in a base
3099   std::map<CXXRecordDecl*, NamedDecl*> Bases;
3100   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3101                            CXXBasePath &Path) {
3102     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3103     // Record an ambiguous path directly
3104     if (Bases.find(Base) != Bases.end())
3105       return true;
3106     for (const auto Field : Base->lookup(FieldName)) {
3107       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3108           Field->getAccess() != AS_private) {
3109         assert(Field->getAccess() != AS_none);
3110         assert(Bases.find(Base) == Bases.end());
3111         Bases[Base] = Field;
3112         return true;
3113       }
3114     }
3115     return false;
3116   };
3117
3118   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3119                      /*DetectVirtual=*/true);
3120   if (!RD->lookupInBases(FieldShadowed, Paths))
3121     return;
3122
3123   for (const auto &P : Paths) {
3124     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3125     auto It = Bases.find(Base);
3126     // Skip duplicated bases
3127     if (It == Bases.end())
3128       continue;
3129     auto BaseField = It->second;
3130     assert(BaseField->getAccess() != AS_private);
3131     if (AS_none !=
3132         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3133       Diag(Loc, diag::warn_shadow_field)
3134         << FieldName << RD << Base << DeclIsField;
3135       Diag(BaseField->getLocation(), diag::note_shadow_field);
3136       Bases.erase(It);
3137     }
3138   }
3139 }
3140
3141 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3142 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3143 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
3144 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3145 /// present (but parsing it has been deferred).
3146 NamedDecl *
3147 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3148                                MultiTemplateParamsArg TemplateParameterLists,
3149                                Expr *BW, const VirtSpecifiers &VS,
3150                                InClassInitStyle InitStyle) {
3151   const DeclSpec &DS = D.getDeclSpec();
3152   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3153   DeclarationName Name = NameInfo.getName();
3154   SourceLocation Loc = NameInfo.getLoc();
3155
3156   // For anonymous bitfields, the location should point to the type.
3157   if (Loc.isInvalid())
3158     Loc = D.getBeginLoc();
3159
3160   Expr *BitWidth = static_cast<Expr*>(BW);
3161
3162   assert(isa<CXXRecordDecl>(CurContext));
3163   assert(!DS.isFriendSpecified());
3164
3165   bool isFunc = D.isDeclarationOfFunction();
3166   const ParsedAttr *MSPropertyAttr =
3167       getMSPropertyAttr(D.getDeclSpec().getAttributes());
3168
3169   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3170     // The Microsoft extension __interface only permits public member functions
3171     // and prohibits constructors, destructors, operators, non-public member
3172     // functions, static methods and data members.
3173     unsigned InvalidDecl;
3174     bool ShowDeclName = true;
3175     if (!isFunc &&
3176         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3177       InvalidDecl = 0;
3178     else if (!isFunc)
3179       InvalidDecl = 1;
3180     else if (AS != AS_public)
3181       InvalidDecl = 2;
3182     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3183       InvalidDecl = 3;
3184     else switch (Name.getNameKind()) {
3185       case DeclarationName::CXXConstructorName:
3186         InvalidDecl = 4;
3187         ShowDeclName = false;
3188         break;
3189
3190       case DeclarationName::CXXDestructorName:
3191         InvalidDecl = 5;
3192         ShowDeclName = false;
3193         break;
3194
3195       case DeclarationName::CXXOperatorName:
3196       case DeclarationName::CXXConversionFunctionName:
3197         InvalidDecl = 6;
3198         break;
3199
3200       default:
3201         InvalidDecl = 0;
3202         break;
3203     }
3204
3205     if (InvalidDecl) {
3206       if (ShowDeclName)
3207         Diag(Loc, diag::err_invalid_member_in_interface)
3208           << (InvalidDecl-1) << Name;
3209       else
3210         Diag(Loc, diag::err_invalid_member_in_interface)
3211           << (InvalidDecl-1) << "";
3212       return nullptr;
3213     }
3214   }
3215
3216   // C++ 9.2p6: A member shall not be declared to have automatic storage
3217   // duration (auto, register) or with the extern storage-class-specifier.
3218   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3219   // data members and cannot be applied to names declared const or static,
3220   // and cannot be applied to reference members.
3221   switch (DS.getStorageClassSpec()) {
3222   case DeclSpec::SCS_unspecified:
3223   case DeclSpec::SCS_typedef:
3224   case DeclSpec::SCS_static:
3225     break;
3226   case DeclSpec::SCS_mutable:
3227     if (isFunc) {
3228       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3229
3230       // FIXME: It would be nicer if the keyword was ignored only for this
3231       // declarator. Otherwise we could get follow-up errors.
3232       D.getMutableDeclSpec().ClearStorageClassSpecs();
3233     }
3234     break;
3235   default:
3236     Diag(DS.getStorageClassSpecLoc(),
3237          diag::err_storageclass_invalid_for_member);
3238     D.getMutableDeclSpec().ClearStorageClassSpecs();
3239     break;
3240   }
3241
3242   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3243                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3244                       !isFunc);
3245
3246   if (DS.hasConstexprSpecifier() && isInstField) {
3247     SemaDiagnosticBuilder B =
3248         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3249     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3250     if (InitStyle == ICIS_NoInit) {
3251       B << 0 << 0;
3252       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3253         B << FixItHint::CreateRemoval(ConstexprLoc);
3254       else {
3255         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3256         D.getMutableDeclSpec().ClearConstexprSpec();
3257         const char *PrevSpec;
3258         unsigned DiagID;
3259         bool Failed = D.getMutableDeclSpec().SetTypeQual(
3260             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3261         (void)Failed;
3262         assert(!Failed && "Making a constexpr member const shouldn't fail");
3263       }
3264     } else {
3265       B << 1;
3266       const char *PrevSpec;
3267       unsigned DiagID;
3268       if (D.getMutableDeclSpec().SetStorageClassSpec(
3269           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3270           Context.getPrintingPolicy())) {
3271         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3272                "This is the only DeclSpec that should fail to be applied");
3273         B << 1;
3274       } else {
3275         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3276         isInstField = false;
3277       }
3278     }
3279   }
3280
3281   NamedDecl *Member;
3282   if (isInstField) {
3283     CXXScopeSpec &SS = D.getCXXScopeSpec();
3284
3285     // Data members must have identifiers for names.
3286     if (!Name.isIdentifier()) {
3287       Diag(Loc, diag::err_bad_variable_name)
3288         << Name;
3289       return nullptr;
3290     }
3291
3292     IdentifierInfo *II = Name.getAsIdentifierInfo();
3293
3294     // Member field could not be with "template" keyword.
3295     // So TemplateParameterLists should be empty in this case.
3296     if (TemplateParameterLists.size()) {
3297       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3298       if (TemplateParams->size()) {
3299         // There is no such thing as a member field template.
3300         Diag(D.getIdentifierLoc(), diag::err_template_member)
3301             << II
3302             << SourceRange(TemplateParams->getTemplateLoc(),
3303                 TemplateParams->getRAngleLoc());
3304       } else {
3305         // There is an extraneous 'template<>' for this member.
3306         Diag(TemplateParams->getTemplateLoc(),
3307             diag::err_template_member_noparams)
3308             << II
3309             << SourceRange(TemplateParams->getTemplateLoc(),
3310                 TemplateParams->getRAngleLoc());
3311       }
3312       return nullptr;
3313     }
3314
3315     if (SS.isSet() && !SS.isInvalid()) {
3316       // The user provided a superfluous scope specifier inside a class
3317       // definition:
3318       //
3319       // class X {
3320       //   int X::member;
3321       // };
3322       if (DeclContext *DC = computeDeclContext(SS, false))
3323         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3324                                      D.getName().getKind() ==
3325                                          UnqualifiedIdKind::IK_TemplateId);
3326       else
3327         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3328           << Name << SS.getRange();
3329
3330       SS.clear();
3331     }
3332
3333     if (MSPropertyAttr) {
3334       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3335                                 BitWidth, InitStyle, AS, *MSPropertyAttr);
3336       if (!Member)
3337         return nullptr;
3338       isInstField = false;
3339     } else {
3340       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3341                                 BitWidth, InitStyle, AS);
3342       if (!Member)
3343         return nullptr;
3344     }
3345
3346     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3347   } else {
3348     Member = HandleDeclarator(S, D, TemplateParameterLists);
3349     if (!Member)
3350       return nullptr;
3351
3352     // Non-instance-fields can't have a bitfield.
3353     if (BitWidth) {
3354       if (Member->isInvalidDecl()) {
3355         // don't emit another diagnostic.
3356       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3357         // C++ 9.6p3: A bit-field shall not be a static member.
3358         // "static member 'A' cannot be a bit-field"
3359         Diag(Loc, diag::err_static_not_bitfield)
3360           << Name << BitWidth->getSourceRange();
3361       } else if (isa<TypedefDecl>(Member)) {
3362         // "typedef member 'x' cannot be a bit-field"
3363         Diag(Loc, diag::err_typedef_not_bitfield)
3364           << Name << BitWidth->getSourceRange();
3365       } else {
3366         // A function typedef ("typedef int f(); f a;").
3367         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3368         Diag(Loc, diag::err_not_integral_type_bitfield)
3369           << Name << cast<ValueDecl>(Member)->getType()
3370           << BitWidth->getSourceRange();
3371       }
3372
3373       BitWidth = nullptr;
3374       Member->setInvalidDecl();
3375     }
3376
3377     NamedDecl *NonTemplateMember = Member;
3378     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3379       NonTemplateMember = FunTmpl->getTemplatedDecl();
3380     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3381       NonTemplateMember = VarTmpl->getTemplatedDecl();
3382
3383     Member->setAccess(AS);
3384
3385     // If we have declared a member function template or static data member
3386     // template, set the access of the templated declaration as well.
3387     if (NonTemplateMember != Member)
3388       NonTemplateMember->setAccess(AS);
3389
3390     // C++ [temp.deduct.guide]p3:
3391     //   A deduction guide [...] for a member class template [shall be
3392     //   declared] with the same access [as the template].
3393     if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3394       auto *TD = DG->getDeducedTemplate();
3395       // Access specifiers are only meaningful if both the template and the
3396       // deduction guide are from the same scope.
3397       if (AS != TD->getAccess() &&
3398           TD->getDeclContext()->getRedeclContext()->Equals(
3399               DG->getDeclContext()->getRedeclContext())) {
3400         Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3401         Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3402             << TD->getAccess();
3403         const AccessSpecDecl *LastAccessSpec = nullptr;
3404         for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3405           if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3406             LastAccessSpec = AccessSpec;
3407         }
3408         assert(LastAccessSpec && "differing access with no access specifier");
3409         Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3410             << AS;
3411       }
3412     }
3413   }
3414
3415   if (VS.isOverrideSpecified())
3416     Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
3417                                          AttributeCommonInfo::AS_Keyword));
3418   if (VS.isFinalSpecified())
3419     Member->addAttr(FinalAttr::Create(
3420         Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
3421         static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
3422
3423   if (VS.getLastLocation().isValid()) {
3424     // Update the end location of a method that has a virt-specifiers.
3425     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3426       MD->setRangeEnd(VS.getLastLocation());
3427   }
3428
3429   CheckOverrideControl(Member);
3430
3431   assert((Name || isInstField) && "No identifier for non-field ?");
3432
3433   if (isInstField) {
3434     FieldDecl *FD = cast<FieldDecl>(Member);
3435     FieldCollector->Add(FD);
3436
3437     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3438       // Remember all explicit private FieldDecls that have a name, no side
3439       // effects and are not part of a dependent type declaration.
3440       if (!FD->isImplicit() && FD->getDeclName() &&
3441           FD->getAccess() == AS_private &&
3442           !FD->hasAttr<UnusedAttr>() &&
3443           !FD->getParent()->isDependentContext() &&
3444           !InitializationHasSideEffects(*FD))
3445         UnusedPrivateFields.insert(FD);
3446     }
3447   }
3448
3449   return Member;
3450 }
3451
3452 namespace {
3453   class UninitializedFieldVisitor
3454       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3455     Sema &S;
3456     // List of Decls to generate a warning on.  Also remove Decls that become
3457     // initialized.
3458     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3459     // List of base classes of the record.  Classes are removed after their
3460     // initializers.
3461     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3462     // Vector of decls to be removed from the Decl set prior to visiting the
3463     // nodes.  These Decls may have been initialized in the prior initializer.
3464     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3465     // If non-null, add a note to the warning pointing back to the constructor.
3466     const CXXConstructorDecl *Constructor;
3467     // Variables to hold state when processing an initializer list.  When
3468     // InitList is true, special case initialization of FieldDecls matching
3469     // InitListFieldDecl.
3470     bool InitList;
3471     FieldDecl *InitListFieldDecl;
3472     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3473
3474   public:
3475     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3476     UninitializedFieldVisitor(Sema &S,
3477                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3478                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3479       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3480         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3481
3482     // Returns true if the use of ME is not an uninitialized use.
3483     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3484                                          bool CheckReferenceOnly) {
3485       llvm::SmallVector<FieldDecl*, 4> Fields;
3486       bool ReferenceField = false;
3487       while (ME) {
3488         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3489         if (!FD)
3490           return false;
3491         Fields.push_back(FD);
3492         if (FD->getType()->isReferenceType())
3493           ReferenceField = true;
3494         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3495       }
3496
3497       // Binding a reference to an uninitialized field is not an
3498       // uninitialized use.
3499       if (CheckReferenceOnly && !ReferenceField)
3500         return true;
3501
3502       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3503       // Discard the first field since it is the field decl that is being
3504       // initialized.
3505       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3506         UsedFieldIndex.push_back((*I)->getFieldIndex());
3507       }
3508
3509       for (auto UsedIter = UsedFieldIndex.begin(),
3510                 UsedEnd = UsedFieldIndex.end(),
3511                 OrigIter = InitFieldIndex.begin(),
3512                 OrigEnd = InitFieldIndex.end();
3513            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3514         if (*UsedIter < *OrigIter)
3515           return true;
3516         if (*UsedIter > *OrigIter)
3517           break;
3518       }
3519
3520       return false;
3521     }
3522
3523     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3524                           bool AddressOf) {
3525       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3526         return;
3527
3528       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3529       // or union.
3530       MemberExpr *FieldME = ME;
3531
3532       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3533
3534       Expr *Base = ME;
3535       while (MemberExpr *SubME =
3536                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3537
3538         if (isa<VarDecl>(SubME->getMemberDecl()))
3539           return;
3540
3541         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3542           if (!FD->isAnonymousStructOrUnion())
3543             FieldME = SubME;
3544
3545         if (!FieldME->getType().isPODType(S.Context))
3546           AllPODFields = false;
3547
3548         Base = SubME->getBase();
3549       }
3550
3551       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3552         return;
3553
3554       if (AddressOf && AllPODFields)
3555         return;
3556
3557       ValueDecl* FoundVD = FieldME->getMemberDecl();
3558
3559       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3560         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3561           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3562         }
3563
3564         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3565           QualType T = BaseCast->getType();
3566           if (T->isPointerType() &&
3567               BaseClasses.count(T->getPointeeType())) {
3568             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3569                 << T->getPointeeType() << FoundVD;
3570           }
3571         }
3572       }
3573
3574       if (!Decls.count(FoundVD))
3575         return;
3576
3577       const bool IsReference = FoundVD->getType()->isReferenceType();
3578
3579       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3580         // Special checking for initializer lists.
3581         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3582           return;
3583         }
3584       } else {
3585         // Prevent double warnings on use of unbounded references.
3586         if (CheckReferenceOnly && !IsReference)
3587           return;
3588       }
3589
3590       unsigned diag = IsReference
3591           ? diag::warn_reference_field_is_uninit
3592           : diag::warn_field_is_uninit;
3593       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3594       if (Constructor)
3595         S.Diag(Constructor->getLocation(),
3596                diag::note_uninit_in_this_constructor)
3597           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3598
3599     }
3600
3601     void HandleValue(Expr *E, bool AddressOf) {
3602       E = E->IgnoreParens();
3603
3604       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3605         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3606                          AddressOf /*AddressOf*/);
3607         return;
3608       }
3609
3610       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3611         Visit(CO->getCond());
3612         HandleValue(CO->getTrueExpr(), AddressOf);
3613         HandleValue(CO->getFalseExpr(), AddressOf);
3614         return;
3615       }
3616
3617       if (BinaryConditionalOperator *BCO =
3618               dyn_cast<BinaryConditionalOperator>(E)) {
3619         Visit(BCO->getCond());
3620         HandleValue(BCO->getFalseExpr(), AddressOf);
3621         return;
3622       }
3623
3624       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3625         HandleValue(OVE->getSourceExpr(), AddressOf);
3626         return;
3627       }
3628
3629       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3630         switch (BO->getOpcode()) {
3631         default:
3632           break;
3633         case(BO_PtrMemD):
3634         case(BO_PtrMemI):
3635           HandleValue(BO->getLHS(), AddressOf);
3636           Visit(BO->getRHS());
3637           return;
3638         case(BO_Comma):
3639           Visit(BO->getLHS());
3640           HandleValue(BO->getRHS(), AddressOf);
3641           return;
3642         }
3643       }
3644
3645       Visit(E);
3646     }
3647
3648     void CheckInitListExpr(InitListExpr *ILE) {
3649       InitFieldIndex.push_back(0);
3650       for (auto Child : ILE->children()) {
3651         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3652           CheckInitListExpr(SubList);
3653         } else {
3654           Visit(Child);
3655         }
3656         ++InitFieldIndex.back();
3657       }
3658       InitFieldIndex.pop_back();
3659     }
3660
3661     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3662                           FieldDecl *Field, const Type *BaseClass) {
3663       // Remove Decls that may have been initialized in the previous
3664       // initializer.
3665       for (ValueDecl* VD : DeclsToRemove)
3666         Decls.erase(VD);
3667       DeclsToRemove.clear();
3668
3669       Constructor = FieldConstructor;
3670       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3671
3672       if (ILE && Field) {
3673         InitList = true;
3674         InitListFieldDecl = Field;
3675         InitFieldIndex.clear();
3676         CheckInitListExpr(ILE);
3677       } else {
3678         InitList = false;
3679         Visit(E);
3680       }
3681
3682       if (Field)
3683         Decls.erase(Field);
3684       if (BaseClass)
3685         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3686     }
3687
3688     void VisitMemberExpr(MemberExpr *ME) {
3689       // All uses of unbounded reference fields will warn.
3690       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3691     }
3692
3693     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3694       if (E->getCastKind() == CK_LValueToRValue) {
3695         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3696         return;
3697       }
3698
3699       Inherited::VisitImplicitCastExpr(E);
3700     }
3701
3702     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3703       if (E->getConstructor()->isCopyConstructor()) {
3704         Expr *ArgExpr = E->getArg(0);
3705         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3706           if (ILE->getNumInits() == 1)
3707             ArgExpr = ILE->getInit(0);
3708         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3709           if (ICE->getCastKind() == CK_NoOp)
3710             ArgExpr = ICE->getSubExpr();
3711         HandleValue(ArgExpr, false /*AddressOf*/);
3712         return;
3713       }
3714       Inherited::VisitCXXConstructExpr(E);
3715     }
3716
3717     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3718       Expr *Callee = E->getCallee();
3719       if (isa<MemberExpr>(Callee)) {
3720         HandleValue(Callee, false /*AddressOf*/);
3721         for (auto Arg : E->arguments())
3722           Visit(Arg);
3723         return;
3724       }
3725
3726       Inherited::VisitCXXMemberCallExpr(E);
3727     }
3728
3729     void VisitCallExpr(CallExpr *E) {
3730       // Treat std::move as a use.
3731       if (E->isCallToStdMove()) {
3732         HandleValue(E->getArg(0), /*AddressOf=*/false);
3733         return;
3734       }
3735
3736       Inherited::VisitCallExpr(E);
3737     }
3738
3739     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3740       Expr *Callee = E->getCallee();
3741
3742       if (isa<UnresolvedLookupExpr>(Callee))
3743         return Inherited::VisitCXXOperatorCallExpr(E);
3744
3745       Visit(Callee);
3746       for (auto Arg : E->arguments())
3747         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3748     }
3749
3750     void VisitBinaryOperator(BinaryOperator *E) {
3751       // If a field assignment is detected, remove the field from the
3752       // uninitiailized field set.
3753       if (E->getOpcode() == BO_Assign)
3754         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3755           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3756             if (!FD->getType()->isReferenceType())
3757               DeclsToRemove.push_back(FD);
3758
3759       if (E->isCompoundAssignmentOp()) {
3760         HandleValue(E->getLHS(), false /*AddressOf*/);
3761         Visit(E->getRHS());
3762         return;
3763       }
3764
3765       Inherited::VisitBinaryOperator(E);
3766     }
3767
3768     void VisitUnaryOperator(UnaryOperator *E) {
3769       if (E->isIncrementDecrementOp()) {
3770         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3771         return;
3772       }
3773       if (E->getOpcode() == UO_AddrOf) {
3774         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3775           HandleValue(ME->getBase(), true /*AddressOf*/);
3776           return;
3777         }
3778       }
3779
3780       Inherited::VisitUnaryOperator(E);
3781     }
3782   };
3783
3784   // Diagnose value-uses of fields to initialize themselves, e.g.
3785   //   foo(foo)
3786   // where foo is not also a parameter to the constructor.
3787   // Also diagnose across field uninitialized use such as
3788   //   x(y), y(x)
3789   // TODO: implement -Wuninitialized and fold this into that framework.
3790   static void DiagnoseUninitializedFields(
3791       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3792
3793     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3794                                            Constructor->getLocation())) {
3795       return;
3796     }
3797
3798     if (Constructor->isInvalidDecl())
3799       return;
3800
3801     const CXXRecordDecl *RD = Constructor->getParent();
3802
3803     if (RD->getDescribedClassTemplate())
3804       return;
3805
3806     // Holds fields that are uninitialized.
3807     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3808
3809     // At the beginning, all fields are uninitialized.
3810     for (auto *I : RD->decls()) {
3811       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3812         UninitializedFields.insert(FD);
3813       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3814         UninitializedFields.insert(IFD->getAnonField());
3815       }
3816     }
3817
3818     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3819     for (auto I : RD->bases())
3820       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3821
3822     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3823       return;
3824
3825     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3826                                                    UninitializedFields,
3827                                                    UninitializedBaseClasses);
3828
3829     for (const auto *FieldInit : Constructor->inits()) {
3830       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3831         break;
3832
3833       Expr *InitExpr = FieldInit->getInit();
3834       if (!InitExpr)
3835         continue;
3836
3837       if (CXXDefaultInitExpr *Default =
3838               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3839         InitExpr = Default->getExpr();
3840         if (!InitExpr)
3841           continue;
3842         // In class initializers will point to the constructor.
3843         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3844                                               FieldInit->getAnyMember(),
3845                                               FieldInit->getBaseClass());
3846       } else {
3847         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3848                                               FieldInit->getAnyMember(),
3849                                               FieldInit->getBaseClass());
3850       }
3851     }
3852   }
3853 } // namespace
3854
3855 /// Enter a new C++ default initializer scope. After calling this, the
3856 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3857 /// parsing or instantiating the initializer failed.
3858 void Sema::ActOnStartCXXInClassMemberInitializer() {
3859   // Create a synthetic function scope to represent the call to the constructor
3860   // that notionally surrounds a use of this initializer.
3861   PushFunctionScope();
3862 }
3863
3864 /// This is invoked after parsing an in-class initializer for a
3865 /// non-static C++ class member, and after instantiating an in-class initializer
3866 /// in a class template. Such actions are deferred until the class is complete.
3867 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3868                                                   SourceLocation InitLoc,
3869                                                   Expr *InitExpr) {
3870   // Pop the notional constructor scope we created earlier.
3871   PopFunctionScopeInfo(nullptr, D);
3872
3873   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3874   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3875          "must set init style when field is created");
3876
3877   if (!InitExpr) {
3878     D->setInvalidDecl();
3879     if (FD)
3880       FD->removeInClassInitializer();
3881     return;
3882   }
3883
3884   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3885     FD->setInvalidDecl();
3886     FD->removeInClassInitializer();
3887     return;
3888   }
3889
3890   ExprResult Init = InitExpr;
3891   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3892     InitializedEntity Entity =
3893         InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
3894     InitializationKind Kind =
3895         FD->getInClassInitStyle() == ICIS_ListInit
3896             ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
3897                                                    InitExpr->getBeginLoc(),
3898                                                    InitExpr->getEndLoc())
3899             : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
3900     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3901     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3902     if (Init.isInvalid()) {
3903       FD->setInvalidDecl();
3904       return;
3905     }
3906   }
3907
3908   // C++11 [class.base.init]p7:
3909   //   The initialization of each base and member constitutes a
3910   //   full-expression.
3911   Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
3912   if (Init.isInvalid()) {
3913     FD->setInvalidDecl();
3914     return;
3915   }
3916
3917   InitExpr = Init.get();
3918
3919   FD->setInClassInitializer(InitExpr);
3920 }
3921
3922 /// Find the direct and/or virtual base specifiers that
3923 /// correspond to the given base type, for use in base initialization
3924 /// within a constructor.
3925 static bool FindBaseInitializer(Sema &SemaRef,
3926                                 CXXRecordDecl *ClassDecl,
3927                                 QualType BaseType,
3928                                 const CXXBaseSpecifier *&DirectBaseSpec,
3929                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
3930   // First, check for a direct base class.
3931   DirectBaseSpec = nullptr;
3932   for (const auto &Base : ClassDecl->bases()) {
3933     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3934       // We found a direct base of this type. That's what we're
3935       // initializing.
3936       DirectBaseSpec = &Base;
3937       break;
3938     }
3939   }
3940
3941   // Check for a virtual base class.
3942   // FIXME: We might be able to short-circuit this if we know in advance that
3943   // there are no virtual bases.
3944   VirtualBaseSpec = nullptr;
3945   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3946     // We haven't found a base yet; search the class hierarchy for a
3947     // virtual base class.
3948     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3949                        /*DetectVirtual=*/false);
3950     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3951                               SemaRef.Context.getTypeDeclType(ClassDecl),
3952                               BaseType, Paths)) {
3953       for (CXXBasePaths::paths_iterator Path = Paths.begin();
3954            Path != Paths.end(); ++Path) {
3955         if (Path->back().Base->isVirtual()) {
3956           VirtualBaseSpec = Path->back().Base;
3957           break;
3958         }
3959       }
3960     }
3961   }
3962
3963   return DirectBaseSpec || VirtualBaseSpec;
3964 }
3965
3966 /// Handle a C++ member initializer using braced-init-list syntax.
3967 MemInitResult
3968 Sema::ActOnMemInitializer(Decl *ConstructorD,
3969                           Scope *S,
3970                           CXXScopeSpec &SS,
3971                           IdentifierInfo *MemberOrBase,
3972                           ParsedType TemplateTypeTy,
3973                           const DeclSpec &DS,
3974                           SourceLocation IdLoc,
3975                           Expr *InitList,
3976                           SourceLocation EllipsisLoc) {
3977   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3978                              DS, IdLoc, InitList,
3979                              EllipsisLoc);
3980 }
3981
3982 /// Handle a C++ member initializer using parentheses syntax.
3983 MemInitResult
3984 Sema::ActOnMemInitializer(Decl *ConstructorD,
3985                           Scope *S,
3986                           CXXScopeSpec &SS,
3987                           IdentifierInfo *MemberOrBase,
3988                           ParsedType TemplateTypeTy,
3989                           const DeclSpec &DS,
3990                           SourceLocation IdLoc,
3991                           SourceLocation LParenLoc,
3992                           ArrayRef<Expr *> Args,
3993                           SourceLocation RParenLoc,
3994                           SourceLocation EllipsisLoc) {
3995   Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
3996   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3997                              DS, IdLoc, List, EllipsisLoc);
3998 }
3999
4000 namespace {
4001
4002 // Callback to only accept typo corrections that can be a valid C++ member
4003 // intializer: either a non-static field member or a base class.
4004 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4005 public:
4006   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4007       : ClassDecl(ClassDecl) {}
4008
4009   bool ValidateCandidate(const TypoCorrection &candidate) override {
4010     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4011       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4012         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4013       return isa<TypeDecl>(ND);
4014     }
4015     return false;
4016   }
4017
4018   std::unique_ptr<CorrectionCandidateCallback> clone() override {
4019     return std::make_unique<MemInitializerValidatorCCC>(*this);
4020   }
4021
4022 private:
4023   CXXRecordDecl *ClassDecl;
4024 };
4025
4026 }
4027
4028 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4029                                              CXXScopeSpec &SS,
4030                                              ParsedType TemplateTypeTy,
4031                                              IdentifierInfo *MemberOrBase) {
4032   if (SS.getScopeRep() || TemplateTypeTy)
4033     return nullptr;
4034   DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
4035   if (Result.empty())
4036     return nullptr;
4037   ValueDecl *Member;
4038   if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
4039       (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
4040     return Member;
4041   return nullptr;
4042 }
4043
4044 /// Handle a C++ member initializer.
4045 MemInitResult
4046 Sema::BuildMemInitializer(Decl *ConstructorD,
4047                           Scope *S,
4048                           CXXScopeSpec &SS,
4049                           IdentifierInfo *MemberOrBase,
4050                           ParsedType TemplateTypeTy,
4051                           const DeclSpec &DS,
4052                           SourceLocation IdLoc,
4053                           Expr *Init,
4054                           SourceLocation EllipsisLoc) {
4055   ExprResult Res = CorrectDelayedTyposInExpr(Init);
4056   if (!Res.isUsable())
4057     return true;
4058   Init = Res.get();
4059
4060   if (!ConstructorD)
4061     return true;
4062
4063   AdjustDeclIfTemplate(ConstructorD);
4064
4065   CXXConstructorDecl *Constructor
4066     = dyn_cast<CXXConstructorDecl>(ConstructorD);
4067   if (!Constructor) {
4068     // The user wrote a constructor initializer on a function that is
4069     // not a C++ constructor. Ignore the error for now, because we may
4070     // have more member initializers coming; we'll diagnose it just
4071     // once in ActOnMemInitializers.
4072     return true;
4073   }
4074
4075   CXXRecordDecl *ClassDecl = Constructor->getParent();
4076
4077   // C++ [class.base.init]p2:
4078   //   Names in a mem-initializer-id are looked up in the scope of the
4079   //   constructor's class and, if not found in that scope, are looked
4080   //   up in the scope containing the constructor's definition.
4081   //   [Note: if the constructor's class contains a member with the
4082   //   same name as a direct or virtual base class of the class, a
4083   //   mem-initializer-id naming the member or base class and composed
4084   //   of a single identifier refers to the class member. A
4085   //   mem-initializer-id for the hidden base class may be specified
4086   //   using a qualified name. ]
4087
4088   // Look for a member, first.
4089   if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4090           ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4091     if (EllipsisLoc.isValid())
4092       Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4093           << MemberOrBase
4094           << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4095
4096     return BuildMemberInitializer(Member, Init, IdLoc);
4097   }
4098   // It didn't name a member, so see if it names a class.
4099   QualType BaseType;
4100   TypeSourceInfo *TInfo = nullptr;
4101
4102   if (TemplateTypeTy) {
4103     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4104     if (BaseType.isNull())
4105       return true;
4106   } else if (DS.getTypeSpecType() == TST_decltype) {
4107     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
4108   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4109     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4110     return true;
4111   } else {
4112     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4113     LookupParsedName(R, S, &SS);
4114
4115     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4116     if (!TyD) {
4117       if (R.isAmbiguous()) return true;
4118
4119       // We don't want access-control diagnostics here.
4120       R.suppressDiagnostics();
4121
4122       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4123         bool NotUnknownSpecialization = false;
4124         DeclContext *DC = computeDeclContext(SS, false);
4125         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4126           NotUnknownSpecialization = !Record->hasAnyDependentBases();
4127
4128         if (!NotUnknownSpecialization) {
4129           // When the scope specifier can refer to a member of an unknown
4130           // specialization, we take it as a type name.
4131           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
4132                                        SS.getWithLocInContext(Context),
4133                                        *MemberOrBase, IdLoc);
4134           if (BaseType.isNull())
4135             return true;
4136
4137           TInfo = Context.CreateTypeSourceInfo(BaseType);
4138           DependentNameTypeLoc TL =
4139               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4140           if (!TL.isNull()) {
4141             TL.setNameLoc(IdLoc);
4142             TL.setElaboratedKeywordLoc(SourceLocation());
4143             TL.setQualifierLoc(SS.getWithLocInContext(Context));
4144           }
4145
4146           R.clear();
4147           R.setLookupName(MemberOrBase);
4148         }
4149       }
4150
4151       // If no results were found, try to correct typos.
4152       TypoCorrection Corr;
4153       MemInitializerValidatorCCC CCC(ClassDecl);
4154       if (R.empty() && BaseType.isNull() &&
4155           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4156                               CCC, CTK_ErrorRecovery, ClassDecl))) {
4157         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4158           // We have found a non-static data member with a similar
4159           // name to what was typed; complain and initialize that
4160           // member.
4161           diagnoseTypo(Corr,
4162                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
4163                          << MemberOrBase << true);
4164           return BuildMemberInitializer(Member, Init, IdLoc);
4165         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4166           const CXXBaseSpecifier *DirectBaseSpec;
4167           const CXXBaseSpecifier *VirtualBaseSpec;
4168           if (FindBaseInitializer(*this, ClassDecl,
4169                                   Context.getTypeDeclType(Type),
4170                                   DirectBaseSpec, VirtualBaseSpec)) {
4171             // We have found a direct or virtual base class with a
4172             // similar name to what was typed; complain and initialize
4173             // that base class.
4174             diagnoseTypo(Corr,
4175                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
4176                            << MemberOrBase << false,
4177                          PDiag() /*Suppress note, we provide our own.*/);
4178
4179             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4180                                                               : VirtualBaseSpec;
4181             Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4182                 << BaseSpec->getType() << BaseSpec->getSourceRange();
4183
4184             TyD = Type;
4185           }
4186         }
4187       }
4188
4189       if (!TyD && BaseType.isNull()) {
4190         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4191           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4192         return true;
4193       }
4194     }
4195
4196     if (BaseType.isNull()) {
4197       BaseType = Context.getTypeDeclType(TyD);
4198       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4199       if (SS.isSet()) {
4200         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
4201                                              BaseType);
4202         TInfo = Context.CreateTypeSourceInfo(BaseType);
4203         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4204         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4205         TL.setElaboratedKeywordLoc(SourceLocation());
4206         TL.setQualifierLoc(SS.getWithLocInContext(Context));
4207       }
4208     }
4209   }
4210
4211   if (!TInfo)
4212     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4213
4214   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4215 }
4216
4217 MemInitResult
4218 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4219                              SourceLocation IdLoc) {
4220   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4221   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4222   assert((DirectMember || IndirectMember) &&
4223          "Member must be a FieldDecl or IndirectFieldDecl");
4224
4225   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4226     return true;
4227
4228   if (Member->isInvalidDecl())
4229     return true;
4230
4231   MultiExprArg Args;
4232   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4233     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4234   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4235     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4236   } else {
4237     // Template instantiation doesn't reconstruct ParenListExprs for us.
4238     Args = Init;
4239   }
4240
4241   SourceRange InitRange = Init->getSourceRange();
4242
4243   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4244     // Can't check initialization for a member of dependent type or when
4245     // any of the arguments are type-dependent expressions.
4246     DiscardCleanupsInEvaluationContext();
4247   } else {
4248     bool InitList = false;
4249     if (isa<InitListExpr>(Init)) {
4250       InitList = true;
4251       Args = Init;
4252     }
4253
4254     // Initialize the member.
4255     InitializedEntity MemberEntity =
4256       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4257                    : InitializedEntity::InitializeMember(IndirectMember,
4258                                                          nullptr);
4259     InitializationKind Kind =
4260         InitList ? InitializationKind::CreateDirectList(
4261                        IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4262                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4263                                                     InitRange.getEnd());
4264
4265     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4266     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4267                                             nullptr);
4268     if (MemberInit.isInvalid())
4269       return true;
4270
4271     // C++11 [class.base.init]p7:
4272     //   The initialization of each base and member constitutes a
4273     //   full-expression.
4274     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4275                                      /*DiscardedValue*/ false);
4276     if (MemberInit.isInvalid())
4277       return true;
4278
4279     Init = MemberInit.get();
4280   }
4281
4282   if (DirectMember) {
4283     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4284                                             InitRange.getBegin(), Init,
4285                                             InitRange.getEnd());
4286   } else {
4287     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4288                                             InitRange.getBegin(), Init,
4289                                             InitRange.getEnd());
4290   }
4291 }
4292
4293 MemInitResult
4294 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4295                                  CXXRecordDecl *ClassDecl) {
4296   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4297   if (!LangOpts.CPlusPlus11)
4298     return Diag(NameLoc, diag::err_delegating_ctor)
4299       << TInfo->getTypeLoc().getLocalSourceRange();
4300   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4301
4302   bool InitList = true;
4303   MultiExprArg Args = Init;
4304   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4305     InitList = false;
4306     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4307   }
4308
4309   SourceRange InitRange = Init->getSourceRange();
4310   // Initialize the object.
4311   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4312                                      QualType(ClassDecl->getTypeForDecl(), 0));
4313   InitializationKind Kind =
4314       InitList ? InitializationKind::CreateDirectList(
4315                      NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4316                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4317                                                   InitRange.getEnd());
4318   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4319   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4320                                               Args, nullptr);
4321   if (DelegationInit.isInvalid())
4322     return true;
4323
4324   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4325          "Delegating constructor with no target?");
4326
4327   // C++11 [class.base.init]p7:
4328   //   The initialization of each base and member constitutes a
4329   //   full-expression.
4330   DelegationInit = ActOnFinishFullExpr(
4331       DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4332   if (DelegationInit.isInvalid())
4333     return true;
4334
4335   // If we are in a dependent context, template instantiation will
4336   // perform this type-checking again. Just save the arguments that we
4337   // received in a ParenListExpr.
4338   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4339   // of the information that we have about the base
4340   // initializer. However, deconstructing the ASTs is a dicey process,
4341   // and this approach is far more likely to get the corner cases right.
4342   if (CurContext->isDependentContext())
4343     DelegationInit = Init;
4344
4345   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4346                                           DelegationInit.getAs<Expr>(),
4347                                           InitRange.getEnd());
4348 }
4349
4350 MemInitResult
4351 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4352                            Expr *Init, CXXRecordDecl *ClassDecl,
4353                            SourceLocation EllipsisLoc) {
4354   SourceLocation BaseLoc
4355     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4356
4357   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4358     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4359              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4360
4361   // C++ [class.base.init]p2:
4362   //   [...] Unless the mem-initializer-id names a nonstatic data
4363   //   member of the constructor's class or a direct or virtual base
4364   //   of that class, the mem-initializer is ill-formed. A
4365   //   mem-initializer-list can initialize a base class using any
4366   //   name that denotes that base class type.
4367   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4368
4369   SourceRange InitRange = Init->getSourceRange();
4370   if (EllipsisLoc.isValid()) {
4371     // This is a pack expansion.
4372     if (!BaseType->containsUnexpandedParameterPack())  {
4373       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4374         << SourceRange(BaseLoc, InitRange.getEnd());
4375
4376       EllipsisLoc = SourceLocation();
4377     }
4378   } else {
4379     // Check for any unexpanded parameter packs.
4380     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4381       return true;
4382
4383     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4384       return true;
4385   }
4386
4387   // Check for direct and virtual base classes.
4388   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4389   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4390   if (!Dependent) {
4391     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4392                                        BaseType))
4393       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4394
4395     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4396                         VirtualBaseSpec);
4397
4398     // C++ [base.class.init]p2:
4399     // Unless the mem-initializer-id names a nonstatic data member of the
4400     // constructor's class or a direct or virtual base of that class, the
4401     // mem-initializer is ill-formed.
4402     if (!DirectBaseSpec && !VirtualBaseSpec) {
4403       // If the class has any dependent bases, then it's possible that
4404       // one of those types will resolve to the same type as
4405       // BaseType. Therefore, just treat this as a dependent base
4406       // class initialization.  FIXME: Should we try to check the
4407       // initialization anyway? It seems odd.
4408       if (ClassDecl->hasAnyDependentBases())
4409         Dependent = true;
4410       else
4411         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4412           << BaseType << Context.getTypeDeclType(ClassDecl)
4413           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4414     }
4415   }
4416
4417   if (Dependent) {
4418     DiscardCleanupsInEvaluationContext();
4419
4420     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4421                                             /*IsVirtual=*/false,
4422                                             InitRange.getBegin(), Init,
4423                                             InitRange.getEnd(), EllipsisLoc);
4424   }
4425
4426   // C++ [base.class.init]p2:
4427   //   If a mem-initializer-id is ambiguous because it designates both
4428   //   a direct non-virtual base class and an inherited virtual base
4429   //   class, the mem-initializer is ill-formed.
4430   if (DirectBaseSpec && VirtualBaseSpec)
4431     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4432       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4433
4434   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4435   if (!BaseSpec)
4436     BaseSpec = VirtualBaseSpec;
4437
4438   // Initialize the base.
4439   bool InitList = true;
4440   MultiExprArg Args = Init;
4441   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4442     InitList = false;
4443     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4444   }
4445
4446   InitializedEntity BaseEntity =
4447     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4448   InitializationKind Kind =
4449       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4450                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4451                                                   InitRange.getEnd());
4452   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4453   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4454   if (BaseInit.isInvalid())
4455     return true;
4456
4457   // C++11 [class.base.init]p7:
4458   //   The initialization of each base and member constitutes a
4459   //   full-expression.
4460   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4461                                  /*DiscardedValue*/ false);
4462   if (BaseInit.isInvalid())
4463     return true;
4464
4465   // If we are in a dependent context, template instantiation will
4466   // perform this type-checking again. Just save the arguments that we
4467   // received in a ParenListExpr.
4468   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4469   // of the information that we have about the base
4470   // initializer. However, deconstructing the ASTs is a dicey process,
4471   // and this approach is far more likely to get the corner cases right.
4472   if (CurContext->isDependentContext())
4473     BaseInit = Init;
4474
4475   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4476                                           BaseSpec->isVirtual(),
4477                                           InitRange.getBegin(),
4478                                           BaseInit.getAs<Expr>(),
4479                                           InitRange.getEnd(), EllipsisLoc);
4480 }
4481
4482 // Create a static_cast\<T&&>(expr).
4483 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4484   if (T.isNull()) T = E->getType();
4485   QualType TargetType = SemaRef.BuildReferenceType(
4486       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4487   SourceLocation ExprLoc = E->getBeginLoc();
4488   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4489       TargetType, ExprLoc);
4490
4491   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4492                                    SourceRange(ExprLoc, ExprLoc),
4493                                    E->getSourceRange()).get();
4494 }
4495
4496 /// ImplicitInitializerKind - How an implicit base or member initializer should
4497 /// initialize its base or member.
4498 enum ImplicitInitializerKind {
4499   IIK_Default,
4500   IIK_Copy,
4501   IIK_Move,
4502   IIK_Inherit
4503 };
4504
4505 static bool
4506 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4507                              ImplicitInitializerKind ImplicitInitKind,
4508                              CXXBaseSpecifier *BaseSpec,
4509                              bool IsInheritedVirtualBase,
4510                              CXXCtorInitializer *&CXXBaseInit) {
4511   InitializedEntity InitEntity
4512     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4513                                         IsInheritedVirtualBase);
4514
4515   ExprResult BaseInit;
4516
4517   switch (ImplicitInitKind) {
4518   case IIK_Inherit:
4519   case IIK_Default: {
4520     InitializationKind InitKind
4521       = InitializationKind::CreateDefault(Constructor->getLocation());
4522     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4523     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4524     break;
4525   }
4526
4527   case IIK_Move:
4528   case IIK_Copy: {
4529     bool Moving = ImplicitInitKind == IIK_Move;
4530     ParmVarDecl *Param = Constructor->getParamDecl(0);
4531     QualType ParamType = Param->getType().getNonReferenceType();
4532
4533     Expr *CopyCtorArg =
4534       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4535                           SourceLocation(), Param, false,
4536                           Constructor->getLocation(), ParamType,
4537                           VK_LValue, nullptr);
4538
4539     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4540
4541     // Cast to the base class to avoid ambiguities.
4542     QualType ArgTy =
4543       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4544                                        ParamType.getQualifiers());
4545
4546     if (Moving) {
4547       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4548     }
4549
4550     CXXCastPath BasePath;
4551     BasePath.push_back(BaseSpec);
4552     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4553                                             CK_UncheckedDerivedToBase,
4554                                             Moving ? VK_XValue : VK_LValue,
4555                                             &BasePath).get();
4556
4557     InitializationKind InitKind
4558       = InitializationKind::CreateDirect(Constructor->getLocation(),
4559                                          SourceLocation(), SourceLocation());
4560     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4561     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4562     break;
4563   }
4564   }
4565
4566   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4567   if (BaseInit.isInvalid())
4568     return true;
4569
4570   CXXBaseInit =
4571     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4572                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4573                                                         SourceLocation()),
4574                                              BaseSpec->isVirtual(),
4575                                              SourceLocation(),
4576                                              BaseInit.getAs<Expr>(),
4577                                              SourceLocation(),
4578                                              SourceLocation());
4579
4580   return false;
4581 }
4582
4583 static bool RefersToRValueRef(Expr *MemRef) {
4584   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4585   return Referenced->getType()->isRValueReferenceType();
4586 }
4587
4588 static bool
4589 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4590                                ImplicitInitializerKind ImplicitInitKind,
4591                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4592                                CXXCtorInitializer *&CXXMemberInit) {
4593   if (Field->isInvalidDecl())
4594     return true;
4595
4596   SourceLocation Loc = Constructor->getLocation();
4597
4598   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4599     bool Moving = ImplicitInitKind == IIK_Move;
4600     ParmVarDecl *Param = Constructor->getParamDecl(0);
4601     QualType ParamType = Param->getType().getNonReferenceType();
4602
4603     // Suppress copying zero-width bitfields.
4604     if (Field->isZeroLengthBitField(SemaRef.Context))
4605       return false;
4606
4607     Expr *MemberExprBase =
4608       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4609                           SourceLocation(), Param, false,
4610                           Loc, ParamType, VK_LValue, nullptr);
4611
4612     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4613
4614     if (Moving) {
4615       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4616     }
4617
4618     // Build a reference to this field within the parameter.
4619     CXXScopeSpec SS;
4620     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4621                               Sema::LookupMemberName);
4622     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4623                                   : cast<ValueDecl>(Field), AS_public);
4624     MemberLookup.resolveKind();
4625     ExprResult CtorArg
4626       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4627                                          ParamType, Loc,
4628                                          /*IsArrow=*/false,
4629                                          SS,
4630                                          /*TemplateKWLoc=*/SourceLocation(),
4631                                          /*FirstQualifierInScope=*/nullptr,
4632                                          MemberLookup,
4633                                          /*TemplateArgs=*/nullptr,
4634                                          /*S*/nullptr);
4635     if (CtorArg.isInvalid())
4636       return true;
4637
4638     // C++11 [class.copy]p15:
4639     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4640     //     with static_cast<T&&>(x.m);
4641     if (RefersToRValueRef(CtorArg.get())) {
4642       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4643     }
4644
4645     InitializedEntity Entity =
4646         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4647                                                        /*Implicit*/ true)
4648                  : InitializedEntity::InitializeMember(Field, nullptr,
4649                                                        /*Implicit*/ true);
4650
4651     // Direct-initialize to use the copy constructor.
4652     InitializationKind InitKind =
4653       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4654
4655     Expr *CtorArgE = CtorArg.getAs<Expr>();
4656     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4657     ExprResult MemberInit =
4658         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4659     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4660     if (MemberInit.isInvalid())
4661       return true;
4662
4663     if (Indirect)
4664       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4665           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4666     else
4667       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4668           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4669     return false;
4670   }
4671
4672   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4673          "Unhandled implicit init kind!");
4674
4675   QualType FieldBaseElementType =
4676     SemaRef.Context.getBaseElementType(Field->getType());
4677
4678   if (FieldBaseElementType->isRecordType()) {
4679     InitializedEntity InitEntity =
4680         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4681                                                        /*Implicit*/ true)
4682                  : InitializedEntity::InitializeMember(Field, nullptr,
4683                                                        /*Implicit*/ true);
4684     InitializationKind InitKind =
4685       InitializationKind::CreateDefault(Loc);
4686
4687     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4688     ExprResult MemberInit =
4689       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4690
4691     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4692     if (MemberInit.isInvalid())
4693       return true;
4694
4695     if (Indirect)
4696       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4697                                                                Indirect, Loc,
4698                                                                Loc,
4699                                                                MemberInit.get(),
4700                                                                Loc);
4701     else
4702       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4703                                                                Field, Loc, Loc,
4704                                                                MemberInit.get(),
4705                                                                Loc);
4706     return false;
4707   }
4708
4709   if (!Field->getParent()->isUnion()) {
4710     if (FieldBaseElementType->isReferenceType()) {
4711       SemaRef.Diag(Constructor->getLocation(),
4712                    diag::err_uninitialized_member_in_ctor)
4713       << (int)Constructor->isImplicit()
4714       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4715       << 0 << Field->getDeclName();
4716       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4717       return true;
4718     }
4719
4720     if (FieldBaseElementType.isConstQualified()) {
4721       SemaRef.Diag(Constructor->getLocation(),
4722                    diag::err_uninitialized_member_in_ctor)
4723       << (int)Constructor->isImplicit()
4724       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4725       << 1 << Field->getDeclName();
4726       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4727       return true;
4728     }
4729   }
4730
4731   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4732     // ARC and Weak:
4733     //   Default-initialize Objective-C pointers to NULL.
4734     CXXMemberInit
4735       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4736                                                  Loc, Loc,
4737                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4738                                                  Loc);
4739     return false;
4740   }
4741
4742   // Nothing to initialize.
4743   CXXMemberInit = nullptr;
4744   return false;
4745 }
4746
4747 namespace {
4748 struct BaseAndFieldInfo {
4749   Sema &S;
4750   CXXConstructorDecl *Ctor;
4751   bool AnyErrorsInInits;
4752   ImplicitInitializerKind IIK;
4753   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4754   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4755   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4756
4757   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4758     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4759     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4760     if (Ctor->getInheritedConstructor())
4761       IIK = IIK_Inherit;
4762     else if (Generated && Ctor->isCopyConstructor())
4763       IIK = IIK_Copy;
4764     else if (Generated && Ctor->isMoveConstructor())
4765       IIK = IIK_Move;
4766     else
4767       IIK = IIK_Default;
4768   }
4769
4770   bool isImplicitCopyOrMove() const {
4771     switch (IIK) {
4772     case IIK_Copy:
4773     case IIK_Move:
4774       return true;
4775
4776     case IIK_Default:
4777     case IIK_Inherit:
4778       return false;
4779     }
4780
4781     llvm_unreachable("Invalid ImplicitInitializerKind!");
4782   }
4783
4784   bool addFieldInitializer(CXXCtorInitializer *Init) {
4785     AllToInit.push_back(Init);
4786
4787     // Check whether this initializer makes the field "used".
4788     if (Init->getInit()->HasSideEffects(S.Context))
4789       S.UnusedPrivateFields.remove(Init->getAnyMember());
4790
4791     return false;
4792   }
4793
4794   bool isInactiveUnionMember(FieldDecl *Field) {
4795     RecordDecl *Record = Field->getParent();
4796     if (!Record->isUnion())
4797       return false;
4798
4799     if (FieldDecl *Active =
4800             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4801       return Active != Field->getCanonicalDecl();
4802
4803     // In an implicit copy or move constructor, ignore any in-class initializer.
4804     if (isImplicitCopyOrMove())
4805       return true;
4806
4807     // If there's no explicit initialization, the field is active only if it
4808     // has an in-class initializer...
4809     if (Field->hasInClassInitializer())
4810       return false;
4811     // ... or it's an anonymous struct or union whose class has an in-class
4812     // initializer.
4813     if (!Field->isAnonymousStructOrUnion())
4814       return true;
4815     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4816     return !FieldRD->hasInClassInitializer();
4817   }
4818
4819   /// Determine whether the given field is, or is within, a union member
4820   /// that is inactive (because there was an initializer given for a different
4821   /// member of the union, or because the union was not initialized at all).
4822   bool isWithinInactiveUnionMember(FieldDecl *Field,
4823                                    IndirectFieldDecl *Indirect) {
4824     if (!Indirect)
4825       return isInactiveUnionMember(Field);
4826
4827     for (auto *C : Indirect->chain()) {
4828       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4829       if (Field && isInactiveUnionMember(Field))
4830         return true;
4831     }
4832     return false;
4833   }
4834 };
4835 }
4836
4837 /// Determine whether the given type is an incomplete or zero-lenfgth
4838 /// array type.
4839 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4840   if (T->isIncompleteArrayType())
4841     return true;
4842
4843   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4844     if (!ArrayT->getSize())
4845       return true;
4846
4847     T = ArrayT->getElementType();
4848   }
4849
4850   return false;
4851 }
4852
4853 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4854                                     FieldDecl *Field,
4855                                     IndirectFieldDecl *Indirect = nullptr) {
4856   if (Field->isInvalidDecl())
4857     return false;
4858
4859   // Overwhelmingly common case: we have a direct initializer for this field.
4860   if (CXXCtorInitializer *Init =
4861           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4862     return Info.addFieldInitializer(Init);
4863
4864   // C++11 [class.base.init]p8:
4865   //   if the entity is a non-static data member that has a
4866   //   brace-or-equal-initializer and either
4867   //   -- the constructor's class is a union and no other variant member of that
4868   //      union is designated by a mem-initializer-id or
4869   //   -- the constructor's class is not a union, and, if the entity is a member
4870   //      of an anonymous union, no other member of that union is designated by
4871   //      a mem-initializer-id,
4872   //   the entity is initialized as specified in [dcl.init].
4873   //
4874   // We also apply the same rules to handle anonymous structs within anonymous
4875   // unions.
4876   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4877     return false;
4878
4879   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4880     ExprResult DIE =
4881         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4882     if (DIE.isInvalid())
4883       return true;
4884
4885     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4886     SemaRef.checkInitializerLifetime(Entity, DIE.get());
4887
4888     CXXCtorInitializer *Init;
4889     if (Indirect)
4890       Init = new (SemaRef.Context)
4891           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4892                              SourceLocation(), DIE.get(), SourceLocation());
4893     else
4894       Init = new (SemaRef.Context)
4895           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4896                              SourceLocation(), DIE.get(), SourceLocation());
4897     return Info.addFieldInitializer(Init);
4898   }
4899
4900   // Don't initialize incomplete or zero-length arrays.
4901   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4902     return false;
4903
4904   // Don't try to build an implicit initializer if there were semantic
4905   // errors in any of the initializers (and therefore we might be
4906   // missing some that the user actually wrote).
4907   if (Info.AnyErrorsInInits)
4908     return false;
4909
4910   CXXCtorInitializer *Init = nullptr;
4911   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4912                                      Indirect, Init))
4913     return true;
4914
4915   if (!Init)
4916     return false;
4917
4918   return Info.addFieldInitializer(Init);
4919 }
4920
4921 bool
4922 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4923                                CXXCtorInitializer *Initializer) {
4924   assert(Initializer->isDelegatingInitializer());
4925   Constructor->setNumCtorInitializers(1);
4926   CXXCtorInitializer **initializer =
4927     new (Context) CXXCtorInitializer*[1];
4928   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4929   Constructor->setCtorInitializers(initializer);
4930
4931   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4932     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4933     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4934   }
4935
4936   DelegatingCtorDecls.push_back(Constructor);
4937
4938   DiagnoseUninitializedFields(*this, Constructor);
4939
4940   return false;
4941 }
4942
4943 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4944                                ArrayRef<CXXCtorInitializer *> Initializers) {
4945   if (Constructor->isDependentContext()) {
4946     // Just store the initializers as written, they will be checked during
4947     // instantiation.
4948     if (!Initializers.empty()) {
4949       Constructor->setNumCtorInitializers(Initializers.size());
4950       CXXCtorInitializer **baseOrMemberInitializers =
4951         new (Context) CXXCtorInitializer*[Initializers.size()];
4952       memcpy(baseOrMemberInitializers, Initializers.data(),
4953              Initializers.size() * sizeof(CXXCtorInitializer*));
4954       Constructor->setCtorInitializers(baseOrMemberInitializers);
4955     }
4956
4957     // Let template instantiation know whether we had errors.
4958     if (AnyErrors)
4959       Constructor->setInvalidDecl();
4960
4961     return false;
4962   }
4963
4964   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4965
4966   // We need to build the initializer AST according to order of construction
4967   // and not what user specified in the Initializers list.
4968   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4969   if (!ClassDecl)
4970     return true;
4971
4972   bool HadError = false;
4973
4974   for (unsigned i = 0; i < Initializers.size(); i++) {
4975     CXXCtorInitializer *Member = Initializers[i];
4976
4977     if (Member->isBaseInitializer())
4978       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4979     else {
4980       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4981
4982       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4983         for (auto *C : F->chain()) {
4984           FieldDecl *FD = dyn_cast<FieldDecl>(C);
4985           if (FD && FD->getParent()->isUnion())
4986             Info.ActiveUnionMember.insert(std::make_pair(
4987                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4988         }
4989       } else if (FieldDecl *FD = Member->getMember()) {
4990         if (FD->getParent()->isUnion())
4991           Info.ActiveUnionMember.insert(std::make_pair(
4992               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4993       }
4994     }
4995   }
4996
4997   // Keep track of the direct virtual bases.
4998   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4999   for (auto &I : ClassDecl->bases()) {
5000     if (I.isVirtual())
5001       DirectVBases.insert(&I);
5002   }
5003
5004   // Push virtual bases before others.
5005   for (auto &VBase : ClassDecl->vbases()) {
5006     if (CXXCtorInitializer *Value
5007         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5008       // [class.base.init]p7, per DR257:
5009       //   A mem-initializer where the mem-initializer-id names a virtual base
5010       //   class is ignored during execution of a constructor of any class that
5011       //   is not the most derived class.
5012       if (ClassDecl->isAbstract()) {
5013         // FIXME: Provide a fixit to remove the base specifier. This requires
5014         // tracking the location of the associated comma for a base specifier.
5015         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5016           << VBase.getType() << ClassDecl;
5017         DiagnoseAbstractType(ClassDecl);
5018       }
5019
5020       Info.AllToInit.push_back(Value);
5021     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5022       // [class.base.init]p8, per DR257:
5023       //   If a given [...] base class is not named by a mem-initializer-id
5024       //   [...] and the entity is not a virtual base class of an abstract
5025       //   class, then [...] the entity is default-initialized.
5026       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5027       CXXCtorInitializer *CXXBaseInit;
5028       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5029                                        &VBase, IsInheritedVirtualBase,
5030                                        CXXBaseInit)) {
5031         HadError = true;
5032         continue;
5033       }
5034
5035       Info.AllToInit.push_back(CXXBaseInit);
5036     }
5037   }
5038
5039   // Non-virtual bases.
5040   for (auto &Base : ClassDecl->bases()) {
5041     // Virtuals are in the virtual base list and already constructed.
5042     if (Base.isVirtual())
5043       continue;
5044
5045     if (CXXCtorInitializer *Value
5046           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5047       Info.AllToInit.push_back(Value);
5048     } else if (!AnyErrors) {
5049       CXXCtorInitializer *CXXBaseInit;
5050       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5051                                        &Base, /*IsInheritedVirtualBase=*/false,
5052                                        CXXBaseInit)) {
5053         HadError = true;
5054         continue;
5055       }
5056
5057       Info.AllToInit.push_back(CXXBaseInit);
5058     }
5059   }
5060
5061   // Fields.
5062   for (auto *Mem : ClassDecl->decls()) {
5063     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5064       // C++ [class.bit]p2:
5065       //   A declaration for a bit-field that omits the identifier declares an
5066       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
5067       //   initialized.
5068       if (F->isUnnamedBitfield())
5069         continue;
5070
5071       // If we're not generating the implicit copy/move constructor, then we'll
5072       // handle anonymous struct/union fields based on their individual
5073       // indirect fields.
5074       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5075         continue;
5076
5077       if (CollectFieldInitializer(*this, Info, F))
5078         HadError = true;
5079       continue;
5080     }
5081
5082     // Beyond this point, we only consider default initialization.
5083     if (Info.isImplicitCopyOrMove())
5084       continue;
5085
5086     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5087       if (F->getType()->isIncompleteArrayType()) {
5088         assert(ClassDecl->hasFlexibleArrayMember() &&
5089                "Incomplete array type is not valid");
5090         continue;
5091       }
5092
5093       // Initialize each field of an anonymous struct individually.
5094       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5095         HadError = true;
5096
5097       continue;
5098     }
5099   }
5100
5101   unsigned NumInitializers = Info.AllToInit.size();
5102   if (NumInitializers > 0) {
5103     Constructor->setNumCtorInitializers(NumInitializers);
5104     CXXCtorInitializer **baseOrMemberInitializers =
5105       new (Context) CXXCtorInitializer*[NumInitializers];
5106     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5107            NumInitializers * sizeof(CXXCtorInitializer*));
5108     Constructor->setCtorInitializers(baseOrMemberInitializers);
5109
5110     // Constructors implicitly reference the base and member
5111     // destructors.
5112     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5113                                            Constructor->getParent());
5114   }
5115
5116   return HadError;
5117 }
5118
5119 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5120   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5121     const RecordDecl *RD = RT->getDecl();
5122     if (RD->isAnonymousStructOrUnion()) {
5123       for (auto *Field : RD->fields())
5124         PopulateKeysForFields(Field, IdealInits);
5125       return;
5126     }
5127   }
5128   IdealInits.push_back(Field->getCanonicalDecl());
5129 }
5130
5131 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5132   return Context.getCanonicalType(BaseType).getTypePtr();
5133 }
5134
5135 static const void *GetKeyForMember(ASTContext &Context,
5136                                    CXXCtorInitializer *Member) {
5137   if (!Member->isAnyMemberInitializer())
5138     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5139
5140   return Member->getAnyMember()->getCanonicalDecl();
5141 }
5142
5143 static void DiagnoseBaseOrMemInitializerOrder(
5144     Sema &SemaRef, const CXXConstructorDecl *Constructor,
5145     ArrayRef<CXXCtorInitializer *> Inits) {
5146   if (Constructor->getDeclContext()->isDependentContext())
5147     return;
5148
5149   // Don't check initializers order unless the warning is enabled at the
5150   // location of at least one initializer.
5151   bool ShouldCheckOrder = false;
5152   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5153     CXXCtorInitializer *Init = Inits[InitIndex];
5154     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5155                                  Init->getSourceLocation())) {
5156       ShouldCheckOrder = true;
5157       break;
5158     }
5159   }
5160   if (!ShouldCheckOrder)
5161     return;
5162
5163   // Build the list of bases and members in the order that they'll
5164   // actually be initialized.  The explicit initializers should be in
5165   // this same order but may be missing things.
5166   SmallVector<const void*, 32> IdealInitKeys;
5167
5168   const CXXRecordDecl *ClassDecl = Constructor->getParent();
5169
5170   // 1. Virtual bases.
5171   for (const auto &VBase : ClassDecl->vbases())
5172     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5173
5174   // 2. Non-virtual bases.
5175   for (const auto &Base : ClassDecl->bases()) {
5176     if (Base.isVirtual())
5177       continue;
5178     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5179   }
5180
5181   // 3. Direct fields.
5182   for (auto *Field : ClassDecl->fields()) {
5183     if (Field->isUnnamedBitfield())
5184       continue;
5185
5186     PopulateKeysForFields(Field, IdealInitKeys);
5187   }
5188
5189   unsigned NumIdealInits = IdealInitKeys.size();
5190   unsigned IdealIndex = 0;
5191
5192   CXXCtorInitializer *PrevInit = nullptr;
5193   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5194     CXXCtorInitializer *Init = Inits[InitIndex];
5195     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
5196
5197     // Scan forward to try to find this initializer in the idealized
5198     // initializers list.
5199     for (; IdealIndex != NumIdealInits; ++IdealIndex)
5200       if (InitKey == IdealInitKeys[IdealIndex])
5201         break;
5202
5203     // If we didn't find this initializer, it must be because we
5204     // scanned past it on a previous iteration.  That can only
5205     // happen if we're out of order;  emit a warning.
5206     if (IdealIndex == NumIdealInits && PrevInit) {
5207       Sema::SemaDiagnosticBuilder D =
5208         SemaRef.Diag(PrevInit->getSourceLocation(),
5209                      diag::warn_initializer_out_of_order);
5210
5211       if (PrevInit->isAnyMemberInitializer())
5212         D << 0 << PrevInit->getAnyMember()->getDeclName();
5213       else
5214         D << 1 << PrevInit->getTypeSourceInfo()->getType();
5215
5216       if (Init->isAnyMemberInitializer())
5217         D << 0 << Init->getAnyMember()->getDeclName();
5218       else
5219         D << 1 << Init->getTypeSourceInfo()->getType();
5220
5221       // Move back to the initializer's location in the ideal list.
5222       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5223         if (InitKey == IdealInitKeys[IdealIndex])
5224           break;
5225
5226       assert(IdealIndex < NumIdealInits &&
5227              "initializer not found in initializer list");
5228     }
5229
5230     PrevInit = Init;
5231   }
5232 }
5233
5234 namespace {
5235 bool CheckRedundantInit(Sema &S,
5236                         CXXCtorInitializer *Init,
5237                         CXXCtorInitializer *&PrevInit) {
5238   if (!PrevInit) {
5239     PrevInit = Init;
5240     return false;
5241   }
5242
5243   if (FieldDecl *Field = Init->getAnyMember())
5244     S.Diag(Init->getSourceLocation(),
5245            diag::err_multiple_mem_initialization)
5246       << Field->getDeclName()
5247       << Init->getSourceRange();
5248   else {
5249     const Type *BaseClass = Init->getBaseClass();
5250     assert(BaseClass && "neither field nor base");
5251     S.Diag(Init->getSourceLocation(),
5252            diag::err_multiple_base_initialization)
5253       << QualType(BaseClass, 0)
5254       << Init->getSourceRange();
5255   }
5256   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5257     << 0 << PrevInit->getSourceRange();
5258
5259   return true;
5260 }
5261
5262 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5263 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5264
5265 bool CheckRedundantUnionInit(Sema &S,
5266                              CXXCtorInitializer *Init,
5267                              RedundantUnionMap &Unions) {
5268   FieldDecl *Field = Init->getAnyMember();
5269   RecordDecl *Parent = Field->getParent();
5270   NamedDecl *Child = Field;
5271
5272   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5273     if (Parent->isUnion()) {
5274       UnionEntry &En = Unions[Parent];
5275       if (En.first && En.first != Child) {
5276         S.Diag(Init->getSourceLocation(),
5277                diag::err_multiple_mem_union_initialization)
5278           << Field->getDeclName()
5279           << Init->getSourceRange();
5280         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5281           << 0 << En.second->getSourceRange();
5282         return true;
5283       }
5284       if (!En.first) {
5285         En.first = Child;
5286         En.second = Init;
5287       }
5288       if (!Parent->isAnonymousStructOrUnion())
5289         return false;
5290     }
5291
5292     Child = Parent;
5293     Parent = cast<RecordDecl>(Parent->getDeclContext());
5294   }
5295
5296   return false;
5297 }
5298 }
5299
5300 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5301 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5302                                 SourceLocation ColonLoc,
5303                                 ArrayRef<CXXCtorInitializer*> MemInits,
5304                                 bool AnyErrors) {
5305   if (!ConstructorDecl)
5306     return;
5307
5308   AdjustDeclIfTemplate(ConstructorDecl);
5309
5310   CXXConstructorDecl *Constructor
5311     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5312
5313   if (!Constructor) {
5314     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5315     return;
5316   }
5317
5318   // Mapping for the duplicate initializers check.
5319   // For member initializers, this is keyed with a FieldDecl*.
5320   // For base initializers, this is keyed with a Type*.
5321   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5322
5323   // Mapping for the inconsistent anonymous-union initializers check.
5324   RedundantUnionMap MemberUnions;
5325
5326   bool HadError = false;
5327   for (unsigned i = 0; i < MemInits.size(); i++) {
5328     CXXCtorInitializer *Init = MemInits[i];
5329
5330     // Set the source order index.
5331     Init->setSourceOrder(i);
5332
5333     if (Init->isAnyMemberInitializer()) {
5334       const void *Key = GetKeyForMember(Context, Init);
5335       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5336           CheckRedundantUnionInit(*this, Init, MemberUnions))
5337         HadError = true;
5338     } else if (Init->isBaseInitializer()) {
5339       const void *Key = GetKeyForMember(Context, Init);
5340       if (CheckRedundantInit(*this, Init, Members[Key]))
5341         HadError = true;
5342     } else {
5343       assert(Init->isDelegatingInitializer());
5344       // This must be the only initializer
5345       if (MemInits.size() != 1) {
5346         Diag(Init->getSourceLocation(),
5347              diag::err_delegating_initializer_alone)
5348           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5349         // We will treat this as being the only initializer.
5350       }
5351       SetDelegatingInitializer(Constructor, MemInits[i]);
5352       // Return immediately as the initializer is set.
5353       return;
5354     }
5355   }
5356
5357   if (HadError)
5358     return;
5359
5360   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5361
5362   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5363
5364   DiagnoseUninitializedFields(*this, Constructor);
5365 }
5366
5367 void
5368 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5369                                              CXXRecordDecl *ClassDecl) {
5370   // Ignore dependent contexts. Also ignore unions, since their members never
5371   // have destructors implicitly called.
5372   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5373     return;
5374
5375   // FIXME: all the access-control diagnostics are positioned on the
5376   // field/base declaration.  That's probably good; that said, the
5377   // user might reasonably want to know why the destructor is being
5378   // emitted, and we currently don't say.
5379
5380   // Non-static data members.
5381   for (auto *Field : ClassDecl->fields()) {
5382     if (Field->isInvalidDecl())
5383       continue;
5384
5385     // Don't destroy incomplete or zero-length arrays.
5386     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5387       continue;
5388
5389     QualType FieldType = Context.getBaseElementType(Field->getType());
5390
5391     const RecordType* RT = FieldType->getAs<RecordType>();
5392     if (!RT)
5393       continue;
5394
5395     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5396     if (FieldClassDecl->isInvalidDecl())
5397       continue;
5398     if (FieldClassDecl->hasIrrelevantDestructor())
5399       continue;
5400     // The destructor for an implicit anonymous union member is never invoked.
5401     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5402       continue;
5403
5404     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5405     assert(Dtor && "No dtor found for FieldClassDecl!");
5406     CheckDestructorAccess(Field->getLocation(), Dtor,
5407                           PDiag(diag::err_access_dtor_field)
5408                             << Field->getDeclName()
5409                             << FieldType);
5410
5411     MarkFunctionReferenced(Location, Dtor);
5412     DiagnoseUseOfDecl(Dtor, Location);
5413   }
5414
5415   // We only potentially invoke the destructors of potentially constructed
5416   // subobjects.
5417   bool VisitVirtualBases = !ClassDecl->isAbstract();
5418
5419   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5420
5421   // Bases.
5422   for (const auto &Base : ClassDecl->bases()) {
5423     // Bases are always records in a well-formed non-dependent class.
5424     const RecordType *RT = Base.getType()->getAs<RecordType>();
5425
5426     // Remember direct virtual bases.
5427     if (Base.isVirtual()) {
5428       if (!VisitVirtualBases)
5429         continue;
5430       DirectVirtualBases.insert(RT);
5431     }
5432
5433     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5434     // If our base class is invalid, we probably can't get its dtor anyway.
5435     if (BaseClassDecl->isInvalidDecl())
5436       continue;
5437     if (BaseClassDecl->hasIrrelevantDestructor())
5438       continue;
5439
5440     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5441     assert(Dtor && "No dtor found for BaseClassDecl!");
5442
5443     // FIXME: caret should be on the start of the class name
5444     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5445                           PDiag(diag::err_access_dtor_base)
5446                               << Base.getType() << Base.getSourceRange(),
5447                           Context.getTypeDeclType(ClassDecl));
5448
5449     MarkFunctionReferenced(Location, Dtor);
5450     DiagnoseUseOfDecl(Dtor, Location);
5451   }
5452
5453   if (!VisitVirtualBases)
5454     return;
5455
5456   // Virtual bases.
5457   for (const auto &VBase : ClassDecl->vbases()) {
5458     // Bases are always records in a well-formed non-dependent class.
5459     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5460
5461     // Ignore direct virtual bases.
5462     if (DirectVirtualBases.count(RT))
5463       continue;
5464
5465     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5466     // If our base class is invalid, we probably can't get its dtor anyway.
5467     if (BaseClassDecl->isInvalidDecl())
5468       continue;
5469     if (BaseClassDecl->hasIrrelevantDestructor())
5470       continue;
5471
5472     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5473     assert(Dtor && "No dtor found for BaseClassDecl!");
5474     if (CheckDestructorAccess(
5475             ClassDecl->getLocation(), Dtor,
5476             PDiag(diag::err_access_dtor_vbase)
5477                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5478             Context.getTypeDeclType(ClassDecl)) ==
5479         AR_accessible) {
5480       CheckDerivedToBaseConversion(
5481           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5482           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5483           SourceRange(), DeclarationName(), nullptr);
5484     }
5485
5486     MarkFunctionReferenced(Location, Dtor);
5487     DiagnoseUseOfDecl(Dtor, Location);
5488   }
5489 }
5490
5491 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5492   if (!CDtorDecl)
5493     return;
5494
5495   if (CXXConstructorDecl *Constructor
5496       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5497     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5498     DiagnoseUninitializedFields(*this, Constructor);
5499   }
5500 }
5501
5502 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5503   if (!getLangOpts().CPlusPlus)
5504     return false;
5505
5506   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5507   if (!RD)
5508     return false;
5509
5510   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5511   // class template specialization here, but doing so breaks a lot of code.
5512
5513   // We can't answer whether something is abstract until it has a
5514   // definition. If it's currently being defined, we'll walk back
5515   // over all the declarations when we have a full definition.
5516   const CXXRecordDecl *Def = RD->getDefinition();
5517   if (!Def || Def->isBeingDefined())
5518     return false;
5519
5520   return RD->isAbstract();
5521 }
5522
5523 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5524                                   TypeDiagnoser &Diagnoser) {
5525   if (!isAbstractType(Loc, T))
5526     return false;
5527
5528   T = Context.getBaseElementType(T);
5529   Diagnoser.diagnose(*this, Loc, T);
5530   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5531   return true;
5532 }
5533
5534 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5535   // Check if we've already emitted the list of pure virtual functions
5536   // for this class.
5537   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5538     return;
5539
5540   // If the diagnostic is suppressed, don't emit the notes. We're only
5541   // going to emit them once, so try to attach them to a diagnostic we're
5542   // actually going to show.
5543   if (Diags.isLastDiagnosticIgnored())
5544     return;
5545
5546   CXXFinalOverriderMap FinalOverriders;
5547   RD->getFinalOverriders(FinalOverriders);
5548
5549   // Keep a set of seen pure methods so we won't diagnose the same method
5550   // more than once.
5551   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5552
5553   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5554                                    MEnd = FinalOverriders.end();
5555        M != MEnd;
5556        ++M) {
5557     for (OverridingMethods::iterator SO = M->second.begin(),
5558                                   SOEnd = M->second.end();
5559          SO != SOEnd; ++SO) {
5560       // C++ [class.abstract]p4:
5561       //   A class is abstract if it contains or inherits at least one
5562       //   pure virtual function for which the final overrider is pure
5563       //   virtual.
5564
5565       //
5566       if (SO->second.size() != 1)
5567         continue;
5568
5569       if (!SO->second.front().Method->isPure())
5570         continue;
5571
5572       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5573         continue;
5574
5575       Diag(SO->second.front().Method->getLocation(),
5576            diag::note_pure_virtual_function)
5577         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5578     }
5579   }
5580
5581   if (!PureVirtualClassDiagSet)
5582     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5583   PureVirtualClassDiagSet->insert(RD);
5584 }
5585
5586 namespace {
5587 struct AbstractUsageInfo {
5588   Sema &S;
5589   CXXRecordDecl *Record;
5590   CanQualType AbstractType;
5591   bool Invalid;
5592
5593   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5594     : S(S), Record(Record),
5595       AbstractType(S.Context.getCanonicalType(
5596                    S.Context.getTypeDeclType(Record))),
5597       Invalid(false) {}
5598
5599   void DiagnoseAbstractType() {
5600     if (Invalid) return;
5601     S.DiagnoseAbstractType(Record);
5602     Invalid = true;
5603   }
5604
5605   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5606 };
5607
5608 struct CheckAbstractUsage {
5609   AbstractUsageInfo &Info;
5610   const NamedDecl *Ctx;
5611
5612   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5613     : Info(Info), Ctx(Ctx) {}
5614
5615   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5616     switch (TL.getTypeLocClass()) {
5617 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5618 #define TYPELOC(CLASS, PARENT) \
5619     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5620 #include "clang/AST/TypeLocNodes.def"
5621     }
5622   }
5623
5624   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5625     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5626     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5627       if (!TL.getParam(I))
5628         continue;
5629
5630       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5631       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5632     }
5633   }
5634
5635   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5636     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5637   }
5638
5639   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5640     // Visit the type parameters from a permissive context.
5641     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5642       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5643       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5644         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5645           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5646       // TODO: other template argument types?
5647     }
5648   }
5649
5650   // Visit pointee types from a permissive context.
5651 #define CheckPolymorphic(Type) \
5652   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5653     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5654   }
5655   CheckPolymorphic(PointerTypeLoc)
5656   CheckPolymorphic(ReferenceTypeLoc)
5657   CheckPolymorphic(MemberPointerTypeLoc)
5658   CheckPolymorphic(BlockPointerTypeLoc)
5659   CheckPolymorphic(AtomicTypeLoc)
5660
5661   /// Handle all the types we haven't given a more specific
5662   /// implementation for above.
5663   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5664     // Every other kind of type that we haven't called out already
5665     // that has an inner type is either (1) sugar or (2) contains that
5666     // inner type in some way as a subobject.
5667     if (TypeLoc Next = TL.getNextTypeLoc())
5668       return Visit(Next, Sel);
5669
5670     // If there's no inner type and we're in a permissive context,
5671     // don't diagnose.
5672     if (Sel == Sema::AbstractNone) return;
5673
5674     // Check whether the type matches the abstract type.
5675     QualType T = TL.getType();
5676     if (T->isArrayType()) {
5677       Sel = Sema::AbstractArrayType;
5678       T = Info.S.Context.getBaseElementType(T);
5679     }
5680     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5681     if (CT != Info.AbstractType) return;
5682
5683     // It matched; do some magic.
5684     if (Sel == Sema::AbstractArrayType) {
5685       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5686         << T << TL.getSourceRange();
5687     } else {
5688       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5689         << Sel << T << TL.getSourceRange();
5690     }
5691     Info.DiagnoseAbstractType();
5692   }
5693 };
5694
5695 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5696                                   Sema::AbstractDiagSelID Sel) {
5697   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5698 }
5699
5700 }
5701
5702 /// Check for invalid uses of an abstract type in a method declaration.
5703 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5704                                     CXXMethodDecl *MD) {
5705   // No need to do the check on definitions, which require that
5706   // the return/param types be complete.
5707   if (MD->doesThisDeclarationHaveABody())
5708     return;
5709
5710   // For safety's sake, just ignore it if we don't have type source
5711   // information.  This should never happen for non-implicit methods,
5712   // but...
5713   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5714     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5715 }
5716
5717 /// Check for invalid uses of an abstract type within a class definition.
5718 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5719                                     CXXRecordDecl *RD) {
5720   for (auto *D : RD->decls()) {
5721     if (D->isImplicit()) continue;
5722
5723     // Methods and method templates.
5724     if (isa<CXXMethodDecl>(D)) {
5725       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5726     } else if (isa<FunctionTemplateDecl>(D)) {
5727       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5728       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5729
5730     // Fields and static variables.
5731     } else if (isa<FieldDecl>(D)) {
5732       FieldDecl *FD = cast<FieldDecl>(D);
5733       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5734         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5735     } else if (isa<VarDecl>(D)) {
5736       VarDecl *VD = cast<VarDecl>(D);
5737       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5738         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5739
5740     // Nested classes and class templates.
5741     } else if (isa<CXXRecordDecl>(D)) {
5742       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5743     } else if (isa<ClassTemplateDecl>(D)) {
5744       CheckAbstractClassUsage(Info,
5745                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5746     }
5747   }
5748 }
5749
5750 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5751   Attr *ClassAttr = getDLLAttr(Class);
5752   if (!ClassAttr)
5753     return;
5754
5755   assert(ClassAttr->getKind() == attr::DLLExport);
5756
5757   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5758
5759   if (TSK == TSK_ExplicitInstantiationDeclaration)
5760     // Don't go any further if this is just an explicit instantiation
5761     // declaration.
5762     return;
5763
5764   if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
5765     S.MarkVTableUsed(Class->getLocation(), Class, true);
5766
5767   for (Decl *Member : Class->decls()) {
5768     // Defined static variables that are members of an exported base
5769     // class must be marked export too.
5770     auto *VD = dyn_cast<VarDecl>(Member);
5771     if (VD && Member->getAttr<DLLExportAttr>() &&
5772         VD->getStorageClass() == SC_Static &&
5773         TSK == TSK_ImplicitInstantiation)
5774       S.MarkVariableReferenced(VD->getLocation(), VD);
5775
5776     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5777     if (!MD)
5778       continue;
5779
5780     if (Member->getAttr<DLLExportAttr>()) {
5781       if (MD->isUserProvided()) {
5782         // Instantiate non-default class member functions ...
5783
5784         // .. except for certain kinds of template specializations.
5785         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5786           continue;
5787
5788         S.MarkFunctionReferenced(Class->getLocation(), MD);
5789
5790         // The function will be passed to the consumer when its definition is
5791         // encountered.
5792       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5793                  MD->isCopyAssignmentOperator() ||
5794                  MD->isMoveAssignmentOperator()) {
5795         // Synthesize and instantiate non-trivial implicit methods, explicitly
5796         // defaulted methods, and the copy and move assignment operators. The
5797         // latter are exported even if they are trivial, because the address of
5798         // an operator can be taken and should compare equal across libraries.
5799         DiagnosticErrorTrap Trap(S.Diags);
5800         S.MarkFunctionReferenced(Class->getLocation(), MD);
5801         if (Trap.hasErrorOccurred()) {
5802           S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5803               << Class << !S.getLangOpts().CPlusPlus11;
5804           break;
5805         }
5806
5807         // There is no later point when we will see the definition of this
5808         // function, so pass it to the consumer now.
5809         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5810       }
5811     }
5812   }
5813 }
5814
5815 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5816                                                         CXXRecordDecl *Class) {
5817   // Only the MS ABI has default constructor closures, so we don't need to do
5818   // this semantic checking anywhere else.
5819   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5820     return;
5821
5822   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5823   for (Decl *Member : Class->decls()) {
5824     // Look for exported default constructors.
5825     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5826     if (!CD || !CD->isDefaultConstructor())
5827       continue;
5828     auto *Attr = CD->getAttr<DLLExportAttr>();
5829     if (!Attr)
5830       continue;
5831
5832     // If the class is non-dependent, mark the default arguments as ODR-used so
5833     // that we can properly codegen the constructor closure.
5834     if (!Class->isDependentContext()) {
5835       for (ParmVarDecl *PD : CD->parameters()) {
5836         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5837         S.DiscardCleanupsInEvaluationContext();
5838       }
5839     }
5840
5841     if (LastExportedDefaultCtor) {
5842       S.Diag(LastExportedDefaultCtor->getLocation(),
5843              diag::err_attribute_dll_ambiguous_default_ctor)
5844           << Class;
5845       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5846           << CD->getDeclName();
5847       return;
5848     }
5849     LastExportedDefaultCtor = CD;
5850   }
5851 }
5852
5853 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
5854   // Mark any compiler-generated routines with the implicit code_seg attribute.
5855   for (auto *Method : Class->methods()) {
5856     if (Method->isUserProvided())
5857       continue;
5858     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
5859       Method->addAttr(A);
5860   }
5861 }
5862
5863 /// Check class-level dllimport/dllexport attribute.
5864 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
5865   Attr *ClassAttr = getDLLAttr(Class);
5866
5867   // MSVC inherits DLL attributes to partial class template specializations.
5868   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5869     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5870       if (Attr *TemplateAttr =
5871               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5872         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5873         A->setInherited(true);
5874         ClassAttr = A;
5875       }
5876     }
5877   }
5878
5879   if (!ClassAttr)
5880     return;
5881
5882   if (!Class->isExternallyVisible()) {
5883     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5884         << Class << ClassAttr;
5885     return;
5886   }
5887
5888   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5889       !ClassAttr->isInherited()) {
5890     // Diagnose dll attributes on members of class with dll attribute.
5891     for (Decl *Member : Class->decls()) {
5892       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5893         continue;
5894       InheritableAttr *MemberAttr = getDLLAttr(Member);
5895       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5896         continue;
5897
5898       Diag(MemberAttr->getLocation(),
5899              diag::err_attribute_dll_member_of_dll_class)
5900           << MemberAttr << ClassAttr;
5901       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5902       Member->setInvalidDecl();
5903     }
5904   }
5905
5906   if (Class->getDescribedClassTemplate())
5907     // Don't inherit dll attribute until the template is instantiated.
5908     return;
5909
5910   // The class is either imported or exported.
5911   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5912
5913   // Check if this was a dllimport attribute propagated from a derived class to
5914   // a base class template specialization. We don't apply these attributes to
5915   // static data members.
5916   const bool PropagatedImport =
5917       !ClassExported &&
5918       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
5919
5920   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5921
5922   // Ignore explicit dllexport on explicit class template instantiation
5923   // declarations, except in MinGW mode.
5924   if (ClassExported && !ClassAttr->isInherited() &&
5925       TSK == TSK_ExplicitInstantiationDeclaration &&
5926       !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
5927     Class->dropAttr<DLLExportAttr>();
5928     return;
5929   }
5930
5931   // Force declaration of implicit members so they can inherit the attribute.
5932   ForceDeclarationOfImplicitMembers(Class);
5933
5934   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5935   // seem to be true in practice?
5936
5937   for (Decl *Member : Class->decls()) {
5938     VarDecl *VD = dyn_cast<VarDecl>(Member);
5939     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5940
5941     // Only methods and static fields inherit the attributes.
5942     if (!VD && !MD)
5943       continue;
5944
5945     if (MD) {
5946       // Don't process deleted methods.
5947       if (MD->isDeleted())
5948         continue;
5949
5950       if (MD->isInlined()) {
5951         // MinGW does not import or export inline methods. But do it for
5952         // template instantiations.
5953         if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5954             !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() &&
5955             TSK != TSK_ExplicitInstantiationDeclaration &&
5956             TSK != TSK_ExplicitInstantiationDefinition)
5957           continue;
5958
5959         // MSVC versions before 2015 don't export the move assignment operators
5960         // and move constructor, so don't attempt to import/export them if
5961         // we have a definition.
5962         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5963         if ((MD->isMoveAssignmentOperator() ||
5964              (Ctor && Ctor->isMoveConstructor())) &&
5965             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5966           continue;
5967
5968         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5969         // operator is exported anyway.
5970         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5971             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5972           continue;
5973       }
5974     }
5975
5976     // Don't apply dllimport attributes to static data members of class template
5977     // instantiations when the attribute is propagated from a derived class.
5978     if (VD && PropagatedImport)
5979       continue;
5980
5981     if (!cast<NamedDecl>(Member)->isExternallyVisible())
5982       continue;
5983
5984     if (!getDLLAttr(Member)) {
5985       InheritableAttr *NewAttr = nullptr;
5986
5987       // Do not export/import inline function when -fno-dllexport-inlines is
5988       // passed. But add attribute for later local static var check.
5989       if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
5990           TSK != TSK_ExplicitInstantiationDeclaration &&
5991           TSK != TSK_ExplicitInstantiationDefinition) {
5992         if (ClassExported) {
5993           NewAttr = ::new (getASTContext())
5994               DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
5995         } else {
5996           NewAttr = ::new (getASTContext())
5997               DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
5998         }
5999       } else {
6000         NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6001       }
6002
6003       NewAttr->setInherited(true);
6004       Member->addAttr(NewAttr);
6005
6006       if (MD) {
6007         // Propagate DLLAttr to friend re-declarations of MD that have already
6008         // been constructed.
6009         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6010              FD = FD->getPreviousDecl()) {
6011           if (FD->getFriendObjectKind() == Decl::FOK_None)
6012             continue;
6013           assert(!getDLLAttr(FD) &&
6014                  "friend re-decl should not already have a DLLAttr");
6015           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6016           NewAttr->setInherited(true);
6017           FD->addAttr(NewAttr);
6018         }
6019       }
6020     }
6021   }
6022
6023   if (ClassExported)
6024     DelayedDllExportClasses.push_back(Class);
6025 }
6026
6027 /// Perform propagation of DLL attributes from a derived class to a
6028 /// templated base class for MS compatibility.
6029 void Sema::propagateDLLAttrToBaseClassTemplate(
6030     CXXRecordDecl *Class, Attr *ClassAttr,
6031     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6032   if (getDLLAttr(
6033           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6034     // If the base class template has a DLL attribute, don't try to change it.
6035     return;
6036   }
6037
6038   auto TSK = BaseTemplateSpec->getSpecializationKind();
6039   if (!getDLLAttr(BaseTemplateSpec) &&
6040       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6041        TSK == TSK_ImplicitInstantiation)) {
6042     // The template hasn't been instantiated yet (or it has, but only as an
6043     // explicit instantiation declaration or implicit instantiation, which means
6044     // we haven't codegenned any members yet), so propagate the attribute.
6045     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6046     NewAttr->setInherited(true);
6047     BaseTemplateSpec->addAttr(NewAttr);
6048
6049     // If this was an import, mark that we propagated it from a derived class to
6050     // a base class template specialization.
6051     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6052       ImportAttr->setPropagatedToBaseTemplate();
6053
6054     // If the template is already instantiated, checkDLLAttributeRedeclaration()
6055     // needs to be run again to work see the new attribute. Otherwise this will
6056     // get run whenever the template is instantiated.
6057     if (TSK != TSK_Undeclared)
6058       checkClassLevelDLLAttribute(BaseTemplateSpec);
6059
6060     return;
6061   }
6062
6063   if (getDLLAttr(BaseTemplateSpec)) {
6064     // The template has already been specialized or instantiated with an
6065     // attribute, explicitly or through propagation. We should not try to change
6066     // it.
6067     return;
6068   }
6069
6070   // The template was previously instantiated or explicitly specialized without
6071   // a dll attribute, It's too late for us to add an attribute, so warn that
6072   // this is unsupported.
6073   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6074       << BaseTemplateSpec->isExplicitSpecialization();
6075   Diag(ClassAttr->getLocation(), diag::note_attribute);
6076   if (BaseTemplateSpec->isExplicitSpecialization()) {
6077     Diag(BaseTemplateSpec->getLocation(),
6078            diag::note_template_class_explicit_specialization_was_here)
6079         << BaseTemplateSpec;
6080   } else {
6081     Diag(BaseTemplateSpec->getPointOfInstantiation(),
6082            diag::note_template_class_instantiation_was_here)
6083         << BaseTemplateSpec;
6084   }
6085 }
6086
6087 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
6088                                         SourceLocation DefaultLoc) {
6089   switch (S.getSpecialMember(MD)) {
6090   case Sema::CXXDefaultConstructor:
6091     S.DefineImplicitDefaultConstructor(DefaultLoc,
6092                                        cast<CXXConstructorDecl>(MD));
6093     break;
6094   case Sema::CXXCopyConstructor:
6095     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
6096     break;
6097   case Sema::CXXCopyAssignment:
6098     S.DefineImplicitCopyAssignment(DefaultLoc, MD);
6099     break;
6100   case Sema::CXXDestructor:
6101     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
6102     break;
6103   case Sema::CXXMoveConstructor:
6104     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
6105     break;
6106   case Sema::CXXMoveAssignment:
6107     S.DefineImplicitMoveAssignment(DefaultLoc, MD);
6108     break;
6109   case Sema::CXXInvalid:
6110     llvm_unreachable("Invalid special member.");
6111   }
6112 }
6113
6114 /// Determine whether a type is permitted to be passed or returned in
6115 /// registers, per C++ [class.temporary]p3.
6116 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6117                                TargetInfo::CallingConvKind CCK) {
6118   if (D->isDependentType() || D->isInvalidDecl())
6119     return false;
6120
6121   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6122   // The PS4 platform ABI follows the behavior of Clang 3.2.
6123   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6124     return !D->hasNonTrivialDestructorForCall() &&
6125            !D->hasNonTrivialCopyConstructorForCall();
6126
6127   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6128     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6129     bool DtorIsTrivialForCall = false;
6130
6131     // If a class has at least one non-deleted, trivial copy constructor, it
6132     // is passed according to the C ABI. Otherwise, it is passed indirectly.
6133     //
6134     // Note: This permits classes with non-trivial copy or move ctors to be
6135     // passed in registers, so long as they *also* have a trivial copy ctor,
6136     // which is non-conforming.
6137     if (D->needsImplicitCopyConstructor()) {
6138       if (!D->defaultedCopyConstructorIsDeleted()) {
6139         if (D->hasTrivialCopyConstructor())
6140           CopyCtorIsTrivial = true;
6141         if (D->hasTrivialCopyConstructorForCall())
6142           CopyCtorIsTrivialForCall = true;
6143       }
6144     } else {
6145       for (const CXXConstructorDecl *CD : D->ctors()) {
6146         if (CD->isCopyConstructor() && !CD->isDeleted()) {
6147           if (CD->isTrivial())
6148             CopyCtorIsTrivial = true;
6149           if (CD->isTrivialForCall())
6150             CopyCtorIsTrivialForCall = true;
6151         }
6152       }
6153     }
6154
6155     if (D->needsImplicitDestructor()) {
6156       if (!D->defaultedDestructorIsDeleted() &&
6157           D->hasTrivialDestructorForCall())
6158         DtorIsTrivialForCall = true;
6159     } else if (const auto *DD = D->getDestructor()) {
6160       if (!DD->isDeleted() && DD->isTrivialForCall())
6161         DtorIsTrivialForCall = true;
6162     }
6163
6164     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6165     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6166       return true;
6167
6168     // If a class has a destructor, we'd really like to pass it indirectly
6169     // because it allows us to elide copies.  Unfortunately, MSVC makes that
6170     // impossible for small types, which it will pass in a single register or
6171     // stack slot. Most objects with dtors are large-ish, so handle that early.
6172     // We can't call out all large objects as being indirect because there are
6173     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6174     // how we pass large POD types.
6175
6176     // Note: This permits small classes with nontrivial destructors to be
6177     // passed in registers, which is non-conforming.
6178     bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6179     uint64_t TypeSize = isAArch64 ? 128 : 64;
6180
6181     if (CopyCtorIsTrivial &&
6182         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6183       return true;
6184     return false;
6185   }
6186
6187   // Per C++ [class.temporary]p3, the relevant condition is:
6188   //   each copy constructor, move constructor, and destructor of X is
6189   //   either trivial or deleted, and X has at least one non-deleted copy
6190   //   or move constructor
6191   bool HasNonDeletedCopyOrMove = false;
6192
6193   if (D->needsImplicitCopyConstructor() &&
6194       !D->defaultedCopyConstructorIsDeleted()) {
6195     if (!D->hasTrivialCopyConstructorForCall())
6196       return false;
6197     HasNonDeletedCopyOrMove = true;
6198   }
6199
6200   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6201       !D->defaultedMoveConstructorIsDeleted()) {
6202     if (!D->hasTrivialMoveConstructorForCall())
6203       return false;
6204     HasNonDeletedCopyOrMove = true;
6205   }
6206
6207   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6208       !D->hasTrivialDestructorForCall())
6209     return false;
6210
6211   for (const CXXMethodDecl *MD : D->methods()) {
6212     if (MD->isDeleted())
6213       continue;
6214
6215     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6216     if (CD && CD->isCopyOrMoveConstructor())
6217       HasNonDeletedCopyOrMove = true;
6218     else if (!isa<CXXDestructorDecl>(MD))
6219       continue;
6220
6221     if (!MD->isTrivialForCall())
6222       return false;
6223   }
6224
6225   return HasNonDeletedCopyOrMove;
6226 }
6227
6228 /// Perform semantic checks on a class definition that has been
6229 /// completing, introducing implicitly-declared members, checking for
6230 /// abstract types, etc.
6231 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
6232   if (!Record)
6233     return;
6234
6235   if (Record->isAbstract() && !Record->isInvalidDecl()) {
6236     AbstractUsageInfo Info(*this, Record);
6237     CheckAbstractClassUsage(Info, Record);
6238   }
6239
6240   // If this is not an aggregate type and has no user-declared constructor,
6241   // complain about any non-static data members of reference or const scalar
6242   // type, since they will never get initializers.
6243   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6244       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6245       !Record->isLambda()) {
6246     bool Complained = false;
6247     for (const auto *F : Record->fields()) {
6248       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6249         continue;
6250
6251       if (F->getType()->isReferenceType() ||
6252           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6253         if (!Complained) {
6254           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6255             << Record->getTagKind() << Record;
6256           Complained = true;
6257         }
6258
6259         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6260           << F->getType()->isReferenceType()
6261           << F->getDeclName();
6262       }
6263     }
6264   }
6265
6266   if (Record->getIdentifier()) {
6267     // C++ [class.mem]p13:
6268     //   If T is the name of a class, then each of the following shall have a
6269     //   name different from T:
6270     //     - every member of every anonymous union that is a member of class T.
6271     //
6272     // C++ [class.mem]p14:
6273     //   In addition, if class T has a user-declared constructor (12.1), every
6274     //   non-static data member of class T shall have a name different from T.
6275     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6276     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6277          ++I) {
6278       NamedDecl *D = (*I)->getUnderlyingDecl();
6279       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6280            Record->hasUserDeclaredConstructor()) ||
6281           isa<IndirectFieldDecl>(D)) {
6282         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6283           << D->getDeclName();
6284         break;
6285       }
6286     }
6287   }
6288
6289   // Warn if the class has virtual methods but non-virtual public destructor.
6290   if (Record->isPolymorphic() && !Record->isDependentType()) {
6291     CXXDestructorDecl *dtor = Record->getDestructor();
6292     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6293         !Record->hasAttr<FinalAttr>())
6294       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6295            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6296   }
6297
6298   if (Record->isAbstract()) {
6299     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6300       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6301         << FA->isSpelledAsSealed();
6302       DiagnoseAbstractType(Record);
6303     }
6304   }
6305
6306   // Warn if the class has a final destructor but is not itself marked final.
6307   if (!Record->hasAttr<FinalAttr>()) {
6308     if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6309       if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6310         Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6311             << FA->isSpelledAsSealed()
6312             << FixItHint::CreateInsertion(
6313                    getLocForEndOfToken(Record->getLocation()),
6314                    (FA->isSpelledAsSealed() ? " sealed" : " final"));
6315         Diag(Record->getLocation(),
6316              diag::note_final_dtor_non_final_class_silence)
6317             << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6318       }
6319     }
6320   }
6321
6322   // See if trivial_abi has to be dropped.
6323   if (Record->hasAttr<TrivialABIAttr>())
6324     checkIllFormedTrivialABIStruct(*Record);
6325
6326   // Set HasTrivialSpecialMemberForCall if the record has attribute
6327   // "trivial_abi".
6328   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6329
6330   if (HasTrivialABI)
6331     Record->setHasTrivialSpecialMemberForCall();
6332
6333   auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6334     // Check whether the explicitly-defaulted special members are valid.
6335     if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
6336       CheckExplicitlyDefaultedSpecialMember(M);
6337
6338     // For an explicitly defaulted or deleted special member, we defer
6339     // determining triviality until the class is complete. That time is now!
6340     CXXSpecialMember CSM = getSpecialMember(M);
6341     if (!M->isImplicit() && !M->isUserProvided()) {
6342       if (CSM != CXXInvalid) {
6343         M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6344         // Inform the class that we've finished declaring this member.
6345         Record->finishedDefaultedOrDeletedMember(M);
6346         M->setTrivialForCall(
6347             HasTrivialABI ||
6348             SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6349         Record->setTrivialForCallFlags(M);
6350       }
6351     }
6352
6353     // Set triviality for the purpose of calls if this is a user-provided
6354     // copy/move constructor or destructor.
6355     if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6356          CSM == CXXDestructor) && M->isUserProvided()) {
6357       M->setTrivialForCall(HasTrivialABI);
6358       Record->setTrivialForCallFlags(M);
6359     }
6360
6361     if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6362         M->hasAttr<DLLExportAttr>()) {
6363       if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6364           M->isTrivial() &&
6365           (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6366            CSM == CXXDestructor))
6367         M->dropAttr<DLLExportAttr>();
6368
6369       if (M->hasAttr<DLLExportAttr>()) {
6370         // Define after any fields with in-class initializers have been parsed.
6371         DelayedDllExportMemberFunctions.push_back(M);
6372       }
6373     }
6374
6375     // Define defaulted constexpr virtual functions that override a base class
6376     // function right away.
6377     // FIXME: We can defer doing this until the vtable is marked as used.
6378     if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods())
6379       DefineImplicitSpecialMember(*this, M, M->getLocation());
6380   };
6381
6382   bool HasMethodWithOverrideControl = false,
6383        HasOverridingMethodWithoutOverrideControl = false;
6384   if (!Record->isDependentType()) {
6385     // Check the destructor before any other member function. We need to
6386     // determine whether it's trivial in order to determine whether the claas
6387     // type is a literal type, which is a prerequisite for determining whether
6388     // other special member functions are valid and whether they're implicitly
6389     // 'constexpr'.
6390     if (CXXDestructorDecl *Dtor = Record->getDestructor())
6391       CompleteMemberFunction(Dtor);
6392
6393     for (auto *M : Record->methods()) {
6394       // See if a method overloads virtual methods in a base
6395       // class without overriding any.
6396       if (!M->isStatic())
6397         DiagnoseHiddenVirtualMethods(M);
6398       if (M->hasAttr<OverrideAttr>())
6399         HasMethodWithOverrideControl = true;
6400       else if (M->size_overridden_methods() > 0)
6401         HasOverridingMethodWithoutOverrideControl = true;
6402
6403       if (!isa<CXXDestructorDecl>(M))
6404         CompleteMemberFunction(M);
6405     }
6406   }
6407
6408   if (HasMethodWithOverrideControl &&
6409       HasOverridingMethodWithoutOverrideControl) {
6410     // At least one method has the 'override' control declared.
6411     // Diagnose all other overridden methods which do not have 'override' specified on them.
6412     for (auto *M : Record->methods())
6413       DiagnoseAbsenceOfOverrideControl(M);
6414   }
6415
6416   // ms_struct is a request to use the same ABI rules as MSVC.  Check
6417   // whether this class uses any C++ features that are implemented
6418   // completely differently in MSVC, and if so, emit a diagnostic.
6419   // That diagnostic defaults to an error, but we allow projects to
6420   // map it down to a warning (or ignore it).  It's a fairly common
6421   // practice among users of the ms_struct pragma to mass-annotate
6422   // headers, sweeping up a bunch of types that the project doesn't
6423   // really rely on MSVC-compatible layout for.  We must therefore
6424   // support "ms_struct except for C++ stuff" as a secondary ABI.
6425   if (Record->isMsStruct(Context) &&
6426       (Record->isPolymorphic() || Record->getNumBases())) {
6427     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6428   }
6429
6430   checkClassLevelDLLAttribute(Record);
6431   checkClassLevelCodeSegAttribute(Record);
6432
6433   bool ClangABICompat4 =
6434       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6435   TargetInfo::CallingConvKind CCK =
6436       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6437   bool CanPass = canPassInRegisters(*this, Record, CCK);
6438
6439   // Do not change ArgPassingRestrictions if it has already been set to
6440   // APK_CanNeverPassInRegs.
6441   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6442     Record->setArgPassingRestrictions(CanPass
6443                                           ? RecordDecl::APK_CanPassInRegs
6444                                           : RecordDecl::APK_CannotPassInRegs);
6445
6446   // If canPassInRegisters returns true despite the record having a non-trivial
6447   // destructor, the record is destructed in the callee. This happens only when
6448   // the record or one of its subobjects has a field annotated with trivial_abi
6449   // or a field qualified with ObjC __strong/__weak.
6450   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6451     Record->setParamDestroyedInCallee(true);
6452   else if (Record->hasNonTrivialDestructor())
6453     Record->setParamDestroyedInCallee(CanPass);
6454
6455   if (getLangOpts().ForceEmitVTables) {
6456     // If we want to emit all the vtables, we need to mark it as used.  This
6457     // is especially required for cases like vtable assumption loads.
6458     MarkVTableUsed(Record->getInnerLocStart(), Record);
6459   }
6460 }
6461
6462 /// Look up the special member function that would be called by a special
6463 /// member function for a subobject of class type.
6464 ///
6465 /// \param Class The class type of the subobject.
6466 /// \param CSM The kind of special member function.
6467 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6468 /// \param ConstRHS True if this is a copy operation with a const object
6469 ///        on its RHS, that is, if the argument to the outer special member
6470 ///        function is 'const' and this is not a field marked 'mutable'.
6471 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6472     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6473     unsigned FieldQuals, bool ConstRHS) {
6474   unsigned LHSQuals = 0;
6475   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6476     LHSQuals = FieldQuals;
6477
6478   unsigned RHSQuals = FieldQuals;
6479   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6480     RHSQuals = 0;
6481   else if (ConstRHS)
6482     RHSQuals |= Qualifiers::Const;
6483
6484   return S.LookupSpecialMember(Class, CSM,
6485                                RHSQuals & Qualifiers::Const,
6486                                RHSQuals & Qualifiers::Volatile,
6487                                false,
6488                                LHSQuals & Qualifiers::Const,
6489                                LHSQuals & Qualifiers::Volatile);
6490 }
6491
6492 class Sema::InheritedConstructorInfo {
6493   Sema &S;
6494   SourceLocation UseLoc;
6495
6496   /// A mapping from the base classes through which the constructor was
6497   /// inherited to the using shadow declaration in that base class (or a null
6498   /// pointer if the constructor was declared in that base class).
6499   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6500       InheritedFromBases;
6501
6502 public:
6503   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6504                            ConstructorUsingShadowDecl *Shadow)
6505       : S(S), UseLoc(UseLoc) {
6506     bool DiagnosedMultipleConstructedBases = false;
6507     CXXRecordDecl *ConstructedBase = nullptr;
6508     UsingDecl *ConstructedBaseUsing = nullptr;
6509
6510     // Find the set of such base class subobjects and check that there's a
6511     // unique constructed subobject.
6512     for (auto *D : Shadow->redecls()) {
6513       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6514       auto *DNominatedBase = DShadow->getNominatedBaseClass();
6515       auto *DConstructedBase = DShadow->getConstructedBaseClass();
6516
6517       InheritedFromBases.insert(
6518           std::make_pair(DNominatedBase->getCanonicalDecl(),
6519                          DShadow->getNominatedBaseClassShadowDecl()));
6520       if (DShadow->constructsVirtualBase())
6521         InheritedFromBases.insert(
6522             std::make_pair(DConstructedBase->getCanonicalDecl(),
6523                            DShadow->getConstructedBaseClassShadowDecl()));
6524       else
6525         assert(DNominatedBase == DConstructedBase);
6526
6527       // [class.inhctor.init]p2:
6528       //   If the constructor was inherited from multiple base class subobjects
6529       //   of type B, the program is ill-formed.
6530       if (!ConstructedBase) {
6531         ConstructedBase = DConstructedBase;
6532         ConstructedBaseUsing = D->getUsingDecl();
6533       } else if (ConstructedBase != DConstructedBase &&
6534                  !Shadow->isInvalidDecl()) {
6535         if (!DiagnosedMultipleConstructedBases) {
6536           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6537               << Shadow->getTargetDecl();
6538           S.Diag(ConstructedBaseUsing->getLocation(),
6539                diag::note_ambiguous_inherited_constructor_using)
6540               << ConstructedBase;
6541           DiagnosedMultipleConstructedBases = true;
6542         }
6543         S.Diag(D->getUsingDecl()->getLocation(),
6544                diag::note_ambiguous_inherited_constructor_using)
6545             << DConstructedBase;
6546       }
6547     }
6548
6549     if (DiagnosedMultipleConstructedBases)
6550       Shadow->setInvalidDecl();
6551   }
6552
6553   /// Find the constructor to use for inherited construction of a base class,
6554   /// and whether that base class constructor inherits the constructor from a
6555   /// virtual base class (in which case it won't actually invoke it).
6556   std::pair<CXXConstructorDecl *, bool>
6557   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6558     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6559     if (It == InheritedFromBases.end())
6560       return std::make_pair(nullptr, false);
6561
6562     // This is an intermediary class.
6563     if (It->second)
6564       return std::make_pair(
6565           S.findInheritingConstructor(UseLoc, Ctor, It->second),
6566           It->second->constructsVirtualBase());
6567
6568     // This is the base class from which the constructor was inherited.
6569     return std::make_pair(Ctor, false);
6570   }
6571 };
6572
6573 /// Is the special member function which would be selected to perform the
6574 /// specified operation on the specified class type a constexpr constructor?
6575 static bool
6576 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6577                          Sema::CXXSpecialMember CSM, unsigned Quals,
6578                          bool ConstRHS,
6579                          CXXConstructorDecl *InheritedCtor = nullptr,
6580                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
6581   // If we're inheriting a constructor, see if we need to call it for this base
6582   // class.
6583   if (InheritedCtor) {
6584     assert(CSM == Sema::CXXDefaultConstructor);
6585     auto BaseCtor =
6586         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6587     if (BaseCtor)
6588       return BaseCtor->isConstexpr();
6589   }
6590
6591   if (CSM == Sema::CXXDefaultConstructor)
6592     return ClassDecl->hasConstexprDefaultConstructor();
6593   if (CSM == Sema::CXXDestructor)
6594     return ClassDecl->hasConstexprDestructor();
6595
6596   Sema::SpecialMemberOverloadResult SMOR =
6597       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6598   if (!SMOR.getMethod())
6599     // A constructor we wouldn't select can't be "involved in initializing"
6600     // anything.
6601     return true;
6602   return SMOR.getMethod()->isConstexpr();
6603 }
6604
6605 /// Determine whether the specified special member function would be constexpr
6606 /// if it were implicitly defined.
6607 static bool defaultedSpecialMemberIsConstexpr(
6608     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6609     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6610     Sema::InheritedConstructorInfo *Inherited = nullptr) {
6611   if (!S.getLangOpts().CPlusPlus11)
6612     return false;
6613
6614   // C++11 [dcl.constexpr]p4:
6615   // In the definition of a constexpr constructor [...]
6616   bool Ctor = true;
6617   switch (CSM) {
6618   case Sema::CXXDefaultConstructor:
6619     if (Inherited)
6620       break;
6621     // Since default constructor lookup is essentially trivial (and cannot
6622     // involve, for instance, template instantiation), we compute whether a
6623     // defaulted default constructor is constexpr directly within CXXRecordDecl.
6624     //
6625     // This is important for performance; we need to know whether the default
6626     // constructor is constexpr to determine whether the type is a literal type.
6627     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6628
6629   case Sema::CXXCopyConstructor:
6630   case Sema::CXXMoveConstructor:
6631     // For copy or move constructors, we need to perform overload resolution.
6632     break;
6633
6634   case Sema::CXXCopyAssignment:
6635   case Sema::CXXMoveAssignment:
6636     if (!S.getLangOpts().CPlusPlus14)
6637       return false;
6638     // In C++1y, we need to perform overload resolution.
6639     Ctor = false;
6640     break;
6641
6642   case Sema::CXXDestructor:
6643     return ClassDecl->defaultedDestructorIsConstexpr();
6644
6645   case Sema::CXXInvalid:
6646     return false;
6647   }
6648
6649   //   -- if the class is a non-empty union, or for each non-empty anonymous
6650   //      union member of a non-union class, exactly one non-static data member
6651   //      shall be initialized; [DR1359]
6652   //
6653   // If we squint, this is guaranteed, since exactly one non-static data member
6654   // will be initialized (if the constructor isn't deleted), we just don't know
6655   // which one.
6656   if (Ctor && ClassDecl->isUnion())
6657     return CSM == Sema::CXXDefaultConstructor
6658                ? ClassDecl->hasInClassInitializer() ||
6659                      !ClassDecl->hasVariantMembers()
6660                : true;
6661
6662   //   -- the class shall not have any virtual base classes;
6663   if (Ctor && ClassDecl->getNumVBases())
6664     return false;
6665
6666   // C++1y [class.copy]p26:
6667   //   -- [the class] is a literal type, and
6668   if (!Ctor && !ClassDecl->isLiteral())
6669     return false;
6670
6671   //   -- every constructor involved in initializing [...] base class
6672   //      sub-objects shall be a constexpr constructor;
6673   //   -- the assignment operator selected to copy/move each direct base
6674   //      class is a constexpr function, and
6675   for (const auto &B : ClassDecl->bases()) {
6676     const RecordType *BaseType = B.getType()->getAs<RecordType>();
6677     if (!BaseType) continue;
6678
6679     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6680     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6681                                   InheritedCtor, Inherited))
6682       return false;
6683   }
6684
6685   //   -- every constructor involved in initializing non-static data members
6686   //      [...] shall be a constexpr constructor;
6687   //   -- every non-static data member and base class sub-object shall be
6688   //      initialized
6689   //   -- for each non-static data member of X that is of class type (or array
6690   //      thereof), the assignment operator selected to copy/move that member is
6691   //      a constexpr function
6692   for (const auto *F : ClassDecl->fields()) {
6693     if (F->isInvalidDecl())
6694       continue;
6695     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6696       continue;
6697     QualType BaseType = S.Context.getBaseElementType(F->getType());
6698     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
6699       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6700       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6701                                     BaseType.getCVRQualifiers(),
6702                                     ConstArg && !F->isMutable()))
6703         return false;
6704     } else if (CSM == Sema::CXXDefaultConstructor) {
6705       return false;
6706     }
6707   }
6708
6709   // All OK, it's constexpr!
6710   return true;
6711 }
6712
6713 static Sema::ImplicitExceptionSpecification
6714 ComputeDefaultedSpecialMemberExceptionSpec(
6715     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6716     Sema::InheritedConstructorInfo *ICI);
6717
6718 static Sema::ImplicitExceptionSpecification
6719 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6720   auto CSM = S.getSpecialMember(MD);
6721   if (CSM != Sema::CXXInvalid)
6722     return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
6723
6724   auto *CD = cast<CXXConstructorDecl>(MD);
6725   assert(CD->getInheritedConstructor() &&
6726          "only special members have implicit exception specs");
6727   Sema::InheritedConstructorInfo ICI(
6728       S, Loc, CD->getInheritedConstructor().getShadowDecl());
6729   return ComputeDefaultedSpecialMemberExceptionSpec(
6730       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
6731 }
6732
6733 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6734                                                             CXXMethodDecl *MD) {
6735   FunctionProtoType::ExtProtoInfo EPI;
6736
6737   // Build an exception specification pointing back at this member.
6738   EPI.ExceptionSpec.Type = EST_Unevaluated;
6739   EPI.ExceptionSpec.SourceDecl = MD;
6740
6741   // Set the calling convention to the default for C++ instance methods.
6742   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6743       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6744                                             /*IsCXXMethod=*/true));
6745   return EPI;
6746 }
6747
6748 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6749   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6750   if (FPT->getExceptionSpecType() != EST_Unevaluated)
6751     return;
6752
6753   // Evaluate the exception specification.
6754   auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6755   auto ESI = IES.getExceptionSpec();
6756
6757   // Update the type of the special member to use it.
6758   UpdateExceptionSpec(MD, ESI);
6759
6760   // A user-provided destructor can be defined outside the class. When that
6761   // happens, be sure to update the exception specification on both
6762   // declarations.
6763   const FunctionProtoType *CanonicalFPT =
6764     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6765   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
6766     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
6767 }
6768
6769 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6770   CXXRecordDecl *RD = MD->getParent();
6771   CXXSpecialMember CSM = getSpecialMember(MD);
6772
6773   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6774          "not an explicitly-defaulted special member");
6775
6776   // Whether this was the first-declared instance of the constructor.
6777   // This affects whether we implicitly add an exception spec and constexpr.
6778   bool First = MD == MD->getCanonicalDecl();
6779
6780   bool HadError = false;
6781
6782   // C++11 [dcl.fct.def.default]p1:
6783   //   A function that is explicitly defaulted shall
6784   //     -- be a special member function (checked elsewhere),
6785   //     -- have the same type (except for ref-qualifiers, and except that a
6786   //        copy operation can take a non-const reference) as an implicit
6787   //        declaration, and
6788   //     -- not have default arguments.
6789   // C++2a changes the second bullet to instead delete the function if it's
6790   // defaulted on its first declaration, unless it's "an assignment operator,
6791   // and its return type differs or its parameter type is not a reference".
6792   bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First;
6793   bool ShouldDeleteForTypeMismatch = false;
6794   unsigned ExpectedParams = 1;
6795   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6796     ExpectedParams = 0;
6797   if (MD->getNumParams() != ExpectedParams) {
6798     // This checks for default arguments: a copy or move constructor with a
6799     // default argument is classified as a default constructor, and assignment
6800     // operations and destructors can't have default arguments.
6801     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6802       << CSM << MD->getSourceRange();
6803     HadError = true;
6804   } else if (MD->isVariadic()) {
6805     if (DeleteOnTypeMismatch)
6806       ShouldDeleteForTypeMismatch = true;
6807     else {
6808       Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6809         << CSM << MD->getSourceRange();
6810       HadError = true;
6811     }
6812   }
6813
6814   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
6815
6816   bool CanHaveConstParam = false;
6817   if (CSM == CXXCopyConstructor)
6818     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
6819   else if (CSM == CXXCopyAssignment)
6820     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
6821
6822   QualType ReturnType = Context.VoidTy;
6823   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6824     // Check for return type matching.
6825     ReturnType = Type->getReturnType();
6826
6827     QualType DeclType = Context.getTypeDeclType(RD);
6828     DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
6829     QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
6830
6831     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6832       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6833         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6834       HadError = true;
6835     }
6836
6837     // A defaulted special member cannot have cv-qualifiers.
6838     if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
6839       if (DeleteOnTypeMismatch)
6840         ShouldDeleteForTypeMismatch = true;
6841       else {
6842         Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
6843           << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
6844         HadError = true;
6845       }
6846     }
6847   }
6848
6849   // Check for parameter type matching.
6850   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
6851   bool HasConstParam = false;
6852   if (ExpectedParams && ArgType->isReferenceType()) {
6853     // Argument must be reference to possibly-const T.
6854     QualType ReferentType = ArgType->getPointeeType();
6855     HasConstParam = ReferentType.isConstQualified();
6856
6857     if (ReferentType.isVolatileQualified()) {
6858       if (DeleteOnTypeMismatch)
6859         ShouldDeleteForTypeMismatch = true;
6860       else {
6861         Diag(MD->getLocation(),
6862              diag::err_defaulted_special_member_volatile_param) << CSM;
6863         HadError = true;
6864       }
6865     }
6866
6867     if (HasConstParam && !CanHaveConstParam) {
6868       if (DeleteOnTypeMismatch)
6869         ShouldDeleteForTypeMismatch = true;
6870       else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6871         Diag(MD->getLocation(),
6872              diag::err_defaulted_special_member_copy_const_param)
6873           << (CSM == CXXCopyAssignment);
6874         // FIXME: Explain why this special member can't be const.
6875         HadError = true;
6876       } else {
6877         Diag(MD->getLocation(),
6878              diag::err_defaulted_special_member_move_const_param)
6879           << (CSM == CXXMoveAssignment);
6880         HadError = true;
6881       }
6882     }
6883   } else if (ExpectedParams) {
6884     // A copy assignment operator can take its argument by value, but a
6885     // defaulted one cannot.
6886     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
6887     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
6888     HadError = true;
6889   }
6890
6891   // C++11 [dcl.fct.def.default]p2:
6892   //   An explicitly-defaulted function may be declared constexpr only if it
6893   //   would have been implicitly declared as constexpr,
6894   // Do not apply this rule to members of class templates, since core issue 1358
6895   // makes such functions always instantiate to constexpr functions. For
6896   // functions which cannot be constexpr (for non-constructors in C++11 and for
6897   // destructors in C++14 and C++17), this is checked elsewhere.
6898   //
6899   // FIXME: This should not apply if the member is deleted.
6900   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6901                                                      HasConstParam);
6902   if ((getLangOpts().CPlusPlus2a ||
6903        (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
6904                                   : isa<CXXConstructorDecl>(MD))) &&
6905       MD->isConstexpr() && !Constexpr &&
6906       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6907     Diag(MD->getBeginLoc(), MD->isConsteval()
6908                                 ? diag::err_incorrect_defaulted_consteval
6909                                 : diag::err_incorrect_defaulted_constexpr)
6910         << CSM;
6911     // FIXME: Explain why the special member can't be constexpr.
6912     HadError = true;
6913   }
6914
6915   if (First) {
6916     // C++2a [dcl.fct.def.default]p3:
6917     //   If a function is explicitly defaulted on its first declaration, it is
6918     //   implicitly considered to be constexpr if the implicit declaration
6919     //   would be.
6920     MD->setConstexprKind(Constexpr ? CSK_constexpr : CSK_unspecified);
6921
6922     if (!Type->hasExceptionSpec()) {
6923       // C++2a [except.spec]p3:
6924       //   If a declaration of a function does not have a noexcept-specifier
6925       //   [and] is defaulted on its first declaration, [...] the exception
6926       //   specification is as specified below
6927       FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
6928       EPI.ExceptionSpec.Type = EST_Unevaluated;
6929       EPI.ExceptionSpec.SourceDecl = MD;
6930       MD->setType(Context.getFunctionType(ReturnType,
6931                                           llvm::makeArrayRef(&ArgType,
6932                                                              ExpectedParams),
6933                                           EPI));
6934     }
6935   }
6936
6937   if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
6938     if (First) {
6939       SetDeclDeleted(MD, MD->getLocation());
6940       if (!inTemplateInstantiation() && !HadError) {
6941         Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
6942         if (ShouldDeleteForTypeMismatch) {
6943           Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
6944         } else {
6945           ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6946         }
6947       }
6948       if (ShouldDeleteForTypeMismatch && !HadError) {
6949         Diag(MD->getLocation(),
6950              diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
6951       }
6952     } else {
6953       // C++11 [dcl.fct.def.default]p4:
6954       //   [For a] user-provided explicitly-defaulted function [...] if such a
6955       //   function is implicitly defined as deleted, the program is ill-formed.
6956       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
6957       assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
6958       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6959       HadError = true;
6960     }
6961   }
6962
6963   if (HadError)
6964     MD->setInvalidDecl();
6965 }
6966
6967 void Sema::CheckDelayedMemberExceptionSpecs() {
6968   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
6969   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
6970
6971   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
6972   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
6973
6974   // Perform any deferred checking of exception specifications for virtual
6975   // destructors.
6976   for (auto &Check : Overriding)
6977     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
6978
6979   // Perform any deferred checking of exception specifications for befriended
6980   // special members.
6981   for (auto &Check : Equivalent)
6982     CheckEquivalentExceptionSpec(Check.second, Check.first);
6983 }
6984
6985 namespace {
6986 /// CRTP base class for visiting operations performed by a special member
6987 /// function (or inherited constructor).
6988 template<typename Derived>
6989 struct SpecialMemberVisitor {
6990   Sema &S;
6991   CXXMethodDecl *MD;
6992   Sema::CXXSpecialMember CSM;
6993   Sema::InheritedConstructorInfo *ICI;
6994
6995   // Properties of the special member, computed for convenience.
6996   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
6997
6998   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6999                        Sema::InheritedConstructorInfo *ICI)
7000       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
7001     switch (CSM) {
7002     case Sema::CXXDefaultConstructor:
7003     case Sema::CXXCopyConstructor:
7004     case Sema::CXXMoveConstructor:
7005       IsConstructor = true;
7006       break;
7007     case Sema::CXXCopyAssignment:
7008     case Sema::CXXMoveAssignment:
7009       IsAssignment = true;
7010       break;
7011     case Sema::CXXDestructor:
7012       break;
7013     case Sema::CXXInvalid:
7014       llvm_unreachable("invalid special member kind");
7015     }
7016
7017     if (MD->getNumParams()) {
7018       if (const ReferenceType *RT =
7019               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
7020         ConstArg = RT->getPointeeType().isConstQualified();
7021     }
7022   }
7023
7024   Derived &getDerived() { return static_cast<Derived&>(*this); }
7025
7026   /// Is this a "move" special member?
7027   bool isMove() const {
7028     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
7029   }
7030
7031   /// Look up the corresponding special member in the given class.
7032   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
7033                                              unsigned Quals, bool IsMutable) {
7034     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
7035                                        ConstArg && !IsMutable);
7036   }
7037
7038   /// Look up the constructor for the specified base class to see if it's
7039   /// overridden due to this being an inherited constructor.
7040   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
7041     if (!ICI)
7042       return {};
7043     assert(CSM == Sema::CXXDefaultConstructor);
7044     auto *BaseCtor =
7045       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
7046     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
7047       return MD;
7048     return {};
7049   }
7050
7051   /// A base or member subobject.
7052   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
7053
7054   /// Get the location to use for a subobject in diagnostics.
7055   static SourceLocation getSubobjectLoc(Subobject Subobj) {
7056     // FIXME: For an indirect virtual base, the direct base leading to
7057     // the indirect virtual base would be a more useful choice.
7058     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
7059       return B->getBaseTypeLoc();
7060     else
7061       return Subobj.get<FieldDecl*>()->getLocation();
7062   }
7063
7064   enum BasesToVisit {
7065     /// Visit all non-virtual (direct) bases.
7066     VisitNonVirtualBases,
7067     /// Visit all direct bases, virtual or not.
7068     VisitDirectBases,
7069     /// Visit all non-virtual bases, and all virtual bases if the class
7070     /// is not abstract.
7071     VisitPotentiallyConstructedBases,
7072     /// Visit all direct or virtual bases.
7073     VisitAllBases
7074   };
7075
7076   // Visit the bases and members of the class.
7077   bool visit(BasesToVisit Bases) {
7078     CXXRecordDecl *RD = MD->getParent();
7079
7080     if (Bases == VisitPotentiallyConstructedBases)
7081       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
7082
7083     for (auto &B : RD->bases())
7084       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
7085           getDerived().visitBase(&B))
7086         return true;
7087
7088     if (Bases == VisitAllBases)
7089       for (auto &B : RD->vbases())
7090         if (getDerived().visitBase(&B))
7091           return true;
7092
7093     for (auto *F : RD->fields())
7094       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
7095           getDerived().visitField(F))
7096         return true;
7097
7098     return false;
7099   }
7100 };
7101 }
7102
7103 namespace {
7104 struct SpecialMemberDeletionInfo
7105     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
7106   bool Diagnose;
7107
7108   SourceLocation Loc;
7109
7110   bool AllFieldsAreConst;
7111
7112   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
7113                             Sema::CXXSpecialMember CSM,
7114                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
7115       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
7116         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
7117
7118   bool inUnion() const { return MD->getParent()->isUnion(); }
7119
7120   Sema::CXXSpecialMember getEffectiveCSM() {
7121     return ICI ? Sema::CXXInvalid : CSM;
7122   }
7123
7124   bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
7125
7126   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
7127   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
7128
7129   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
7130   bool shouldDeleteForField(FieldDecl *FD);
7131   bool shouldDeleteForAllConstMembers();
7132
7133   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
7134                                      unsigned Quals);
7135   bool shouldDeleteForSubobjectCall(Subobject Subobj,
7136                                     Sema::SpecialMemberOverloadResult SMOR,
7137                                     bool IsDtorCallInCtor);
7138
7139   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
7140 };
7141 }
7142
7143 /// Is the given special member inaccessible when used on the given
7144 /// sub-object.
7145 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
7146                                              CXXMethodDecl *target) {
7147   /// If we're operating on a base class, the object type is the
7148   /// type of this special member.
7149   QualType objectTy;
7150   AccessSpecifier access = target->getAccess();
7151   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
7152     objectTy = S.Context.getTypeDeclType(MD->getParent());
7153     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
7154
7155   // If we're operating on a field, the object type is the type of the field.
7156   } else {
7157     objectTy = S.Context.getTypeDeclType(target->getParent());
7158   }
7159
7160   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
7161 }
7162
7163 /// Check whether we should delete a special member due to the implicit
7164 /// definition containing a call to a special member of a subobject.
7165 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
7166     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
7167     bool IsDtorCallInCtor) {
7168   CXXMethodDecl *Decl = SMOR.getMethod();
7169   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
7170
7171   int DiagKind = -1;
7172
7173   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
7174     DiagKind = !Decl ? 0 : 1;
7175   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
7176     DiagKind = 2;
7177   else if (!isAccessible(Subobj, Decl))
7178     DiagKind = 3;
7179   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
7180            !Decl->isTrivial()) {
7181     // A member of a union must have a trivial corresponding special member.
7182     // As a weird special case, a destructor call from a union's constructor
7183     // must be accessible and non-deleted, but need not be trivial. Such a
7184     // destructor is never actually called, but is semantically checked as
7185     // if it were.
7186     DiagKind = 4;
7187   }
7188
7189   if (DiagKind == -1)
7190     return false;
7191
7192   if (Diagnose) {
7193     if (Field) {
7194       S.Diag(Field->getLocation(),
7195              diag::note_deleted_special_member_class_subobject)
7196         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
7197         << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
7198     } else {
7199       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
7200       S.Diag(Base->getBeginLoc(),
7201              diag::note_deleted_special_member_class_subobject)
7202           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
7203           << Base->getType() << DiagKind << IsDtorCallInCtor
7204           << /*IsObjCPtr*/false;
7205     }
7206
7207     if (DiagKind == 1)
7208       S.NoteDeletedFunction(Decl);
7209     // FIXME: Explain inaccessibility if DiagKind == 3.
7210   }
7211
7212   return true;
7213 }
7214
7215 /// Check whether we should delete a special member function due to having a
7216 /// direct or virtual base class or non-static data member of class type M.
7217 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
7218     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
7219   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
7220   bool IsMutable = Field && Field->isMutable();
7221
7222   // C++11 [class.ctor]p5:
7223   // -- any direct or virtual base class, or non-static data member with no
7224   //    brace-or-equal-initializer, has class type M (or array thereof) and
7225   //    either M has no default constructor or overload resolution as applied
7226   //    to M's default constructor results in an ambiguity or in a function
7227   //    that is deleted or inaccessible
7228   // C++11 [class.copy]p11, C++11 [class.copy]p23:
7229   // -- a direct or virtual base class B that cannot be copied/moved because
7230   //    overload resolution, as applied to B's corresponding special member,
7231   //    results in an ambiguity or a function that is deleted or inaccessible
7232   //    from the defaulted special member
7233   // C++11 [class.dtor]p5:
7234   // -- any direct or virtual base class [...] has a type with a destructor
7235   //    that is deleted or inaccessible
7236   if (!(CSM == Sema::CXXDefaultConstructor &&
7237         Field && Field->hasInClassInitializer()) &&
7238       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
7239                                    false))
7240     return true;
7241
7242   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
7243   // -- any direct or virtual base class or non-static data member has a
7244   //    type with a destructor that is deleted or inaccessible
7245   if (IsConstructor) {
7246     Sema::SpecialMemberOverloadResult SMOR =
7247         S.LookupSpecialMember(Class, Sema::CXXDestructor,
7248                               false, false, false, false, false);
7249     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
7250       return true;
7251   }
7252
7253   return false;
7254 }
7255
7256 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
7257     FieldDecl *FD, QualType FieldType) {
7258   // The defaulted special functions are defined as deleted if this is a variant
7259   // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
7260   // type under ARC.
7261   if (!FieldType.hasNonTrivialObjCLifetime())
7262     return false;
7263
7264   // Don't make the defaulted default constructor defined as deleted if the
7265   // member has an in-class initializer.
7266   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
7267     return false;
7268
7269   if (Diagnose) {
7270     auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
7271     S.Diag(FD->getLocation(),
7272            diag::note_deleted_special_member_class_subobject)
7273         << getEffectiveCSM() << ParentClass << /*IsField*/true
7274         << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
7275   }
7276
7277   return true;
7278 }
7279
7280 /// Check whether we should delete a special member function due to the class
7281 /// having a particular direct or virtual base class.
7282 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
7283   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
7284   // If program is correct, BaseClass cannot be null, but if it is, the error
7285   // must be reported elsewhere.
7286   if (!BaseClass)
7287     return false;
7288   // If we have an inheriting constructor, check whether we're calling an
7289   // inherited constructor instead of a default constructor.
7290   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
7291   if (auto *BaseCtor = SMOR.getMethod()) {
7292     // Note that we do not check access along this path; other than that,
7293     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
7294     // FIXME: Check that the base has a usable destructor! Sink this into
7295     // shouldDeleteForClassSubobject.
7296     if (BaseCtor->isDeleted() && Diagnose) {
7297       S.Diag(Base->getBeginLoc(),
7298              diag::note_deleted_special_member_class_subobject)
7299           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
7300           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
7301           << /*IsObjCPtr*/false;
7302       S.NoteDeletedFunction(BaseCtor);
7303     }
7304     return BaseCtor->isDeleted();
7305   }
7306   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
7307 }
7308
7309 /// Check whether we should delete a special member function due to the class
7310 /// having a particular non-static data member.
7311 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
7312   QualType FieldType = S.Context.getBaseElementType(FD->getType());
7313   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
7314
7315   if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
7316     return true;
7317
7318   if (CSM == Sema::CXXDefaultConstructor) {
7319     // For a default constructor, all references must be initialized in-class
7320     // and, if a union, it must have a non-const member.
7321     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
7322       if (Diagnose)
7323         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
7324           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
7325       return true;
7326     }
7327     // C++11 [class.ctor]p5: any non-variant non-static data member of
7328     // const-qualified type (or array thereof) with no
7329     // brace-or-equal-initializer does not have a user-provided default
7330     // constructor.
7331     if (!inUnion() && FieldType.isConstQualified() &&
7332         !FD->hasInClassInitializer() &&
7333         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
7334       if (Diagnose)
7335         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
7336           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
7337       return true;
7338     }
7339
7340     if (inUnion() && !FieldType.isConstQualified())
7341       AllFieldsAreConst = false;
7342   } else if (CSM == Sema::CXXCopyConstructor) {
7343     // For a copy constructor, data members must not be of rvalue reference
7344     // type.
7345     if (FieldType->isRValueReferenceType()) {
7346       if (Diagnose)
7347         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
7348           << MD->getParent() << FD << FieldType;
7349       return true;
7350     }
7351   } else if (IsAssignment) {
7352     // For an assignment operator, data members must not be of reference type.
7353     if (FieldType->isReferenceType()) {
7354       if (Diagnose)
7355         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7356           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
7357       return true;
7358     }
7359     if (!FieldRecord && FieldType.isConstQualified()) {
7360       // C++11 [class.copy]p23:
7361       // -- a non-static data member of const non-class type (or array thereof)
7362       if (Diagnose)
7363         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7364           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
7365       return true;
7366     }
7367   }
7368
7369   if (FieldRecord) {
7370     // Some additional restrictions exist on the variant members.
7371     if (!inUnion() && FieldRecord->isUnion() &&
7372         FieldRecord->isAnonymousStructOrUnion()) {
7373       bool AllVariantFieldsAreConst = true;
7374
7375       // FIXME: Handle anonymous unions declared within anonymous unions.
7376       for (auto *UI : FieldRecord->fields()) {
7377         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
7378
7379         if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
7380           return true;
7381
7382         if (!UnionFieldType.isConstQualified())
7383           AllVariantFieldsAreConst = false;
7384
7385         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
7386         if (UnionFieldRecord &&
7387             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
7388                                           UnionFieldType.getCVRQualifiers()))
7389           return true;
7390       }
7391
7392       // At least one member in each anonymous union must be non-const
7393       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
7394           !FieldRecord->field_empty()) {
7395         if (Diagnose)
7396           S.Diag(FieldRecord->getLocation(),
7397                  diag::note_deleted_default_ctor_all_const)
7398             << !!ICI << MD->getParent() << /*anonymous union*/1;
7399         return true;
7400       }
7401
7402       // Don't check the implicit member of the anonymous union type.
7403       // This is technically non-conformant, but sanity demands it.
7404       return false;
7405     }
7406
7407     if (shouldDeleteForClassSubobject(FieldRecord, FD,
7408                                       FieldType.getCVRQualifiers()))
7409       return true;
7410   }
7411
7412   return false;
7413 }
7414
7415 /// C++11 [class.ctor] p5:
7416 ///   A defaulted default constructor for a class X is defined as deleted if
7417 /// X is a union and all of its variant members are of const-qualified type.
7418 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
7419   // This is a silly definition, because it gives an empty union a deleted
7420   // default constructor. Don't do that.
7421   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
7422     bool AnyFields = false;
7423     for (auto *F : MD->getParent()->fields())
7424       if ((AnyFields = !F->isUnnamedBitfield()))
7425         break;
7426     if (!AnyFields)
7427       return false;
7428     if (Diagnose)
7429       S.Diag(MD->getParent()->getLocation(),
7430              diag::note_deleted_default_ctor_all_const)
7431         << !!ICI << MD->getParent() << /*not anonymous union*/0;
7432     return true;
7433   }
7434   return false;
7435 }
7436
7437 /// Determine whether a defaulted special member function should be defined as
7438 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
7439 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
7440 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
7441                                      InheritedConstructorInfo *ICI,
7442                                      bool Diagnose) {
7443   if (MD->isInvalidDecl())
7444     return false;
7445   CXXRecordDecl *RD = MD->getParent();
7446   assert(!RD->isDependentType() && "do deletion after instantiation");
7447   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
7448     return false;
7449
7450   // C++11 [expr.lambda.prim]p19:
7451   //   The closure type associated with a lambda-expression has a
7452   //   deleted (8.4.3) default constructor and a deleted copy
7453   //   assignment operator.
7454   // C++2a adds back these operators if the lambda has no lambda-capture.
7455   if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
7456       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
7457     if (Diagnose)
7458       Diag(RD->getLocation(), diag::note_lambda_decl);
7459     return true;
7460   }
7461
7462   // For an anonymous struct or union, the copy and assignment special members
7463   // will never be used, so skip the check. For an anonymous union declared at
7464   // namespace scope, the constructor and destructor are used.
7465   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
7466       RD->isAnonymousStructOrUnion())
7467     return false;
7468
7469   // C++11 [class.copy]p7, p18:
7470   //   If the class definition declares a move constructor or move assignment
7471   //   operator, an implicitly declared copy constructor or copy assignment
7472   //   operator is defined as deleted.
7473   if (MD->isImplicit() &&
7474       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
7475     CXXMethodDecl *UserDeclaredMove = nullptr;
7476
7477     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
7478     // deletion of the corresponding copy operation, not both copy operations.
7479     // MSVC 2015 has adopted the standards conforming behavior.
7480     bool DeletesOnlyMatchingCopy =
7481         getLangOpts().MSVCCompat &&
7482         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
7483
7484     if (RD->hasUserDeclaredMoveConstructor() &&
7485         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
7486       if (!Diagnose) return true;
7487
7488       // Find any user-declared move constructor.
7489       for (auto *I : RD->ctors()) {
7490         if (I->isMoveConstructor()) {
7491           UserDeclaredMove = I;
7492           break;
7493         }
7494       }
7495       assert(UserDeclaredMove);
7496     } else if (RD->hasUserDeclaredMoveAssignment() &&
7497                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
7498       if (!Diagnose) return true;
7499
7500       // Find any user-declared move assignment operator.
7501       for (auto *I : RD->methods()) {
7502         if (I->isMoveAssignmentOperator()) {
7503           UserDeclaredMove = I;
7504           break;
7505         }
7506       }
7507       assert(UserDeclaredMove);
7508     }
7509
7510     if (UserDeclaredMove) {
7511       Diag(UserDeclaredMove->getLocation(),
7512            diag::note_deleted_copy_user_declared_move)
7513         << (CSM == CXXCopyAssignment) << RD
7514         << UserDeclaredMove->isMoveAssignmentOperator();
7515       return true;
7516     }
7517   }
7518
7519   // Do access control from the special member function
7520   ContextRAII MethodContext(*this, MD);
7521
7522   // C++11 [class.dtor]p5:
7523   // -- for a virtual destructor, lookup of the non-array deallocation function
7524   //    results in an ambiguity or in a function that is deleted or inaccessible
7525   if (CSM == CXXDestructor && MD->isVirtual()) {
7526     FunctionDecl *OperatorDelete = nullptr;
7527     DeclarationName Name =
7528       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
7529     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
7530                                  OperatorDelete, /*Diagnose*/false)) {
7531       if (Diagnose)
7532         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
7533       return true;
7534     }
7535   }
7536
7537   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
7538
7539   // Per DR1611, do not consider virtual bases of constructors of abstract
7540   // classes, since we are not going to construct them.
7541   // Per DR1658, do not consider virtual bases of destructors of abstract
7542   // classes either.
7543   // Per DR2180, for assignment operators we only assign (and thus only
7544   // consider) direct bases.
7545   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
7546                                  : SMI.VisitPotentiallyConstructedBases))
7547     return true;
7548
7549   if (SMI.shouldDeleteForAllConstMembers())
7550     return true;
7551
7552   if (getLangOpts().CUDA) {
7553     // We should delete the special member in CUDA mode if target inference
7554     // failed.
7555     // For inherited constructors (non-null ICI), CSM may be passed so that MD
7556     // is treated as certain special member, which may not reflect what special
7557     // member MD really is. However inferCUDATargetForImplicitSpecialMember
7558     // expects CSM to match MD, therefore recalculate CSM.
7559     assert(ICI || CSM == getSpecialMember(MD));
7560     auto RealCSM = CSM;
7561     if (ICI)
7562       RealCSM = getSpecialMember(MD);
7563
7564     return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
7565                                                    SMI.ConstArg, Diagnose);
7566   }
7567
7568   return false;
7569 }
7570
7571 /// Perform lookup for a special member of the specified kind, and determine
7572 /// whether it is trivial. If the triviality can be determined without the
7573 /// lookup, skip it. This is intended for use when determining whether a
7574 /// special member of a containing object is trivial, and thus does not ever
7575 /// perform overload resolution for default constructors.
7576 ///
7577 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
7578 /// member that was most likely to be intended to be trivial, if any.
7579 ///
7580 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
7581 /// determine whether the special member is trivial.
7582 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
7583                                      Sema::CXXSpecialMember CSM, unsigned Quals,
7584                                      bool ConstRHS,
7585                                      Sema::TrivialABIHandling TAH,
7586                                      CXXMethodDecl **Selected) {
7587   if (Selected)
7588     *Selected = nullptr;
7589
7590   switch (CSM) {
7591   case Sema::CXXInvalid:
7592     llvm_unreachable("not a special member");
7593
7594   case Sema::CXXDefaultConstructor:
7595     // C++11 [class.ctor]p5:
7596     //   A default constructor is trivial if:
7597     //    - all the [direct subobjects] have trivial default constructors
7598     //
7599     // Note, no overload resolution is performed in this case.
7600     if (RD->hasTrivialDefaultConstructor())
7601       return true;
7602
7603     if (Selected) {
7604       // If there's a default constructor which could have been trivial, dig it
7605       // out. Otherwise, if there's any user-provided default constructor, point
7606       // to that as an example of why there's not a trivial one.
7607       CXXConstructorDecl *DefCtor = nullptr;
7608       if (RD->needsImplicitDefaultConstructor())
7609         S.DeclareImplicitDefaultConstructor(RD);
7610       for (auto *CI : RD->ctors()) {
7611         if (!CI->isDefaultConstructor())
7612           continue;
7613         DefCtor = CI;
7614         if (!DefCtor->isUserProvided())
7615           break;
7616       }
7617
7618       *Selected = DefCtor;
7619     }
7620
7621     return false;
7622
7623   case Sema::CXXDestructor:
7624     // C++11 [class.dtor]p5:
7625     //   A destructor is trivial if:
7626     //    - all the direct [subobjects] have trivial destructors
7627     if (RD->hasTrivialDestructor() ||
7628         (TAH == Sema::TAH_ConsiderTrivialABI &&
7629          RD->hasTrivialDestructorForCall()))
7630       return true;
7631
7632     if (Selected) {
7633       if (RD->needsImplicitDestructor())
7634         S.DeclareImplicitDestructor(RD);
7635       *Selected = RD->getDestructor();
7636     }
7637
7638     return false;
7639
7640   case Sema::CXXCopyConstructor:
7641     // C++11 [class.copy]p12:
7642     //   A copy constructor is trivial if:
7643     //    - the constructor selected to copy each direct [subobject] is trivial
7644     if (RD->hasTrivialCopyConstructor() ||
7645         (TAH == Sema::TAH_ConsiderTrivialABI &&
7646          RD->hasTrivialCopyConstructorForCall())) {
7647       if (Quals == Qualifiers::Const)
7648         // We must either select the trivial copy constructor or reach an
7649         // ambiguity; no need to actually perform overload resolution.
7650         return true;
7651     } else if (!Selected) {
7652       return false;
7653     }
7654     // In C++98, we are not supposed to perform overload resolution here, but we
7655     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
7656     // cases like B as having a non-trivial copy constructor:
7657     //   struct A { template<typename T> A(T&); };
7658     //   struct B { mutable A a; };
7659     goto NeedOverloadResolution;
7660
7661   case Sema::CXXCopyAssignment:
7662     // C++11 [class.copy]p25:
7663     //   A copy assignment operator is trivial if:
7664     //    - the assignment operator selected to copy each direct [subobject] is
7665     //      trivial
7666     if (RD->hasTrivialCopyAssignment()) {
7667       if (Quals == Qualifiers::Const)
7668         return true;
7669     } else if (!Selected) {
7670       return false;
7671     }
7672     // In C++98, we are not supposed to perform overload resolution here, but we
7673     // treat that as a language defect.
7674     goto NeedOverloadResolution;
7675
7676   case Sema::CXXMoveConstructor:
7677   case Sema::CXXMoveAssignment:
7678   NeedOverloadResolution:
7679     Sema::SpecialMemberOverloadResult SMOR =
7680         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
7681
7682     // The standard doesn't describe how to behave if the lookup is ambiguous.
7683     // We treat it as not making the member non-trivial, just like the standard
7684     // mandates for the default constructor. This should rarely matter, because
7685     // the member will also be deleted.
7686     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
7687       return true;
7688
7689     if (!SMOR.getMethod()) {
7690       assert(SMOR.getKind() ==
7691              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
7692       return false;
7693     }
7694
7695     // We deliberately don't check if we found a deleted special member. We're
7696     // not supposed to!
7697     if (Selected)
7698       *Selected = SMOR.getMethod();
7699
7700     if (TAH == Sema::TAH_ConsiderTrivialABI &&
7701         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
7702       return SMOR.getMethod()->isTrivialForCall();
7703     return SMOR.getMethod()->isTrivial();
7704   }
7705
7706   llvm_unreachable("unknown special method kind");
7707 }
7708
7709 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
7710   for (auto *CI : RD->ctors())
7711     if (!CI->isImplicit())
7712       return CI;
7713
7714   // Look for constructor templates.
7715   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
7716   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
7717     if (CXXConstructorDecl *CD =
7718           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
7719       return CD;
7720   }
7721
7722   return nullptr;
7723 }
7724
7725 /// The kind of subobject we are checking for triviality. The values of this
7726 /// enumeration are used in diagnostics.
7727 enum TrivialSubobjectKind {
7728   /// The subobject is a base class.
7729   TSK_BaseClass,
7730   /// The subobject is a non-static data member.
7731   TSK_Field,
7732   /// The object is actually the complete object.
7733   TSK_CompleteObject
7734 };
7735
7736 /// Check whether the special member selected for a given type would be trivial.
7737 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
7738                                       QualType SubType, bool ConstRHS,
7739                                       Sema::CXXSpecialMember CSM,
7740                                       TrivialSubobjectKind Kind,
7741                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
7742   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
7743   if (!SubRD)
7744     return true;
7745
7746   CXXMethodDecl *Selected;
7747   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
7748                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
7749     return true;
7750
7751   if (Diagnose) {
7752     if (ConstRHS)
7753       SubType.addConst();
7754
7755     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
7756       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
7757         << Kind << SubType.getUnqualifiedType();
7758       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
7759         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
7760     } else if (!Selected)
7761       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
7762         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
7763     else if (Selected->isUserProvided()) {
7764       if (Kind == TSK_CompleteObject)
7765         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
7766           << Kind << SubType.getUnqualifiedType() << CSM;
7767       else {
7768         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
7769           << Kind << SubType.getUnqualifiedType() << CSM;
7770         S.Diag(Selected->getLocation(), diag::note_declared_at);
7771       }
7772     } else {
7773       if (Kind != TSK_CompleteObject)
7774         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
7775           << Kind << SubType.getUnqualifiedType() << CSM;
7776
7777       // Explain why the defaulted or deleted special member isn't trivial.
7778       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
7779                                Diagnose);
7780     }
7781   }
7782
7783   return false;
7784 }
7785
7786 /// Check whether the members of a class type allow a special member to be
7787 /// trivial.
7788 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7789                                      Sema::CXXSpecialMember CSM,
7790                                      bool ConstArg,
7791                                      Sema::TrivialABIHandling TAH,
7792                                      bool Diagnose) {
7793   for (const auto *FI : RD->fields()) {
7794     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7795       continue;
7796
7797     QualType FieldType = S.Context.getBaseElementType(FI->getType());
7798
7799     // Pretend anonymous struct or union members are members of this class.
7800     if (FI->isAnonymousStructOrUnion()) {
7801       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7802                                     CSM, ConstArg, TAH, Diagnose))
7803         return false;
7804       continue;
7805     }
7806
7807     // C++11 [class.ctor]p5:
7808     //   A default constructor is trivial if [...]
7809     //    -- no non-static data member of its class has a
7810     //       brace-or-equal-initializer
7811     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7812       if (Diagnose)
7813         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
7814       return false;
7815     }
7816
7817     // Objective C ARC 4.3.5:
7818     //   [...] nontrivally ownership-qualified types are [...] not trivially
7819     //   default constructible, copy constructible, move constructible, copy
7820     //   assignable, move assignable, or destructible [...]
7821     if (FieldType.hasNonTrivialObjCLifetime()) {
7822       if (Diagnose)
7823         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7824           << RD << FieldType.getObjCLifetime();
7825       return false;
7826     }
7827
7828     bool ConstRHS = ConstArg && !FI->isMutable();
7829     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7830                                    CSM, TSK_Field, TAH, Diagnose))
7831       return false;
7832   }
7833
7834   return true;
7835 }
7836
7837 /// Diagnose why the specified class does not have a trivial special member of
7838 /// the given kind.
7839 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7840   QualType Ty = Context.getRecordType(RD);
7841
7842   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7843   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
7844                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
7845                             /*Diagnose*/true);
7846 }
7847
7848 /// Determine whether a defaulted or deleted special member function is trivial,
7849 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7850 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7851 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7852                                   TrivialABIHandling TAH, bool Diagnose) {
7853   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7854
7855   CXXRecordDecl *RD = MD->getParent();
7856
7857   bool ConstArg = false;
7858
7859   // C++11 [class.copy]p12, p25: [DR1593]
7860   //   A [special member] is trivial if [...] its parameter-type-list is
7861   //   equivalent to the parameter-type-list of an implicit declaration [...]
7862   switch (CSM) {
7863   case CXXDefaultConstructor:
7864   case CXXDestructor:
7865     // Trivial default constructors and destructors cannot have parameters.
7866     break;
7867
7868   case CXXCopyConstructor:
7869   case CXXCopyAssignment: {
7870     // Trivial copy operations always have const, non-volatile parameter types.
7871     ConstArg = true;
7872     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7873     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7874     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7875       if (Diagnose)
7876         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7877           << Param0->getSourceRange() << Param0->getType()
7878           << Context.getLValueReferenceType(
7879                Context.getRecordType(RD).withConst());
7880       return false;
7881     }
7882     break;
7883   }
7884
7885   case CXXMoveConstructor:
7886   case CXXMoveAssignment: {
7887     // Trivial move operations always have non-cv-qualified parameters.
7888     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7889     const RValueReferenceType *RT =
7890       Param0->getType()->getAs<RValueReferenceType>();
7891     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7892       if (Diagnose)
7893         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7894           << Param0->getSourceRange() << Param0->getType()
7895           << Context.getRValueReferenceType(Context.getRecordType(RD));
7896       return false;
7897     }
7898     break;
7899   }
7900
7901   case CXXInvalid:
7902     llvm_unreachable("not a special member");
7903   }
7904
7905   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7906     if (Diagnose)
7907       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7908            diag::note_nontrivial_default_arg)
7909         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7910     return false;
7911   }
7912   if (MD->isVariadic()) {
7913     if (Diagnose)
7914       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7915     return false;
7916   }
7917
7918   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7919   //   A copy/move [constructor or assignment operator] is trivial if
7920   //    -- the [member] selected to copy/move each direct base class subobject
7921   //       is trivial
7922   //
7923   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7924   //   A [default constructor or destructor] is trivial if
7925   //    -- all the direct base classes have trivial [default constructors or
7926   //       destructors]
7927   for (const auto &BI : RD->bases())
7928     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
7929                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
7930       return false;
7931
7932   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7933   //   A copy/move [constructor or assignment operator] for a class X is
7934   //   trivial if
7935   //    -- for each non-static data member of X that is of class type (or array
7936   //       thereof), the constructor selected to copy/move that member is
7937   //       trivial
7938   //
7939   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7940   //   A [default constructor or destructor] is trivial if
7941   //    -- for all of the non-static data members of its class that are of class
7942   //       type (or array thereof), each such class has a trivial [default
7943   //       constructor or destructor]
7944   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
7945     return false;
7946
7947   // C++11 [class.dtor]p5:
7948   //   A destructor is trivial if [...]
7949   //    -- the destructor is not virtual
7950   if (CSM == CXXDestructor && MD->isVirtual()) {
7951     if (Diagnose)
7952       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7953     return false;
7954   }
7955
7956   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7957   //   A [special member] for class X is trivial if [...]
7958   //    -- class X has no virtual functions and no virtual base classes
7959   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7960     if (!Diagnose)
7961       return false;
7962
7963     if (RD->getNumVBases()) {
7964       // Check for virtual bases. We already know that the corresponding
7965       // member in all bases is trivial, so vbases must all be direct.
7966       CXXBaseSpecifier &BS = *RD->vbases_begin();
7967       assert(BS.isVirtual());
7968       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
7969       return false;
7970     }
7971
7972     // Must have a virtual method.
7973     for (const auto *MI : RD->methods()) {
7974       if (MI->isVirtual()) {
7975         SourceLocation MLoc = MI->getBeginLoc();
7976         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7977         return false;
7978       }
7979     }
7980
7981     llvm_unreachable("dynamic class with no vbases and no virtual functions");
7982   }
7983
7984   // Looks like it's trivial!
7985   return true;
7986 }
7987
7988 namespace {
7989 struct FindHiddenVirtualMethod {
7990   Sema *S;
7991   CXXMethodDecl *Method;
7992   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7993   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7994
7995 private:
7996   /// Check whether any most overridden method from MD in Methods
7997   static bool CheckMostOverridenMethods(
7998       const CXXMethodDecl *MD,
7999       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
8000     if (MD->size_overridden_methods() == 0)
8001       return Methods.count(MD->getCanonicalDecl());
8002     for (const CXXMethodDecl *O : MD->overridden_methods())
8003       if (CheckMostOverridenMethods(O, Methods))
8004         return true;
8005     return false;
8006   }
8007
8008 public:
8009   /// Member lookup function that determines whether a given C++
8010   /// method overloads virtual methods in a base class without overriding any,
8011   /// to be used with CXXRecordDecl::lookupInBases().
8012   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8013     RecordDecl *BaseRecord =
8014         Specifier->getType()->castAs<RecordType>()->getDecl();
8015
8016     DeclarationName Name = Method->getDeclName();
8017     assert(Name.getNameKind() == DeclarationName::Identifier);
8018
8019     bool foundSameNameMethod = false;
8020     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
8021     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
8022          Path.Decls = Path.Decls.slice(1)) {
8023       NamedDecl *D = Path.Decls.front();
8024       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
8025         MD = MD->getCanonicalDecl();
8026         foundSameNameMethod = true;
8027         // Interested only in hidden virtual methods.
8028         if (!MD->isVirtual())
8029           continue;
8030         // If the method we are checking overrides a method from its base
8031         // don't warn about the other overloaded methods. Clang deviates from
8032         // GCC by only diagnosing overloads of inherited virtual functions that
8033         // do not override any other virtual functions in the base. GCC's
8034         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
8035         // function from a base class. These cases may be better served by a
8036         // warning (not specific to virtual functions) on call sites when the
8037         // call would select a different function from the base class, were it
8038         // visible.
8039         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
8040         if (!S->IsOverload(Method, MD, false))
8041           return true;
8042         // Collect the overload only if its hidden.
8043         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
8044           overloadedMethods.push_back(MD);
8045       }
8046     }
8047
8048     if (foundSameNameMethod)
8049       OverloadedMethods.append(overloadedMethods.begin(),
8050                                overloadedMethods.end());
8051     return foundSameNameMethod;
8052   }
8053 };
8054 } // end anonymous namespace
8055
8056 /// Add the most overriden methods from MD to Methods
8057 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
8058                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
8059   if (MD->size_overridden_methods() == 0)
8060     Methods.insert(MD->getCanonicalDecl());
8061   else
8062     for (const CXXMethodDecl *O : MD->overridden_methods())
8063       AddMostOverridenMethods(O, Methods);
8064 }
8065
8066 /// Check if a method overloads virtual methods in a base class without
8067 /// overriding any.
8068 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
8069                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
8070   if (!MD->getDeclName().isIdentifier())
8071     return;
8072
8073   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
8074                      /*bool RecordPaths=*/false,
8075                      /*bool DetectVirtual=*/false);
8076   FindHiddenVirtualMethod FHVM;
8077   FHVM.Method = MD;
8078   FHVM.S = this;
8079
8080   // Keep the base methods that were overridden or introduced in the subclass
8081   // by 'using' in a set. A base method not in this set is hidden.
8082   CXXRecordDecl *DC = MD->getParent();
8083   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
8084   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
8085     NamedDecl *ND = *I;
8086     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
8087       ND = shad->getTargetDecl();
8088     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
8089       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
8090   }
8091
8092   if (DC->lookupInBases(FHVM, Paths))
8093     OverloadedMethods = FHVM.OverloadedMethods;
8094 }
8095
8096 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
8097                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
8098   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
8099     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
8100     PartialDiagnostic PD = PDiag(
8101          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
8102     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
8103     Diag(overloadedMD->getLocation(), PD);
8104   }
8105 }
8106
8107 /// Diagnose methods which overload virtual methods in a base class
8108 /// without overriding any.
8109 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
8110   if (MD->isInvalidDecl())
8111     return;
8112
8113   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
8114     return;
8115
8116   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
8117   FindHiddenVirtualMethods(MD, OverloadedMethods);
8118   if (!OverloadedMethods.empty()) {
8119     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
8120       << MD << (OverloadedMethods.size() > 1);
8121
8122     NoteHiddenVirtualMethods(MD, OverloadedMethods);
8123   }
8124 }
8125
8126 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
8127   auto PrintDiagAndRemoveAttr = [&]() {
8128     // No diagnostics if this is a template instantiation.
8129     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind()))
8130       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
8131            diag::ext_cannot_use_trivial_abi) << &RD;
8132     RD.dropAttr<TrivialABIAttr>();
8133   };
8134
8135   // Ill-formed if the struct has virtual functions.
8136   if (RD.isPolymorphic()) {
8137     PrintDiagAndRemoveAttr();
8138     return;
8139   }
8140
8141   for (const auto &B : RD.bases()) {
8142     // Ill-formed if the base class is non-trivial for the purpose of calls or a
8143     // virtual base.
8144     if ((!B.getType()->isDependentType() &&
8145          !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) ||
8146         B.isVirtual()) {
8147       PrintDiagAndRemoveAttr();
8148       return;
8149     }
8150   }
8151
8152   for (const auto *FD : RD.fields()) {
8153     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
8154     // non-trivial for the purpose of calls.
8155     QualType FT = FD->getType();
8156     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
8157       PrintDiagAndRemoveAttr();
8158       return;
8159     }
8160
8161     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
8162       if (!RT->isDependentType() &&
8163           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
8164         PrintDiagAndRemoveAttr();
8165         return;
8166       }
8167   }
8168 }
8169
8170 void Sema::ActOnFinishCXXMemberSpecification(
8171     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
8172     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
8173   if (!TagDecl)
8174     return;
8175
8176   AdjustDeclIfTemplate(TagDecl);
8177
8178   for (const ParsedAttr &AL : AttrList) {
8179     if (AL.getKind() != ParsedAttr::AT_Visibility)
8180       continue;
8181     AL.setInvalid();
8182     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
8183   }
8184
8185   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
8186               // strict aliasing violation!
8187               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
8188               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
8189
8190   CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl));
8191 }
8192
8193 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
8194 /// special functions, such as the default constructor, copy
8195 /// constructor, or destructor, to the given C++ class (C++
8196 /// [special]p1).  This routine can only be executed just before the
8197 /// definition of the class is complete.
8198 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
8199   if (ClassDecl->needsImplicitDefaultConstructor()) {
8200     ++getASTContext().NumImplicitDefaultConstructors;
8201
8202     if (ClassDecl->hasInheritedConstructor())
8203       DeclareImplicitDefaultConstructor(ClassDecl);
8204   }
8205
8206   if (ClassDecl->needsImplicitCopyConstructor()) {
8207     ++getASTContext().NumImplicitCopyConstructors;
8208
8209     // If the properties or semantics of the copy constructor couldn't be
8210     // determined while the class was being declared, force a declaration
8211     // of it now.
8212     if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
8213         ClassDecl->hasInheritedConstructor())
8214       DeclareImplicitCopyConstructor(ClassDecl);
8215     // For the MS ABI we need to know whether the copy ctor is deleted. A
8216     // prerequisite for deleting the implicit copy ctor is that the class has a
8217     // move ctor or move assignment that is either user-declared or whose
8218     // semantics are inherited from a subobject. FIXME: We should provide a more
8219     // direct way for CodeGen to ask whether the constructor was deleted.
8220     else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8221              (ClassDecl->hasUserDeclaredMoveConstructor() ||
8222               ClassDecl->needsOverloadResolutionForMoveConstructor() ||
8223               ClassDecl->hasUserDeclaredMoveAssignment() ||
8224               ClassDecl->needsOverloadResolutionForMoveAssignment()))
8225       DeclareImplicitCopyConstructor(ClassDecl);
8226   }
8227
8228   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
8229     ++getASTContext().NumImplicitMoveConstructors;
8230
8231     if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
8232         ClassDecl->hasInheritedConstructor())
8233       DeclareImplicitMoveConstructor(ClassDecl);
8234   }
8235
8236   if (ClassDecl->needsImplicitCopyAssignment()) {
8237     ++getASTContext().NumImplicitCopyAssignmentOperators;
8238
8239     // If we have a dynamic class, then the copy assignment operator may be
8240     // virtual, so we have to declare it immediately. This ensures that, e.g.,
8241     // it shows up in the right place in the vtable and that we diagnose
8242     // problems with the implicit exception specification.
8243     if (ClassDecl->isDynamicClass() ||
8244         ClassDecl->needsOverloadResolutionForCopyAssignment() ||
8245         ClassDecl->hasInheritedAssignment())
8246       DeclareImplicitCopyAssignment(ClassDecl);
8247   }
8248
8249   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
8250     ++getASTContext().NumImplicitMoveAssignmentOperators;
8251
8252     // Likewise for the move assignment operator.
8253     if (ClassDecl->isDynamicClass() ||
8254         ClassDecl->needsOverloadResolutionForMoveAssignment() ||
8255         ClassDecl->hasInheritedAssignment())
8256       DeclareImplicitMoveAssignment(ClassDecl);
8257   }
8258
8259   if (ClassDecl->needsImplicitDestructor()) {
8260     ++getASTContext().NumImplicitDestructors;
8261
8262     // If we have a dynamic class, then the destructor may be virtual, so we
8263     // have to declare the destructor immediately. This ensures that, e.g., it
8264     // shows up in the right place in the vtable and that we diagnose problems
8265     // with the implicit exception specification.
8266     if (ClassDecl->isDynamicClass() ||
8267         ClassDecl->needsOverloadResolutionForDestructor())
8268       DeclareImplicitDestructor(ClassDecl);
8269   }
8270 }
8271
8272 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
8273   if (!D)
8274     return 0;
8275
8276   // The order of template parameters is not important here. All names
8277   // get added to the same scope.
8278   SmallVector<TemplateParameterList *, 4> ParameterLists;
8279
8280   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
8281     D = TD->getTemplatedDecl();
8282
8283   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
8284     ParameterLists.push_back(PSD->getTemplateParameters());
8285
8286   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
8287     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
8288       ParameterLists.push_back(DD->getTemplateParameterList(i));
8289
8290     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8291       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
8292         ParameterLists.push_back(FTD->getTemplateParameters());
8293     }
8294   }
8295
8296   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
8297     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
8298       ParameterLists.push_back(TD->getTemplateParameterList(i));
8299
8300     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
8301       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
8302         ParameterLists.push_back(CTD->getTemplateParameters());
8303     }
8304   }
8305
8306   unsigned Count = 0;
8307   for (TemplateParameterList *Params : ParameterLists) {
8308     if (Params->size() > 0)
8309       // Ignore explicit specializations; they don't contribute to the template
8310       // depth.
8311       ++Count;
8312     for (NamedDecl *Param : *Params) {
8313       if (Param->getDeclName()) {
8314         S->AddDecl(Param);
8315         IdResolver.AddDecl(Param);
8316       }
8317     }
8318   }
8319
8320   return Count;
8321 }
8322
8323 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
8324   if (!RecordD) return;
8325   AdjustDeclIfTemplate(RecordD);
8326   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
8327   PushDeclContext(S, Record);
8328 }
8329
8330 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
8331   if (!RecordD) return;
8332   PopDeclContext();
8333 }
8334
8335 /// This is used to implement the constant expression evaluation part of the
8336 /// attribute enable_if extension. There is nothing in standard C++ which would
8337 /// require reentering parameters.
8338 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
8339   if (!Param)
8340     return;
8341
8342   S->AddDecl(Param);
8343   if (Param->getDeclName())
8344     IdResolver.AddDecl(Param);
8345 }
8346
8347 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
8348 /// parsing a top-level (non-nested) C++ class, and we are now
8349 /// parsing those parts of the given Method declaration that could
8350 /// not be parsed earlier (C++ [class.mem]p2), such as default
8351 /// arguments. This action should enter the scope of the given
8352 /// Method declaration as if we had just parsed the qualified method
8353 /// name. However, it should not bring the parameters into scope;
8354 /// that will be performed by ActOnDelayedCXXMethodParameter.
8355 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8356 }
8357
8358 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
8359 /// C++ method declaration. We're (re-)introducing the given
8360 /// function parameter into scope for use in parsing later parts of
8361 /// the method declaration. For example, we could see an
8362 /// ActOnParamDefaultArgument event for this parameter.
8363 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
8364   if (!ParamD)
8365     return;
8366
8367   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
8368
8369   // If this parameter has an unparsed default argument, clear it out
8370   // to make way for the parsed default argument.
8371   if (Param->hasUnparsedDefaultArg())
8372     Param->setDefaultArg(nullptr);
8373
8374   S->AddDecl(Param);
8375   if (Param->getDeclName())
8376     IdResolver.AddDecl(Param);
8377 }
8378
8379 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
8380 /// processing the delayed method declaration for Method. The method
8381 /// declaration is now considered finished. There may be a separate
8382 /// ActOnStartOfFunctionDef action later (not necessarily
8383 /// immediately!) for this method, if it was also defined inside the
8384 /// class body.
8385 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8386   if (!MethodD)
8387     return;
8388
8389   AdjustDeclIfTemplate(MethodD);
8390
8391   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
8392
8393   // Now that we have our default arguments, check the constructor
8394   // again. It could produce additional diagnostics or affect whether
8395   // the class has implicitly-declared destructors, among other
8396   // things.
8397   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
8398     CheckConstructor(Constructor);
8399
8400   // Check the default arguments, which we may have added.
8401   if (!Method->isInvalidDecl())
8402     CheckCXXDefaultArguments(Method);
8403 }
8404
8405 // Emit the given diagnostic for each non-address-space qualifier.
8406 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
8407 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
8408   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8409   if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
8410     bool DiagOccured = false;
8411     FTI.MethodQualifiers->forEachQualifier(
8412         [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
8413                                    SourceLocation SL) {
8414           // This diagnostic should be emitted on any qualifier except an addr
8415           // space qualifier. However, forEachQualifier currently doesn't visit
8416           // addr space qualifiers, so there's no way to write this condition
8417           // right now; we just diagnose on everything.
8418           S.Diag(SL, DiagID) << QualName << SourceRange(SL);
8419           DiagOccured = true;
8420         });
8421     if (DiagOccured)
8422       D.setInvalidType();
8423   }
8424 }
8425
8426 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
8427 /// the well-formedness of the constructor declarator @p D with type @p
8428 /// R. If there are any errors in the declarator, this routine will
8429 /// emit diagnostics and set the invalid bit to true.  In any case, the type
8430 /// will be updated to reflect a well-formed type for the constructor and
8431 /// returned.
8432 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
8433                                           StorageClass &SC) {
8434   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8435
8436   // C++ [class.ctor]p3:
8437   //   A constructor shall not be virtual (10.3) or static (9.4). A
8438   //   constructor can be invoked for a const, volatile or const
8439   //   volatile object. A constructor shall not be declared const,
8440   //   volatile, or const volatile (9.3.2).
8441   if (isVirtual) {
8442     if (!D.isInvalidType())
8443       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8444         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
8445         << SourceRange(D.getIdentifierLoc());
8446     D.setInvalidType();
8447   }
8448   if (SC == SC_Static) {
8449     if (!D.isInvalidType())
8450       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8451         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8452         << SourceRange(D.getIdentifierLoc());
8453     D.setInvalidType();
8454     SC = SC_None;
8455   }
8456
8457   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8458     diagnoseIgnoredQualifiers(
8459         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
8460         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
8461         D.getDeclSpec().getRestrictSpecLoc(),
8462         D.getDeclSpec().getAtomicSpecLoc());
8463     D.setInvalidType();
8464   }
8465
8466   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
8467
8468   // C++0x [class.ctor]p4:
8469   //   A constructor shall not be declared with a ref-qualifier.
8470   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8471   if (FTI.hasRefQualifier()) {
8472     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
8473       << FTI.RefQualifierIsLValueRef
8474       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8475     D.setInvalidType();
8476   }
8477
8478   // Rebuild the function type "R" without any type qualifiers (in
8479   // case any of the errors above fired) and with "void" as the
8480   // return type, since constructors don't have return types.
8481   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8482   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
8483     return R;
8484
8485   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8486   EPI.TypeQuals = Qualifiers();
8487   EPI.RefQualifier = RQ_None;
8488
8489   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
8490 }
8491
8492 /// CheckConstructor - Checks a fully-formed constructor for
8493 /// well-formedness, issuing any diagnostics required. Returns true if
8494 /// the constructor declarator is invalid.
8495 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
8496   CXXRecordDecl *ClassDecl
8497     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
8498   if (!ClassDecl)
8499     return Constructor->setInvalidDecl();
8500
8501   // C++ [class.copy]p3:
8502   //   A declaration of a constructor for a class X is ill-formed if
8503   //   its first parameter is of type (optionally cv-qualified) X and
8504   //   either there are no other parameters or else all other
8505   //   parameters have default arguments.
8506   if (!Constructor->isInvalidDecl() &&
8507       ((Constructor->getNumParams() == 1) ||
8508        (Constructor->getNumParams() > 1 &&
8509         Constructor->getParamDecl(1)->hasDefaultArg())) &&
8510       Constructor->getTemplateSpecializationKind()
8511                                               != TSK_ImplicitInstantiation) {
8512     QualType ParamType = Constructor->getParamDecl(0)->getType();
8513     QualType ClassTy = Context.getTagDeclType(ClassDecl);
8514     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
8515       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
8516       const char *ConstRef
8517         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
8518                                                         : " const &";
8519       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
8520         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
8521
8522       // FIXME: Rather that making the constructor invalid, we should endeavor
8523       // to fix the type.
8524       Constructor->setInvalidDecl();
8525     }
8526   }
8527 }
8528
8529 /// CheckDestructor - Checks a fully-formed destructor definition for
8530 /// well-formedness, issuing any diagnostics required.  Returns true
8531 /// on error.
8532 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
8533   CXXRecordDecl *RD = Destructor->getParent();
8534
8535   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
8536     SourceLocation Loc;
8537
8538     if (!Destructor->isImplicit())
8539       Loc = Destructor->getLocation();
8540     else
8541       Loc = RD->getLocation();
8542
8543     // If we have a virtual destructor, look up the deallocation function
8544     if (FunctionDecl *OperatorDelete =
8545             FindDeallocationFunctionForDestructor(Loc, RD)) {
8546       Expr *ThisArg = nullptr;
8547
8548       // If the notional 'delete this' expression requires a non-trivial
8549       // conversion from 'this' to the type of a destroying operator delete's
8550       // first parameter, perform that conversion now.
8551       if (OperatorDelete->isDestroyingOperatorDelete()) {
8552         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
8553         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
8554           // C++ [class.dtor]p13:
8555           //   ... as if for the expression 'delete this' appearing in a
8556           //   non-virtual destructor of the destructor's class.
8557           ContextRAII SwitchContext(*this, Destructor);
8558           ExprResult This =
8559               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
8560           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
8561           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
8562           if (This.isInvalid()) {
8563             // FIXME: Register this as a context note so that it comes out
8564             // in the right order.
8565             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
8566             return true;
8567           }
8568           ThisArg = This.get();
8569         }
8570       }
8571
8572       DiagnoseUseOfDecl(OperatorDelete, Loc);
8573       MarkFunctionReferenced(Loc, OperatorDelete);
8574       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
8575     }
8576   }
8577
8578   return false;
8579 }
8580
8581 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
8582 /// the well-formednes of the destructor declarator @p D with type @p
8583 /// R. If there are any errors in the declarator, this routine will
8584 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
8585 /// will be updated to reflect a well-formed type for the destructor and
8586 /// returned.
8587 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
8588                                          StorageClass& SC) {
8589   // C++ [class.dtor]p1:
8590   //   [...] A typedef-name that names a class is a class-name
8591   //   (7.1.3); however, a typedef-name that names a class shall not
8592   //   be used as the identifier in the declarator for a destructor
8593   //   declaration.
8594   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
8595   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
8596     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8597       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
8598   else if (const TemplateSpecializationType *TST =
8599              DeclaratorType->getAs<TemplateSpecializationType>())
8600     if (TST->isTypeAlias())
8601       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8602         << DeclaratorType << 1;
8603
8604   // C++ [class.dtor]p2:
8605   //   A destructor is used to destroy objects of its class type. A
8606   //   destructor takes no parameters, and no return type can be
8607   //   specified for it (not even void). The address of a destructor
8608   //   shall not be taken. A destructor shall not be static. A
8609   //   destructor can be invoked for a const, volatile or const
8610   //   volatile object. A destructor shall not be declared const,
8611   //   volatile or const volatile (9.3.2).
8612   if (SC == SC_Static) {
8613     if (!D.isInvalidType())
8614       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
8615         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8616         << SourceRange(D.getIdentifierLoc())
8617         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8618
8619     SC = SC_None;
8620   }
8621   if (!D.isInvalidType()) {
8622     // Destructors don't have return types, but the parser will
8623     // happily parse something like:
8624     //
8625     //   class X {
8626     //     float ~X();
8627     //   };
8628     //
8629     // The return type will be eliminated later.
8630     if (D.getDeclSpec().hasTypeSpecifier())
8631       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
8632         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8633         << SourceRange(D.getIdentifierLoc());
8634     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8635       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
8636                                 SourceLocation(),
8637                                 D.getDeclSpec().getConstSpecLoc(),
8638                                 D.getDeclSpec().getVolatileSpecLoc(),
8639                                 D.getDeclSpec().getRestrictSpecLoc(),
8640                                 D.getDeclSpec().getAtomicSpecLoc());
8641       D.setInvalidType();
8642     }
8643   }
8644
8645   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
8646
8647   // C++0x [class.dtor]p2:
8648   //   A destructor shall not be declared with a ref-qualifier.
8649   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8650   if (FTI.hasRefQualifier()) {
8651     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
8652       << FTI.RefQualifierIsLValueRef
8653       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8654     D.setInvalidType();
8655   }
8656
8657   // Make sure we don't have any parameters.
8658   if (FTIHasNonVoidParameters(FTI)) {
8659     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
8660
8661     // Delete the parameters.
8662     FTI.freeParams();
8663     D.setInvalidType();
8664   }
8665
8666   // Make sure the destructor isn't variadic.
8667   if (FTI.isVariadic) {
8668     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
8669     D.setInvalidType();
8670   }
8671
8672   // Rebuild the function type "R" without any type qualifiers or
8673   // parameters (in case any of the errors above fired) and with
8674   // "void" as the return type, since destructors don't have return
8675   // types.
8676   if (!D.isInvalidType())
8677     return R;
8678
8679   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8680   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8681   EPI.Variadic = false;
8682   EPI.TypeQuals = Qualifiers();
8683   EPI.RefQualifier = RQ_None;
8684   return Context.getFunctionType(Context.VoidTy, None, EPI);
8685 }
8686
8687 static void extendLeft(SourceRange &R, SourceRange Before) {
8688   if (Before.isInvalid())
8689     return;
8690   R.setBegin(Before.getBegin());
8691   if (R.getEnd().isInvalid())
8692     R.setEnd(Before.getEnd());
8693 }
8694
8695 static void extendRight(SourceRange &R, SourceRange After) {
8696   if (After.isInvalid())
8697     return;
8698   if (R.getBegin().isInvalid())
8699     R.setBegin(After.getBegin());
8700   R.setEnd(After.getEnd());
8701 }
8702
8703 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
8704 /// well-formednes of the conversion function declarator @p D with
8705 /// type @p R. If there are any errors in the declarator, this routine
8706 /// will emit diagnostics and return true. Otherwise, it will return
8707 /// false. Either way, the type @p R will be updated to reflect a
8708 /// well-formed type for the conversion operator.
8709 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
8710                                      StorageClass& SC) {
8711   // C++ [class.conv.fct]p1:
8712   //   Neither parameter types nor return type can be specified. The
8713   //   type of a conversion function (8.3.5) is "function taking no
8714   //   parameter returning conversion-type-id."
8715   if (SC == SC_Static) {
8716     if (!D.isInvalidType())
8717       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
8718         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8719         << D.getName().getSourceRange();
8720     D.setInvalidType();
8721     SC = SC_None;
8722   }
8723
8724   TypeSourceInfo *ConvTSI = nullptr;
8725   QualType ConvType =
8726       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
8727
8728   const DeclSpec &DS = D.getDeclSpec();
8729   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
8730     // Conversion functions don't have return types, but the parser will
8731     // happily parse something like:
8732     //
8733     //   class X {
8734     //     float operator bool();
8735     //   };
8736     //
8737     // The return type will be changed later anyway.
8738     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
8739       << SourceRange(DS.getTypeSpecTypeLoc())
8740       << SourceRange(D.getIdentifierLoc());
8741     D.setInvalidType();
8742   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
8743     // It's also plausible that the user writes type qualifiers in the wrong
8744     // place, such as:
8745     //   struct S { const operator int(); };
8746     // FIXME: we could provide a fixit to move the qualifiers onto the
8747     // conversion type.
8748     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
8749         << SourceRange(D.getIdentifierLoc()) << 0;
8750     D.setInvalidType();
8751   }
8752
8753   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8754
8755   // Make sure we don't have any parameters.
8756   if (Proto->getNumParams() > 0) {
8757     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
8758
8759     // Delete the parameters.
8760     D.getFunctionTypeInfo().freeParams();
8761     D.setInvalidType();
8762   } else if (Proto->isVariadic()) {
8763     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
8764     D.setInvalidType();
8765   }
8766
8767   // Diagnose "&operator bool()" and other such nonsense.  This
8768   // is actually a gcc extension which we don't support.
8769   if (Proto->getReturnType() != ConvType) {
8770     bool NeedsTypedef = false;
8771     SourceRange Before, After;
8772
8773     // Walk the chunks and extract information on them for our diagnostic.
8774     bool PastFunctionChunk = false;
8775     for (auto &Chunk : D.type_objects()) {
8776       switch (Chunk.Kind) {
8777       case DeclaratorChunk::Function:
8778         if (!PastFunctionChunk) {
8779           if (Chunk.Fun.HasTrailingReturnType) {
8780             TypeSourceInfo *TRT = nullptr;
8781             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
8782             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
8783           }
8784           PastFunctionChunk = true;
8785           break;
8786         }
8787         LLVM_FALLTHROUGH;
8788       case DeclaratorChunk::Array:
8789         NeedsTypedef = true;
8790         extendRight(After, Chunk.getSourceRange());
8791         break;
8792
8793       case DeclaratorChunk::Pointer:
8794       case DeclaratorChunk::BlockPointer:
8795       case DeclaratorChunk::Reference:
8796       case DeclaratorChunk::MemberPointer:
8797       case DeclaratorChunk::Pipe:
8798         extendLeft(Before, Chunk.getSourceRange());
8799         break;
8800
8801       case DeclaratorChunk::Paren:
8802         extendLeft(Before, Chunk.Loc);
8803         extendRight(After, Chunk.EndLoc);
8804         break;
8805       }
8806     }
8807
8808     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
8809                          After.isValid()  ? After.getBegin() :
8810                                             D.getIdentifierLoc();
8811     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
8812     DB << Before << After;
8813
8814     if (!NeedsTypedef) {
8815       DB << /*don't need a typedef*/0;
8816
8817       // If we can provide a correct fix-it hint, do so.
8818       if (After.isInvalid() && ConvTSI) {
8819         SourceLocation InsertLoc =
8820             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
8821         DB << FixItHint::CreateInsertion(InsertLoc, " ")
8822            << FixItHint::CreateInsertionFromRange(
8823                   InsertLoc, CharSourceRange::getTokenRange(Before))
8824            << FixItHint::CreateRemoval(Before);
8825       }
8826     } else if (!Proto->getReturnType()->isDependentType()) {
8827       DB << /*typedef*/1 << Proto->getReturnType();
8828     } else if (getLangOpts().CPlusPlus11) {
8829       DB << /*alias template*/2 << Proto->getReturnType();
8830     } else {
8831       DB << /*might not be fixable*/3;
8832     }
8833
8834     // Recover by incorporating the other type chunks into the result type.
8835     // Note, this does *not* change the name of the function. This is compatible
8836     // with the GCC extension:
8837     //   struct S { &operator int(); } s;
8838     //   int &r = s.operator int(); // ok in GCC
8839     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
8840     ConvType = Proto->getReturnType();
8841   }
8842
8843   // C++ [class.conv.fct]p4:
8844   //   The conversion-type-id shall not represent a function type nor
8845   //   an array type.
8846   if (ConvType->isArrayType()) {
8847     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
8848     ConvType = Context.getPointerType(ConvType);
8849     D.setInvalidType();
8850   } else if (ConvType->isFunctionType()) {
8851     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
8852     ConvType = Context.getPointerType(ConvType);
8853     D.setInvalidType();
8854   }
8855
8856   // Rebuild the function type "R" without any parameters (in case any
8857   // of the errors above fired) and with the conversion type as the
8858   // return type.
8859   if (D.isInvalidType())
8860     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
8861
8862   // C++0x explicit conversion operators.
8863   if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus2a)
8864     Diag(DS.getExplicitSpecLoc(),
8865          getLangOpts().CPlusPlus11
8866              ? diag::warn_cxx98_compat_explicit_conversion_functions
8867              : diag::ext_explicit_conversion_functions)
8868         << SourceRange(DS.getExplicitSpecRange());
8869 }
8870
8871 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8872 /// the declaration of the given C++ conversion function. This routine
8873 /// is responsible for recording the conversion function in the C++
8874 /// class, if possible.
8875 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
8876   assert(Conversion && "Expected to receive a conversion function declaration");
8877
8878   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
8879
8880   // Make sure we aren't redeclaring the conversion function.
8881   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
8882
8883   // C++ [class.conv.fct]p1:
8884   //   [...] A conversion function is never used to convert a
8885   //   (possibly cv-qualified) object to the (possibly cv-qualified)
8886   //   same object type (or a reference to it), to a (possibly
8887   //   cv-qualified) base class of that type (or a reference to it),
8888   //   or to (possibly cv-qualified) void.
8889   // FIXME: Suppress this warning if the conversion function ends up being a
8890   // virtual function that overrides a virtual function in a base class.
8891   QualType ClassType
8892     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8893   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
8894     ConvType = ConvTypeRef->getPointeeType();
8895   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8896       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
8897     /* Suppress diagnostics for instantiations. */;
8898   else if (ConvType->isRecordType()) {
8899     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8900     if (ConvType == ClassType)
8901       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
8902         << ClassType;
8903     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
8904       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
8905         <<  ClassType << ConvType;
8906   } else if (ConvType->isVoidType()) {
8907     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
8908       << ClassType << ConvType;
8909   }
8910
8911   if (FunctionTemplateDecl *ConversionTemplate
8912                                 = Conversion->getDescribedFunctionTemplate())
8913     return ConversionTemplate;
8914
8915   return Conversion;
8916 }
8917
8918 namespace {
8919 /// Utility class to accumulate and print a diagnostic listing the invalid
8920 /// specifier(s) on a declaration.
8921 struct BadSpecifierDiagnoser {
8922   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
8923       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
8924   ~BadSpecifierDiagnoser() {
8925     Diagnostic << Specifiers;
8926   }
8927
8928   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
8929     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
8930   }
8931   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
8932     return check(SpecLoc,
8933                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
8934   }
8935   void check(SourceLocation SpecLoc, const char *Spec) {
8936     if (SpecLoc.isInvalid()) return;
8937     Diagnostic << SourceRange(SpecLoc, SpecLoc);
8938     if (!Specifiers.empty()) Specifiers += " ";
8939     Specifiers += Spec;
8940   }
8941
8942   Sema &S;
8943   Sema::SemaDiagnosticBuilder Diagnostic;
8944   std::string Specifiers;
8945 };
8946 }
8947
8948 /// Check the validity of a declarator that we parsed for a deduction-guide.
8949 /// These aren't actually declarators in the grammar, so we need to check that
8950 /// the user didn't specify any pieces that are not part of the deduction-guide
8951 /// grammar.
8952 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
8953                                          StorageClass &SC) {
8954   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
8955   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
8956   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
8957
8958   // C++ [temp.deduct.guide]p3:
8959   //   A deduction-gide shall be declared in the same scope as the
8960   //   corresponding class template.
8961   if (!CurContext->getRedeclContext()->Equals(
8962           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
8963     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
8964       << GuidedTemplateDecl;
8965     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
8966   }
8967
8968   auto &DS = D.getMutableDeclSpec();
8969   // We leave 'friend' and 'virtual' to be rejected in the normal way.
8970   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
8971       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
8972       DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
8973     BadSpecifierDiagnoser Diagnoser(
8974         *this, D.getIdentifierLoc(),
8975         diag::err_deduction_guide_invalid_specifier);
8976
8977     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
8978     DS.ClearStorageClassSpecs();
8979     SC = SC_None;
8980
8981     // 'explicit' is permitted.
8982     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
8983     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
8984     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
8985     DS.ClearConstexprSpec();
8986
8987     Diagnoser.check(DS.getConstSpecLoc(), "const");
8988     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
8989     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
8990     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
8991     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
8992     DS.ClearTypeQualifiers();
8993
8994     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
8995     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
8996     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
8997     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
8998     DS.ClearTypeSpecType();
8999   }
9000
9001   if (D.isInvalidType())
9002     return;
9003
9004   // Check the declarator is simple enough.
9005   bool FoundFunction = false;
9006   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
9007     if (Chunk.Kind == DeclaratorChunk::Paren)
9008       continue;
9009     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
9010       Diag(D.getDeclSpec().getBeginLoc(),
9011            diag::err_deduction_guide_with_complex_decl)
9012           << D.getSourceRange();
9013       break;
9014     }
9015     if (!Chunk.Fun.hasTrailingReturnType()) {
9016       Diag(D.getName().getBeginLoc(),
9017            diag::err_deduction_guide_no_trailing_return_type);
9018       break;
9019     }
9020
9021     // Check that the return type is written as a specialization of
9022     // the template specified as the deduction-guide's name.
9023     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
9024     TypeSourceInfo *TSI = nullptr;
9025     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
9026     assert(TSI && "deduction guide has valid type but invalid return type?");
9027     bool AcceptableReturnType = false;
9028     bool MightInstantiateToSpecialization = false;
9029     if (auto RetTST =
9030             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
9031       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
9032       bool TemplateMatches =
9033           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
9034       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
9035         AcceptableReturnType = true;
9036       else {
9037         // This could still instantiate to the right type, unless we know it
9038         // names the wrong class template.
9039         auto *TD = SpecifiedName.getAsTemplateDecl();
9040         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
9041                                              !TemplateMatches);
9042       }
9043     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
9044       MightInstantiateToSpecialization = true;
9045     }
9046
9047     if (!AcceptableReturnType) {
9048       Diag(TSI->getTypeLoc().getBeginLoc(),
9049            diag::err_deduction_guide_bad_trailing_return_type)
9050           << GuidedTemplate << TSI->getType()
9051           << MightInstantiateToSpecialization
9052           << TSI->getTypeLoc().getSourceRange();
9053     }
9054
9055     // Keep going to check that we don't have any inner declarator pieces (we
9056     // could still have a function returning a pointer to a function).
9057     FoundFunction = true;
9058   }
9059
9060   if (D.isFunctionDefinition())
9061     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
9062 }
9063
9064 //===----------------------------------------------------------------------===//
9065 // Namespace Handling
9066 //===----------------------------------------------------------------------===//
9067
9068 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
9069 /// reopened.
9070 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
9071                                             SourceLocation Loc,
9072                                             IdentifierInfo *II, bool *IsInline,
9073                                             NamespaceDecl *PrevNS) {
9074   assert(*IsInline != PrevNS->isInline());
9075
9076   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
9077   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
9078   // inline namespaces, with the intention of bringing names into namespace std.
9079   //
9080   // We support this just well enough to get that case working; this is not
9081   // sufficient to support reopening namespaces as inline in general.
9082   if (*IsInline && II && II->getName().startswith("__atomic") &&
9083       S.getSourceManager().isInSystemHeader(Loc)) {
9084     // Mark all prior declarations of the namespace as inline.
9085     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
9086          NS = NS->getPreviousDecl())
9087       NS->setInline(*IsInline);
9088     // Patch up the lookup table for the containing namespace. This isn't really
9089     // correct, but it's good enough for this particular case.
9090     for (auto *I : PrevNS->decls())
9091       if (auto *ND = dyn_cast<NamedDecl>(I))
9092         PrevNS->getParent()->makeDeclVisibleInContext(ND);
9093     return;
9094   }
9095
9096   if (PrevNS->isInline())
9097     // The user probably just forgot the 'inline', so suggest that it
9098     // be added back.
9099     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
9100       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
9101   else
9102     S.Diag(Loc, diag::err_inline_namespace_mismatch);
9103
9104   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
9105   *IsInline = PrevNS->isInline();
9106 }
9107
9108 /// ActOnStartNamespaceDef - This is called at the start of a namespace
9109 /// definition.
9110 Decl *Sema::ActOnStartNamespaceDef(
9111     Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
9112     SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
9113     const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
9114   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
9115   // For anonymous namespace, take the location of the left brace.
9116   SourceLocation Loc = II ? IdentLoc : LBrace;
9117   bool IsInline = InlineLoc.isValid();
9118   bool IsInvalid = false;
9119   bool IsStd = false;
9120   bool AddToKnown = false;
9121   Scope *DeclRegionScope = NamespcScope->getParent();
9122
9123   NamespaceDecl *PrevNS = nullptr;
9124   if (II) {
9125     // C++ [namespace.def]p2:
9126     //   The identifier in an original-namespace-definition shall not
9127     //   have been previously defined in the declarative region in
9128     //   which the original-namespace-definition appears. The
9129     //   identifier in an original-namespace-definition is the name of
9130     //   the namespace. Subsequently in that declarative region, it is
9131     //   treated as an original-namespace-name.
9132     //
9133     // Since namespace names are unique in their scope, and we don't
9134     // look through using directives, just look for any ordinary names
9135     // as if by qualified name lookup.
9136     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
9137                    ForExternalRedeclaration);
9138     LookupQualifiedName(R, CurContext->getRedeclContext());
9139     NamedDecl *PrevDecl =
9140         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
9141     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
9142
9143     if (PrevNS) {
9144       // This is an extended namespace definition.
9145       if (IsInline != PrevNS->isInline())
9146         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
9147                                         &IsInline, PrevNS);
9148     } else if (PrevDecl) {
9149       // This is an invalid name redefinition.
9150       Diag(Loc, diag::err_redefinition_different_kind)
9151         << II;
9152       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
9153       IsInvalid = true;
9154       // Continue on to push Namespc as current DeclContext and return it.
9155     } else if (II->isStr("std") &&
9156                CurContext->getRedeclContext()->isTranslationUnit()) {
9157       // This is the first "real" definition of the namespace "std", so update
9158       // our cache of the "std" namespace to point at this definition.
9159       PrevNS = getStdNamespace();
9160       IsStd = true;
9161       AddToKnown = !IsInline;
9162     } else {
9163       // We've seen this namespace for the first time.
9164       AddToKnown = !IsInline;
9165     }
9166   } else {
9167     // Anonymous namespaces.
9168
9169     // Determine whether the parent already has an anonymous namespace.
9170     DeclContext *Parent = CurContext->getRedeclContext();
9171     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
9172       PrevNS = TU->getAnonymousNamespace();
9173     } else {
9174       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
9175       PrevNS = ND->getAnonymousNamespace();
9176     }
9177
9178     if (PrevNS && IsInline != PrevNS->isInline())
9179       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
9180                                       &IsInline, PrevNS);
9181   }
9182
9183   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
9184                                                  StartLoc, Loc, II, PrevNS);
9185   if (IsInvalid)
9186     Namespc->setInvalidDecl();
9187
9188   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
9189   AddPragmaAttributes(DeclRegionScope, Namespc);
9190
9191   // FIXME: Should we be merging attributes?
9192   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
9193     PushNamespaceVisibilityAttr(Attr, Loc);
9194
9195   if (IsStd)
9196     StdNamespace = Namespc;
9197   if (AddToKnown)
9198     KnownNamespaces[Namespc] = false;
9199
9200   if (II) {
9201     PushOnScopeChains(Namespc, DeclRegionScope);
9202   } else {
9203     // Link the anonymous namespace into its parent.
9204     DeclContext *Parent = CurContext->getRedeclContext();
9205     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
9206       TU->setAnonymousNamespace(Namespc);
9207     } else {
9208       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
9209     }
9210
9211     CurContext->addDecl(Namespc);
9212
9213     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
9214     //   behaves as if it were replaced by
9215     //     namespace unique { /* empty body */ }
9216     //     using namespace unique;
9217     //     namespace unique { namespace-body }
9218     //   where all occurrences of 'unique' in a translation unit are
9219     //   replaced by the same identifier and this identifier differs
9220     //   from all other identifiers in the entire program.
9221
9222     // We just create the namespace with an empty name and then add an
9223     // implicit using declaration, just like the standard suggests.
9224     //
9225     // CodeGen enforces the "universally unique" aspect by giving all
9226     // declarations semantically contained within an anonymous
9227     // namespace internal linkage.
9228
9229     if (!PrevNS) {
9230       UD = UsingDirectiveDecl::Create(Context, Parent,
9231                                       /* 'using' */ LBrace,
9232                                       /* 'namespace' */ SourceLocation(),
9233                                       /* qualifier */ NestedNameSpecifierLoc(),
9234                                       /* identifier */ SourceLocation(),
9235                                       Namespc,
9236                                       /* Ancestor */ Parent);
9237       UD->setImplicit();
9238       Parent->addDecl(UD);
9239     }
9240   }
9241
9242   ActOnDocumentableDecl(Namespc);
9243
9244   // Although we could have an invalid decl (i.e. the namespace name is a
9245   // redefinition), push it as current DeclContext and try to continue parsing.
9246   // FIXME: We should be able to push Namespc here, so that the each DeclContext
9247   // for the namespace has the declarations that showed up in that particular
9248   // namespace definition.
9249   PushDeclContext(NamespcScope, Namespc);
9250   return Namespc;
9251 }
9252
9253 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
9254 /// is a namespace alias, returns the namespace it points to.
9255 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
9256   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
9257     return AD->getNamespace();
9258   return dyn_cast_or_null<NamespaceDecl>(D);
9259 }
9260
9261 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
9262 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
9263 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
9264   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
9265   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
9266   Namespc->setRBraceLoc(RBrace);
9267   PopDeclContext();
9268   if (Namespc->hasAttr<VisibilityAttr>())
9269     PopPragmaVisibility(true, RBrace);
9270   // If this namespace contains an export-declaration, export it now.
9271   if (DeferredExportedNamespaces.erase(Namespc))
9272     Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
9273 }
9274
9275 CXXRecordDecl *Sema::getStdBadAlloc() const {
9276   return cast_or_null<CXXRecordDecl>(
9277                                   StdBadAlloc.get(Context.getExternalSource()));
9278 }
9279
9280 EnumDecl *Sema::getStdAlignValT() const {
9281   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
9282 }
9283
9284 NamespaceDecl *Sema::getStdNamespace() const {
9285   return cast_or_null<NamespaceDecl>(
9286                                  StdNamespace.get(Context.getExternalSource()));
9287 }
9288
9289 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
9290   if (!StdExperimentalNamespaceCache) {
9291     if (auto Std = getStdNamespace()) {
9292       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
9293                           SourceLocation(), LookupNamespaceName);
9294       if (!LookupQualifiedName(Result, Std) ||
9295           !(StdExperimentalNamespaceCache =
9296                 Result.getAsSingle<NamespaceDecl>()))
9297         Result.suppressDiagnostics();
9298     }
9299   }
9300   return StdExperimentalNamespaceCache;
9301 }
9302
9303 namespace {
9304
9305 enum UnsupportedSTLSelect {
9306   USS_InvalidMember,
9307   USS_MissingMember,
9308   USS_NonTrivial,
9309   USS_Other
9310 };
9311
9312 struct InvalidSTLDiagnoser {
9313   Sema &S;
9314   SourceLocation Loc;
9315   QualType TyForDiags;
9316
9317   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
9318                       const VarDecl *VD = nullptr) {
9319     {
9320       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
9321                << TyForDiags << ((int)Sel);
9322       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
9323         assert(!Name.empty());
9324         D << Name;
9325       }
9326     }
9327     if (Sel == USS_InvalidMember) {
9328       S.Diag(VD->getLocation(), diag::note_var_declared_here)
9329           << VD << VD->getSourceRange();
9330     }
9331     return QualType();
9332   }
9333 };
9334 } // namespace
9335
9336 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
9337                                            SourceLocation Loc) {
9338   assert(getLangOpts().CPlusPlus &&
9339          "Looking for comparison category type outside of C++.");
9340
9341   // Check if we've already successfully checked the comparison category type
9342   // before. If so, skip checking it again.
9343   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
9344   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)])
9345     return Info->getType();
9346
9347   // If lookup failed
9348   if (!Info) {
9349     std::string NameForDiags = "std::";
9350     NameForDiags += ComparisonCategories::getCategoryString(Kind);
9351     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
9352         << NameForDiags;
9353     return QualType();
9354   }
9355
9356   assert(Info->Kind == Kind);
9357   assert(Info->Record);
9358
9359   // Update the Record decl in case we encountered a forward declaration on our
9360   // first pass. FIXME: This is a bit of a hack.
9361   if (Info->Record->hasDefinition())
9362     Info->Record = Info->Record->getDefinition();
9363
9364   // Use an elaborated type for diagnostics which has a name containing the
9365   // prepended 'std' namespace but not any inline namespace names.
9366   QualType TyForDiags = [&]() {
9367     auto *NNS =
9368         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
9369     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
9370   }();
9371
9372   if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type))
9373     return QualType();
9374
9375   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags};
9376
9377   if (!Info->Record->isTriviallyCopyable())
9378     return UnsupportedSTLError(USS_NonTrivial);
9379
9380   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
9381     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
9382     // Tolerate empty base classes.
9383     if (Base->isEmpty())
9384       continue;
9385     // Reject STL implementations which have at least one non-empty base.
9386     return UnsupportedSTLError();
9387   }
9388
9389   // Check that the STL has implemented the types using a single integer field.
9390   // This expectation allows better codegen for builtin operators. We require:
9391   //   (1) The class has exactly one field.
9392   //   (2) The field is an integral or enumeration type.
9393   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
9394   if (std::distance(FIt, FEnd) != 1 ||
9395       !FIt->getType()->isIntegralOrEnumerationType()) {
9396     return UnsupportedSTLError();
9397   }
9398
9399   // Build each of the require values and store them in Info.
9400   for (ComparisonCategoryResult CCR :
9401        ComparisonCategories::getPossibleResultsForType(Kind)) {
9402     StringRef MemName = ComparisonCategories::getResultString(CCR);
9403     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
9404
9405     if (!ValInfo)
9406       return UnsupportedSTLError(USS_MissingMember, MemName);
9407
9408     VarDecl *VD = ValInfo->VD;
9409     assert(VD && "should not be null!");
9410
9411     // Attempt to diagnose reasons why the STL definition of this type
9412     // might be foobar, including it failing to be a constant expression.
9413     // TODO Handle more ways the lookup or result can be invalid.
9414     if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
9415         !VD->checkInitIsICE())
9416       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
9417
9418     // Attempt to evaluate the var decl as a constant expression and extract
9419     // the value of its first field as a ICE. If this fails, the STL
9420     // implementation is not supported.
9421     if (!ValInfo->hasValidIntValue())
9422       return UnsupportedSTLError();
9423
9424     MarkVariableReferenced(Loc, VD);
9425   }
9426
9427   // We've successfully built the required types and expressions. Update
9428   // the cache and return the newly cached value.
9429   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
9430   return Info->getType();
9431 }
9432
9433 /// Retrieve the special "std" namespace, which may require us to
9434 /// implicitly define the namespace.
9435 NamespaceDecl *Sema::getOrCreateStdNamespace() {
9436   if (!StdNamespace) {
9437     // The "std" namespace has not yet been defined, so build one implicitly.
9438     StdNamespace = NamespaceDecl::Create(Context,
9439                                          Context.getTranslationUnitDecl(),
9440                                          /*Inline=*/false,
9441                                          SourceLocation(), SourceLocation(),
9442                                          &PP.getIdentifierTable().get("std"),
9443                                          /*PrevDecl=*/nullptr);
9444     getStdNamespace()->setImplicit(true);
9445   }
9446
9447   return getStdNamespace();
9448 }
9449
9450 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
9451   assert(getLangOpts().CPlusPlus &&
9452          "Looking for std::initializer_list outside of C++.");
9453
9454   // We're looking for implicit instantiations of
9455   // template <typename E> class std::initializer_list.
9456
9457   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
9458     return false;
9459
9460   ClassTemplateDecl *Template = nullptr;
9461   const TemplateArgument *Arguments = nullptr;
9462
9463   if (const RecordType *RT = Ty->getAs<RecordType>()) {
9464
9465     ClassTemplateSpecializationDecl *Specialization =
9466         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
9467     if (!Specialization)
9468       return false;
9469
9470     Template = Specialization->getSpecializedTemplate();
9471     Arguments = Specialization->getTemplateArgs().data();
9472   } else if (const TemplateSpecializationType *TST =
9473                  Ty->getAs<TemplateSpecializationType>()) {
9474     Template = dyn_cast_or_null<ClassTemplateDecl>(
9475         TST->getTemplateName().getAsTemplateDecl());
9476     Arguments = TST->getArgs();
9477   }
9478   if (!Template)
9479     return false;
9480
9481   if (!StdInitializerList) {
9482     // Haven't recognized std::initializer_list yet, maybe this is it.
9483     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
9484     if (TemplateClass->getIdentifier() !=
9485             &PP.getIdentifierTable().get("initializer_list") ||
9486         !getStdNamespace()->InEnclosingNamespaceSetOf(
9487             TemplateClass->getDeclContext()))
9488       return false;
9489     // This is a template called std::initializer_list, but is it the right
9490     // template?
9491     TemplateParameterList *Params = Template->getTemplateParameters();
9492     if (Params->getMinRequiredArguments() != 1)
9493       return false;
9494     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
9495       return false;
9496
9497     // It's the right template.
9498     StdInitializerList = Template;
9499   }
9500
9501   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
9502     return false;
9503
9504   // This is an instance of std::initializer_list. Find the argument type.
9505   if (Element)
9506     *Element = Arguments[0].getAsType();
9507   return true;
9508 }
9509
9510 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
9511   NamespaceDecl *Std = S.getStdNamespace();
9512   if (!Std) {
9513     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9514     return nullptr;
9515   }
9516
9517   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
9518                       Loc, Sema::LookupOrdinaryName);
9519   if (!S.LookupQualifiedName(Result, Std)) {
9520     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9521     return nullptr;
9522   }
9523   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
9524   if (!Template) {
9525     Result.suppressDiagnostics();
9526     // We found something weird. Complain about the first thing we found.
9527     NamedDecl *Found = *Result.begin();
9528     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
9529     return nullptr;
9530   }
9531
9532   // We found some template called std::initializer_list. Now verify that it's
9533   // correct.
9534   TemplateParameterList *Params = Template->getTemplateParameters();
9535   if (Params->getMinRequiredArguments() != 1 ||
9536       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
9537     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
9538     return nullptr;
9539   }
9540
9541   return Template;
9542 }
9543
9544 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
9545   if (!StdInitializerList) {
9546     StdInitializerList = LookupStdInitializerList(*this, Loc);
9547     if (!StdInitializerList)
9548       return QualType();
9549   }
9550
9551   TemplateArgumentListInfo Args(Loc, Loc);
9552   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
9553                                        Context.getTrivialTypeSourceInfo(Element,
9554                                                                         Loc)));
9555   return Context.getCanonicalType(
9556       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
9557 }
9558
9559 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
9560   // C++ [dcl.init.list]p2:
9561   //   A constructor is an initializer-list constructor if its first parameter
9562   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
9563   //   std::initializer_list<E> for some type E, and either there are no other
9564   //   parameters or else all other parameters have default arguments.
9565   if (Ctor->getNumParams() < 1 ||
9566       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
9567     return false;
9568
9569   QualType ArgType = Ctor->getParamDecl(0)->getType();
9570   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
9571     ArgType = RT->getPointeeType().getUnqualifiedType();
9572
9573   return isStdInitializerList(ArgType, nullptr);
9574 }
9575
9576 /// Determine whether a using statement is in a context where it will be
9577 /// apply in all contexts.
9578 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
9579   switch (CurContext->getDeclKind()) {
9580     case Decl::TranslationUnit:
9581       return true;
9582     case Decl::LinkageSpec:
9583       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
9584     default:
9585       return false;
9586   }
9587 }
9588
9589 namespace {
9590
9591 // Callback to only accept typo corrections that are namespaces.
9592 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
9593 public:
9594   bool ValidateCandidate(const TypoCorrection &candidate) override {
9595     if (NamedDecl *ND = candidate.getCorrectionDecl())
9596       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
9597     return false;
9598   }
9599
9600   std::unique_ptr<CorrectionCandidateCallback> clone() override {
9601     return std::make_unique<NamespaceValidatorCCC>(*this);
9602   }
9603 };
9604
9605 }
9606
9607 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
9608                                        CXXScopeSpec &SS,
9609                                        SourceLocation IdentLoc,
9610                                        IdentifierInfo *Ident) {
9611   R.clear();
9612   NamespaceValidatorCCC CCC{};
9613   if (TypoCorrection Corrected =
9614           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
9615                         Sema::CTK_ErrorRecovery)) {
9616     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
9617       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
9618       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
9619                               Ident->getName().equals(CorrectedStr);
9620       S.diagnoseTypo(Corrected,
9621                      S.PDiag(diag::err_using_directive_member_suggest)
9622                        << Ident << DC << DroppedSpecifier << SS.getRange(),
9623                      S.PDiag(diag::note_namespace_defined_here));
9624     } else {
9625       S.diagnoseTypo(Corrected,
9626                      S.PDiag(diag::err_using_directive_suggest) << Ident,
9627                      S.PDiag(diag::note_namespace_defined_here));
9628     }
9629     R.addDecl(Corrected.getFoundDecl());
9630     return true;
9631   }
9632   return false;
9633 }
9634
9635 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
9636                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
9637                                 SourceLocation IdentLoc,
9638                                 IdentifierInfo *NamespcName,
9639                                 const ParsedAttributesView &AttrList) {
9640   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9641   assert(NamespcName && "Invalid NamespcName.");
9642   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
9643
9644   // This can only happen along a recovery path.
9645   while (S->isTemplateParamScope())
9646     S = S->getParent();
9647   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9648
9649   UsingDirectiveDecl *UDir = nullptr;
9650   NestedNameSpecifier *Qualifier = nullptr;
9651   if (SS.isSet())
9652     Qualifier = SS.getScopeRep();
9653
9654   // Lookup namespace name.
9655   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
9656   LookupParsedName(R, S, &SS);
9657   if (R.isAmbiguous())
9658     return nullptr;
9659
9660   if (R.empty()) {
9661     R.clear();
9662     // Allow "using namespace std;" or "using namespace ::std;" even if
9663     // "std" hasn't been defined yet, for GCC compatibility.
9664     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
9665         NamespcName->isStr("std")) {
9666       Diag(IdentLoc, diag::ext_using_undefined_std);
9667       R.addDecl(getOrCreateStdNamespace());
9668       R.resolveKind();
9669     }
9670     // Otherwise, attempt typo correction.
9671     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
9672   }
9673
9674   if (!R.empty()) {
9675     NamedDecl *Named = R.getRepresentativeDecl();
9676     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
9677     assert(NS && "expected namespace decl");
9678
9679     // The use of a nested name specifier may trigger deprecation warnings.
9680     DiagnoseUseOfDecl(Named, IdentLoc);
9681
9682     // C++ [namespace.udir]p1:
9683     //   A using-directive specifies that the names in the nominated
9684     //   namespace can be used in the scope in which the
9685     //   using-directive appears after the using-directive. During
9686     //   unqualified name lookup (3.4.1), the names appear as if they
9687     //   were declared in the nearest enclosing namespace which
9688     //   contains both the using-directive and the nominated
9689     //   namespace. [Note: in this context, "contains" means "contains
9690     //   directly or indirectly". ]
9691
9692     // Find enclosing context containing both using-directive and
9693     // nominated namespace.
9694     DeclContext *CommonAncestor = NS;
9695     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
9696       CommonAncestor = CommonAncestor->getParent();
9697
9698     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
9699                                       SS.getWithLocInContext(Context),
9700                                       IdentLoc, Named, CommonAncestor);
9701
9702     if (IsUsingDirectiveInToplevelContext(CurContext) &&
9703         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
9704       Diag(IdentLoc, diag::warn_using_directive_in_header);
9705     }
9706
9707     PushUsingDirective(S, UDir);
9708   } else {
9709     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
9710   }
9711
9712   if (UDir)
9713     ProcessDeclAttributeList(S, UDir, AttrList);
9714
9715   return UDir;
9716 }
9717
9718 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
9719   // If the scope has an associated entity and the using directive is at
9720   // namespace or translation unit scope, add the UsingDirectiveDecl into
9721   // its lookup structure so qualified name lookup can find it.
9722   DeclContext *Ctx = S->getEntity();
9723   if (Ctx && !Ctx->isFunctionOrMethod())
9724     Ctx->addDecl(UDir);
9725   else
9726     // Otherwise, it is at block scope. The using-directives will affect lookup
9727     // only to the end of the scope.
9728     S->PushUsingDirective(UDir);
9729 }
9730
9731 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
9732                                   SourceLocation UsingLoc,
9733                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
9734                                   UnqualifiedId &Name,
9735                                   SourceLocation EllipsisLoc,
9736                                   const ParsedAttributesView &AttrList) {
9737   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9738
9739   if (SS.isEmpty()) {
9740     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
9741     return nullptr;
9742   }
9743
9744   switch (Name.getKind()) {
9745   case UnqualifiedIdKind::IK_ImplicitSelfParam:
9746   case UnqualifiedIdKind::IK_Identifier:
9747   case UnqualifiedIdKind::IK_OperatorFunctionId:
9748   case UnqualifiedIdKind::IK_LiteralOperatorId:
9749   case UnqualifiedIdKind::IK_ConversionFunctionId:
9750     break;
9751
9752   case UnqualifiedIdKind::IK_ConstructorName:
9753   case UnqualifiedIdKind::IK_ConstructorTemplateId:
9754     // C++11 inheriting constructors.
9755     Diag(Name.getBeginLoc(),
9756          getLangOpts().CPlusPlus11
9757              ? diag::warn_cxx98_compat_using_decl_constructor
9758              : diag::err_using_decl_constructor)
9759         << SS.getRange();
9760
9761     if (getLangOpts().CPlusPlus11) break;
9762
9763     return nullptr;
9764
9765   case UnqualifiedIdKind::IK_DestructorName:
9766     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
9767     return nullptr;
9768
9769   case UnqualifiedIdKind::IK_TemplateId:
9770     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
9771         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
9772     return nullptr;
9773
9774   case UnqualifiedIdKind::IK_DeductionGuideName:
9775     llvm_unreachable("cannot parse qualified deduction guide name");
9776   }
9777
9778   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
9779   DeclarationName TargetName = TargetNameInfo.getName();
9780   if (!TargetName)
9781     return nullptr;
9782
9783   // Warn about access declarations.
9784   if (UsingLoc.isInvalid()) {
9785     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
9786                                  ? diag::err_access_decl
9787                                  : diag::warn_access_decl_deprecated)
9788         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
9789   }
9790
9791   if (EllipsisLoc.isInvalid()) {
9792     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
9793         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
9794       return nullptr;
9795   } else {
9796     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
9797         !TargetNameInfo.containsUnexpandedParameterPack()) {
9798       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
9799         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
9800       EllipsisLoc = SourceLocation();
9801     }
9802   }
9803
9804   NamedDecl *UD =
9805       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
9806                             SS, TargetNameInfo, EllipsisLoc, AttrList,
9807                             /*IsInstantiation*/false);
9808   if (UD)
9809     PushOnScopeChains(UD, S, /*AddToContext*/ false);
9810
9811   return UD;
9812 }
9813
9814 /// Determine whether a using declaration considers the given
9815 /// declarations as "equivalent", e.g., if they are redeclarations of
9816 /// the same entity or are both typedefs of the same type.
9817 static bool
9818 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
9819   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
9820     return true;
9821
9822   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
9823     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
9824       return Context.hasSameType(TD1->getUnderlyingType(),
9825                                  TD2->getUnderlyingType());
9826
9827   return false;
9828 }
9829
9830
9831 /// Determines whether to create a using shadow decl for a particular
9832 /// decl, given the set of decls existing prior to this using lookup.
9833 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
9834                                 const LookupResult &Previous,
9835                                 UsingShadowDecl *&PrevShadow) {
9836   // Diagnose finding a decl which is not from a base class of the
9837   // current class.  We do this now because there are cases where this
9838   // function will silently decide not to build a shadow decl, which
9839   // will pre-empt further diagnostics.
9840   //
9841   // We don't need to do this in C++11 because we do the check once on
9842   // the qualifier.
9843   //
9844   // FIXME: diagnose the following if we care enough:
9845   //   struct A { int foo; };
9846   //   struct B : A { using A::foo; };
9847   //   template <class T> struct C : A {};
9848   //   template <class T> struct D : C<T> { using B::foo; } // <---
9849   // This is invalid (during instantiation) in C++03 because B::foo
9850   // resolves to the using decl in B, which is not a base class of D<T>.
9851   // We can't diagnose it immediately because C<T> is an unknown
9852   // specialization.  The UsingShadowDecl in D<T> then points directly
9853   // to A::foo, which will look well-formed when we instantiate.
9854   // The right solution is to not collapse the shadow-decl chain.
9855   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
9856     DeclContext *OrigDC = Orig->getDeclContext();
9857
9858     // Handle enums and anonymous structs.
9859     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
9860     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
9861     while (OrigRec->isAnonymousStructOrUnion())
9862       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
9863
9864     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
9865       if (OrigDC == CurContext) {
9866         Diag(Using->getLocation(),
9867              diag::err_using_decl_nested_name_specifier_is_current_class)
9868           << Using->getQualifierLoc().getSourceRange();
9869         Diag(Orig->getLocation(), diag::note_using_decl_target);
9870         Using->setInvalidDecl();
9871         return true;
9872       }
9873
9874       Diag(Using->getQualifierLoc().getBeginLoc(),
9875            diag::err_using_decl_nested_name_specifier_is_not_base_class)
9876         << Using->getQualifier()
9877         << cast<CXXRecordDecl>(CurContext)
9878         << Using->getQualifierLoc().getSourceRange();
9879       Diag(Orig->getLocation(), diag::note_using_decl_target);
9880       Using->setInvalidDecl();
9881       return true;
9882     }
9883   }
9884
9885   if (Previous.empty()) return false;
9886
9887   NamedDecl *Target = Orig;
9888   if (isa<UsingShadowDecl>(Target))
9889     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9890
9891   // If the target happens to be one of the previous declarations, we
9892   // don't have a conflict.
9893   //
9894   // FIXME: but we might be increasing its access, in which case we
9895   // should redeclare it.
9896   NamedDecl *NonTag = nullptr, *Tag = nullptr;
9897   bool FoundEquivalentDecl = false;
9898   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9899          I != E; ++I) {
9900     NamedDecl *D = (*I)->getUnderlyingDecl();
9901     // We can have UsingDecls in our Previous results because we use the same
9902     // LookupResult for checking whether the UsingDecl itself is a valid
9903     // redeclaration.
9904     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
9905       continue;
9906
9907     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
9908       // C++ [class.mem]p19:
9909       //   If T is the name of a class, then [every named member other than
9910       //   a non-static data member] shall have a name different from T
9911       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
9912           !isa<IndirectFieldDecl>(Target) &&
9913           !isa<UnresolvedUsingValueDecl>(Target) &&
9914           DiagnoseClassNameShadow(
9915               CurContext,
9916               DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
9917         return true;
9918     }
9919
9920     if (IsEquivalentForUsingDecl(Context, D, Target)) {
9921       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
9922         PrevShadow = Shadow;
9923       FoundEquivalentDecl = true;
9924     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
9925       // We don't conflict with an existing using shadow decl of an equivalent
9926       // declaration, but we're not a redeclaration of it.
9927       FoundEquivalentDecl = true;
9928     }
9929
9930     if (isVisible(D))
9931       (isa<TagDecl>(D) ? Tag : NonTag) = D;
9932   }
9933
9934   if (FoundEquivalentDecl)
9935     return false;
9936
9937   if (FunctionDecl *FD = Target->getAsFunction()) {
9938     NamedDecl *OldDecl = nullptr;
9939     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
9940                           /*IsForUsingDecl*/ true)) {
9941     case Ovl_Overload:
9942       return false;
9943
9944     case Ovl_NonFunction:
9945       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9946       break;
9947
9948     // We found a decl with the exact signature.
9949     case Ovl_Match:
9950       // If we're in a record, we want to hide the target, so we
9951       // return true (without a diagnostic) to tell the caller not to
9952       // build a shadow decl.
9953       if (CurContext->isRecord())
9954         return true;
9955
9956       // If we're not in a record, this is an error.
9957       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9958       break;
9959     }
9960
9961     Diag(Target->getLocation(), diag::note_using_decl_target);
9962     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
9963     Using->setInvalidDecl();
9964     return true;
9965   }
9966
9967   // Target is not a function.
9968
9969   if (isa<TagDecl>(Target)) {
9970     // No conflict between a tag and a non-tag.
9971     if (!Tag) return false;
9972
9973     Diag(Using->getLocation(), diag::err_using_decl_conflict);
9974     Diag(Target->getLocation(), diag::note_using_decl_target);
9975     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
9976     Using->setInvalidDecl();
9977     return true;
9978   }
9979
9980   // No conflict between a tag and a non-tag.
9981   if (!NonTag) return false;
9982
9983   Diag(Using->getLocation(), diag::err_using_decl_conflict);
9984   Diag(Target->getLocation(), diag::note_using_decl_target);
9985   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
9986   Using->setInvalidDecl();
9987   return true;
9988 }
9989
9990 /// Determine whether a direct base class is a virtual base class.
9991 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
9992   if (!Derived->getNumVBases())
9993     return false;
9994   for (auto &B : Derived->bases())
9995     if (B.getType()->getAsCXXRecordDecl() == Base)
9996       return B.isVirtual();
9997   llvm_unreachable("not a direct base class");
9998 }
9999
10000 /// Builds a shadow declaration corresponding to a 'using' declaration.
10001 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
10002                                             UsingDecl *UD,
10003                                             NamedDecl *Orig,
10004                                             UsingShadowDecl *PrevDecl) {
10005   // If we resolved to another shadow declaration, just coalesce them.
10006   NamedDecl *Target = Orig;
10007   if (isa<UsingShadowDecl>(Target)) {
10008     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
10009     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
10010   }
10011
10012   NamedDecl *NonTemplateTarget = Target;
10013   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
10014     NonTemplateTarget = TargetTD->getTemplatedDecl();
10015
10016   UsingShadowDecl *Shadow;
10017   if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
10018     bool IsVirtualBase =
10019         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
10020                             UD->getQualifier()->getAsRecordDecl());
10021     Shadow = ConstructorUsingShadowDecl::Create(
10022         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
10023   } else {
10024     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
10025                                      Target);
10026   }
10027   UD->addShadowDecl(Shadow);
10028
10029   Shadow->setAccess(UD->getAccess());
10030   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
10031     Shadow->setInvalidDecl();
10032
10033   Shadow->setPreviousDecl(PrevDecl);
10034
10035   if (S)
10036     PushOnScopeChains(Shadow, S);
10037   else
10038     CurContext->addDecl(Shadow);
10039
10040
10041   return Shadow;
10042 }
10043
10044 /// Hides a using shadow declaration.  This is required by the current
10045 /// using-decl implementation when a resolvable using declaration in a
10046 /// class is followed by a declaration which would hide or override
10047 /// one or more of the using decl's targets; for example:
10048 ///
10049 ///   struct Base { void foo(int); };
10050 ///   struct Derived : Base {
10051 ///     using Base::foo;
10052 ///     void foo(int);
10053 ///   };
10054 ///
10055 /// The governing language is C++03 [namespace.udecl]p12:
10056 ///
10057 ///   When a using-declaration brings names from a base class into a
10058 ///   derived class scope, member functions in the derived class
10059 ///   override and/or hide member functions with the same name and
10060 ///   parameter types in a base class (rather than conflicting).
10061 ///
10062 /// There are two ways to implement this:
10063 ///   (1) optimistically create shadow decls when they're not hidden
10064 ///       by existing declarations, or
10065 ///   (2) don't create any shadow decls (or at least don't make them
10066 ///       visible) until we've fully parsed/instantiated the class.
10067 /// The problem with (1) is that we might have to retroactively remove
10068 /// a shadow decl, which requires several O(n) operations because the
10069 /// decl structures are (very reasonably) not designed for removal.
10070 /// (2) avoids this but is very fiddly and phase-dependent.
10071 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
10072   if (Shadow->getDeclName().getNameKind() ==
10073         DeclarationName::CXXConversionFunctionName)
10074     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
10075
10076   // Remove it from the DeclContext...
10077   Shadow->getDeclContext()->removeDecl(Shadow);
10078
10079   // ...and the scope, if applicable...
10080   if (S) {
10081     S->RemoveDecl(Shadow);
10082     IdResolver.RemoveDecl(Shadow);
10083   }
10084
10085   // ...and the using decl.
10086   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
10087
10088   // TODO: complain somehow if Shadow was used.  It shouldn't
10089   // be possible for this to happen, because...?
10090 }
10091
10092 /// Find the base specifier for a base class with the given type.
10093 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
10094                                                 QualType DesiredBase,
10095                                                 bool &AnyDependentBases) {
10096   // Check whether the named type is a direct base class.
10097   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
10098     .getUnqualifiedType();
10099   for (auto &Base : Derived->bases()) {
10100     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
10101     if (CanonicalDesiredBase == BaseType)
10102       return &Base;
10103     if (BaseType->isDependentType())
10104       AnyDependentBases = true;
10105   }
10106   return nullptr;
10107 }
10108
10109 namespace {
10110 class UsingValidatorCCC final : public CorrectionCandidateCallback {
10111 public:
10112   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
10113                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
10114       : HasTypenameKeyword(HasTypenameKeyword),
10115         IsInstantiation(IsInstantiation), OldNNS(NNS),
10116         RequireMemberOf(RequireMemberOf) {}
10117
10118   bool ValidateCandidate(const TypoCorrection &Candidate) override {
10119     NamedDecl *ND = Candidate.getCorrectionDecl();
10120
10121     // Keywords are not valid here.
10122     if (!ND || isa<NamespaceDecl>(ND))
10123       return false;
10124
10125     // Completely unqualified names are invalid for a 'using' declaration.
10126     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
10127       return false;
10128
10129     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
10130     // reject.
10131
10132     if (RequireMemberOf) {
10133       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
10134       if (FoundRecord && FoundRecord->isInjectedClassName()) {
10135         // No-one ever wants a using-declaration to name an injected-class-name
10136         // of a base class, unless they're declaring an inheriting constructor.
10137         ASTContext &Ctx = ND->getASTContext();
10138         if (!Ctx.getLangOpts().CPlusPlus11)
10139           return false;
10140         QualType FoundType = Ctx.getRecordType(FoundRecord);
10141
10142         // Check that the injected-class-name is named as a member of its own
10143         // type; we don't want to suggest 'using Derived::Base;', since that
10144         // means something else.
10145         NestedNameSpecifier *Specifier =
10146             Candidate.WillReplaceSpecifier()
10147                 ? Candidate.getCorrectionSpecifier()
10148                 : OldNNS;
10149         if (!Specifier->getAsType() ||
10150             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
10151           return false;
10152
10153         // Check that this inheriting constructor declaration actually names a
10154         // direct base class of the current class.
10155         bool AnyDependentBases = false;
10156         if (!findDirectBaseWithType(RequireMemberOf,
10157                                     Ctx.getRecordType(FoundRecord),
10158                                     AnyDependentBases) &&
10159             !AnyDependentBases)
10160           return false;
10161       } else {
10162         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
10163         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
10164           return false;
10165
10166         // FIXME: Check that the base class member is accessible?
10167       }
10168     } else {
10169       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
10170       if (FoundRecord && FoundRecord->isInjectedClassName())
10171         return false;
10172     }
10173
10174     if (isa<TypeDecl>(ND))
10175       return HasTypenameKeyword || !IsInstantiation;
10176
10177     return !HasTypenameKeyword;
10178   }
10179
10180   std::unique_ptr<CorrectionCandidateCallback> clone() override {
10181     return std::make_unique<UsingValidatorCCC>(*this);
10182   }
10183
10184 private:
10185   bool HasTypenameKeyword;
10186   bool IsInstantiation;
10187   NestedNameSpecifier *OldNNS;
10188   CXXRecordDecl *RequireMemberOf;
10189 };
10190 } // end anonymous namespace
10191
10192 /// Builds a using declaration.
10193 ///
10194 /// \param IsInstantiation - Whether this call arises from an
10195 ///   instantiation of an unresolved using declaration.  We treat
10196 ///   the lookup differently for these declarations.
10197 NamedDecl *Sema::BuildUsingDeclaration(
10198     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
10199     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
10200     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
10201     const ParsedAttributesView &AttrList, bool IsInstantiation) {
10202   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
10203   SourceLocation IdentLoc = NameInfo.getLoc();
10204   assert(IdentLoc.isValid() && "Invalid TargetName location.");
10205
10206   // FIXME: We ignore attributes for now.
10207
10208   // For an inheriting constructor declaration, the name of the using
10209   // declaration is the name of a constructor in this class, not in the
10210   // base class.
10211   DeclarationNameInfo UsingName = NameInfo;
10212   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
10213     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
10214       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
10215           Context.getCanonicalType(Context.getRecordType(RD))));
10216
10217   // Do the redeclaration lookup in the current scope.
10218   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
10219                         ForVisibleRedeclaration);
10220   Previous.setHideTags(false);
10221   if (S) {
10222     LookupName(Previous, S);
10223
10224     // It is really dumb that we have to do this.
10225     LookupResult::Filter F = Previous.makeFilter();
10226     while (F.hasNext()) {
10227       NamedDecl *D = F.next();
10228       if (!isDeclInScope(D, CurContext, S))
10229         F.erase();
10230       // If we found a local extern declaration that's not ordinarily visible,
10231       // and this declaration is being added to a non-block scope, ignore it.
10232       // We're only checking for scope conflicts here, not also for violations
10233       // of the linkage rules.
10234       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
10235                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
10236         F.erase();
10237     }
10238     F.done();
10239   } else {
10240     assert(IsInstantiation && "no scope in non-instantiation");
10241     if (CurContext->isRecord())
10242       LookupQualifiedName(Previous, CurContext);
10243     else {
10244       // No redeclaration check is needed here; in non-member contexts we
10245       // diagnosed all possible conflicts with other using-declarations when
10246       // building the template:
10247       //
10248       // For a dependent non-type using declaration, the only valid case is
10249       // if we instantiate to a single enumerator. We check for conflicts
10250       // between shadow declarations we introduce, and we check in the template
10251       // definition for conflicts between a non-type using declaration and any
10252       // other declaration, which together covers all cases.
10253       //
10254       // A dependent typename using declaration will never successfully
10255       // instantiate, since it will always name a class member, so we reject
10256       // that in the template definition.
10257     }
10258   }
10259
10260   // Check for invalid redeclarations.
10261   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
10262                                   SS, IdentLoc, Previous))
10263     return nullptr;
10264
10265   // Check for bad qualifiers.
10266   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
10267                               IdentLoc))
10268     return nullptr;
10269
10270   DeclContext *LookupContext = computeDeclContext(SS);
10271   NamedDecl *D;
10272   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10273   if (!LookupContext || EllipsisLoc.isValid()) {
10274     if (HasTypenameKeyword) {
10275       // FIXME: not all declaration name kinds are legal here
10276       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
10277                                               UsingLoc, TypenameLoc,
10278                                               QualifierLoc,
10279                                               IdentLoc, NameInfo.getName(),
10280                                               EllipsisLoc);
10281     } else {
10282       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
10283                                            QualifierLoc, NameInfo, EllipsisLoc);
10284     }
10285     D->setAccess(AS);
10286     CurContext->addDecl(D);
10287     return D;
10288   }
10289
10290   auto Build = [&](bool Invalid) {
10291     UsingDecl *UD =
10292         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
10293                           UsingName, HasTypenameKeyword);
10294     UD->setAccess(AS);
10295     CurContext->addDecl(UD);
10296     UD->setInvalidDecl(Invalid);
10297     return UD;
10298   };
10299   auto BuildInvalid = [&]{ return Build(true); };
10300   auto BuildValid = [&]{ return Build(false); };
10301
10302   if (RequireCompleteDeclContext(SS, LookupContext))
10303     return BuildInvalid();
10304
10305   // Look up the target name.
10306   LookupResult R(*this, NameInfo, LookupOrdinaryName);
10307
10308   // Unlike most lookups, we don't always want to hide tag
10309   // declarations: tag names are visible through the using declaration
10310   // even if hidden by ordinary names, *except* in a dependent context
10311   // where it's important for the sanity of two-phase lookup.
10312   if (!IsInstantiation)
10313     R.setHideTags(false);
10314
10315   // For the purposes of this lookup, we have a base object type
10316   // equal to that of the current context.
10317   if (CurContext->isRecord()) {
10318     R.setBaseObjectType(
10319                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
10320   }
10321
10322   LookupQualifiedName(R, LookupContext);
10323
10324   // Try to correct typos if possible. If constructor name lookup finds no
10325   // results, that means the named class has no explicit constructors, and we
10326   // suppressed declaring implicit ones (probably because it's dependent or
10327   // invalid).
10328   if (R.empty() &&
10329       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
10330     // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
10331     // it will believe that glibc provides a ::gets in cases where it does not,
10332     // and will try to pull it into namespace std with a using-declaration.
10333     // Just ignore the using-declaration in that case.
10334     auto *II = NameInfo.getName().getAsIdentifierInfo();
10335     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
10336         CurContext->isStdNamespace() &&
10337         isa<TranslationUnitDecl>(LookupContext) &&
10338         getSourceManager().isInSystemHeader(UsingLoc))
10339       return nullptr;
10340     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
10341                           dyn_cast<CXXRecordDecl>(CurContext));
10342     if (TypoCorrection Corrected =
10343             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
10344                         CTK_ErrorRecovery)) {
10345       // We reject candidates where DroppedSpecifier == true, hence the
10346       // literal '0' below.
10347       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
10348                                 << NameInfo.getName() << LookupContext << 0
10349                                 << SS.getRange());
10350
10351       // If we picked a correction with no attached Decl we can't do anything
10352       // useful with it, bail out.
10353       NamedDecl *ND = Corrected.getCorrectionDecl();
10354       if (!ND)
10355         return BuildInvalid();
10356
10357       // If we corrected to an inheriting constructor, handle it as one.
10358       auto *RD = dyn_cast<CXXRecordDecl>(ND);
10359       if (RD && RD->isInjectedClassName()) {
10360         // The parent of the injected class name is the class itself.
10361         RD = cast<CXXRecordDecl>(RD->getParent());
10362
10363         // Fix up the information we'll use to build the using declaration.
10364         if (Corrected.WillReplaceSpecifier()) {
10365           NestedNameSpecifierLocBuilder Builder;
10366           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
10367                               QualifierLoc.getSourceRange());
10368           QualifierLoc = Builder.getWithLocInContext(Context);
10369         }
10370
10371         // In this case, the name we introduce is the name of a derived class
10372         // constructor.
10373         auto *CurClass = cast<CXXRecordDecl>(CurContext);
10374         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
10375             Context.getCanonicalType(Context.getRecordType(CurClass))));
10376         UsingName.setNamedTypeInfo(nullptr);
10377         for (auto *Ctor : LookupConstructors(RD))
10378           R.addDecl(Ctor);
10379         R.resolveKind();
10380       } else {
10381         // FIXME: Pick up all the declarations if we found an overloaded
10382         // function.
10383         UsingName.setName(ND->getDeclName());
10384         R.addDecl(ND);
10385       }
10386     } else {
10387       Diag(IdentLoc, diag::err_no_member)
10388         << NameInfo.getName() << LookupContext << SS.getRange();
10389       return BuildInvalid();
10390     }
10391   }
10392
10393   if (R.isAmbiguous())
10394     return BuildInvalid();
10395
10396   if (HasTypenameKeyword) {
10397     // If we asked for a typename and got a non-type decl, error out.
10398     if (!R.getAsSingle<TypeDecl>()) {
10399       Diag(IdentLoc, diag::err_using_typename_non_type);
10400       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10401         Diag((*I)->getUnderlyingDecl()->getLocation(),
10402              diag::note_using_decl_target);
10403       return BuildInvalid();
10404     }
10405   } else {
10406     // If we asked for a non-typename and we got a type, error out,
10407     // but only if this is an instantiation of an unresolved using
10408     // decl.  Otherwise just silently find the type name.
10409     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
10410       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
10411       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
10412       return BuildInvalid();
10413     }
10414   }
10415
10416   // C++14 [namespace.udecl]p6:
10417   // A using-declaration shall not name a namespace.
10418   if (R.getAsSingle<NamespaceDecl>()) {
10419     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
10420       << SS.getRange();
10421     return BuildInvalid();
10422   }
10423
10424   // C++14 [namespace.udecl]p7:
10425   // A using-declaration shall not name a scoped enumerator.
10426   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
10427     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
10428       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
10429         << SS.getRange();
10430       return BuildInvalid();
10431     }
10432   }
10433
10434   UsingDecl *UD = BuildValid();
10435
10436   // Some additional rules apply to inheriting constructors.
10437   if (UsingName.getName().getNameKind() ==
10438         DeclarationName::CXXConstructorName) {
10439     // Suppress access diagnostics; the access check is instead performed at the
10440     // point of use for an inheriting constructor.
10441     R.suppressDiagnostics();
10442     if (CheckInheritingConstructorUsingDecl(UD))
10443       return UD;
10444   }
10445
10446   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
10447     UsingShadowDecl *PrevDecl = nullptr;
10448     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
10449       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
10450   }
10451
10452   return UD;
10453 }
10454
10455 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
10456                                     ArrayRef<NamedDecl *> Expansions) {
10457   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
10458          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
10459          isa<UsingPackDecl>(InstantiatedFrom));
10460
10461   auto *UPD =
10462       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
10463   UPD->setAccess(InstantiatedFrom->getAccess());
10464   CurContext->addDecl(UPD);
10465   return UPD;
10466 }
10467
10468 /// Additional checks for a using declaration referring to a constructor name.
10469 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
10470   assert(!UD->hasTypename() && "expecting a constructor name");
10471
10472   const Type *SourceType = UD->getQualifier()->getAsType();
10473   assert(SourceType &&
10474          "Using decl naming constructor doesn't have type in scope spec.");
10475   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
10476
10477   // Check whether the named type is a direct base class.
10478   bool AnyDependentBases = false;
10479   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
10480                                       AnyDependentBases);
10481   if (!Base && !AnyDependentBases) {
10482     Diag(UD->getUsingLoc(),
10483          diag::err_using_decl_constructor_not_in_direct_base)
10484       << UD->getNameInfo().getSourceRange()
10485       << QualType(SourceType, 0) << TargetClass;
10486     UD->setInvalidDecl();
10487     return true;
10488   }
10489
10490   if (Base)
10491     Base->setInheritConstructors();
10492
10493   return false;
10494 }
10495
10496 /// Checks that the given using declaration is not an invalid
10497 /// redeclaration.  Note that this is checking only for the using decl
10498 /// itself, not for any ill-formedness among the UsingShadowDecls.
10499 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
10500                                        bool HasTypenameKeyword,
10501                                        const CXXScopeSpec &SS,
10502                                        SourceLocation NameLoc,
10503                                        const LookupResult &Prev) {
10504   NestedNameSpecifier *Qual = SS.getScopeRep();
10505
10506   // C++03 [namespace.udecl]p8:
10507   // C++0x [namespace.udecl]p10:
10508   //   A using-declaration is a declaration and can therefore be used
10509   //   repeatedly where (and only where) multiple declarations are
10510   //   allowed.
10511   //
10512   // That's in non-member contexts.
10513   if (!CurContext->getRedeclContext()->isRecord()) {
10514     // A dependent qualifier outside a class can only ever resolve to an
10515     // enumeration type. Therefore it conflicts with any other non-type
10516     // declaration in the same scope.
10517     // FIXME: How should we check for dependent type-type conflicts at block
10518     // scope?
10519     if (Qual->isDependent() && !HasTypenameKeyword) {
10520       for (auto *D : Prev) {
10521         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
10522           bool OldCouldBeEnumerator =
10523               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
10524           Diag(NameLoc,
10525                OldCouldBeEnumerator ? diag::err_redefinition
10526                                     : diag::err_redefinition_different_kind)
10527               << Prev.getLookupName();
10528           Diag(D->getLocation(), diag::note_previous_definition);
10529           return true;
10530         }
10531       }
10532     }
10533     return false;
10534   }
10535
10536   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
10537     NamedDecl *D = *I;
10538
10539     bool DTypename;
10540     NestedNameSpecifier *DQual;
10541     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
10542       DTypename = UD->hasTypename();
10543       DQual = UD->getQualifier();
10544     } else if (UnresolvedUsingValueDecl *UD
10545                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
10546       DTypename = false;
10547       DQual = UD->getQualifier();
10548     } else if (UnresolvedUsingTypenameDecl *UD
10549                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
10550       DTypename = true;
10551       DQual = UD->getQualifier();
10552     } else continue;
10553
10554     // using decls differ if one says 'typename' and the other doesn't.
10555     // FIXME: non-dependent using decls?
10556     if (HasTypenameKeyword != DTypename) continue;
10557
10558     // using decls differ if they name different scopes (but note that
10559     // template instantiation can cause this check to trigger when it
10560     // didn't before instantiation).
10561     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
10562         Context.getCanonicalNestedNameSpecifier(DQual))
10563       continue;
10564
10565     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
10566     Diag(D->getLocation(), diag::note_using_decl) << 1;
10567     return true;
10568   }
10569
10570   return false;
10571 }
10572
10573
10574 /// Checks that the given nested-name qualifier used in a using decl
10575 /// in the current context is appropriately related to the current
10576 /// scope.  If an error is found, diagnoses it and returns true.
10577 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
10578                                    bool HasTypename,
10579                                    const CXXScopeSpec &SS,
10580                                    const DeclarationNameInfo &NameInfo,
10581                                    SourceLocation NameLoc) {
10582   DeclContext *NamedContext = computeDeclContext(SS);
10583
10584   if (!CurContext->isRecord()) {
10585     // C++03 [namespace.udecl]p3:
10586     // C++0x [namespace.udecl]p8:
10587     //   A using-declaration for a class member shall be a member-declaration.
10588
10589     // If we weren't able to compute a valid scope, it might validly be a
10590     // dependent class scope or a dependent enumeration unscoped scope. If
10591     // we have a 'typename' keyword, the scope must resolve to a class type.
10592     if ((HasTypename && !NamedContext) ||
10593         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
10594       auto *RD = NamedContext
10595                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
10596                      : nullptr;
10597       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
10598         RD = nullptr;
10599
10600       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
10601         << SS.getRange();
10602
10603       // If we have a complete, non-dependent source type, try to suggest a
10604       // way to get the same effect.
10605       if (!RD)
10606         return true;
10607
10608       // Find what this using-declaration was referring to.
10609       LookupResult R(*this, NameInfo, LookupOrdinaryName);
10610       R.setHideTags(false);
10611       R.suppressDiagnostics();
10612       LookupQualifiedName(R, RD);
10613
10614       if (R.getAsSingle<TypeDecl>()) {
10615         if (getLangOpts().CPlusPlus11) {
10616           // Convert 'using X::Y;' to 'using Y = X::Y;'.
10617           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
10618             << 0 // alias declaration
10619             << FixItHint::CreateInsertion(SS.getBeginLoc(),
10620                                           NameInfo.getName().getAsString() +
10621                                               " = ");
10622         } else {
10623           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
10624           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
10625           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
10626             << 1 // typedef declaration
10627             << FixItHint::CreateReplacement(UsingLoc, "typedef")
10628             << FixItHint::CreateInsertion(
10629                    InsertLoc, " " + NameInfo.getName().getAsString());
10630         }
10631       } else if (R.getAsSingle<VarDecl>()) {
10632         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10633         // repeating the type of the static data member here.
10634         FixItHint FixIt;
10635         if (getLangOpts().CPlusPlus11) {
10636           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10637           FixIt = FixItHint::CreateReplacement(
10638               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
10639         }
10640
10641         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10642           << 2 // reference declaration
10643           << FixIt;
10644       } else if (R.getAsSingle<EnumConstantDecl>()) {
10645         // Don't provide a fixit outside C++11 mode; we don't want to suggest
10646         // repeating the type of the enumeration here, and we can't do so if
10647         // the type is anonymous.
10648         FixItHint FixIt;
10649         if (getLangOpts().CPlusPlus11) {
10650           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10651           FixIt = FixItHint::CreateReplacement(
10652               UsingLoc,
10653               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
10654         }
10655
10656         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10657           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
10658           << FixIt;
10659       }
10660       return true;
10661     }
10662
10663     // Otherwise, this might be valid.
10664     return false;
10665   }
10666
10667   // The current scope is a record.
10668
10669   // If the named context is dependent, we can't decide much.
10670   if (!NamedContext) {
10671     // FIXME: in C++0x, we can diagnose if we can prove that the
10672     // nested-name-specifier does not refer to a base class, which is
10673     // still possible in some cases.
10674
10675     // Otherwise we have to conservatively report that things might be
10676     // okay.
10677     return false;
10678   }
10679
10680   if (!NamedContext->isRecord()) {
10681     // Ideally this would point at the last name in the specifier,
10682     // but we don't have that level of source info.
10683     Diag(SS.getRange().getBegin(),
10684          diag::err_using_decl_nested_name_specifier_is_not_class)
10685       << SS.getScopeRep() << SS.getRange();
10686     return true;
10687   }
10688
10689   if (!NamedContext->isDependentContext() &&
10690       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
10691     return true;
10692
10693   if (getLangOpts().CPlusPlus11) {
10694     // C++11 [namespace.udecl]p3:
10695     //   In a using-declaration used as a member-declaration, the
10696     //   nested-name-specifier shall name a base class of the class
10697     //   being defined.
10698
10699     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
10700                                  cast<CXXRecordDecl>(NamedContext))) {
10701       if (CurContext == NamedContext) {
10702         Diag(NameLoc,
10703              diag::err_using_decl_nested_name_specifier_is_current_class)
10704           << SS.getRange();
10705         return true;
10706       }
10707
10708       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
10709         Diag(SS.getRange().getBegin(),
10710              diag::err_using_decl_nested_name_specifier_is_not_base_class)
10711           << SS.getScopeRep()
10712           << cast<CXXRecordDecl>(CurContext)
10713           << SS.getRange();
10714       }
10715       return true;
10716     }
10717
10718     return false;
10719   }
10720
10721   // C++03 [namespace.udecl]p4:
10722   //   A using-declaration used as a member-declaration shall refer
10723   //   to a member of a base class of the class being defined [etc.].
10724
10725   // Salient point: SS doesn't have to name a base class as long as
10726   // lookup only finds members from base classes.  Therefore we can
10727   // diagnose here only if we can prove that that can't happen,
10728   // i.e. if the class hierarchies provably don't intersect.
10729
10730   // TODO: it would be nice if "definitely valid" results were cached
10731   // in the UsingDecl and UsingShadowDecl so that these checks didn't
10732   // need to be repeated.
10733
10734   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
10735   auto Collect = [&Bases](const CXXRecordDecl *Base) {
10736     Bases.insert(Base);
10737     return true;
10738   };
10739
10740   // Collect all bases. Return false if we find a dependent base.
10741   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
10742     return false;
10743
10744   // Returns true if the base is dependent or is one of the accumulated base
10745   // classes.
10746   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
10747     return !Bases.count(Base);
10748   };
10749
10750   // Return false if the class has a dependent base or if it or one
10751   // of its bases is present in the base set of the current context.
10752   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
10753       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
10754     return false;
10755
10756   Diag(SS.getRange().getBegin(),
10757        diag::err_using_decl_nested_name_specifier_is_not_base_class)
10758     << SS.getScopeRep()
10759     << cast<CXXRecordDecl>(CurContext)
10760     << SS.getRange();
10761
10762   return true;
10763 }
10764
10765 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
10766                                   MultiTemplateParamsArg TemplateParamLists,
10767                                   SourceLocation UsingLoc, UnqualifiedId &Name,
10768                                   const ParsedAttributesView &AttrList,
10769                                   TypeResult Type, Decl *DeclFromDeclSpec) {
10770   // Skip up to the relevant declaration scope.
10771   while (S->isTemplateParamScope())
10772     S = S->getParent();
10773   assert((S->getFlags() & Scope::DeclScope) &&
10774          "got alias-declaration outside of declaration scope");
10775
10776   if (Type.isInvalid())
10777     return nullptr;
10778
10779   bool Invalid = false;
10780   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
10781   TypeSourceInfo *TInfo = nullptr;
10782   GetTypeFromParser(Type.get(), &TInfo);
10783
10784   if (DiagnoseClassNameShadow(CurContext, NameInfo))
10785     return nullptr;
10786
10787   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
10788                                       UPPC_DeclarationType)) {
10789     Invalid = true;
10790     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10791                                              TInfo->getTypeLoc().getBeginLoc());
10792   }
10793
10794   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10795                         TemplateParamLists.size()
10796                             ? forRedeclarationInCurContext()
10797                             : ForVisibleRedeclaration);
10798   LookupName(Previous, S);
10799
10800   // Warn about shadowing the name of a template parameter.
10801   if (Previous.isSingleResult() &&
10802       Previous.getFoundDecl()->isTemplateParameter()) {
10803     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
10804     Previous.clear();
10805   }
10806
10807   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
10808          "name in alias declaration must be an identifier");
10809   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
10810                                                Name.StartLocation,
10811                                                Name.Identifier, TInfo);
10812
10813   NewTD->setAccess(AS);
10814
10815   if (Invalid)
10816     NewTD->setInvalidDecl();
10817
10818   ProcessDeclAttributeList(S, NewTD, AttrList);
10819   AddPragmaAttributes(S, NewTD);
10820
10821   CheckTypedefForVariablyModifiedType(S, NewTD);
10822   Invalid |= NewTD->isInvalidDecl();
10823
10824   bool Redeclaration = false;
10825
10826   NamedDecl *NewND;
10827   if (TemplateParamLists.size()) {
10828     TypeAliasTemplateDecl *OldDecl = nullptr;
10829     TemplateParameterList *OldTemplateParams = nullptr;
10830
10831     if (TemplateParamLists.size() != 1) {
10832       Diag(UsingLoc, diag::err_alias_template_extra_headers)
10833         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
10834          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
10835     }
10836     TemplateParameterList *TemplateParams = TemplateParamLists[0];
10837
10838     // Check that we can declare a template here.
10839     if (CheckTemplateDeclScope(S, TemplateParams))
10840       return nullptr;
10841
10842     // Only consider previous declarations in the same scope.
10843     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
10844                          /*ExplicitInstantiationOrSpecialization*/false);
10845     if (!Previous.empty()) {
10846       Redeclaration = true;
10847
10848       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
10849       if (!OldDecl && !Invalid) {
10850         Diag(UsingLoc, diag::err_redefinition_different_kind)
10851           << Name.Identifier;
10852
10853         NamedDecl *OldD = Previous.getRepresentativeDecl();
10854         if (OldD->getLocation().isValid())
10855           Diag(OldD->getLocation(), diag::note_previous_definition);
10856
10857         Invalid = true;
10858       }
10859
10860       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
10861         if (TemplateParameterListsAreEqual(TemplateParams,
10862                                            OldDecl->getTemplateParameters(),
10863                                            /*Complain=*/true,
10864                                            TPL_TemplateMatch))
10865           OldTemplateParams =
10866               OldDecl->getMostRecentDecl()->getTemplateParameters();
10867         else
10868           Invalid = true;
10869
10870         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
10871         if (!Invalid &&
10872             !Context.hasSameType(OldTD->getUnderlyingType(),
10873                                  NewTD->getUnderlyingType())) {
10874           // FIXME: The C++0x standard does not clearly say this is ill-formed,
10875           // but we can't reasonably accept it.
10876           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
10877             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
10878           if (OldTD->getLocation().isValid())
10879             Diag(OldTD->getLocation(), diag::note_previous_definition);
10880           Invalid = true;
10881         }
10882       }
10883     }
10884
10885     // Merge any previous default template arguments into our parameters,
10886     // and check the parameter list.
10887     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
10888                                    TPC_TypeAliasTemplate))
10889       return nullptr;
10890
10891     TypeAliasTemplateDecl *NewDecl =
10892       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
10893                                     Name.Identifier, TemplateParams,
10894                                     NewTD);
10895     NewTD->setDescribedAliasTemplate(NewDecl);
10896
10897     NewDecl->setAccess(AS);
10898
10899     if (Invalid)
10900       NewDecl->setInvalidDecl();
10901     else if (OldDecl) {
10902       NewDecl->setPreviousDecl(OldDecl);
10903       CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
10904     }
10905
10906     NewND = NewDecl;
10907   } else {
10908     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
10909       setTagNameForLinkagePurposes(TD, NewTD);
10910       handleTagNumbering(TD, S);
10911     }
10912     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
10913     NewND = NewTD;
10914   }
10915
10916   PushOnScopeChains(NewND, S);
10917   ActOnDocumentableDecl(NewND);
10918   return NewND;
10919 }
10920
10921 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
10922                                    SourceLocation AliasLoc,
10923                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
10924                                    SourceLocation IdentLoc,
10925                                    IdentifierInfo *Ident) {
10926
10927   // Lookup the namespace name.
10928   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
10929   LookupParsedName(R, S, &SS);
10930
10931   if (R.isAmbiguous())
10932     return nullptr;
10933
10934   if (R.empty()) {
10935     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
10936       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
10937       return nullptr;
10938     }
10939   }
10940   assert(!R.isAmbiguous() && !R.empty());
10941   NamedDecl *ND = R.getRepresentativeDecl();
10942
10943   // Check if we have a previous declaration with the same name.
10944   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
10945                      ForVisibleRedeclaration);
10946   LookupName(PrevR, S);
10947
10948   // Check we're not shadowing a template parameter.
10949   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
10950     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
10951     PrevR.clear();
10952   }
10953
10954   // Filter out any other lookup result from an enclosing scope.
10955   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
10956                        /*AllowInlineNamespace*/false);
10957
10958   // Find the previous declaration and check that we can redeclare it.
10959   NamespaceAliasDecl *Prev = nullptr;
10960   if (PrevR.isSingleResult()) {
10961     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
10962     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
10963       // We already have an alias with the same name that points to the same
10964       // namespace; check that it matches.
10965       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
10966         Prev = AD;
10967       } else if (isVisible(PrevDecl)) {
10968         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
10969           << Alias;
10970         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
10971           << AD->getNamespace();
10972         return nullptr;
10973       }
10974     } else if (isVisible(PrevDecl)) {
10975       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
10976                             ? diag::err_redefinition
10977                             : diag::err_redefinition_different_kind;
10978       Diag(AliasLoc, DiagID) << Alias;
10979       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10980       return nullptr;
10981     }
10982   }
10983
10984   // The use of a nested name specifier may trigger deprecation warnings.
10985   DiagnoseUseOfDecl(ND, IdentLoc);
10986
10987   NamespaceAliasDecl *AliasDecl =
10988     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
10989                                Alias, SS.getWithLocInContext(Context),
10990                                IdentLoc, ND);
10991   if (Prev)
10992     AliasDecl->setPreviousDecl(Prev);
10993
10994   PushOnScopeChains(AliasDecl, S);
10995   return AliasDecl;
10996 }
10997
10998 namespace {
10999 struct SpecialMemberExceptionSpecInfo
11000     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
11001   SourceLocation Loc;
11002   Sema::ImplicitExceptionSpecification ExceptSpec;
11003
11004   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
11005                                  Sema::CXXSpecialMember CSM,
11006                                  Sema::InheritedConstructorInfo *ICI,
11007                                  SourceLocation Loc)
11008       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
11009
11010   bool visitBase(CXXBaseSpecifier *Base);
11011   bool visitField(FieldDecl *FD);
11012
11013   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
11014                            unsigned Quals);
11015
11016   void visitSubobjectCall(Subobject Subobj,
11017                           Sema::SpecialMemberOverloadResult SMOR);
11018 };
11019 }
11020
11021 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
11022   auto *RT = Base->getType()->getAs<RecordType>();
11023   if (!RT)
11024     return false;
11025
11026   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
11027   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
11028   if (auto *BaseCtor = SMOR.getMethod()) {
11029     visitSubobjectCall(Base, BaseCtor);
11030     return false;
11031   }
11032
11033   visitClassSubobject(BaseClass, Base, 0);
11034   return false;
11035 }
11036
11037 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
11038   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
11039     Expr *E = FD->getInClassInitializer();
11040     if (!E)
11041       // FIXME: It's a little wasteful to build and throw away a
11042       // CXXDefaultInitExpr here.
11043       // FIXME: We should have a single context note pointing at Loc, and
11044       // this location should be MD->getLocation() instead, since that's
11045       // the location where we actually use the default init expression.
11046       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
11047     if (E)
11048       ExceptSpec.CalledExpr(E);
11049   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
11050                             ->getAs<RecordType>()) {
11051     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
11052                         FD->getType().getCVRQualifiers());
11053   }
11054   return false;
11055 }
11056
11057 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
11058                                                          Subobject Subobj,
11059                                                          unsigned Quals) {
11060   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
11061   bool IsMutable = Field && Field->isMutable();
11062   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
11063 }
11064
11065 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
11066     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
11067   // Note, if lookup fails, it doesn't matter what exception specification we
11068   // choose because the special member will be deleted.
11069   if (CXXMethodDecl *MD = SMOR.getMethod())
11070     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
11071 }
11072
11073 namespace {
11074 /// RAII object to register a special member as being currently declared.
11075 struct ComputingExceptionSpec {
11076   Sema &S;
11077
11078   ComputingExceptionSpec(Sema &S, CXXMethodDecl *MD, SourceLocation Loc)
11079       : S(S) {
11080     Sema::CodeSynthesisContext Ctx;
11081     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
11082     Ctx.PointOfInstantiation = Loc;
11083     Ctx.Entity = MD;
11084     S.pushCodeSynthesisContext(Ctx);
11085   }
11086   ~ComputingExceptionSpec() {
11087     S.popCodeSynthesisContext();
11088   }
11089 };
11090 }
11091
11092 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
11093   llvm::APSInt Result;
11094   ExprResult Converted = CheckConvertedConstantExpression(
11095       ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
11096   ExplicitSpec.setExpr(Converted.get());
11097   if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
11098     ExplicitSpec.setKind(Result.getBoolValue()
11099                              ? ExplicitSpecKind::ResolvedTrue
11100                              : ExplicitSpecKind::ResolvedFalse);
11101     return true;
11102   }
11103   ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
11104   return false;
11105 }
11106
11107 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
11108   ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
11109   if (!ExplicitExpr->isTypeDependent())
11110     tryResolveExplicitSpecifier(ES);
11111   return ES;
11112 }
11113
11114 static Sema::ImplicitExceptionSpecification
11115 ComputeDefaultedSpecialMemberExceptionSpec(
11116     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
11117     Sema::InheritedConstructorInfo *ICI) {
11118   ComputingExceptionSpec CES(S, MD, Loc);
11119
11120   CXXRecordDecl *ClassDecl = MD->getParent();
11121
11122   // C++ [except.spec]p14:
11123   //   An implicitly declared special member function (Clause 12) shall have an
11124   //   exception-specification. [...]
11125   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
11126   if (ClassDecl->isInvalidDecl())
11127     return Info.ExceptSpec;
11128
11129   // FIXME: If this diagnostic fires, we're probably missing a check for
11130   // attempting to resolve an exception specification before it's known
11131   // at a higher level.
11132   if (S.RequireCompleteType(MD->getLocation(),
11133                             S.Context.getRecordType(ClassDecl),
11134                             diag::err_exception_spec_incomplete_type))
11135     return Info.ExceptSpec;
11136
11137   // C++1z [except.spec]p7:
11138   //   [Look for exceptions thrown by] a constructor selected [...] to
11139   //   initialize a potentially constructed subobject,
11140   // C++1z [except.spec]p8:
11141   //   The exception specification for an implicitly-declared destructor, or a
11142   //   destructor without a noexcept-specifier, is potentially-throwing if and
11143   //   only if any of the destructors for any of its potentially constructed
11144   //   subojects is potentially throwing.
11145   // FIXME: We respect the first rule but ignore the "potentially constructed"
11146   // in the second rule to resolve a core issue (no number yet) that would have
11147   // us reject:
11148   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
11149   //   struct B : A {};
11150   //   struct C : B { void f(); };
11151   // ... due to giving B::~B() a non-throwing exception specification.
11152   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
11153                                 : Info.VisitAllBases);
11154
11155   return Info.ExceptSpec;
11156 }
11157
11158 namespace {
11159 /// RAII object to register a special member as being currently declared.
11160 struct DeclaringSpecialMember {
11161   Sema &S;
11162   Sema::SpecialMemberDecl D;
11163   Sema::ContextRAII SavedContext;
11164   bool WasAlreadyBeingDeclared;
11165
11166   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
11167       : S(S), D(RD, CSM), SavedContext(S, RD) {
11168     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
11169     if (WasAlreadyBeingDeclared)
11170       // This almost never happens, but if it does, ensure that our cache
11171       // doesn't contain a stale result.
11172       S.SpecialMemberCache.clear();
11173     else {
11174       // Register a note to be produced if we encounter an error while
11175       // declaring the special member.
11176       Sema::CodeSynthesisContext Ctx;
11177       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
11178       // FIXME: We don't have a location to use here. Using the class's
11179       // location maintains the fiction that we declare all special members
11180       // with the class, but (1) it's not clear that lying about that helps our
11181       // users understand what's going on, and (2) there may be outer contexts
11182       // on the stack (some of which are relevant) and printing them exposes
11183       // our lies.
11184       Ctx.PointOfInstantiation = RD->getLocation();
11185       Ctx.Entity = RD;
11186       Ctx.SpecialMember = CSM;
11187       S.pushCodeSynthesisContext(Ctx);
11188     }
11189   }
11190   ~DeclaringSpecialMember() {
11191     if (!WasAlreadyBeingDeclared) {
11192       S.SpecialMembersBeingDeclared.erase(D);
11193       S.popCodeSynthesisContext();
11194     }
11195   }
11196
11197   /// Are we already trying to declare this special member?
11198   bool isAlreadyBeingDeclared() const {
11199     return WasAlreadyBeingDeclared;
11200   }
11201 };
11202 }
11203
11204 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
11205   // Look up any existing declarations, but don't trigger declaration of all
11206   // implicit special members with this name.
11207   DeclarationName Name = FD->getDeclName();
11208   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
11209                  ForExternalRedeclaration);
11210   for (auto *D : FD->getParent()->lookup(Name))
11211     if (auto *Acceptable = R.getAcceptableDecl(D))
11212       R.addDecl(Acceptable);
11213   R.resolveKind();
11214   R.suppressDiagnostics();
11215
11216   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
11217 }
11218
11219 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
11220                                           QualType ResultTy,
11221                                           ArrayRef<QualType> Args) {
11222   // Build an exception specification pointing back at this constructor.
11223   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
11224
11225   if (getLangOpts().OpenCLCPlusPlus) {
11226     // OpenCL: Implicitly defaulted special member are of the generic address
11227     // space.
11228     EPI.TypeQuals.addAddressSpace(LangAS::opencl_generic);
11229   }
11230
11231   auto QT = Context.getFunctionType(ResultTy, Args, EPI);
11232   SpecialMem->setType(QT);
11233 }
11234
11235 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
11236                                                      CXXRecordDecl *ClassDecl) {
11237   // C++ [class.ctor]p5:
11238   //   A default constructor for a class X is a constructor of class X
11239   //   that can be called without an argument. If there is no
11240   //   user-declared constructor for class X, a default constructor is
11241   //   implicitly declared. An implicitly-declared default constructor
11242   //   is an inline public member of its class.
11243   assert(ClassDecl->needsImplicitDefaultConstructor() &&
11244          "Should not build implicit default constructor!");
11245
11246   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
11247   if (DSM.isAlreadyBeingDeclared())
11248     return nullptr;
11249
11250   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11251                                                      CXXDefaultConstructor,
11252                                                      false);
11253
11254   // Create the actual constructor declaration.
11255   CanQualType ClassType
11256     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11257   SourceLocation ClassLoc = ClassDecl->getLocation();
11258   DeclarationName Name
11259     = Context.DeclarationNames.getCXXConstructorName(ClassType);
11260   DeclarationNameInfo NameInfo(Name, ClassLoc);
11261   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
11262       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
11263       /*TInfo=*/nullptr, ExplicitSpecifier(),
11264       /*isInline=*/true, /*isImplicitlyDeclared=*/true,
11265       Constexpr ? CSK_constexpr : CSK_unspecified);
11266   DefaultCon->setAccess(AS_public);
11267   DefaultCon->setDefaulted();
11268
11269   if (getLangOpts().CUDA) {
11270     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
11271                                             DefaultCon,
11272                                             /* ConstRHS */ false,
11273                                             /* Diagnose */ false);
11274   }
11275
11276   setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
11277
11278   // We don't need to use SpecialMemberIsTrivial here; triviality for default
11279   // constructors is easy to compute.
11280   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
11281
11282   // Note that we have declared this constructor.
11283   ++getASTContext().NumImplicitDefaultConstructorsDeclared;
11284
11285   Scope *S = getScopeForContext(ClassDecl);
11286   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
11287
11288   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
11289     SetDeclDeleted(DefaultCon, ClassLoc);
11290
11291   if (S)
11292     PushOnScopeChains(DefaultCon, S, false);
11293   ClassDecl->addDecl(DefaultCon);
11294
11295   return DefaultCon;
11296 }
11297
11298 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
11299                                             CXXConstructorDecl *Constructor) {
11300   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
11301           !Constructor->doesThisDeclarationHaveABody() &&
11302           !Constructor->isDeleted()) &&
11303     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
11304   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
11305     return;
11306
11307   CXXRecordDecl *ClassDecl = Constructor->getParent();
11308   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
11309
11310   SynthesizedFunctionScope Scope(*this, Constructor);
11311
11312   // The exception specification is needed because we are defining the
11313   // function.
11314   ResolveExceptionSpec(CurrentLocation,
11315                        Constructor->getType()->castAs<FunctionProtoType>());
11316   MarkVTableUsed(CurrentLocation, ClassDecl);
11317
11318   // Add a context note for diagnostics produced after this point.
11319   Scope.addContextNote(CurrentLocation);
11320
11321   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
11322     Constructor->setInvalidDecl();
11323     return;
11324   }
11325
11326   SourceLocation Loc = Constructor->getEndLoc().isValid()
11327                            ? Constructor->getEndLoc()
11328                            : Constructor->getLocation();
11329   Constructor->setBody(new (Context) CompoundStmt(Loc));
11330   Constructor->markUsed(Context);
11331
11332   if (ASTMutationListener *L = getASTMutationListener()) {
11333     L->CompletedImplicitDefinition(Constructor);
11334   }
11335
11336   DiagnoseUninitializedFields(*this, Constructor);
11337 }
11338
11339 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
11340   // Perform any delayed checks on exception specifications.
11341   CheckDelayedMemberExceptionSpecs();
11342 }
11343
11344 /// Find or create the fake constructor we synthesize to model constructing an
11345 /// object of a derived class via a constructor of a base class.
11346 CXXConstructorDecl *
11347 Sema::findInheritingConstructor(SourceLocation Loc,
11348                                 CXXConstructorDecl *BaseCtor,
11349                                 ConstructorUsingShadowDecl *Shadow) {
11350   CXXRecordDecl *Derived = Shadow->getParent();
11351   SourceLocation UsingLoc = Shadow->getLocation();
11352
11353   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
11354   // For now we use the name of the base class constructor as a member of the
11355   // derived class to indicate a (fake) inherited constructor name.
11356   DeclarationName Name = BaseCtor->getDeclName();
11357
11358   // Check to see if we already have a fake constructor for this inherited
11359   // constructor call.
11360   for (NamedDecl *Ctor : Derived->lookup(Name))
11361     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
11362                                ->getInheritedConstructor()
11363                                .getConstructor(),
11364                            BaseCtor))
11365       return cast<CXXConstructorDecl>(Ctor);
11366
11367   DeclarationNameInfo NameInfo(Name, UsingLoc);
11368   TypeSourceInfo *TInfo =
11369       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
11370   FunctionProtoTypeLoc ProtoLoc =
11371       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
11372
11373   // Check the inherited constructor is valid and find the list of base classes
11374   // from which it was inherited.
11375   InheritedConstructorInfo ICI(*this, Loc, Shadow);
11376
11377   bool Constexpr =
11378       BaseCtor->isConstexpr() &&
11379       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
11380                                         false, BaseCtor, &ICI);
11381
11382   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
11383       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
11384       BaseCtor->getExplicitSpecifier(), /*isInline=*/true,
11385       /*isImplicitlyDeclared=*/true,
11386       Constexpr ? BaseCtor->getConstexprKind() : CSK_unspecified,
11387       InheritedConstructor(Shadow, BaseCtor));
11388   if (Shadow->isInvalidDecl())
11389     DerivedCtor->setInvalidDecl();
11390
11391   // Build an unevaluated exception specification for this fake constructor.
11392   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
11393   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11394   EPI.ExceptionSpec.Type = EST_Unevaluated;
11395   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
11396   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
11397                                                FPT->getParamTypes(), EPI));
11398
11399   // Build the parameter declarations.
11400   SmallVector<ParmVarDecl *, 16> ParamDecls;
11401   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
11402     TypeSourceInfo *TInfo =
11403         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
11404     ParmVarDecl *PD = ParmVarDecl::Create(
11405         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
11406         FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
11407     PD->setScopeInfo(0, I);
11408     PD->setImplicit();
11409     // Ensure attributes are propagated onto parameters (this matters for
11410     // format, pass_object_size, ...).
11411     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
11412     ParamDecls.push_back(PD);
11413     ProtoLoc.setParam(I, PD);
11414   }
11415
11416   // Set up the new constructor.
11417   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
11418   DerivedCtor->setAccess(BaseCtor->getAccess());
11419   DerivedCtor->setParams(ParamDecls);
11420   Derived->addDecl(DerivedCtor);
11421
11422   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
11423     SetDeclDeleted(DerivedCtor, UsingLoc);
11424
11425   return DerivedCtor;
11426 }
11427
11428 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
11429   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
11430                                Ctor->getInheritedConstructor().getShadowDecl());
11431   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
11432                             /*Diagnose*/true);
11433 }
11434
11435 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
11436                                        CXXConstructorDecl *Constructor) {
11437   CXXRecordDecl *ClassDecl = Constructor->getParent();
11438   assert(Constructor->getInheritedConstructor() &&
11439          !Constructor->doesThisDeclarationHaveABody() &&
11440          !Constructor->isDeleted());
11441   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
11442     return;
11443
11444   // Initializations are performed "as if by a defaulted default constructor",
11445   // so enter the appropriate scope.
11446   SynthesizedFunctionScope Scope(*this, Constructor);
11447
11448   // The exception specification is needed because we are defining the
11449   // function.
11450   ResolveExceptionSpec(CurrentLocation,
11451                        Constructor->getType()->castAs<FunctionProtoType>());
11452   MarkVTableUsed(CurrentLocation, ClassDecl);
11453
11454   // Add a context note for diagnostics produced after this point.
11455   Scope.addContextNote(CurrentLocation);
11456
11457   ConstructorUsingShadowDecl *Shadow =
11458       Constructor->getInheritedConstructor().getShadowDecl();
11459   CXXConstructorDecl *InheritedCtor =
11460       Constructor->getInheritedConstructor().getConstructor();
11461
11462   // [class.inhctor.init]p1:
11463   //   initialization proceeds as if a defaulted default constructor is used to
11464   //   initialize the D object and each base class subobject from which the
11465   //   constructor was inherited
11466
11467   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
11468   CXXRecordDecl *RD = Shadow->getParent();
11469   SourceLocation InitLoc = Shadow->getLocation();
11470
11471   // Build explicit initializers for all base classes from which the
11472   // constructor was inherited.
11473   SmallVector<CXXCtorInitializer*, 8> Inits;
11474   for (bool VBase : {false, true}) {
11475     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
11476       if (B.isVirtual() != VBase)
11477         continue;
11478
11479       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
11480       if (!BaseRD)
11481         continue;
11482
11483       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
11484       if (!BaseCtor.first)
11485         continue;
11486
11487       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
11488       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
11489           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
11490
11491       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
11492       Inits.push_back(new (Context) CXXCtorInitializer(
11493           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
11494           SourceLocation()));
11495     }
11496   }
11497
11498   // We now proceed as if for a defaulted default constructor, with the relevant
11499   // initializers replaced.
11500
11501   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
11502     Constructor->setInvalidDecl();
11503     return;
11504   }
11505
11506   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
11507   Constructor->markUsed(Context);
11508
11509   if (ASTMutationListener *L = getASTMutationListener()) {
11510     L->CompletedImplicitDefinition(Constructor);
11511   }
11512
11513   DiagnoseUninitializedFields(*this, Constructor);
11514 }
11515
11516 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
11517   // C++ [class.dtor]p2:
11518   //   If a class has no user-declared destructor, a destructor is
11519   //   declared implicitly. An implicitly-declared destructor is an
11520   //   inline public member of its class.
11521   assert(ClassDecl->needsImplicitDestructor());
11522
11523   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
11524   if (DSM.isAlreadyBeingDeclared())
11525     return nullptr;
11526
11527   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11528                                                      CXXDestructor,
11529                                                      false);
11530
11531   // Create the actual destructor declaration.
11532   CanQualType ClassType
11533     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11534   SourceLocation ClassLoc = ClassDecl->getLocation();
11535   DeclarationName Name
11536     = Context.DeclarationNames.getCXXDestructorName(ClassType);
11537   DeclarationNameInfo NameInfo(Name, ClassLoc);
11538   CXXDestructorDecl *Destructor =
11539       CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
11540                                 QualType(), nullptr, /*isInline=*/true,
11541                                 /*isImplicitlyDeclared=*/true,
11542                                 Constexpr ? CSK_constexpr : CSK_unspecified);
11543   Destructor->setAccess(AS_public);
11544   Destructor->setDefaulted();
11545
11546   if (getLangOpts().CUDA) {
11547     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
11548                                             Destructor,
11549                                             /* ConstRHS */ false,
11550                                             /* Diagnose */ false);
11551   }
11552
11553   setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
11554
11555   // We don't need to use SpecialMemberIsTrivial here; triviality for
11556   // destructors is easy to compute.
11557   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
11558   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
11559                                 ClassDecl->hasTrivialDestructorForCall());
11560
11561   // Note that we have declared this destructor.
11562   ++getASTContext().NumImplicitDestructorsDeclared;
11563
11564   Scope *S = getScopeForContext(ClassDecl);
11565   CheckImplicitSpecialMemberDeclaration(S, Destructor);
11566
11567   // We can't check whether an implicit destructor is deleted before we complete
11568   // the definition of the class, because its validity depends on the alignment
11569   // of the class. We'll check this from ActOnFields once the class is complete.
11570   if (ClassDecl->isCompleteDefinition() &&
11571       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
11572     SetDeclDeleted(Destructor, ClassLoc);
11573
11574   // Introduce this destructor into its scope.
11575   if (S)
11576     PushOnScopeChains(Destructor, S, false);
11577   ClassDecl->addDecl(Destructor);
11578
11579   return Destructor;
11580 }
11581
11582 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
11583                                     CXXDestructorDecl *Destructor) {
11584   assert((Destructor->isDefaulted() &&
11585           !Destructor->doesThisDeclarationHaveABody() &&
11586           !Destructor->isDeleted()) &&
11587          "DefineImplicitDestructor - call it for implicit default dtor");
11588   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
11589     return;
11590
11591   CXXRecordDecl *ClassDecl = Destructor->getParent();
11592   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
11593
11594   SynthesizedFunctionScope Scope(*this, Destructor);
11595
11596   // The exception specification is needed because we are defining the
11597   // function.
11598   ResolveExceptionSpec(CurrentLocation,
11599                        Destructor->getType()->castAs<FunctionProtoType>());
11600   MarkVTableUsed(CurrentLocation, ClassDecl);
11601
11602   // Add a context note for diagnostics produced after this point.
11603   Scope.addContextNote(CurrentLocation);
11604
11605   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11606                                          Destructor->getParent());
11607
11608   if (CheckDestructor(Destructor)) {
11609     Destructor->setInvalidDecl();
11610     return;
11611   }
11612
11613   SourceLocation Loc = Destructor->getEndLoc().isValid()
11614                            ? Destructor->getEndLoc()
11615                            : Destructor->getLocation();
11616   Destructor->setBody(new (Context) CompoundStmt(Loc));
11617   Destructor->markUsed(Context);
11618
11619   if (ASTMutationListener *L = getASTMutationListener()) {
11620     L->CompletedImplicitDefinition(Destructor);
11621   }
11622 }
11623
11624 /// Perform any semantic analysis which needs to be delayed until all
11625 /// pending class member declarations have been parsed.
11626 void Sema::ActOnFinishCXXMemberDecls() {
11627   // If the context is an invalid C++ class, just suppress these checks.
11628   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
11629     if (Record->isInvalidDecl()) {
11630       DelayedOverridingExceptionSpecChecks.clear();
11631       DelayedEquivalentExceptionSpecChecks.clear();
11632       return;
11633     }
11634     checkForMultipleExportedDefaultConstructors(*this, Record);
11635   }
11636 }
11637
11638 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
11639   referenceDLLExportedClassMethods();
11640
11641   if (!DelayedDllExportMemberFunctions.empty()) {
11642     SmallVector<CXXMethodDecl*, 4> WorkList;
11643     std::swap(DelayedDllExportMemberFunctions, WorkList);
11644     for (CXXMethodDecl *M : WorkList) {
11645       DefineImplicitSpecialMember(*this, M, M->getLocation());
11646
11647       // Pass the method to the consumer to get emitted. This is not necessary
11648       // for explicit instantiation definitions, as they will get emitted
11649       // anyway.
11650       if (M->getParent()->getTemplateSpecializationKind() !=
11651           TSK_ExplicitInstantiationDefinition)
11652         ActOnFinishInlineFunctionDef(M);
11653     }
11654   }
11655 }
11656
11657 void Sema::referenceDLLExportedClassMethods() {
11658   if (!DelayedDllExportClasses.empty()) {
11659     // Calling ReferenceDllExportedMembers might cause the current function to
11660     // be called again, so use a local copy of DelayedDllExportClasses.
11661     SmallVector<CXXRecordDecl *, 4> WorkList;
11662     std::swap(DelayedDllExportClasses, WorkList);
11663     for (CXXRecordDecl *Class : WorkList)
11664       ReferenceDllExportedMembers(*this, Class);
11665   }
11666 }
11667
11668 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
11669   assert(getLangOpts().CPlusPlus11 &&
11670          "adjusting dtor exception specs was introduced in c++11");
11671
11672   if (Destructor->isDependentContext())
11673     return;
11674
11675   // C++11 [class.dtor]p3:
11676   //   A declaration of a destructor that does not have an exception-
11677   //   specification is implicitly considered to have the same exception-
11678   //   specification as an implicit declaration.
11679   const FunctionProtoType *DtorType = Destructor->getType()->
11680                                         getAs<FunctionProtoType>();
11681   if (DtorType->hasExceptionSpec())
11682     return;
11683
11684   // Replace the destructor's type, building off the existing one. Fortunately,
11685   // the only thing of interest in the destructor type is its extended info.
11686   // The return and arguments are fixed.
11687   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
11688   EPI.ExceptionSpec.Type = EST_Unevaluated;
11689   EPI.ExceptionSpec.SourceDecl = Destructor;
11690   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
11691
11692   // FIXME: If the destructor has a body that could throw, and the newly created
11693   // spec doesn't allow exceptions, we should emit a warning, because this
11694   // change in behavior can break conforming C++03 programs at runtime.
11695   // However, we don't have a body or an exception specification yet, so it
11696   // needs to be done somewhere else.
11697 }
11698
11699 namespace {
11700 /// An abstract base class for all helper classes used in building the
11701 //  copy/move operators. These classes serve as factory functions and help us
11702 //  avoid using the same Expr* in the AST twice.
11703 class ExprBuilder {
11704   ExprBuilder(const ExprBuilder&) = delete;
11705   ExprBuilder &operator=(const ExprBuilder&) = delete;
11706
11707 protected:
11708   static Expr *assertNotNull(Expr *E) {
11709     assert(E && "Expression construction must not fail.");
11710     return E;
11711   }
11712
11713 public:
11714   ExprBuilder() {}
11715   virtual ~ExprBuilder() {}
11716
11717   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
11718 };
11719
11720 class RefBuilder: public ExprBuilder {
11721   VarDecl *Var;
11722   QualType VarType;
11723
11724 public:
11725   Expr *build(Sema &S, SourceLocation Loc) const override {
11726     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
11727   }
11728
11729   RefBuilder(VarDecl *Var, QualType VarType)
11730       : Var(Var), VarType(VarType) {}
11731 };
11732
11733 class ThisBuilder: public ExprBuilder {
11734 public:
11735   Expr *build(Sema &S, SourceLocation Loc) const override {
11736     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
11737   }
11738 };
11739
11740 class CastBuilder: public ExprBuilder {
11741   const ExprBuilder &Builder;
11742   QualType Type;
11743   ExprValueKind Kind;
11744   const CXXCastPath &Path;
11745
11746 public:
11747   Expr *build(Sema &S, SourceLocation Loc) const override {
11748     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
11749                                              CK_UncheckedDerivedToBase, Kind,
11750                                              &Path).get());
11751   }
11752
11753   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
11754               const CXXCastPath &Path)
11755       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
11756 };
11757
11758 class DerefBuilder: public ExprBuilder {
11759   const ExprBuilder &Builder;
11760
11761 public:
11762   Expr *build(Sema &S, SourceLocation Loc) const override {
11763     return assertNotNull(
11764         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
11765   }
11766
11767   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11768 };
11769
11770 class MemberBuilder: public ExprBuilder {
11771   const ExprBuilder &Builder;
11772   QualType Type;
11773   CXXScopeSpec SS;
11774   bool IsArrow;
11775   LookupResult &MemberLookup;
11776
11777 public:
11778   Expr *build(Sema &S, SourceLocation Loc) const override {
11779     return assertNotNull(S.BuildMemberReferenceExpr(
11780         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
11781         nullptr, MemberLookup, nullptr, nullptr).get());
11782   }
11783
11784   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
11785                 LookupResult &MemberLookup)
11786       : Builder(Builder), Type(Type), IsArrow(IsArrow),
11787         MemberLookup(MemberLookup) {}
11788 };
11789
11790 class MoveCastBuilder: public ExprBuilder {
11791   const ExprBuilder &Builder;
11792
11793 public:
11794   Expr *build(Sema &S, SourceLocation Loc) const override {
11795     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
11796   }
11797
11798   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11799 };
11800
11801 class LvalueConvBuilder: public ExprBuilder {
11802   const ExprBuilder &Builder;
11803
11804 public:
11805   Expr *build(Sema &S, SourceLocation Loc) const override {
11806     return assertNotNull(
11807         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
11808   }
11809
11810   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11811 };
11812
11813 class SubscriptBuilder: public ExprBuilder {
11814   const ExprBuilder &Base;
11815   const ExprBuilder &Index;
11816
11817 public:
11818   Expr *build(Sema &S, SourceLocation Loc) const override {
11819     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
11820         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
11821   }
11822
11823   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
11824       : Base(Base), Index(Index) {}
11825 };
11826
11827 } // end anonymous namespace
11828
11829 /// When generating a defaulted copy or move assignment operator, if a field
11830 /// should be copied with __builtin_memcpy rather than via explicit assignments,
11831 /// do so. This optimization only applies for arrays of scalars, and for arrays
11832 /// of class type where the selected copy/move-assignment operator is trivial.
11833 static StmtResult
11834 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
11835                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
11836   // Compute the size of the memory buffer to be copied.
11837   QualType SizeType = S.Context.getSizeType();
11838   llvm::APInt Size(S.Context.getTypeSize(SizeType),
11839                    S.Context.getTypeSizeInChars(T).getQuantity());
11840
11841   // Take the address of the field references for "from" and "to". We
11842   // directly construct UnaryOperators here because semantic analysis
11843   // does not permit us to take the address of an xvalue.
11844   Expr *From = FromB.build(S, Loc);
11845   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
11846                          S.Context.getPointerType(From->getType()),
11847                          VK_RValue, OK_Ordinary, Loc, false);
11848   Expr *To = ToB.build(S, Loc);
11849   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
11850                        S.Context.getPointerType(To->getType()),
11851                        VK_RValue, OK_Ordinary, Loc, false);
11852
11853   const Type *E = T->getBaseElementTypeUnsafe();
11854   bool NeedsCollectableMemCpy =
11855       E->isRecordType() &&
11856       E->castAs<RecordType>()->getDecl()->hasObjectMember();
11857
11858   // Create a reference to the __builtin_objc_memmove_collectable function
11859   StringRef MemCpyName = NeedsCollectableMemCpy ?
11860     "__builtin_objc_memmove_collectable" :
11861     "__builtin_memcpy";
11862   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
11863                  Sema::LookupOrdinaryName);
11864   S.LookupName(R, S.TUScope, true);
11865
11866   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
11867   if (!MemCpy)
11868     // Something went horribly wrong earlier, and we will have complained
11869     // about it.
11870     return StmtError();
11871
11872   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
11873                                             VK_RValue, Loc, nullptr);
11874   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
11875
11876   Expr *CallArgs[] = {
11877     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
11878   };
11879   ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
11880                                     Loc, CallArgs, Loc);
11881
11882   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
11883   return Call.getAs<Stmt>();
11884 }
11885
11886 /// Builds a statement that copies/moves the given entity from \p From to
11887 /// \c To.
11888 ///
11889 /// This routine is used to copy/move the members of a class with an
11890 /// implicitly-declared copy/move assignment operator. When the entities being
11891 /// copied are arrays, this routine builds for loops to copy them.
11892 ///
11893 /// \param S The Sema object used for type-checking.
11894 ///
11895 /// \param Loc The location where the implicit copy/move is being generated.
11896 ///
11897 /// \param T The type of the expressions being copied/moved. Both expressions
11898 /// must have this type.
11899 ///
11900 /// \param To The expression we are copying/moving to.
11901 ///
11902 /// \param From The expression we are copying/moving from.
11903 ///
11904 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
11905 /// Otherwise, it's a non-static member subobject.
11906 ///
11907 /// \param Copying Whether we're copying or moving.
11908 ///
11909 /// \param Depth Internal parameter recording the depth of the recursion.
11910 ///
11911 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
11912 /// if a memcpy should be used instead.
11913 static StmtResult
11914 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
11915                                  const ExprBuilder &To, const ExprBuilder &From,
11916                                  bool CopyingBaseSubobject, bool Copying,
11917                                  unsigned Depth = 0) {
11918   // C++11 [class.copy]p28:
11919   //   Each subobject is assigned in the manner appropriate to its type:
11920   //
11921   //     - if the subobject is of class type, as if by a call to operator= with
11922   //       the subobject as the object expression and the corresponding
11923   //       subobject of x as a single function argument (as if by explicit
11924   //       qualification; that is, ignoring any possible virtual overriding
11925   //       functions in more derived classes);
11926   //
11927   // C++03 [class.copy]p13:
11928   //     - if the subobject is of class type, the copy assignment operator for
11929   //       the class is used (as if by explicit qualification; that is,
11930   //       ignoring any possible virtual overriding functions in more derived
11931   //       classes);
11932   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
11933     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
11934
11935     // Look for operator=.
11936     DeclarationName Name
11937       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11938     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
11939     S.LookupQualifiedName(OpLookup, ClassDecl, false);
11940
11941     // Prior to C++11, filter out any result that isn't a copy/move-assignment
11942     // operator.
11943     if (!S.getLangOpts().CPlusPlus11) {
11944       LookupResult::Filter F = OpLookup.makeFilter();
11945       while (F.hasNext()) {
11946         NamedDecl *D = F.next();
11947         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
11948           if (Method->isCopyAssignmentOperator() ||
11949               (!Copying && Method->isMoveAssignmentOperator()))
11950             continue;
11951
11952         F.erase();
11953       }
11954       F.done();
11955     }
11956
11957     // Suppress the protected check (C++ [class.protected]) for each of the
11958     // assignment operators we found. This strange dance is required when
11959     // we're assigning via a base classes's copy-assignment operator. To
11960     // ensure that we're getting the right base class subobject (without
11961     // ambiguities), we need to cast "this" to that subobject type; to
11962     // ensure that we don't go through the virtual call mechanism, we need
11963     // to qualify the operator= name with the base class (see below). However,
11964     // this means that if the base class has a protected copy assignment
11965     // operator, the protected member access check will fail. So, we
11966     // rewrite "protected" access to "public" access in this case, since we
11967     // know by construction that we're calling from a derived class.
11968     if (CopyingBaseSubobject) {
11969       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
11970            L != LEnd; ++L) {
11971         if (L.getAccess() == AS_protected)
11972           L.setAccess(AS_public);
11973       }
11974     }
11975
11976     // Create the nested-name-specifier that will be used to qualify the
11977     // reference to operator=; this is required to suppress the virtual
11978     // call mechanism.
11979     CXXScopeSpec SS;
11980     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
11981     SS.MakeTrivial(S.Context,
11982                    NestedNameSpecifier::Create(S.Context, nullptr, false,
11983                                                CanonicalT),
11984                    Loc);
11985
11986     // Create the reference to operator=.
11987     ExprResult OpEqualRef
11988       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
11989                                    SS, /*TemplateKWLoc=*/SourceLocation(),
11990                                    /*FirstQualifierInScope=*/nullptr,
11991                                    OpLookup,
11992                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
11993                                    /*SuppressQualifierCheck=*/true);
11994     if (OpEqualRef.isInvalid())
11995       return StmtError();
11996
11997     // Build the call to the assignment operator.
11998
11999     Expr *FromInst = From.build(S, Loc);
12000     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
12001                                                   OpEqualRef.getAs<Expr>(),
12002                                                   Loc, FromInst, Loc);
12003     if (Call.isInvalid())
12004       return StmtError();
12005
12006     // If we built a call to a trivial 'operator=' while copying an array,
12007     // bail out. We'll replace the whole shebang with a memcpy.
12008     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
12009     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
12010       return StmtResult((Stmt*)nullptr);
12011
12012     // Convert to an expression-statement, and clean up any produced
12013     // temporaries.
12014     return S.ActOnExprStmt(Call);
12015   }
12016
12017   //     - if the subobject is of scalar type, the built-in assignment
12018   //       operator is used.
12019   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
12020   if (!ArrayTy) {
12021     ExprResult Assignment = S.CreateBuiltinBinOp(
12022         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
12023     if (Assignment.isInvalid())
12024       return StmtError();
12025     return S.ActOnExprStmt(Assignment);
12026   }
12027
12028   //     - if the subobject is an array, each element is assigned, in the
12029   //       manner appropriate to the element type;
12030
12031   // Construct a loop over the array bounds, e.g.,
12032   //
12033   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
12034   //
12035   // that will copy each of the array elements.
12036   QualType SizeType = S.Context.getSizeType();
12037
12038   // Create the iteration variable.
12039   IdentifierInfo *IterationVarName = nullptr;
12040   {
12041     SmallString<8> Str;
12042     llvm::raw_svector_ostream OS(Str);
12043     OS << "__i" << Depth;
12044     IterationVarName = &S.Context.Idents.get(OS.str());
12045   }
12046   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
12047                                           IterationVarName, SizeType,
12048                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
12049                                           SC_None);
12050
12051   // Initialize the iteration variable to zero.
12052   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
12053   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
12054
12055   // Creates a reference to the iteration variable.
12056   RefBuilder IterationVarRef(IterationVar, SizeType);
12057   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
12058
12059   // Create the DeclStmt that holds the iteration variable.
12060   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
12061
12062   // Subscript the "from" and "to" expressions with the iteration variable.
12063   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
12064   MoveCastBuilder FromIndexMove(FromIndexCopy);
12065   const ExprBuilder *FromIndex;
12066   if (Copying)
12067     FromIndex = &FromIndexCopy;
12068   else
12069     FromIndex = &FromIndexMove;
12070
12071   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
12072
12073   // Build the copy/move for an individual element of the array.
12074   StmtResult Copy =
12075     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
12076                                      ToIndex, *FromIndex, CopyingBaseSubobject,
12077                                      Copying, Depth + 1);
12078   // Bail out if copying fails or if we determined that we should use memcpy.
12079   if (Copy.isInvalid() || !Copy.get())
12080     return Copy;
12081
12082   // Create the comparison against the array bound.
12083   llvm::APInt Upper
12084     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
12085   Expr *Comparison
12086     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
12087                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
12088                                      BO_NE, S.Context.BoolTy,
12089                                      VK_RValue, OK_Ordinary, Loc, FPOptions());
12090
12091   // Create the pre-increment of the iteration variable. We can determine
12092   // whether the increment will overflow based on the value of the array
12093   // bound.
12094   Expr *Increment = new (S.Context)
12095       UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType,
12096                     VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue());
12097
12098   // Construct the loop that copies all elements of this array.
12099   return S.ActOnForStmt(
12100       Loc, Loc, InitStmt,
12101       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
12102       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
12103 }
12104
12105 static StmtResult
12106 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
12107                       const ExprBuilder &To, const ExprBuilder &From,
12108                       bool CopyingBaseSubobject, bool Copying) {
12109   // Maybe we should use a memcpy?
12110   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
12111       T.isTriviallyCopyableType(S.Context))
12112     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
12113
12114   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
12115                                                      CopyingBaseSubobject,
12116                                                      Copying, 0));
12117
12118   // If we ended up picking a trivial assignment operator for an array of a
12119   // non-trivially-copyable class type, just emit a memcpy.
12120   if (!Result.isInvalid() && !Result.get())
12121     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
12122
12123   return Result;
12124 }
12125
12126 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
12127   // Note: The following rules are largely analoguous to the copy
12128   // constructor rules. Note that virtual bases are not taken into account
12129   // for determining the argument type of the operator. Note also that
12130   // operators taking an object instead of a reference are allowed.
12131   assert(ClassDecl->needsImplicitCopyAssignment());
12132
12133   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
12134   if (DSM.isAlreadyBeingDeclared())
12135     return nullptr;
12136
12137   QualType ArgType = Context.getTypeDeclType(ClassDecl);
12138   if (Context.getLangOpts().OpenCLCPlusPlus)
12139     ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
12140   QualType RetType = Context.getLValueReferenceType(ArgType);
12141   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
12142   if (Const)
12143     ArgType = ArgType.withConst();
12144
12145   ArgType = Context.getLValueReferenceType(ArgType);
12146
12147   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12148                                                      CXXCopyAssignment,
12149                                                      Const);
12150
12151   //   An implicitly-declared copy assignment operator is an inline public
12152   //   member of its class.
12153   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
12154   SourceLocation ClassLoc = ClassDecl->getLocation();
12155   DeclarationNameInfo NameInfo(Name, ClassLoc);
12156   CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
12157       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
12158       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
12159       /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
12160       SourceLocation());
12161   CopyAssignment->setAccess(AS_public);
12162   CopyAssignment->setDefaulted();
12163   CopyAssignment->setImplicit();
12164
12165   if (getLangOpts().CUDA) {
12166     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
12167                                             CopyAssignment,
12168                                             /* ConstRHS */ Const,
12169                                             /* Diagnose */ false);
12170   }
12171
12172   setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
12173
12174   // Add the parameter to the operator.
12175   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
12176                                                ClassLoc, ClassLoc,
12177                                                /*Id=*/nullptr, ArgType,
12178                                                /*TInfo=*/nullptr, SC_None,
12179                                                nullptr);
12180   CopyAssignment->setParams(FromParam);
12181
12182   CopyAssignment->setTrivial(
12183     ClassDecl->needsOverloadResolutionForCopyAssignment()
12184       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
12185       : ClassDecl->hasTrivialCopyAssignment());
12186
12187   // Note that we have added this copy-assignment operator.
12188   ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
12189
12190   Scope *S = getScopeForContext(ClassDecl);
12191   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
12192
12193   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
12194     SetDeclDeleted(CopyAssignment, ClassLoc);
12195
12196   if (S)
12197     PushOnScopeChains(CopyAssignment, S, false);
12198   ClassDecl->addDecl(CopyAssignment);
12199
12200   return CopyAssignment;
12201 }
12202
12203 /// Diagnose an implicit copy operation for a class which is odr-used, but
12204 /// which is deprecated because the class has a user-declared copy constructor,
12205 /// copy assignment operator, or destructor.
12206 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
12207   assert(CopyOp->isImplicit());
12208
12209   CXXRecordDecl *RD = CopyOp->getParent();
12210   CXXMethodDecl *UserDeclaredOperation = nullptr;
12211
12212   // In Microsoft mode, assignment operations don't affect constructors and
12213   // vice versa.
12214   if (RD->hasUserDeclaredDestructor()) {
12215     UserDeclaredOperation = RD->getDestructor();
12216   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
12217              RD->hasUserDeclaredCopyConstructor() &&
12218              !S.getLangOpts().MSVCCompat) {
12219     // Find any user-declared copy constructor.
12220     for (auto *I : RD->ctors()) {
12221       if (I->isCopyConstructor()) {
12222         UserDeclaredOperation = I;
12223         break;
12224       }
12225     }
12226     assert(UserDeclaredOperation);
12227   } else if (isa<CXXConstructorDecl>(CopyOp) &&
12228              RD->hasUserDeclaredCopyAssignment() &&
12229              !S.getLangOpts().MSVCCompat) {
12230     // Find any user-declared move assignment operator.
12231     for (auto *I : RD->methods()) {
12232       if (I->isCopyAssignmentOperator()) {
12233         UserDeclaredOperation = I;
12234         break;
12235       }
12236     }
12237     assert(UserDeclaredOperation);
12238   }
12239
12240   if (UserDeclaredOperation) {
12241     S.Diag(UserDeclaredOperation->getLocation(),
12242          diag::warn_deprecated_copy_operation)
12243       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
12244       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
12245   }
12246 }
12247
12248 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
12249                                         CXXMethodDecl *CopyAssignOperator) {
12250   assert((CopyAssignOperator->isDefaulted() &&
12251           CopyAssignOperator->isOverloadedOperator() &&
12252           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
12253           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
12254           !CopyAssignOperator->isDeleted()) &&
12255          "DefineImplicitCopyAssignment called for wrong function");
12256   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
12257     return;
12258
12259   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
12260   if (ClassDecl->isInvalidDecl()) {
12261     CopyAssignOperator->setInvalidDecl();
12262     return;
12263   }
12264
12265   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
12266
12267   // The exception specification is needed because we are defining the
12268   // function.
12269   ResolveExceptionSpec(CurrentLocation,
12270                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
12271
12272   // Add a context note for diagnostics produced after this point.
12273   Scope.addContextNote(CurrentLocation);
12274
12275   // C++11 [class.copy]p18:
12276   //   The [definition of an implicitly declared copy assignment operator] is
12277   //   deprecated if the class has a user-declared copy constructor or a
12278   //   user-declared destructor.
12279   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
12280     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
12281
12282   // C++0x [class.copy]p30:
12283   //   The implicitly-defined or explicitly-defaulted copy assignment operator
12284   //   for a non-union class X performs memberwise copy assignment of its
12285   //   subobjects. The direct base classes of X are assigned first, in the
12286   //   order of their declaration in the base-specifier-list, and then the
12287   //   immediate non-static data members of X are assigned, in the order in
12288   //   which they were declared in the class definition.
12289
12290   // The statements that form the synthesized function body.
12291   SmallVector<Stmt*, 8> Statements;
12292
12293   // The parameter for the "other" object, which we are copying from.
12294   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
12295   Qualifiers OtherQuals = Other->getType().getQualifiers();
12296   QualType OtherRefType = Other->getType();
12297   if (const LValueReferenceType *OtherRef
12298                                 = OtherRefType->getAs<LValueReferenceType>()) {
12299     OtherRefType = OtherRef->getPointeeType();
12300     OtherQuals = OtherRefType.getQualifiers();
12301   }
12302
12303   // Our location for everything implicitly-generated.
12304   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
12305                            ? CopyAssignOperator->getEndLoc()
12306                            : CopyAssignOperator->getLocation();
12307
12308   // Builds a DeclRefExpr for the "other" object.
12309   RefBuilder OtherRef(Other, OtherRefType);
12310
12311   // Builds the "this" pointer.
12312   ThisBuilder This;
12313
12314   // Assign base classes.
12315   bool Invalid = false;
12316   for (auto &Base : ClassDecl->bases()) {
12317     // Form the assignment:
12318     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
12319     QualType BaseType = Base.getType().getUnqualifiedType();
12320     if (!BaseType->isRecordType()) {
12321       Invalid = true;
12322       continue;
12323     }
12324
12325     CXXCastPath BasePath;
12326     BasePath.push_back(&Base);
12327
12328     // Construct the "from" expression, which is an implicit cast to the
12329     // appropriately-qualified base type.
12330     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
12331                      VK_LValue, BasePath);
12332
12333     // Dereference "this".
12334     DerefBuilder DerefThis(This);
12335     CastBuilder To(DerefThis,
12336                    Context.getQualifiedType(
12337                        BaseType, CopyAssignOperator->getMethodQualifiers()),
12338                    VK_LValue, BasePath);
12339
12340     // Build the copy.
12341     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
12342                                             To, From,
12343                                             /*CopyingBaseSubobject=*/true,
12344                                             /*Copying=*/true);
12345     if (Copy.isInvalid()) {
12346       CopyAssignOperator->setInvalidDecl();
12347       return;
12348     }
12349
12350     // Success! Record the copy.
12351     Statements.push_back(Copy.getAs<Expr>());
12352   }
12353
12354   // Assign non-static members.
12355   for (auto *Field : ClassDecl->fields()) {
12356     // FIXME: We should form some kind of AST representation for the implied
12357     // memcpy in a union copy operation.
12358     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12359       continue;
12360
12361     if (Field->isInvalidDecl()) {
12362       Invalid = true;
12363       continue;
12364     }
12365
12366     // Check for members of reference type; we can't copy those.
12367     if (Field->getType()->isReferenceType()) {
12368       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12369         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12370       Diag(Field->getLocation(), diag::note_declared_at);
12371       Invalid = true;
12372       continue;
12373     }
12374
12375     // Check for members of const-qualified, non-class type.
12376     QualType BaseType = Context.getBaseElementType(Field->getType());
12377     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12378       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12379         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12380       Diag(Field->getLocation(), diag::note_declared_at);
12381       Invalid = true;
12382       continue;
12383     }
12384
12385     // Suppress assigning zero-width bitfields.
12386     if (Field->isZeroLengthBitField(Context))
12387       continue;
12388
12389     QualType FieldType = Field->getType().getNonReferenceType();
12390     if (FieldType->isIncompleteArrayType()) {
12391       assert(ClassDecl->hasFlexibleArrayMember() &&
12392              "Incomplete array type is not valid");
12393       continue;
12394     }
12395
12396     // Build references to the field in the object we're copying from and to.
12397     CXXScopeSpec SS; // Intentionally empty
12398     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12399                               LookupMemberName);
12400     MemberLookup.addDecl(Field);
12401     MemberLookup.resolveKind();
12402
12403     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
12404
12405     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
12406
12407     // Build the copy of this field.
12408     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
12409                                             To, From,
12410                                             /*CopyingBaseSubobject=*/false,
12411                                             /*Copying=*/true);
12412     if (Copy.isInvalid()) {
12413       CopyAssignOperator->setInvalidDecl();
12414       return;
12415     }
12416
12417     // Success! Record the copy.
12418     Statements.push_back(Copy.getAs<Stmt>());
12419   }
12420
12421   if (!Invalid) {
12422     // Add a "return *this;"
12423     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12424
12425     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12426     if (Return.isInvalid())
12427       Invalid = true;
12428     else
12429       Statements.push_back(Return.getAs<Stmt>());
12430   }
12431
12432   if (Invalid) {
12433     CopyAssignOperator->setInvalidDecl();
12434     return;
12435   }
12436
12437   StmtResult Body;
12438   {
12439     CompoundScopeRAII CompoundScope(*this);
12440     Body = ActOnCompoundStmt(Loc, Loc, Statements,
12441                              /*isStmtExpr=*/false);
12442     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12443   }
12444   CopyAssignOperator->setBody(Body.getAs<Stmt>());
12445   CopyAssignOperator->markUsed(Context);
12446
12447   if (ASTMutationListener *L = getASTMutationListener()) {
12448     L->CompletedImplicitDefinition(CopyAssignOperator);
12449   }
12450 }
12451
12452 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
12453   assert(ClassDecl->needsImplicitMoveAssignment());
12454
12455   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
12456   if (DSM.isAlreadyBeingDeclared())
12457     return nullptr;
12458
12459   // Note: The following rules are largely analoguous to the move
12460   // constructor rules.
12461
12462   QualType ArgType = Context.getTypeDeclType(ClassDecl);
12463   if (Context.getLangOpts().OpenCLCPlusPlus)
12464     ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
12465   QualType RetType = Context.getLValueReferenceType(ArgType);
12466   ArgType = Context.getRValueReferenceType(ArgType);
12467
12468   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12469                                                      CXXMoveAssignment,
12470                                                      false);
12471
12472   //   An implicitly-declared move assignment operator is an inline public
12473   //   member of its class.
12474   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
12475   SourceLocation ClassLoc = ClassDecl->getLocation();
12476   DeclarationNameInfo NameInfo(Name, ClassLoc);
12477   CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
12478       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
12479       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
12480       /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
12481       SourceLocation());
12482   MoveAssignment->setAccess(AS_public);
12483   MoveAssignment->setDefaulted();
12484   MoveAssignment->setImplicit();
12485
12486   if (getLangOpts().CUDA) {
12487     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
12488                                             MoveAssignment,
12489                                             /* ConstRHS */ false,
12490                                             /* Diagnose */ false);
12491   }
12492
12493   // Build an exception specification pointing back at this member.
12494   FunctionProtoType::ExtProtoInfo EPI =
12495       getImplicitMethodEPI(*this, MoveAssignment);
12496   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
12497
12498   // Add the parameter to the operator.
12499   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
12500                                                ClassLoc, ClassLoc,
12501                                                /*Id=*/nullptr, ArgType,
12502                                                /*TInfo=*/nullptr, SC_None,
12503                                                nullptr);
12504   MoveAssignment->setParams(FromParam);
12505
12506   MoveAssignment->setTrivial(
12507     ClassDecl->needsOverloadResolutionForMoveAssignment()
12508       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
12509       : ClassDecl->hasTrivialMoveAssignment());
12510
12511   // Note that we have added this copy-assignment operator.
12512   ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
12513
12514   Scope *S = getScopeForContext(ClassDecl);
12515   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
12516
12517   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
12518     ClassDecl->setImplicitMoveAssignmentIsDeleted();
12519     SetDeclDeleted(MoveAssignment, ClassLoc);
12520   }
12521
12522   if (S)
12523     PushOnScopeChains(MoveAssignment, S, false);
12524   ClassDecl->addDecl(MoveAssignment);
12525
12526   return MoveAssignment;
12527 }
12528
12529 /// Check if we're implicitly defining a move assignment operator for a class
12530 /// with virtual bases. Such a move assignment might move-assign the virtual
12531 /// base multiple times.
12532 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
12533                                                SourceLocation CurrentLocation) {
12534   assert(!Class->isDependentContext() && "should not define dependent move");
12535
12536   // Only a virtual base could get implicitly move-assigned multiple times.
12537   // Only a non-trivial move assignment can observe this. We only want to
12538   // diagnose if we implicitly define an assignment operator that assigns
12539   // two base classes, both of which move-assign the same virtual base.
12540   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
12541       Class->getNumBases() < 2)
12542     return;
12543
12544   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
12545   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
12546   VBaseMap VBases;
12547
12548   for (auto &BI : Class->bases()) {
12549     Worklist.push_back(&BI);
12550     while (!Worklist.empty()) {
12551       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
12552       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
12553
12554       // If the base has no non-trivial move assignment operators,
12555       // we don't care about moves from it.
12556       if (!Base->hasNonTrivialMoveAssignment())
12557         continue;
12558
12559       // If there's nothing virtual here, skip it.
12560       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
12561         continue;
12562
12563       // If we're not actually going to call a move assignment for this base,
12564       // or the selected move assignment is trivial, skip it.
12565       Sema::SpecialMemberOverloadResult SMOR =
12566         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
12567                               /*ConstArg*/false, /*VolatileArg*/false,
12568                               /*RValueThis*/true, /*ConstThis*/false,
12569                               /*VolatileThis*/false);
12570       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
12571           !SMOR.getMethod()->isMoveAssignmentOperator())
12572         continue;
12573
12574       if (BaseSpec->isVirtual()) {
12575         // We're going to move-assign this virtual base, and its move
12576         // assignment operator is not trivial. If this can happen for
12577         // multiple distinct direct bases of Class, diagnose it. (If it
12578         // only happens in one base, we'll diagnose it when synthesizing
12579         // that base class's move assignment operator.)
12580         CXXBaseSpecifier *&Existing =
12581             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
12582                 .first->second;
12583         if (Existing && Existing != &BI) {
12584           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
12585             << Class << Base;
12586           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
12587               << (Base->getCanonicalDecl() ==
12588                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12589               << Base << Existing->getType() << Existing->getSourceRange();
12590           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
12591               << (Base->getCanonicalDecl() ==
12592                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12593               << Base << BI.getType() << BaseSpec->getSourceRange();
12594
12595           // Only diagnose each vbase once.
12596           Existing = nullptr;
12597         }
12598       } else {
12599         // Only walk over bases that have defaulted move assignment operators.
12600         // We assume that any user-provided move assignment operator handles
12601         // the multiple-moves-of-vbase case itself somehow.
12602         if (!SMOR.getMethod()->isDefaulted())
12603           continue;
12604
12605         // We're going to move the base classes of Base. Add them to the list.
12606         for (auto &BI : Base->bases())
12607           Worklist.push_back(&BI);
12608       }
12609     }
12610   }
12611 }
12612
12613 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
12614                                         CXXMethodDecl *MoveAssignOperator) {
12615   assert((MoveAssignOperator->isDefaulted() &&
12616           MoveAssignOperator->isOverloadedOperator() &&
12617           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
12618           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
12619           !MoveAssignOperator->isDeleted()) &&
12620          "DefineImplicitMoveAssignment called for wrong function");
12621   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
12622     return;
12623
12624   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
12625   if (ClassDecl->isInvalidDecl()) {
12626     MoveAssignOperator->setInvalidDecl();
12627     return;
12628   }
12629
12630   // C++0x [class.copy]p28:
12631   //   The implicitly-defined or move assignment operator for a non-union class
12632   //   X performs memberwise move assignment of its subobjects. The direct base
12633   //   classes of X are assigned first, in the order of their declaration in the
12634   //   base-specifier-list, and then the immediate non-static data members of X
12635   //   are assigned, in the order in which they were declared in the class
12636   //   definition.
12637
12638   // Issue a warning if our implicit move assignment operator will move
12639   // from a virtual base more than once.
12640   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
12641
12642   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
12643
12644   // The exception specification is needed because we are defining the
12645   // function.
12646   ResolveExceptionSpec(CurrentLocation,
12647                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
12648
12649   // Add a context note for diagnostics produced after this point.
12650   Scope.addContextNote(CurrentLocation);
12651
12652   // The statements that form the synthesized function body.
12653   SmallVector<Stmt*, 8> Statements;
12654
12655   // The parameter for the "other" object, which we are move from.
12656   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
12657   QualType OtherRefType = Other->getType()->
12658       getAs<RValueReferenceType>()->getPointeeType();
12659
12660   // Our location for everything implicitly-generated.
12661   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
12662                            ? MoveAssignOperator->getEndLoc()
12663                            : MoveAssignOperator->getLocation();
12664
12665   // Builds a reference to the "other" object.
12666   RefBuilder OtherRef(Other, OtherRefType);
12667   // Cast to rvalue.
12668   MoveCastBuilder MoveOther(OtherRef);
12669
12670   // Builds the "this" pointer.
12671   ThisBuilder This;
12672
12673   // Assign base classes.
12674   bool Invalid = false;
12675   for (auto &Base : ClassDecl->bases()) {
12676     // C++11 [class.copy]p28:
12677     //   It is unspecified whether subobjects representing virtual base classes
12678     //   are assigned more than once by the implicitly-defined copy assignment
12679     //   operator.
12680     // FIXME: Do not assign to a vbase that will be assigned by some other base
12681     // class. For a move-assignment, this can result in the vbase being moved
12682     // multiple times.
12683
12684     // Form the assignment:
12685     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
12686     QualType BaseType = Base.getType().getUnqualifiedType();
12687     if (!BaseType->isRecordType()) {
12688       Invalid = true;
12689       continue;
12690     }
12691
12692     CXXCastPath BasePath;
12693     BasePath.push_back(&Base);
12694
12695     // Construct the "from" expression, which is an implicit cast to the
12696     // appropriately-qualified base type.
12697     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
12698
12699     // Dereference "this".
12700     DerefBuilder DerefThis(This);
12701
12702     // Implicitly cast "this" to the appropriately-qualified base type.
12703     CastBuilder To(DerefThis,
12704                    Context.getQualifiedType(
12705                        BaseType, MoveAssignOperator->getMethodQualifiers()),
12706                    VK_LValue, BasePath);
12707
12708     // Build the move.
12709     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
12710                                             To, From,
12711                                             /*CopyingBaseSubobject=*/true,
12712                                             /*Copying=*/false);
12713     if (Move.isInvalid()) {
12714       MoveAssignOperator->setInvalidDecl();
12715       return;
12716     }
12717
12718     // Success! Record the move.
12719     Statements.push_back(Move.getAs<Expr>());
12720   }
12721
12722   // Assign non-static members.
12723   for (auto *Field : ClassDecl->fields()) {
12724     // FIXME: We should form some kind of AST representation for the implied
12725     // memcpy in a union copy operation.
12726     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12727       continue;
12728
12729     if (Field->isInvalidDecl()) {
12730       Invalid = true;
12731       continue;
12732     }
12733
12734     // Check for members of reference type; we can't move those.
12735     if (Field->getType()->isReferenceType()) {
12736       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12737         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12738       Diag(Field->getLocation(), diag::note_declared_at);
12739       Invalid = true;
12740       continue;
12741     }
12742
12743     // Check for members of const-qualified, non-class type.
12744     QualType BaseType = Context.getBaseElementType(Field->getType());
12745     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12746       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12747         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12748       Diag(Field->getLocation(), diag::note_declared_at);
12749       Invalid = true;
12750       continue;
12751     }
12752
12753     // Suppress assigning zero-width bitfields.
12754     if (Field->isZeroLengthBitField(Context))
12755       continue;
12756
12757     QualType FieldType = Field->getType().getNonReferenceType();
12758     if (FieldType->isIncompleteArrayType()) {
12759       assert(ClassDecl->hasFlexibleArrayMember() &&
12760              "Incomplete array type is not valid");
12761       continue;
12762     }
12763
12764     // Build references to the field in the object we're copying from and to.
12765     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12766                               LookupMemberName);
12767     MemberLookup.addDecl(Field);
12768     MemberLookup.resolveKind();
12769     MemberBuilder From(MoveOther, OtherRefType,
12770                        /*IsArrow=*/false, MemberLookup);
12771     MemberBuilder To(This, getCurrentThisType(),
12772                      /*IsArrow=*/true, MemberLookup);
12773
12774     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
12775         "Member reference with rvalue base must be rvalue except for reference "
12776         "members, which aren't allowed for move assignment.");
12777
12778     // Build the move of this field.
12779     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
12780                                             To, From,
12781                                             /*CopyingBaseSubobject=*/false,
12782                                             /*Copying=*/false);
12783     if (Move.isInvalid()) {
12784       MoveAssignOperator->setInvalidDecl();
12785       return;
12786     }
12787
12788     // Success! Record the copy.
12789     Statements.push_back(Move.getAs<Stmt>());
12790   }
12791
12792   if (!Invalid) {
12793     // Add a "return *this;"
12794     ExprResult ThisObj =
12795         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12796
12797     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12798     if (Return.isInvalid())
12799       Invalid = true;
12800     else
12801       Statements.push_back(Return.getAs<Stmt>());
12802   }
12803
12804   if (Invalid) {
12805     MoveAssignOperator->setInvalidDecl();
12806     return;
12807   }
12808
12809   StmtResult Body;
12810   {
12811     CompoundScopeRAII CompoundScope(*this);
12812     Body = ActOnCompoundStmt(Loc, Loc, Statements,
12813                              /*isStmtExpr=*/false);
12814     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12815   }
12816   MoveAssignOperator->setBody(Body.getAs<Stmt>());
12817   MoveAssignOperator->markUsed(Context);
12818
12819   if (ASTMutationListener *L = getASTMutationListener()) {
12820     L->CompletedImplicitDefinition(MoveAssignOperator);
12821   }
12822 }
12823
12824 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
12825                                                     CXXRecordDecl *ClassDecl) {
12826   // C++ [class.copy]p4:
12827   //   If the class definition does not explicitly declare a copy
12828   //   constructor, one is declared implicitly.
12829   assert(ClassDecl->needsImplicitCopyConstructor());
12830
12831   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
12832   if (DSM.isAlreadyBeingDeclared())
12833     return nullptr;
12834
12835   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12836   QualType ArgType = ClassType;
12837   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
12838   if (Const)
12839     ArgType = ArgType.withConst();
12840
12841   if (Context.getLangOpts().OpenCLCPlusPlus)
12842     ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
12843
12844   ArgType = Context.getLValueReferenceType(ArgType);
12845
12846   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12847                                                      CXXCopyConstructor,
12848                                                      Const);
12849
12850   DeclarationName Name
12851     = Context.DeclarationNames.getCXXConstructorName(
12852                                            Context.getCanonicalType(ClassType));
12853   SourceLocation ClassLoc = ClassDecl->getLocation();
12854   DeclarationNameInfo NameInfo(Name, ClassLoc);
12855
12856   //   An implicitly-declared copy constructor is an inline public
12857   //   member of its class.
12858   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
12859       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12860       ExplicitSpecifier(),
12861       /*isInline=*/true,
12862       /*isImplicitlyDeclared=*/true,
12863       Constexpr ? CSK_constexpr : CSK_unspecified);
12864   CopyConstructor->setAccess(AS_public);
12865   CopyConstructor->setDefaulted();
12866
12867   if (getLangOpts().CUDA) {
12868     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
12869                                             CopyConstructor,
12870                                             /* ConstRHS */ Const,
12871                                             /* Diagnose */ false);
12872   }
12873
12874   setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
12875
12876   // Add the parameter to the constructor.
12877   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
12878                                                ClassLoc, ClassLoc,
12879                                                /*IdentifierInfo=*/nullptr,
12880                                                ArgType, /*TInfo=*/nullptr,
12881                                                SC_None, nullptr);
12882   CopyConstructor->setParams(FromParam);
12883
12884   CopyConstructor->setTrivial(
12885       ClassDecl->needsOverloadResolutionForCopyConstructor()
12886           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
12887           : ClassDecl->hasTrivialCopyConstructor());
12888
12889   CopyConstructor->setTrivialForCall(
12890       ClassDecl->hasAttr<TrivialABIAttr>() ||
12891       (ClassDecl->needsOverloadResolutionForCopyConstructor()
12892            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
12893              TAH_ConsiderTrivialABI)
12894            : ClassDecl->hasTrivialCopyConstructorForCall()));
12895
12896   // Note that we have declared this constructor.
12897   ++getASTContext().NumImplicitCopyConstructorsDeclared;
12898
12899   Scope *S = getScopeForContext(ClassDecl);
12900   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
12901
12902   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
12903     ClassDecl->setImplicitCopyConstructorIsDeleted();
12904     SetDeclDeleted(CopyConstructor, ClassLoc);
12905   }
12906
12907   if (S)
12908     PushOnScopeChains(CopyConstructor, S, false);
12909   ClassDecl->addDecl(CopyConstructor);
12910
12911   return CopyConstructor;
12912 }
12913
12914 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
12915                                          CXXConstructorDecl *CopyConstructor) {
12916   assert((CopyConstructor->isDefaulted() &&
12917           CopyConstructor->isCopyConstructor() &&
12918           !CopyConstructor->doesThisDeclarationHaveABody() &&
12919           !CopyConstructor->isDeleted()) &&
12920          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
12921   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
12922     return;
12923
12924   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
12925   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
12926
12927   SynthesizedFunctionScope Scope(*this, CopyConstructor);
12928
12929   // The exception specification is needed because we are defining the
12930   // function.
12931   ResolveExceptionSpec(CurrentLocation,
12932                        CopyConstructor->getType()->castAs<FunctionProtoType>());
12933   MarkVTableUsed(CurrentLocation, ClassDecl);
12934
12935   // Add a context note for diagnostics produced after this point.
12936   Scope.addContextNote(CurrentLocation);
12937
12938   // C++11 [class.copy]p7:
12939   //   The [definition of an implicitly declared copy constructor] is
12940   //   deprecated if the class has a user-declared copy assignment operator
12941   //   or a user-declared destructor.
12942   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
12943     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
12944
12945   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
12946     CopyConstructor->setInvalidDecl();
12947   }  else {
12948     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
12949                              ? CopyConstructor->getEndLoc()
12950                              : CopyConstructor->getLocation();
12951     Sema::CompoundScopeRAII CompoundScope(*this);
12952     CopyConstructor->setBody(
12953         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
12954     CopyConstructor->markUsed(Context);
12955   }
12956
12957   if (ASTMutationListener *L = getASTMutationListener()) {
12958     L->CompletedImplicitDefinition(CopyConstructor);
12959   }
12960 }
12961
12962 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
12963                                                     CXXRecordDecl *ClassDecl) {
12964   assert(ClassDecl->needsImplicitMoveConstructor());
12965
12966   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
12967   if (DSM.isAlreadyBeingDeclared())
12968     return nullptr;
12969
12970   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12971
12972   QualType ArgType = ClassType;
12973   if (Context.getLangOpts().OpenCLCPlusPlus)
12974     ArgType = Context.getAddrSpaceQualType(ClassType, LangAS::opencl_generic);
12975   ArgType = Context.getRValueReferenceType(ArgType);
12976
12977   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12978                                                      CXXMoveConstructor,
12979                                                      false);
12980
12981   DeclarationName Name
12982     = Context.DeclarationNames.getCXXConstructorName(
12983                                            Context.getCanonicalType(ClassType));
12984   SourceLocation ClassLoc = ClassDecl->getLocation();
12985   DeclarationNameInfo NameInfo(Name, ClassLoc);
12986
12987   // C++11 [class.copy]p11:
12988   //   An implicitly-declared copy/move constructor is an inline public
12989   //   member of its class.
12990   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
12991       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12992       ExplicitSpecifier(),
12993       /*isInline=*/true,
12994       /*isImplicitlyDeclared=*/true,
12995       Constexpr ? CSK_constexpr : CSK_unspecified);
12996   MoveConstructor->setAccess(AS_public);
12997   MoveConstructor->setDefaulted();
12998
12999   if (getLangOpts().CUDA) {
13000     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
13001                                             MoveConstructor,
13002                                             /* ConstRHS */ false,
13003                                             /* Diagnose */ false);
13004   }
13005
13006   setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
13007
13008   // Add the parameter to the constructor.
13009   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
13010                                                ClassLoc, ClassLoc,
13011                                                /*IdentifierInfo=*/nullptr,
13012                                                ArgType, /*TInfo=*/nullptr,
13013                                                SC_None, nullptr);
13014   MoveConstructor->setParams(FromParam);
13015
13016   MoveConstructor->setTrivial(
13017       ClassDecl->needsOverloadResolutionForMoveConstructor()
13018           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
13019           : ClassDecl->hasTrivialMoveConstructor());
13020
13021   MoveConstructor->setTrivialForCall(
13022       ClassDecl->hasAttr<TrivialABIAttr>() ||
13023       (ClassDecl->needsOverloadResolutionForMoveConstructor()
13024            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
13025                                     TAH_ConsiderTrivialABI)
13026            : ClassDecl->hasTrivialMoveConstructorForCall()));
13027
13028   // Note that we have declared this constructor.
13029   ++getASTContext().NumImplicitMoveConstructorsDeclared;
13030
13031   Scope *S = getScopeForContext(ClassDecl);
13032   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
13033
13034   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
13035     ClassDecl->setImplicitMoveConstructorIsDeleted();
13036     SetDeclDeleted(MoveConstructor, ClassLoc);
13037   }
13038
13039   if (S)
13040     PushOnScopeChains(MoveConstructor, S, false);
13041   ClassDecl->addDecl(MoveConstructor);
13042
13043   return MoveConstructor;
13044 }
13045
13046 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
13047                                          CXXConstructorDecl *MoveConstructor) {
13048   assert((MoveConstructor->isDefaulted() &&
13049           MoveConstructor->isMoveConstructor() &&
13050           !MoveConstructor->doesThisDeclarationHaveABody() &&
13051           !MoveConstructor->isDeleted()) &&
13052          "DefineImplicitMoveConstructor - call it for implicit move ctor");
13053   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
13054     return;
13055
13056   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
13057   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
13058
13059   SynthesizedFunctionScope Scope(*this, MoveConstructor);
13060
13061   // The exception specification is needed because we are defining the
13062   // function.
13063   ResolveExceptionSpec(CurrentLocation,
13064                        MoveConstructor->getType()->castAs<FunctionProtoType>());
13065   MarkVTableUsed(CurrentLocation, ClassDecl);
13066
13067   // Add a context note for diagnostics produced after this point.
13068   Scope.addContextNote(CurrentLocation);
13069
13070   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
13071     MoveConstructor->setInvalidDecl();
13072   } else {
13073     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
13074                              ? MoveConstructor->getEndLoc()
13075                              : MoveConstructor->getLocation();
13076     Sema::CompoundScopeRAII CompoundScope(*this);
13077     MoveConstructor->setBody(ActOnCompoundStmt(
13078         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
13079     MoveConstructor->markUsed(Context);
13080   }
13081
13082   if (ASTMutationListener *L = getASTMutationListener()) {
13083     L->CompletedImplicitDefinition(MoveConstructor);
13084   }
13085 }
13086
13087 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
13088   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
13089 }
13090
13091 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
13092                             SourceLocation CurrentLocation,
13093                             CXXConversionDecl *Conv) {
13094   SynthesizedFunctionScope Scope(*this, Conv);
13095   assert(!Conv->getReturnType()->isUndeducedType());
13096
13097   CXXRecordDecl *Lambda = Conv->getParent();
13098   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
13099   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
13100
13101   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
13102     CallOp = InstantiateFunctionDeclaration(
13103         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
13104     if (!CallOp)
13105       return;
13106
13107     Invoker = InstantiateFunctionDeclaration(
13108         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
13109     if (!Invoker)
13110       return;
13111   }
13112
13113   if (CallOp->isInvalidDecl())
13114     return;
13115
13116   // Mark the call operator referenced (and add to pending instantiations
13117   // if necessary).
13118   // For both the conversion and static-invoker template specializations
13119   // we construct their body's in this function, so no need to add them
13120   // to the PendingInstantiations.
13121   MarkFunctionReferenced(CurrentLocation, CallOp);
13122
13123   // Fill in the __invoke function with a dummy implementation. IR generation
13124   // will fill in the actual details. Update its type in case it contained
13125   // an 'auto'.
13126   Invoker->markUsed(Context);
13127   Invoker->setReferenced();
13128   Invoker->setType(Conv->getReturnType()->getPointeeType());
13129   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
13130
13131   // Construct the body of the conversion function { return __invoke; }.
13132   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
13133                                        VK_LValue, Conv->getLocation());
13134   assert(FunctionRef && "Can't refer to __invoke function?");
13135   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
13136   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
13137                                      Conv->getLocation()));
13138   Conv->markUsed(Context);
13139   Conv->setReferenced();
13140
13141   if (ASTMutationListener *L = getASTMutationListener()) {
13142     L->CompletedImplicitDefinition(Conv);
13143     L->CompletedImplicitDefinition(Invoker);
13144   }
13145 }
13146
13147
13148
13149 void Sema::DefineImplicitLambdaToBlockPointerConversion(
13150        SourceLocation CurrentLocation,
13151        CXXConversionDecl *Conv)
13152 {
13153   assert(!Conv->getParent()->isGenericLambda());
13154
13155   SynthesizedFunctionScope Scope(*this, Conv);
13156
13157   // Copy-initialize the lambda object as needed to capture it.
13158   Expr *This = ActOnCXXThis(CurrentLocation).get();
13159   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
13160
13161   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
13162                                                         Conv->getLocation(),
13163                                                         Conv, DerefThis);
13164
13165   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
13166   // behavior.  Note that only the general conversion function does this
13167   // (since it's unusable otherwise); in the case where we inline the
13168   // block literal, it has block literal lifetime semantics.
13169   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
13170     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
13171                                           CK_CopyAndAutoreleaseBlockObject,
13172                                           BuildBlock.get(), nullptr, VK_RValue);
13173
13174   if (BuildBlock.isInvalid()) {
13175     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
13176     Conv->setInvalidDecl();
13177     return;
13178   }
13179
13180   // Create the return statement that returns the block from the conversion
13181   // function.
13182   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
13183   if (Return.isInvalid()) {
13184     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
13185     Conv->setInvalidDecl();
13186     return;
13187   }
13188
13189   // Set the body of the conversion function.
13190   Stmt *ReturnS = Return.get();
13191   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
13192                                      Conv->getLocation()));
13193   Conv->markUsed(Context);
13194
13195   // We're done; notify the mutation listener, if any.
13196   if (ASTMutationListener *L = getASTMutationListener()) {
13197     L->CompletedImplicitDefinition(Conv);
13198   }
13199 }
13200
13201 /// Determine whether the given list arguments contains exactly one
13202 /// "real" (non-default) argument.
13203 static bool hasOneRealArgument(MultiExprArg Args) {
13204   switch (Args.size()) {
13205   case 0:
13206     return false;
13207
13208   default:
13209     if (!Args[1]->isDefaultArgument())
13210       return false;
13211
13212     LLVM_FALLTHROUGH;
13213   case 1:
13214     return !Args[0]->isDefaultArgument();
13215   }
13216
13217   return false;
13218 }
13219
13220 ExprResult
13221 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
13222                             NamedDecl *FoundDecl,
13223                             CXXConstructorDecl *Constructor,
13224                             MultiExprArg ExprArgs,
13225                             bool HadMultipleCandidates,
13226                             bool IsListInitialization,
13227                             bool IsStdInitListInitialization,
13228                             bool RequiresZeroInit,
13229                             unsigned ConstructKind,
13230                             SourceRange ParenRange) {
13231   bool Elidable = false;
13232
13233   // C++0x [class.copy]p34:
13234   //   When certain criteria are met, an implementation is allowed to
13235   //   omit the copy/move construction of a class object, even if the
13236   //   copy/move constructor and/or destructor for the object have
13237   //   side effects. [...]
13238   //     - when a temporary class object that has not been bound to a
13239   //       reference (12.2) would be copied/moved to a class object
13240   //       with the same cv-unqualified type, the copy/move operation
13241   //       can be omitted by constructing the temporary object
13242   //       directly into the target of the omitted copy/move
13243   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
13244       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
13245     Expr *SubExpr = ExprArgs[0];
13246     Elidable = SubExpr->isTemporaryObject(
13247         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
13248   }
13249
13250   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
13251                                FoundDecl, Constructor,
13252                                Elidable, ExprArgs, HadMultipleCandidates,
13253                                IsListInitialization,
13254                                IsStdInitListInitialization, RequiresZeroInit,
13255                                ConstructKind, ParenRange);
13256 }
13257
13258 ExprResult
13259 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
13260                             NamedDecl *FoundDecl,
13261                             CXXConstructorDecl *Constructor,
13262                             bool Elidable,
13263                             MultiExprArg ExprArgs,
13264                             bool HadMultipleCandidates,
13265                             bool IsListInitialization,
13266                             bool IsStdInitListInitialization,
13267                             bool RequiresZeroInit,
13268                             unsigned ConstructKind,
13269                             SourceRange ParenRange) {
13270   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
13271     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
13272     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
13273       return ExprError();
13274   }
13275
13276   return BuildCXXConstructExpr(
13277       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
13278       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
13279       RequiresZeroInit, ConstructKind, ParenRange);
13280 }
13281
13282 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
13283 /// including handling of its default argument expressions.
13284 ExprResult
13285 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
13286                             CXXConstructorDecl *Constructor,
13287                             bool Elidable,
13288                             MultiExprArg ExprArgs,
13289                             bool HadMultipleCandidates,
13290                             bool IsListInitialization,
13291                             bool IsStdInitListInitialization,
13292                             bool RequiresZeroInit,
13293                             unsigned ConstructKind,
13294                             SourceRange ParenRange) {
13295   assert(declaresSameEntity(
13296              Constructor->getParent(),
13297              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
13298          "given constructor for wrong type");
13299   MarkFunctionReferenced(ConstructLoc, Constructor);
13300   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
13301     return ExprError();
13302
13303   return CXXConstructExpr::Create(
13304       Context, DeclInitType, ConstructLoc, Constructor, Elidable,
13305       ExprArgs, HadMultipleCandidates, IsListInitialization,
13306       IsStdInitListInitialization, RequiresZeroInit,
13307       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
13308       ParenRange);
13309 }
13310
13311 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
13312   assert(Field->hasInClassInitializer());
13313
13314   // If we already have the in-class initializer nothing needs to be done.
13315   if (Field->getInClassInitializer())
13316     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
13317
13318   // If we might have already tried and failed to instantiate, don't try again.
13319   if (Field->isInvalidDecl())
13320     return ExprError();
13321
13322   // Maybe we haven't instantiated the in-class initializer. Go check the
13323   // pattern FieldDecl to see if it has one.
13324   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
13325
13326   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
13327     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
13328     DeclContext::lookup_result Lookup =
13329         ClassPattern->lookup(Field->getDeclName());
13330
13331     // Lookup can return at most two results: the pattern for the field, or the
13332     // injected class name of the parent record. No other member can have the
13333     // same name as the field.
13334     // In modules mode, lookup can return multiple results (coming from
13335     // different modules).
13336     assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
13337            "more than two lookup results for field name");
13338     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
13339     if (!Pattern) {
13340       assert(isa<CXXRecordDecl>(Lookup[0]) &&
13341              "cannot have other non-field member with same name");
13342       for (auto L : Lookup)
13343         if (isa<FieldDecl>(L)) {
13344           Pattern = cast<FieldDecl>(L);
13345           break;
13346         }
13347       assert(Pattern && "We must have set the Pattern!");
13348     }
13349
13350     if (!Pattern->hasInClassInitializer() ||
13351         InstantiateInClassInitializer(Loc, Field, Pattern,
13352                                       getTemplateInstantiationArgs(Field))) {
13353       // Don't diagnose this again.
13354       Field->setInvalidDecl();
13355       return ExprError();
13356     }
13357     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
13358   }
13359
13360   // DR1351:
13361   //   If the brace-or-equal-initializer of a non-static data member
13362   //   invokes a defaulted default constructor of its class or of an
13363   //   enclosing class in a potentially evaluated subexpression, the
13364   //   program is ill-formed.
13365   //
13366   // This resolution is unworkable: the exception specification of the
13367   // default constructor can be needed in an unevaluated context, in
13368   // particular, in the operand of a noexcept-expression, and we can be
13369   // unable to compute an exception specification for an enclosed class.
13370   //
13371   // Any attempt to resolve the exception specification of a defaulted default
13372   // constructor before the initializer is lexically complete will ultimately
13373   // come here at which point we can diagnose it.
13374   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
13375   Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
13376       << OutermostClass << Field;
13377   Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
13378   // Recover by marking the field invalid, unless we're in a SFINAE context.
13379   if (!isSFINAEContext())
13380     Field->setInvalidDecl();
13381   return ExprError();
13382 }
13383
13384 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
13385   if (VD->isInvalidDecl()) return;
13386
13387   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
13388   if (ClassDecl->isInvalidDecl()) return;
13389   if (ClassDecl->hasIrrelevantDestructor()) return;
13390   if (ClassDecl->isDependentContext()) return;
13391
13392   if (VD->isNoDestroy(getASTContext()))
13393     return;
13394
13395   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13396
13397   // If this is an array, we'll require the destructor during initialization, so
13398   // we can skip over this. We still want to emit exit-time destructor warnings
13399   // though.
13400   if (!VD->getType()->isArrayType()) {
13401     MarkFunctionReferenced(VD->getLocation(), Destructor);
13402     CheckDestructorAccess(VD->getLocation(), Destructor,
13403                           PDiag(diag::err_access_dtor_var)
13404                               << VD->getDeclName() << VD->getType());
13405     DiagnoseUseOfDecl(Destructor, VD->getLocation());
13406   }
13407
13408   if (Destructor->isTrivial()) return;
13409
13410   // If the destructor is constexpr, check whether the variable has constant
13411   // destruction now.
13412   if (Destructor->isConstexpr() && VD->getInit() &&
13413       !VD->getInit()->isValueDependent() && VD->evaluateValue()) {
13414     SmallVector<PartialDiagnosticAt, 8> Notes;
13415     if (!VD->evaluateDestruction(Notes) && VD->isConstexpr()) {
13416       Diag(VD->getLocation(),
13417            diag::err_constexpr_var_requires_const_destruction) << VD;
13418       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13419         Diag(Notes[I].first, Notes[I].second);
13420     }
13421   }
13422
13423   if (!VD->hasGlobalStorage()) return;
13424
13425   // Emit warning for non-trivial dtor in global scope (a real global,
13426   // class-static, function-static).
13427   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
13428
13429   // TODO: this should be re-enabled for static locals by !CXAAtExit
13430   if (!VD->isStaticLocal())
13431     Diag(VD->getLocation(), diag::warn_global_destructor);
13432 }
13433
13434 /// Given a constructor and the set of arguments provided for the
13435 /// constructor, convert the arguments and add any required default arguments
13436 /// to form a proper call to this constructor.
13437 ///
13438 /// \returns true if an error occurred, false otherwise.
13439 bool
13440 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
13441                               MultiExprArg ArgsPtr,
13442                               SourceLocation Loc,
13443                               SmallVectorImpl<Expr*> &ConvertedArgs,
13444                               bool AllowExplicit,
13445                               bool IsListInitialization) {
13446   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
13447   unsigned NumArgs = ArgsPtr.size();
13448   Expr **Args = ArgsPtr.data();
13449
13450   const FunctionProtoType *Proto
13451     = Constructor->getType()->getAs<FunctionProtoType>();
13452   assert(Proto && "Constructor without a prototype?");
13453   unsigned NumParams = Proto->getNumParams();
13454
13455   // If too few arguments are available, we'll fill in the rest with defaults.
13456   if (NumArgs < NumParams)
13457     ConvertedArgs.reserve(NumParams);
13458   else
13459     ConvertedArgs.reserve(NumArgs);
13460
13461   VariadicCallType CallType =
13462     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
13463   SmallVector<Expr *, 8> AllArgs;
13464   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
13465                                         Proto, 0,
13466                                         llvm::makeArrayRef(Args, NumArgs),
13467                                         AllArgs,
13468                                         CallType, AllowExplicit,
13469                                         IsListInitialization);
13470   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
13471
13472   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
13473
13474   CheckConstructorCall(Constructor,
13475                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
13476                        Proto, Loc);
13477
13478   return Invalid;
13479 }
13480
13481 static inline bool
13482 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
13483                                        const FunctionDecl *FnDecl) {
13484   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
13485   if (isa<NamespaceDecl>(DC)) {
13486     return SemaRef.Diag(FnDecl->getLocation(),
13487                         diag::err_operator_new_delete_declared_in_namespace)
13488       << FnDecl->getDeclName();
13489   }
13490
13491   if (isa<TranslationUnitDecl>(DC) &&
13492       FnDecl->getStorageClass() == SC_Static) {
13493     return SemaRef.Diag(FnDecl->getLocation(),
13494                         diag::err_operator_new_delete_declared_static)
13495       << FnDecl->getDeclName();
13496   }
13497
13498   return false;
13499 }
13500
13501 static QualType
13502 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
13503   QualType QTy = PtrTy->getPointeeType();
13504   QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
13505   return SemaRef.Context.getPointerType(QTy);
13506 }
13507
13508 static inline bool
13509 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
13510                             CanQualType ExpectedResultType,
13511                             CanQualType ExpectedFirstParamType,
13512                             unsigned DependentParamTypeDiag,
13513                             unsigned InvalidParamTypeDiag) {
13514   QualType ResultType =
13515       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
13516
13517   // Check that the result type is not dependent.
13518   if (ResultType->isDependentType())
13519     return SemaRef.Diag(FnDecl->getLocation(),
13520                         diag::err_operator_new_delete_dependent_result_type)
13521     << FnDecl->getDeclName() << ExpectedResultType;
13522
13523   // The operator is valid on any address space for OpenCL.
13524   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13525     if (auto *PtrTy = ResultType->getAs<PointerType>()) {
13526       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13527     }
13528   }
13529
13530   // Check that the result type is what we expect.
13531   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
13532     return SemaRef.Diag(FnDecl->getLocation(),
13533                         diag::err_operator_new_delete_invalid_result_type)
13534     << FnDecl->getDeclName() << ExpectedResultType;
13535
13536   // A function template must have at least 2 parameters.
13537   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
13538     return SemaRef.Diag(FnDecl->getLocation(),
13539                       diag::err_operator_new_delete_template_too_few_parameters)
13540         << FnDecl->getDeclName();
13541
13542   // The function decl must have at least 1 parameter.
13543   if (FnDecl->getNumParams() == 0)
13544     return SemaRef.Diag(FnDecl->getLocation(),
13545                         diag::err_operator_new_delete_too_few_parameters)
13546       << FnDecl->getDeclName();
13547
13548   // Check the first parameter type is not dependent.
13549   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
13550   if (FirstParamType->isDependentType())
13551     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
13552       << FnDecl->getDeclName() << ExpectedFirstParamType;
13553
13554   // Check that the first parameter type is what we expect.
13555   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13556     // The operator is valid on any address space for OpenCL.
13557     if (auto *PtrTy =
13558             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
13559       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13560     }
13561   }
13562   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
13563       ExpectedFirstParamType)
13564     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
13565     << FnDecl->getDeclName() << ExpectedFirstParamType;
13566
13567   return false;
13568 }
13569
13570 static bool
13571 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
13572   // C++ [basic.stc.dynamic.allocation]p1:
13573   //   A program is ill-formed if an allocation function is declared in a
13574   //   namespace scope other than global scope or declared static in global
13575   //   scope.
13576   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13577     return true;
13578
13579   CanQualType SizeTy =
13580     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
13581
13582   // C++ [basic.stc.dynamic.allocation]p1:
13583   //  The return type shall be void*. The first parameter shall have type
13584   //  std::size_t.
13585   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
13586                                   SizeTy,
13587                                   diag::err_operator_new_dependent_param_type,
13588                                   diag::err_operator_new_param_type))
13589     return true;
13590
13591   // C++ [basic.stc.dynamic.allocation]p1:
13592   //  The first parameter shall not have an associated default argument.
13593   if (FnDecl->getParamDecl(0)->hasDefaultArg())
13594     return SemaRef.Diag(FnDecl->getLocation(),
13595                         diag::err_operator_new_default_arg)
13596       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
13597
13598   return false;
13599 }
13600
13601 static bool
13602 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
13603   // C++ [basic.stc.dynamic.deallocation]p1:
13604   //   A program is ill-formed if deallocation functions are declared in a
13605   //   namespace scope other than global scope or declared static in global
13606   //   scope.
13607   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13608     return true;
13609
13610   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
13611
13612   // C++ P0722:
13613   //   Within a class C, the first parameter of a destroying operator delete
13614   //   shall be of type C *. The first parameter of any other deallocation
13615   //   function shall be of type void *.
13616   CanQualType ExpectedFirstParamType =
13617       MD && MD->isDestroyingOperatorDelete()
13618           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
13619                 SemaRef.Context.getRecordType(MD->getParent())))
13620           : SemaRef.Context.VoidPtrTy;
13621
13622   // C++ [basic.stc.dynamic.deallocation]p2:
13623   //   Each deallocation function shall return void
13624   if (CheckOperatorNewDeleteTypes(
13625           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
13626           diag::err_operator_delete_dependent_param_type,
13627           diag::err_operator_delete_param_type))
13628     return true;
13629
13630   // C++ P0722:
13631   //   A destroying operator delete shall be a usual deallocation function.
13632   if (MD && !MD->getParent()->isDependentContext() &&
13633       MD->isDestroyingOperatorDelete() &&
13634       !SemaRef.isUsualDeallocationFunction(MD)) {
13635     SemaRef.Diag(MD->getLocation(),
13636                  diag::err_destroying_operator_delete_not_usual);
13637     return true;
13638   }
13639
13640   return false;
13641 }
13642
13643 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
13644 /// of this overloaded operator is well-formed. If so, returns false;
13645 /// otherwise, emits appropriate diagnostics and returns true.
13646 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
13647   assert(FnDecl && FnDecl->isOverloadedOperator() &&
13648          "Expected an overloaded operator declaration");
13649
13650   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
13651
13652   // C++ [over.oper]p5:
13653   //   The allocation and deallocation functions, operator new,
13654   //   operator new[], operator delete and operator delete[], are
13655   //   described completely in 3.7.3. The attributes and restrictions
13656   //   found in the rest of this subclause do not apply to them unless
13657   //   explicitly stated in 3.7.3.
13658   if (Op == OO_Delete || Op == OO_Array_Delete)
13659     return CheckOperatorDeleteDeclaration(*this, FnDecl);
13660
13661   if (Op == OO_New || Op == OO_Array_New)
13662     return CheckOperatorNewDeclaration(*this, FnDecl);
13663
13664   // C++ [over.oper]p6:
13665   //   An operator function shall either be a non-static member
13666   //   function or be a non-member function and have at least one
13667   //   parameter whose type is a class, a reference to a class, an
13668   //   enumeration, or a reference to an enumeration.
13669   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
13670     if (MethodDecl->isStatic())
13671       return Diag(FnDecl->getLocation(),
13672                   diag::err_operator_overload_static) << FnDecl->getDeclName();
13673   } else {
13674     bool ClassOrEnumParam = false;
13675     for (auto Param : FnDecl->parameters()) {
13676       QualType ParamType = Param->getType().getNonReferenceType();
13677       if (ParamType->isDependentType() || ParamType->isRecordType() ||
13678           ParamType->isEnumeralType()) {
13679         ClassOrEnumParam = true;
13680         break;
13681       }
13682     }
13683
13684     if (!ClassOrEnumParam)
13685       return Diag(FnDecl->getLocation(),
13686                   diag::err_operator_overload_needs_class_or_enum)
13687         << FnDecl->getDeclName();
13688   }
13689
13690   // C++ [over.oper]p8:
13691   //   An operator function cannot have default arguments (8.3.6),
13692   //   except where explicitly stated below.
13693   //
13694   // Only the function-call operator allows default arguments
13695   // (C++ [over.call]p1).
13696   if (Op != OO_Call) {
13697     for (auto Param : FnDecl->parameters()) {
13698       if (Param->hasDefaultArg())
13699         return Diag(Param->getLocation(),
13700                     diag::err_operator_overload_default_arg)
13701           << FnDecl->getDeclName() << Param->getDefaultArgRange();
13702     }
13703   }
13704
13705   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
13706     { false, false, false }
13707 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
13708     , { Unary, Binary, MemberOnly }
13709 #include "clang/Basic/OperatorKinds.def"
13710   };
13711
13712   bool CanBeUnaryOperator = OperatorUses[Op][0];
13713   bool CanBeBinaryOperator = OperatorUses[Op][1];
13714   bool MustBeMemberOperator = OperatorUses[Op][2];
13715
13716   // C++ [over.oper]p8:
13717   //   [...] Operator functions cannot have more or fewer parameters
13718   //   than the number required for the corresponding operator, as
13719   //   described in the rest of this subclause.
13720   unsigned NumParams = FnDecl->getNumParams()
13721                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
13722   if (Op != OO_Call &&
13723       ((NumParams == 1 && !CanBeUnaryOperator) ||
13724        (NumParams == 2 && !CanBeBinaryOperator) ||
13725        (NumParams < 1) || (NumParams > 2))) {
13726     // We have the wrong number of parameters.
13727     unsigned ErrorKind;
13728     if (CanBeUnaryOperator && CanBeBinaryOperator) {
13729       ErrorKind = 2;  // 2 -> unary or binary.
13730     } else if (CanBeUnaryOperator) {
13731       ErrorKind = 0;  // 0 -> unary
13732     } else {
13733       assert(CanBeBinaryOperator &&
13734              "All non-call overloaded operators are unary or binary!");
13735       ErrorKind = 1;  // 1 -> binary
13736     }
13737
13738     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
13739       << FnDecl->getDeclName() << NumParams << ErrorKind;
13740   }
13741
13742   // Overloaded operators other than operator() cannot be variadic.
13743   if (Op != OO_Call &&
13744       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
13745     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
13746       << FnDecl->getDeclName();
13747   }
13748
13749   // Some operators must be non-static member functions.
13750   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
13751     return Diag(FnDecl->getLocation(),
13752                 diag::err_operator_overload_must_be_member)
13753       << FnDecl->getDeclName();
13754   }
13755
13756   // C++ [over.inc]p1:
13757   //   The user-defined function called operator++ implements the
13758   //   prefix and postfix ++ operator. If this function is a member
13759   //   function with no parameters, or a non-member function with one
13760   //   parameter of class or enumeration type, it defines the prefix
13761   //   increment operator ++ for objects of that type. If the function
13762   //   is a member function with one parameter (which shall be of type
13763   //   int) or a non-member function with two parameters (the second
13764   //   of which shall be of type int), it defines the postfix
13765   //   increment operator ++ for objects of that type.
13766   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
13767     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
13768     QualType ParamType = LastParam->getType();
13769
13770     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
13771         !ParamType->isDependentType())
13772       return Diag(LastParam->getLocation(),
13773                   diag::err_operator_overload_post_incdec_must_be_int)
13774         << LastParam->getType() << (Op == OO_MinusMinus);
13775   }
13776
13777   return false;
13778 }
13779
13780 static bool
13781 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
13782                                           FunctionTemplateDecl *TpDecl) {
13783   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
13784
13785   // Must have one or two template parameters.
13786   if (TemplateParams->size() == 1) {
13787     NonTypeTemplateParmDecl *PmDecl =
13788         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
13789
13790     // The template parameter must be a char parameter pack.
13791     if (PmDecl && PmDecl->isTemplateParameterPack() &&
13792         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
13793       return false;
13794
13795   } else if (TemplateParams->size() == 2) {
13796     TemplateTypeParmDecl *PmType =
13797         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
13798     NonTypeTemplateParmDecl *PmArgs =
13799         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
13800
13801     // The second template parameter must be a parameter pack with the
13802     // first template parameter as its type.
13803     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
13804         PmArgs->isTemplateParameterPack()) {
13805       const TemplateTypeParmType *TArgs =
13806           PmArgs->getType()->getAs<TemplateTypeParmType>();
13807       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
13808           TArgs->getIndex() == PmType->getIndex()) {
13809         if (!SemaRef.inTemplateInstantiation())
13810           SemaRef.Diag(TpDecl->getLocation(),
13811                        diag::ext_string_literal_operator_template);
13812         return false;
13813       }
13814     }
13815   }
13816
13817   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
13818                diag::err_literal_operator_template)
13819       << TpDecl->getTemplateParameters()->getSourceRange();
13820   return true;
13821 }
13822
13823 /// CheckLiteralOperatorDeclaration - Check whether the declaration
13824 /// of this literal operator function is well-formed. If so, returns
13825 /// false; otherwise, emits appropriate diagnostics and returns true.
13826 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
13827   if (isa<CXXMethodDecl>(FnDecl)) {
13828     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
13829       << FnDecl->getDeclName();
13830     return true;
13831   }
13832
13833   if (FnDecl->isExternC()) {
13834     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
13835     if (const LinkageSpecDecl *LSD =
13836             FnDecl->getDeclContext()->getExternCContext())
13837       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
13838     return true;
13839   }
13840
13841   // This might be the definition of a literal operator template.
13842   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
13843
13844   // This might be a specialization of a literal operator template.
13845   if (!TpDecl)
13846     TpDecl = FnDecl->getPrimaryTemplate();
13847
13848   // template <char...> type operator "" name() and
13849   // template <class T, T...> type operator "" name() are the only valid
13850   // template signatures, and the only valid signatures with no parameters.
13851   if (TpDecl) {
13852     if (FnDecl->param_size() != 0) {
13853       Diag(FnDecl->getLocation(),
13854            diag::err_literal_operator_template_with_params);
13855       return true;
13856     }
13857
13858     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
13859       return true;
13860
13861   } else if (FnDecl->param_size() == 1) {
13862     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
13863
13864     QualType ParamType = Param->getType().getUnqualifiedType();
13865
13866     // Only unsigned long long int, long double, any character type, and const
13867     // char * are allowed as the only parameters.
13868     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
13869         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
13870         Context.hasSameType(ParamType, Context.CharTy) ||
13871         Context.hasSameType(ParamType, Context.WideCharTy) ||
13872         Context.hasSameType(ParamType, Context.Char8Ty) ||
13873         Context.hasSameType(ParamType, Context.Char16Ty) ||
13874         Context.hasSameType(ParamType, Context.Char32Ty)) {
13875     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
13876       QualType InnerType = Ptr->getPointeeType();
13877
13878       // Pointer parameter must be a const char *.
13879       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
13880                                 Context.CharTy) &&
13881             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
13882         Diag(Param->getSourceRange().getBegin(),
13883              diag::err_literal_operator_param)
13884             << ParamType << "'const char *'" << Param->getSourceRange();
13885         return true;
13886       }
13887
13888     } else if (ParamType->isRealFloatingType()) {
13889       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13890           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
13891       return true;
13892
13893     } else if (ParamType->isIntegerType()) {
13894       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13895           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
13896       return true;
13897
13898     } else {
13899       Diag(Param->getSourceRange().getBegin(),
13900            diag::err_literal_operator_invalid_param)
13901           << ParamType << Param->getSourceRange();
13902       return true;
13903     }
13904
13905   } else if (FnDecl->param_size() == 2) {
13906     FunctionDecl::param_iterator Param = FnDecl->param_begin();
13907
13908     // First, verify that the first parameter is correct.
13909
13910     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
13911
13912     // Two parameter function must have a pointer to const as a
13913     // first parameter; let's strip those qualifiers.
13914     const PointerType *PT = FirstParamType->getAs<PointerType>();
13915
13916     if (!PT) {
13917       Diag((*Param)->getSourceRange().getBegin(),
13918            diag::err_literal_operator_param)
13919           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13920       return true;
13921     }
13922
13923     QualType PointeeType = PT->getPointeeType();
13924     // First parameter must be const
13925     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
13926       Diag((*Param)->getSourceRange().getBegin(),
13927            diag::err_literal_operator_param)
13928           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13929       return true;
13930     }
13931
13932     QualType InnerType = PointeeType.getUnqualifiedType();
13933     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
13934     // const char32_t* are allowed as the first parameter to a two-parameter
13935     // function
13936     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
13937           Context.hasSameType(InnerType, Context.WideCharTy) ||
13938           Context.hasSameType(InnerType, Context.Char8Ty) ||
13939           Context.hasSameType(InnerType, Context.Char16Ty) ||
13940           Context.hasSameType(InnerType, Context.Char32Ty))) {
13941       Diag((*Param)->getSourceRange().getBegin(),
13942            diag::err_literal_operator_param)
13943           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13944       return true;
13945     }
13946
13947     // Move on to the second and final parameter.
13948     ++Param;
13949
13950     // The second parameter must be a std::size_t.
13951     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
13952     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
13953       Diag((*Param)->getSourceRange().getBegin(),
13954            diag::err_literal_operator_param)
13955           << SecondParamType << Context.getSizeType()
13956           << (*Param)->getSourceRange();
13957       return true;
13958     }
13959   } else {
13960     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
13961     return true;
13962   }
13963
13964   // Parameters are good.
13965
13966   // A parameter-declaration-clause containing a default argument is not
13967   // equivalent to any of the permitted forms.
13968   for (auto Param : FnDecl->parameters()) {
13969     if (Param->hasDefaultArg()) {
13970       Diag(Param->getDefaultArgRange().getBegin(),
13971            diag::err_literal_operator_default_argument)
13972         << Param->getDefaultArgRange();
13973       break;
13974     }
13975   }
13976
13977   StringRef LiteralName
13978     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
13979   if (LiteralName[0] != '_' &&
13980       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
13981     // C++11 [usrlit.suffix]p1:
13982     //   Literal suffix identifiers that do not start with an underscore
13983     //   are reserved for future standardization.
13984     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
13985       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
13986   }
13987
13988   return false;
13989 }
13990
13991 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
13992 /// linkage specification, including the language and (if present)
13993 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
13994 /// language string literal. LBraceLoc, if valid, provides the location of
13995 /// the '{' brace. Otherwise, this linkage specification does not
13996 /// have any braces.
13997 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
13998                                            Expr *LangStr,
13999                                            SourceLocation LBraceLoc) {
14000   StringLiteral *Lit = cast<StringLiteral>(LangStr);
14001   if (!Lit->isAscii()) {
14002     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
14003       << LangStr->getSourceRange();
14004     return nullptr;
14005   }
14006
14007   StringRef Lang = Lit->getString();
14008   LinkageSpecDecl::LanguageIDs Language;
14009   if (Lang == "C")
14010     Language = LinkageSpecDecl::lang_c;
14011   else if (Lang == "C++")
14012     Language = LinkageSpecDecl::lang_cxx;
14013   else if (Lang == "C++11")
14014     Language = LinkageSpecDecl::lang_cxx_11;
14015   else if (Lang == "C++14")
14016     Language = LinkageSpecDecl::lang_cxx_14;
14017   else {
14018     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
14019       << LangStr->getSourceRange();
14020     return nullptr;
14021   }
14022
14023   // FIXME: Add all the various semantics of linkage specifications
14024
14025   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
14026                                                LangStr->getExprLoc(), Language,
14027                                                LBraceLoc.isValid());
14028   CurContext->addDecl(D);
14029   PushDeclContext(S, D);
14030   return D;
14031 }
14032
14033 /// ActOnFinishLinkageSpecification - Complete the definition of
14034 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
14035 /// valid, it's the position of the closing '}' brace in a linkage
14036 /// specification that uses braces.
14037 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
14038                                             Decl *LinkageSpec,
14039                                             SourceLocation RBraceLoc) {
14040   if (RBraceLoc.isValid()) {
14041     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
14042     LSDecl->setRBraceLoc(RBraceLoc);
14043   }
14044   PopDeclContext();
14045   return LinkageSpec;
14046 }
14047
14048 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
14049                                   const ParsedAttributesView &AttrList,
14050                                   SourceLocation SemiLoc) {
14051   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
14052   // Attribute declarations appertain to empty declaration so we handle
14053   // them here.
14054   ProcessDeclAttributeList(S, ED, AttrList);
14055
14056   CurContext->addDecl(ED);
14057   return ED;
14058 }
14059
14060 /// Perform semantic analysis for the variable declaration that
14061 /// occurs within a C++ catch clause, returning the newly-created
14062 /// variable.
14063 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
14064                                          TypeSourceInfo *TInfo,
14065                                          SourceLocation StartLoc,
14066                                          SourceLocation Loc,
14067                                          IdentifierInfo *Name) {
14068   bool Invalid = false;
14069   QualType ExDeclType = TInfo->getType();
14070
14071   // Arrays and functions decay.
14072   if (ExDeclType->isArrayType())
14073     ExDeclType = Context.getArrayDecayedType(ExDeclType);
14074   else if (ExDeclType->isFunctionType())
14075     ExDeclType = Context.getPointerType(ExDeclType);
14076
14077   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
14078   // The exception-declaration shall not denote a pointer or reference to an
14079   // incomplete type, other than [cv] void*.
14080   // N2844 forbids rvalue references.
14081   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
14082     Diag(Loc, diag::err_catch_rvalue_ref);
14083     Invalid = true;
14084   }
14085
14086   if (ExDeclType->isVariablyModifiedType()) {
14087     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
14088     Invalid = true;
14089   }
14090
14091   QualType BaseType = ExDeclType;
14092   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
14093   unsigned DK = diag::err_catch_incomplete;
14094   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
14095     BaseType = Ptr->getPointeeType();
14096     Mode = 1;
14097     DK = diag::err_catch_incomplete_ptr;
14098   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
14099     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
14100     BaseType = Ref->getPointeeType();
14101     Mode = 2;
14102     DK = diag::err_catch_incomplete_ref;
14103   }
14104   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
14105       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
14106     Invalid = true;
14107
14108   if (!Invalid && !ExDeclType->isDependentType() &&
14109       RequireNonAbstractType(Loc, ExDeclType,
14110                              diag::err_abstract_type_in_decl,
14111                              AbstractVariableType))
14112     Invalid = true;
14113
14114   // Only the non-fragile NeXT runtime currently supports C++ catches
14115   // of ObjC types, and no runtime supports catching ObjC types by value.
14116   if (!Invalid && getLangOpts().ObjC) {
14117     QualType T = ExDeclType;
14118     if (const ReferenceType *RT = T->getAs<ReferenceType>())
14119       T = RT->getPointeeType();
14120
14121     if (T->isObjCObjectType()) {
14122       Diag(Loc, diag::err_objc_object_catch);
14123       Invalid = true;
14124     } else if (T->isObjCObjectPointerType()) {
14125       // FIXME: should this be a test for macosx-fragile specifically?
14126       if (getLangOpts().ObjCRuntime.isFragile())
14127         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
14128     }
14129   }
14130
14131   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
14132                                     ExDeclType, TInfo, SC_None);
14133   ExDecl->setExceptionVariable(true);
14134
14135   // In ARC, infer 'retaining' for variables of retainable type.
14136   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
14137     Invalid = true;
14138
14139   if (!Invalid && !ExDeclType->isDependentType()) {
14140     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
14141       // Insulate this from anything else we might currently be parsing.
14142       EnterExpressionEvaluationContext scope(
14143           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
14144
14145       // C++ [except.handle]p16:
14146       //   The object declared in an exception-declaration or, if the
14147       //   exception-declaration does not specify a name, a temporary (12.2) is
14148       //   copy-initialized (8.5) from the exception object. [...]
14149       //   The object is destroyed when the handler exits, after the destruction
14150       //   of any automatic objects initialized within the handler.
14151       //
14152       // We just pretend to initialize the object with itself, then make sure
14153       // it can be destroyed later.
14154       QualType initType = Context.getExceptionObjectType(ExDeclType);
14155
14156       InitializedEntity entity =
14157         InitializedEntity::InitializeVariable(ExDecl);
14158       InitializationKind initKind =
14159         InitializationKind::CreateCopy(Loc, SourceLocation());
14160
14161       Expr *opaqueValue =
14162         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
14163       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
14164       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
14165       if (result.isInvalid())
14166         Invalid = true;
14167       else {
14168         // If the constructor used was non-trivial, set this as the
14169         // "initializer".
14170         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
14171         if (!construct->getConstructor()->isTrivial()) {
14172           Expr *init = MaybeCreateExprWithCleanups(construct);
14173           ExDecl->setInit(init);
14174         }
14175
14176         // And make sure it's destructable.
14177         FinalizeVarWithDestructor(ExDecl, recordType);
14178       }
14179     }
14180   }
14181
14182   if (Invalid)
14183     ExDecl->setInvalidDecl();
14184
14185   return ExDecl;
14186 }
14187
14188 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
14189 /// handler.
14190 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
14191   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14192   bool Invalid = D.isInvalidType();
14193
14194   // Check for unexpanded parameter packs.
14195   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14196                                       UPPC_ExceptionType)) {
14197     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
14198                                              D.getIdentifierLoc());
14199     Invalid = true;
14200   }
14201
14202   IdentifierInfo *II = D.getIdentifier();
14203   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
14204                                              LookupOrdinaryName,
14205                                              ForVisibleRedeclaration)) {
14206     // The scope should be freshly made just for us. There is just no way
14207     // it contains any previous declaration, except for function parameters in
14208     // a function-try-block's catch statement.
14209     assert(!S->isDeclScope(PrevDecl));
14210     if (isDeclInScope(PrevDecl, CurContext, S)) {
14211       Diag(D.getIdentifierLoc(), diag::err_redefinition)
14212         << D.getIdentifier();
14213       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
14214       Invalid = true;
14215     } else if (PrevDecl->isTemplateParameter())
14216       // Maybe we will complain about the shadowed template parameter.
14217       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14218   }
14219
14220   if (D.getCXXScopeSpec().isSet() && !Invalid) {
14221     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
14222       << D.getCXXScopeSpec().getRange();
14223     Invalid = true;
14224   }
14225
14226   VarDecl *ExDecl = BuildExceptionDeclaration(
14227       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
14228   if (Invalid)
14229     ExDecl->setInvalidDecl();
14230
14231   // Add the exception declaration into this scope.
14232   if (II)
14233     PushOnScopeChains(ExDecl, S);
14234   else
14235     CurContext->addDecl(ExDecl);
14236
14237   ProcessDeclAttributes(S, ExDecl, D);
14238   return ExDecl;
14239 }
14240
14241 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
14242                                          Expr *AssertExpr,
14243                                          Expr *AssertMessageExpr,
14244                                          SourceLocation RParenLoc) {
14245   StringLiteral *AssertMessage =
14246       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
14247
14248   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
14249     return nullptr;
14250
14251   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
14252                                       AssertMessage, RParenLoc, false);
14253 }
14254
14255 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
14256                                          Expr *AssertExpr,
14257                                          StringLiteral *AssertMessage,
14258                                          SourceLocation RParenLoc,
14259                                          bool Failed) {
14260   assert(AssertExpr != nullptr && "Expected non-null condition");
14261   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
14262       !Failed) {
14263     // In a static_assert-declaration, the constant-expression shall be a
14264     // constant expression that can be contextually converted to bool.
14265     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
14266     if (Converted.isInvalid())
14267       Failed = true;
14268
14269     ExprResult FullAssertExpr =
14270         ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
14271                             /*DiscardedValue*/ false,
14272                             /*IsConstexpr*/ true);
14273     if (FullAssertExpr.isInvalid())
14274       Failed = true;
14275     else
14276       AssertExpr = FullAssertExpr.get();
14277
14278     llvm::APSInt Cond;
14279     if (!Failed && VerifyIntegerConstantExpression(AssertExpr, &Cond,
14280           diag::err_static_assert_expression_is_not_constant,
14281           /*AllowFold=*/false).isInvalid())
14282       Failed = true;
14283
14284     if (!Failed && !Cond) {
14285       SmallString<256> MsgBuffer;
14286       llvm::raw_svector_ostream Msg(MsgBuffer);
14287       if (AssertMessage)
14288         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
14289
14290       Expr *InnerCond = nullptr;
14291       std::string InnerCondDescription;
14292       std::tie(InnerCond, InnerCondDescription) =
14293         findFailedBooleanCondition(Converted.get());
14294       if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
14295                     && !isa<IntegerLiteral>(InnerCond)) {
14296         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
14297           << InnerCondDescription << !AssertMessage
14298           << Msg.str() << InnerCond->getSourceRange();
14299       } else {
14300         Diag(StaticAssertLoc, diag::err_static_assert_failed)
14301           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
14302       }
14303       Failed = true;
14304     }
14305   } else {
14306     ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
14307                                                     /*DiscardedValue*/false,
14308                                                     /*IsConstexpr*/true);
14309     if (FullAssertExpr.isInvalid())
14310       Failed = true;
14311     else
14312       AssertExpr = FullAssertExpr.get();
14313   }
14314
14315   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
14316                                         AssertExpr, AssertMessage, RParenLoc,
14317                                         Failed);
14318
14319   CurContext->addDecl(Decl);
14320   return Decl;
14321 }
14322
14323 /// Perform semantic analysis of the given friend type declaration.
14324 ///
14325 /// \returns A friend declaration that.
14326 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
14327                                       SourceLocation FriendLoc,
14328                                       TypeSourceInfo *TSInfo) {
14329   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
14330
14331   QualType T = TSInfo->getType();
14332   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
14333
14334   // C++03 [class.friend]p2:
14335   //   An elaborated-type-specifier shall be used in a friend declaration
14336   //   for a class.*
14337   //
14338   //   * The class-key of the elaborated-type-specifier is required.
14339   if (!CodeSynthesisContexts.empty()) {
14340     // Do not complain about the form of friend template types during any kind
14341     // of code synthesis. For template instantiation, we will have complained
14342     // when the template was defined.
14343   } else {
14344     if (!T->isElaboratedTypeSpecifier()) {
14345       // If we evaluated the type to a record type, suggest putting
14346       // a tag in front.
14347       if (const RecordType *RT = T->getAs<RecordType>()) {
14348         RecordDecl *RD = RT->getDecl();
14349
14350         SmallString<16> InsertionText(" ");
14351         InsertionText += RD->getKindName();
14352
14353         Diag(TypeRange.getBegin(),
14354              getLangOpts().CPlusPlus11 ?
14355                diag::warn_cxx98_compat_unelaborated_friend_type :
14356                diag::ext_unelaborated_friend_type)
14357           << (unsigned) RD->getTagKind()
14358           << T
14359           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
14360                                         InsertionText);
14361       } else {
14362         Diag(FriendLoc,
14363              getLangOpts().CPlusPlus11 ?
14364                diag::warn_cxx98_compat_nonclass_type_friend :
14365                diag::ext_nonclass_type_friend)
14366           << T
14367           << TypeRange;
14368       }
14369     } else if (T->getAs<EnumType>()) {
14370       Diag(FriendLoc,
14371            getLangOpts().CPlusPlus11 ?
14372              diag::warn_cxx98_compat_enum_friend :
14373              diag::ext_enum_friend)
14374         << T
14375         << TypeRange;
14376     }
14377
14378     // C++11 [class.friend]p3:
14379     //   A friend declaration that does not declare a function shall have one
14380     //   of the following forms:
14381     //     friend elaborated-type-specifier ;
14382     //     friend simple-type-specifier ;
14383     //     friend typename-specifier ;
14384     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
14385       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
14386   }
14387
14388   //   If the type specifier in a friend declaration designates a (possibly
14389   //   cv-qualified) class type, that class is declared as a friend; otherwise,
14390   //   the friend declaration is ignored.
14391   return FriendDecl::Create(Context, CurContext,
14392                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
14393                             FriendLoc);
14394 }
14395
14396 /// Handle a friend tag declaration where the scope specifier was
14397 /// templated.
14398 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
14399                                     unsigned TagSpec, SourceLocation TagLoc,
14400                                     CXXScopeSpec &SS, IdentifierInfo *Name,
14401                                     SourceLocation NameLoc,
14402                                     const ParsedAttributesView &Attr,
14403                                     MultiTemplateParamsArg TempParamLists) {
14404   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14405
14406   bool IsMemberSpecialization = false;
14407   bool Invalid = false;
14408
14409   if (TemplateParameterList *TemplateParams =
14410           MatchTemplateParametersToScopeSpecifier(
14411               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
14412               IsMemberSpecialization, Invalid)) {
14413     if (TemplateParams->size() > 0) {
14414       // This is a declaration of a class template.
14415       if (Invalid)
14416         return nullptr;
14417
14418       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
14419                                 NameLoc, Attr, TemplateParams, AS_public,
14420                                 /*ModulePrivateLoc=*/SourceLocation(),
14421                                 FriendLoc, TempParamLists.size() - 1,
14422                                 TempParamLists.data()).get();
14423     } else {
14424       // The "template<>" header is extraneous.
14425       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14426         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14427       IsMemberSpecialization = true;
14428     }
14429   }
14430
14431   if (Invalid) return nullptr;
14432
14433   bool isAllExplicitSpecializations = true;
14434   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
14435     if (TempParamLists[I]->size()) {
14436       isAllExplicitSpecializations = false;
14437       break;
14438     }
14439   }
14440
14441   // FIXME: don't ignore attributes.
14442
14443   // If it's explicit specializations all the way down, just forget
14444   // about the template header and build an appropriate non-templated
14445   // friend.  TODO: for source fidelity, remember the headers.
14446   if (isAllExplicitSpecializations) {
14447     if (SS.isEmpty()) {
14448       bool Owned = false;
14449       bool IsDependent = false;
14450       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
14451                       Attr, AS_public,
14452                       /*ModulePrivateLoc=*/SourceLocation(),
14453                       MultiTemplateParamsArg(), Owned, IsDependent,
14454                       /*ScopedEnumKWLoc=*/SourceLocation(),
14455                       /*ScopedEnumUsesClassTag=*/false,
14456                       /*UnderlyingType=*/TypeResult(),
14457                       /*IsTypeSpecifier=*/false,
14458                       /*IsTemplateParamOrArg=*/false);
14459     }
14460
14461     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
14462     ElaboratedTypeKeyword Keyword
14463       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14464     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
14465                                    *Name, NameLoc);
14466     if (T.isNull())
14467       return nullptr;
14468
14469     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14470     if (isa<DependentNameType>(T)) {
14471       DependentNameTypeLoc TL =
14472           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14473       TL.setElaboratedKeywordLoc(TagLoc);
14474       TL.setQualifierLoc(QualifierLoc);
14475       TL.setNameLoc(NameLoc);
14476     } else {
14477       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
14478       TL.setElaboratedKeywordLoc(TagLoc);
14479       TL.setQualifierLoc(QualifierLoc);
14480       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
14481     }
14482
14483     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14484                                             TSI, FriendLoc, TempParamLists);
14485     Friend->setAccess(AS_public);
14486     CurContext->addDecl(Friend);
14487     return Friend;
14488   }
14489
14490   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
14491
14492
14493
14494   // Handle the case of a templated-scope friend class.  e.g.
14495   //   template <class T> class A<T>::B;
14496   // FIXME: we don't support these right now.
14497   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
14498     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
14499   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14500   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
14501   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14502   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14503   TL.setElaboratedKeywordLoc(TagLoc);
14504   TL.setQualifierLoc(SS.getWithLocInContext(Context));
14505   TL.setNameLoc(NameLoc);
14506
14507   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14508                                           TSI, FriendLoc, TempParamLists);
14509   Friend->setAccess(AS_public);
14510   Friend->setUnsupportedFriend(true);
14511   CurContext->addDecl(Friend);
14512   return Friend;
14513 }
14514
14515 /// Handle a friend type declaration.  This works in tandem with
14516 /// ActOnTag.
14517 ///
14518 /// Notes on friend class templates:
14519 ///
14520 /// We generally treat friend class declarations as if they were
14521 /// declaring a class.  So, for example, the elaborated type specifier
14522 /// in a friend declaration is required to obey the restrictions of a
14523 /// class-head (i.e. no typedefs in the scope chain), template
14524 /// parameters are required to match up with simple template-ids, &c.
14525 /// However, unlike when declaring a template specialization, it's
14526 /// okay to refer to a template specialization without an empty
14527 /// template parameter declaration, e.g.
14528 ///   friend class A<T>::B<unsigned>;
14529 /// We permit this as a special case; if there are any template
14530 /// parameters present at all, require proper matching, i.e.
14531 ///   template <> template \<class T> friend class A<int>::B;
14532 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
14533                                 MultiTemplateParamsArg TempParams) {
14534   SourceLocation Loc = DS.getBeginLoc();
14535
14536   assert(DS.isFriendSpecified());
14537   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14538
14539   // C++ [class.friend]p3:
14540   // A friend declaration that does not declare a function shall have one of
14541   // the following forms:
14542   //     friend elaborated-type-specifier ;
14543   //     friend simple-type-specifier ;
14544   //     friend typename-specifier ;
14545   //
14546   // Any declaration with a type qualifier does not have that form. (It's
14547   // legal to specify a qualified type as a friend, you just can't write the
14548   // keywords.)
14549   if (DS.getTypeQualifiers()) {
14550     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
14551       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
14552     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
14553       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
14554     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
14555       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
14556     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
14557       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
14558     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
14559       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
14560   }
14561
14562   // Try to convert the decl specifier to a type.  This works for
14563   // friend templates because ActOnTag never produces a ClassTemplateDecl
14564   // for a TUK_Friend.
14565   Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
14566   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
14567   QualType T = TSI->getType();
14568   if (TheDeclarator.isInvalidType())
14569     return nullptr;
14570
14571   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
14572     return nullptr;
14573
14574   // This is definitely an error in C++98.  It's probably meant to
14575   // be forbidden in C++0x, too, but the specification is just
14576   // poorly written.
14577   //
14578   // The problem is with declarations like the following:
14579   //   template <T> friend A<T>::foo;
14580   // where deciding whether a class C is a friend or not now hinges
14581   // on whether there exists an instantiation of A that causes
14582   // 'foo' to equal C.  There are restrictions on class-heads
14583   // (which we declare (by fiat) elaborated friend declarations to
14584   // be) that makes this tractable.
14585   //
14586   // FIXME: handle "template <> friend class A<T>;", which
14587   // is possibly well-formed?  Who even knows?
14588   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
14589     Diag(Loc, diag::err_tagless_friend_type_template)
14590       << DS.getSourceRange();
14591     return nullptr;
14592   }
14593
14594   // C++98 [class.friend]p1: A friend of a class is a function
14595   //   or class that is not a member of the class . . .
14596   // This is fixed in DR77, which just barely didn't make the C++03
14597   // deadline.  It's also a very silly restriction that seriously
14598   // affects inner classes and which nobody else seems to implement;
14599   // thus we never diagnose it, not even in -pedantic.
14600   //
14601   // But note that we could warn about it: it's always useless to
14602   // friend one of your own members (it's not, however, worthless to
14603   // friend a member of an arbitrary specialization of your template).
14604
14605   Decl *D;
14606   if (!TempParams.empty())
14607     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
14608                                    TempParams,
14609                                    TSI,
14610                                    DS.getFriendSpecLoc());
14611   else
14612     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
14613
14614   if (!D)
14615     return nullptr;
14616
14617   D->setAccess(AS_public);
14618   CurContext->addDecl(D);
14619
14620   return D;
14621 }
14622
14623 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
14624                                         MultiTemplateParamsArg TemplateParams) {
14625   const DeclSpec &DS = D.getDeclSpec();
14626
14627   assert(DS.isFriendSpecified());
14628   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14629
14630   SourceLocation Loc = D.getIdentifierLoc();
14631   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14632
14633   // C++ [class.friend]p1
14634   //   A friend of a class is a function or class....
14635   // Note that this sees through typedefs, which is intended.
14636   // It *doesn't* see through dependent types, which is correct
14637   // according to [temp.arg.type]p3:
14638   //   If a declaration acquires a function type through a
14639   //   type dependent on a template-parameter and this causes
14640   //   a declaration that does not use the syntactic form of a
14641   //   function declarator to have a function type, the program
14642   //   is ill-formed.
14643   if (!TInfo->getType()->isFunctionType()) {
14644     Diag(Loc, diag::err_unexpected_friend);
14645
14646     // It might be worthwhile to try to recover by creating an
14647     // appropriate declaration.
14648     return nullptr;
14649   }
14650
14651   // C++ [namespace.memdef]p3
14652   //  - If a friend declaration in a non-local class first declares a
14653   //    class or function, the friend class or function is a member
14654   //    of the innermost enclosing namespace.
14655   //  - The name of the friend is not found by simple name lookup
14656   //    until a matching declaration is provided in that namespace
14657   //    scope (either before or after the class declaration granting
14658   //    friendship).
14659   //  - If a friend function is called, its name may be found by the
14660   //    name lookup that considers functions from namespaces and
14661   //    classes associated with the types of the function arguments.
14662   //  - When looking for a prior declaration of a class or a function
14663   //    declared as a friend, scopes outside the innermost enclosing
14664   //    namespace scope are not considered.
14665
14666   CXXScopeSpec &SS = D.getCXXScopeSpec();
14667   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
14668   assert(NameInfo.getName());
14669
14670   // Check for unexpanded parameter packs.
14671   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
14672       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
14673       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
14674     return nullptr;
14675
14676   // The context we found the declaration in, or in which we should
14677   // create the declaration.
14678   DeclContext *DC;
14679   Scope *DCScope = S;
14680   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
14681                         ForExternalRedeclaration);
14682
14683   // There are five cases here.
14684   //   - There's no scope specifier and we're in a local class. Only look
14685   //     for functions declared in the immediately-enclosing block scope.
14686   // We recover from invalid scope qualifiers as if they just weren't there.
14687   FunctionDecl *FunctionContainingLocalClass = nullptr;
14688   if ((SS.isInvalid() || !SS.isSet()) &&
14689       (FunctionContainingLocalClass =
14690            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
14691     // C++11 [class.friend]p11:
14692     //   If a friend declaration appears in a local class and the name
14693     //   specified is an unqualified name, a prior declaration is
14694     //   looked up without considering scopes that are outside the
14695     //   innermost enclosing non-class scope. For a friend function
14696     //   declaration, if there is no prior declaration, the program is
14697     //   ill-formed.
14698
14699     // Find the innermost enclosing non-class scope. This is the block
14700     // scope containing the local class definition (or for a nested class,
14701     // the outer local class).
14702     DCScope = S->getFnParent();
14703
14704     // Look up the function name in the scope.
14705     Previous.clear(LookupLocalFriendName);
14706     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
14707
14708     if (!Previous.empty()) {
14709       // All possible previous declarations must have the same context:
14710       // either they were declared at block scope or they are members of
14711       // one of the enclosing local classes.
14712       DC = Previous.getRepresentativeDecl()->getDeclContext();
14713     } else {
14714       // This is ill-formed, but provide the context that we would have
14715       // declared the function in, if we were permitted to, for error recovery.
14716       DC = FunctionContainingLocalClass;
14717     }
14718     adjustContextForLocalExternDecl(DC);
14719
14720     // C++ [class.friend]p6:
14721     //   A function can be defined in a friend declaration of a class if and
14722     //   only if the class is a non-local class (9.8), the function name is
14723     //   unqualified, and the function has namespace scope.
14724     if (D.isFunctionDefinition()) {
14725       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
14726     }
14727
14728   //   - There's no scope specifier, in which case we just go to the
14729   //     appropriate scope and look for a function or function template
14730   //     there as appropriate.
14731   } else if (SS.isInvalid() || !SS.isSet()) {
14732     // C++11 [namespace.memdef]p3:
14733     //   If the name in a friend declaration is neither qualified nor
14734     //   a template-id and the declaration is a function or an
14735     //   elaborated-type-specifier, the lookup to determine whether
14736     //   the entity has been previously declared shall not consider
14737     //   any scopes outside the innermost enclosing namespace.
14738     bool isTemplateId =
14739         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
14740
14741     // Find the appropriate context according to the above.
14742     DC = CurContext;
14743
14744     // Skip class contexts.  If someone can cite chapter and verse
14745     // for this behavior, that would be nice --- it's what GCC and
14746     // EDG do, and it seems like a reasonable intent, but the spec
14747     // really only says that checks for unqualified existing
14748     // declarations should stop at the nearest enclosing namespace,
14749     // not that they should only consider the nearest enclosing
14750     // namespace.
14751     while (DC->isRecord())
14752       DC = DC->getParent();
14753
14754     DeclContext *LookupDC = DC;
14755     while (LookupDC->isTransparentContext())
14756       LookupDC = LookupDC->getParent();
14757
14758     while (true) {
14759       LookupQualifiedName(Previous, LookupDC);
14760
14761       if (!Previous.empty()) {
14762         DC = LookupDC;
14763         break;
14764       }
14765
14766       if (isTemplateId) {
14767         if (isa<TranslationUnitDecl>(LookupDC)) break;
14768       } else {
14769         if (LookupDC->isFileContext()) break;
14770       }
14771       LookupDC = LookupDC->getParent();
14772     }
14773
14774     DCScope = getScopeForDeclContext(S, DC);
14775
14776   //   - There's a non-dependent scope specifier, in which case we
14777   //     compute it and do a previous lookup there for a function
14778   //     or function template.
14779   } else if (!SS.getScopeRep()->isDependent()) {
14780     DC = computeDeclContext(SS);
14781     if (!DC) return nullptr;
14782
14783     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
14784
14785     LookupQualifiedName(Previous, DC);
14786
14787     // C++ [class.friend]p1: A friend of a class is a function or
14788     //   class that is not a member of the class . . .
14789     if (DC->Equals(CurContext))
14790       Diag(DS.getFriendSpecLoc(),
14791            getLangOpts().CPlusPlus11 ?
14792              diag::warn_cxx98_compat_friend_is_member :
14793              diag::err_friend_is_member);
14794
14795     if (D.isFunctionDefinition()) {
14796       // C++ [class.friend]p6:
14797       //   A function can be defined in a friend declaration of a class if and
14798       //   only if the class is a non-local class (9.8), the function name is
14799       //   unqualified, and the function has namespace scope.
14800       //
14801       // FIXME: We should only do this if the scope specifier names the
14802       // innermost enclosing namespace; otherwise the fixit changes the
14803       // meaning of the code.
14804       SemaDiagnosticBuilder DB
14805         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
14806
14807       DB << SS.getScopeRep();
14808       if (DC->isFileContext())
14809         DB << FixItHint::CreateRemoval(SS.getRange());
14810       SS.clear();
14811     }
14812
14813   //   - There's a scope specifier that does not match any template
14814   //     parameter lists, in which case we use some arbitrary context,
14815   //     create a method or method template, and wait for instantiation.
14816   //   - There's a scope specifier that does match some template
14817   //     parameter lists, which we don't handle right now.
14818   } else {
14819     if (D.isFunctionDefinition()) {
14820       // C++ [class.friend]p6:
14821       //   A function can be defined in a friend declaration of a class if and
14822       //   only if the class is a non-local class (9.8), the function name is
14823       //   unqualified, and the function has namespace scope.
14824       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
14825         << SS.getScopeRep();
14826     }
14827
14828     DC = CurContext;
14829     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
14830   }
14831
14832   if (!DC->isRecord()) {
14833     int DiagArg = -1;
14834     switch (D.getName().getKind()) {
14835     case UnqualifiedIdKind::IK_ConstructorTemplateId:
14836     case UnqualifiedIdKind::IK_ConstructorName:
14837       DiagArg = 0;
14838       break;
14839     case UnqualifiedIdKind::IK_DestructorName:
14840       DiagArg = 1;
14841       break;
14842     case UnqualifiedIdKind::IK_ConversionFunctionId:
14843       DiagArg = 2;
14844       break;
14845     case UnqualifiedIdKind::IK_DeductionGuideName:
14846       DiagArg = 3;
14847       break;
14848     case UnqualifiedIdKind::IK_Identifier:
14849     case UnqualifiedIdKind::IK_ImplicitSelfParam:
14850     case UnqualifiedIdKind::IK_LiteralOperatorId:
14851     case UnqualifiedIdKind::IK_OperatorFunctionId:
14852     case UnqualifiedIdKind::IK_TemplateId:
14853       break;
14854     }
14855     // This implies that it has to be an operator or function.
14856     if (DiagArg >= 0) {
14857       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
14858       return nullptr;
14859     }
14860   }
14861
14862   // FIXME: This is an egregious hack to cope with cases where the scope stack
14863   // does not contain the declaration context, i.e., in an out-of-line
14864   // definition of a class.
14865   Scope FakeDCScope(S, Scope::DeclScope, Diags);
14866   if (!DCScope) {
14867     FakeDCScope.setEntity(DC);
14868     DCScope = &FakeDCScope;
14869   }
14870
14871   bool AddToScope = true;
14872   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
14873                                           TemplateParams, AddToScope);
14874   if (!ND) return nullptr;
14875
14876   assert(ND->getLexicalDeclContext() == CurContext);
14877
14878   // If we performed typo correction, we might have added a scope specifier
14879   // and changed the decl context.
14880   DC = ND->getDeclContext();
14881
14882   // Add the function declaration to the appropriate lookup tables,
14883   // adjusting the redeclarations list as necessary.  We don't
14884   // want to do this yet if the friending class is dependent.
14885   //
14886   // Also update the scope-based lookup if the target context's
14887   // lookup context is in lexical scope.
14888   if (!CurContext->isDependentContext()) {
14889     DC = DC->getRedeclContext();
14890     DC->makeDeclVisibleInContext(ND);
14891     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14892       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
14893   }
14894
14895   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
14896                                        D.getIdentifierLoc(), ND,
14897                                        DS.getFriendSpecLoc());
14898   FrD->setAccess(AS_public);
14899   CurContext->addDecl(FrD);
14900
14901   if (ND->isInvalidDecl()) {
14902     FrD->setInvalidDecl();
14903   } else {
14904     if (DC->isRecord()) CheckFriendAccess(ND);
14905
14906     FunctionDecl *FD;
14907     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
14908       FD = FTD->getTemplatedDecl();
14909     else
14910       FD = cast<FunctionDecl>(ND);
14911
14912     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
14913     // default argument expression, that declaration shall be a definition
14914     // and shall be the only declaration of the function or function
14915     // template in the translation unit.
14916     if (functionDeclHasDefaultArgument(FD)) {
14917       // We can't look at FD->getPreviousDecl() because it may not have been set
14918       // if we're in a dependent context. If the function is known to be a
14919       // redeclaration, we will have narrowed Previous down to the right decl.
14920       if (D.isRedeclaration()) {
14921         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
14922         Diag(Previous.getRepresentativeDecl()->getLocation(),
14923              diag::note_previous_declaration);
14924       } else if (!D.isFunctionDefinition())
14925         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
14926     }
14927
14928     // Mark templated-scope function declarations as unsupported.
14929     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
14930       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
14931         << SS.getScopeRep() << SS.getRange()
14932         << cast<CXXRecordDecl>(CurContext);
14933       FrD->setUnsupportedFriend(true);
14934     }
14935   }
14936
14937   return ND;
14938 }
14939
14940 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
14941   AdjustDeclIfTemplate(Dcl);
14942
14943   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
14944   if (!Fn) {
14945     Diag(DelLoc, diag::err_deleted_non_function);
14946     return;
14947   }
14948
14949   // Deleted function does not have a body.
14950   Fn->setWillHaveBody(false);
14951
14952   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
14953     // Don't consider the implicit declaration we generate for explicit
14954     // specializations. FIXME: Do not generate these implicit declarations.
14955     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
14956          Prev->getPreviousDecl()) &&
14957         !Prev->isDefined()) {
14958       Diag(DelLoc, diag::err_deleted_decl_not_first);
14959       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
14960            Prev->isImplicit() ? diag::note_previous_implicit_declaration
14961                               : diag::note_previous_declaration);
14962     }
14963     // If the declaration wasn't the first, we delete the function anyway for
14964     // recovery.
14965     Fn = Fn->getCanonicalDecl();
14966   }
14967
14968   // dllimport/dllexport cannot be deleted.
14969   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
14970     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
14971     Fn->setInvalidDecl();
14972   }
14973
14974   if (Fn->isDeleted())
14975     return;
14976
14977   // See if we're deleting a function which is already known to override a
14978   // non-deleted virtual function.
14979   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
14980     bool IssuedDiagnostic = false;
14981     for (const CXXMethodDecl *O : MD->overridden_methods()) {
14982       if (!(*MD->begin_overridden_methods())->isDeleted()) {
14983         if (!IssuedDiagnostic) {
14984           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
14985           IssuedDiagnostic = true;
14986         }
14987         Diag(O->getLocation(), diag::note_overridden_virtual_function);
14988       }
14989     }
14990     // If this function was implicitly deleted because it was defaulted,
14991     // explain why it was deleted.
14992     if (IssuedDiagnostic && MD->isDefaulted())
14993       ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
14994                                 /*Diagnose*/true);
14995   }
14996
14997   // C++11 [basic.start.main]p3:
14998   //   A program that defines main as deleted [...] is ill-formed.
14999   if (Fn->isMain())
15000     Diag(DelLoc, diag::err_deleted_main);
15001
15002   // C++11 [dcl.fct.def.delete]p4:
15003   //  A deleted function is implicitly inline.
15004   Fn->setImplicitlyInline();
15005   Fn->setDeletedAsWritten();
15006 }
15007
15008 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
15009   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
15010
15011   if (MD) {
15012     if (MD->getParent()->isDependentType()) {
15013       MD->setDefaulted();
15014       MD->setExplicitlyDefaulted();
15015       return;
15016     }
15017
15018     CXXSpecialMember Member = getSpecialMember(MD);
15019     if (Member == CXXInvalid) {
15020       if (!MD->isInvalidDecl())
15021         Diag(DefaultLoc, diag::err_default_special_members);
15022       return;
15023     }
15024
15025     MD->setDefaulted();
15026     MD->setExplicitlyDefaulted();
15027
15028     // Unset that we will have a body for this function. We might not,
15029     // if it turns out to be trivial, and we don't need this marking now
15030     // that we've marked it as defaulted.
15031     MD->setWillHaveBody(false);
15032
15033     // If this definition appears within the record, do the checking when
15034     // the record is complete.
15035     const FunctionDecl *Primary = MD;
15036     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
15037       // Ask the template instantiation pattern that actually had the
15038       // '= default' on it.
15039       Primary = Pattern;
15040
15041     // If the method was defaulted on its first declaration, we will have
15042     // already performed the checking in CheckCompletedCXXClass. Such a
15043     // declaration doesn't trigger an implicit definition.
15044     if (Primary->getCanonicalDecl()->isDefaulted())
15045       return;
15046
15047     CheckExplicitlyDefaultedSpecialMember(MD);
15048
15049     if (!MD->isInvalidDecl())
15050       DefineImplicitSpecialMember(*this, MD, DefaultLoc);
15051   } else {
15052     Diag(DefaultLoc, diag::err_default_special_members);
15053   }
15054 }
15055
15056 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
15057   for (Stmt *SubStmt : S->children()) {
15058     if (!SubStmt)
15059       continue;
15060     if (isa<ReturnStmt>(SubStmt))
15061       Self.Diag(SubStmt->getBeginLoc(),
15062                 diag::err_return_in_constructor_handler);
15063     if (!isa<Expr>(SubStmt))
15064       SearchForReturnInStmt(Self, SubStmt);
15065   }
15066 }
15067
15068 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
15069   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
15070     CXXCatchStmt *Handler = TryBlock->getHandler(I);
15071     SearchForReturnInStmt(*this, Handler);
15072   }
15073 }
15074
15075 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
15076                                              const CXXMethodDecl *Old) {
15077   const auto *NewFT = New->getType()->getAs<FunctionProtoType>();
15078   const auto *OldFT = Old->getType()->getAs<FunctionProtoType>();
15079
15080   if (OldFT->hasExtParameterInfos()) {
15081     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
15082       // A parameter of the overriding method should be annotated with noescape
15083       // if the corresponding parameter of the overridden method is annotated.
15084       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
15085           !NewFT->getExtParameterInfo(I).isNoEscape()) {
15086         Diag(New->getParamDecl(I)->getLocation(),
15087              diag::warn_overriding_method_missing_noescape);
15088         Diag(Old->getParamDecl(I)->getLocation(),
15089              diag::note_overridden_marked_noescape);
15090       }
15091   }
15092
15093   // Virtual overrides must have the same code_seg.
15094   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
15095   const auto *NewCSA = New->getAttr<CodeSegAttr>();
15096   if ((NewCSA || OldCSA) &&
15097       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
15098     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
15099     Diag(Old->getLocation(), diag::note_previous_declaration);
15100     return true;
15101   }
15102
15103   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
15104
15105   // If the calling conventions match, everything is fine
15106   if (NewCC == OldCC)
15107     return false;
15108
15109   // If the calling conventions mismatch because the new function is static,
15110   // suppress the calling convention mismatch error; the error about static
15111   // function override (err_static_overrides_virtual from
15112   // Sema::CheckFunctionDeclaration) is more clear.
15113   if (New->getStorageClass() == SC_Static)
15114     return false;
15115
15116   Diag(New->getLocation(),
15117        diag::err_conflicting_overriding_cc_attributes)
15118     << New->getDeclName() << New->getType() << Old->getType();
15119   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
15120   return true;
15121 }
15122
15123 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
15124                                              const CXXMethodDecl *Old) {
15125   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
15126   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
15127
15128   if (Context.hasSameType(NewTy, OldTy) ||
15129       NewTy->isDependentType() || OldTy->isDependentType())
15130     return false;
15131
15132   // Check if the return types are covariant
15133   QualType NewClassTy, OldClassTy;
15134
15135   /// Both types must be pointers or references to classes.
15136   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
15137     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
15138       NewClassTy = NewPT->getPointeeType();
15139       OldClassTy = OldPT->getPointeeType();
15140     }
15141   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
15142     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
15143       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
15144         NewClassTy = NewRT->getPointeeType();
15145         OldClassTy = OldRT->getPointeeType();
15146       }
15147     }
15148   }
15149
15150   // The return types aren't either both pointers or references to a class type.
15151   if (NewClassTy.isNull()) {
15152     Diag(New->getLocation(),
15153          diag::err_different_return_type_for_overriding_virtual_function)
15154         << New->getDeclName() << NewTy << OldTy
15155         << New->getReturnTypeSourceRange();
15156     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
15157         << Old->getReturnTypeSourceRange();
15158
15159     return true;
15160   }
15161
15162   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
15163     // C++14 [class.virtual]p8:
15164     //   If the class type in the covariant return type of D::f differs from
15165     //   that of B::f, the class type in the return type of D::f shall be
15166     //   complete at the point of declaration of D::f or shall be the class
15167     //   type D.
15168     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
15169       if (!RT->isBeingDefined() &&
15170           RequireCompleteType(New->getLocation(), NewClassTy,
15171                               diag::err_covariant_return_incomplete,
15172                               New->getDeclName()))
15173         return true;
15174     }
15175
15176     // Check if the new class derives from the old class.
15177     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
15178       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
15179           << New->getDeclName() << NewTy << OldTy
15180           << New->getReturnTypeSourceRange();
15181       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
15182           << Old->getReturnTypeSourceRange();
15183       return true;
15184     }
15185
15186     // Check if we the conversion from derived to base is valid.
15187     if (CheckDerivedToBaseConversion(
15188             NewClassTy, OldClassTy,
15189             diag::err_covariant_return_inaccessible_base,
15190             diag::err_covariant_return_ambiguous_derived_to_base_conv,
15191             New->getLocation(), New->getReturnTypeSourceRange(),
15192             New->getDeclName(), nullptr)) {
15193       // FIXME: this note won't trigger for delayed access control
15194       // diagnostics, and it's impossible to get an undelayed error
15195       // here from access control during the original parse because
15196       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
15197       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
15198           << Old->getReturnTypeSourceRange();
15199       return true;
15200     }
15201   }
15202
15203   // The qualifiers of the return types must be the same.
15204   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
15205     Diag(New->getLocation(),
15206          diag::err_covariant_return_type_different_qualifications)
15207         << New->getDeclName() << NewTy << OldTy
15208         << New->getReturnTypeSourceRange();
15209     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
15210         << Old->getReturnTypeSourceRange();
15211     return true;
15212   }
15213
15214
15215   // The new class type must have the same or less qualifiers as the old type.
15216   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
15217     Diag(New->getLocation(),
15218          diag::err_covariant_return_type_class_type_more_qualified)
15219         << New->getDeclName() << NewTy << OldTy
15220         << New->getReturnTypeSourceRange();
15221     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
15222         << Old->getReturnTypeSourceRange();
15223     return true;
15224   }
15225
15226   return false;
15227 }
15228
15229 /// Mark the given method pure.
15230 ///
15231 /// \param Method the method to be marked pure.
15232 ///
15233 /// \param InitRange the source range that covers the "0" initializer.
15234 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
15235   SourceLocation EndLoc = InitRange.getEnd();
15236   if (EndLoc.isValid())
15237     Method->setRangeEnd(EndLoc);
15238
15239   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
15240     Method->setPure();
15241     return false;
15242   }
15243
15244   if (!Method->isInvalidDecl())
15245     Diag(Method->getLocation(), diag::err_non_virtual_pure)
15246       << Method->getDeclName() << InitRange;
15247   return true;
15248 }
15249
15250 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
15251   if (D->getFriendObjectKind())
15252     Diag(D->getLocation(), diag::err_pure_friend);
15253   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
15254     CheckPureMethod(M, ZeroLoc);
15255   else
15256     Diag(D->getLocation(), diag::err_illegal_initializer);
15257 }
15258
15259 /// Determine whether the given declaration is a global variable or
15260 /// static data member.
15261 static bool isNonlocalVariable(const Decl *D) {
15262   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
15263     return Var->hasGlobalStorage();
15264
15265   return false;
15266 }
15267
15268 /// Invoked when we are about to parse an initializer for the declaration
15269 /// 'Dcl'.
15270 ///
15271 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
15272 /// static data member of class X, names should be looked up in the scope of
15273 /// class X. If the declaration had a scope specifier, a scope will have
15274 /// been created and passed in for this purpose. Otherwise, S will be null.
15275 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
15276   // If there is no declaration, there was an error parsing it.
15277   if (!D || D->isInvalidDecl())
15278     return;
15279
15280   // We will always have a nested name specifier here, but this declaration
15281   // might not be out of line if the specifier names the current namespace:
15282   //   extern int n;
15283   //   int ::n = 0;
15284   if (S && D->isOutOfLine())
15285     EnterDeclaratorContext(S, D->getDeclContext());
15286
15287   // If we are parsing the initializer for a static data member, push a
15288   // new expression evaluation context that is associated with this static
15289   // data member.
15290   if (isNonlocalVariable(D))
15291     PushExpressionEvaluationContext(
15292         ExpressionEvaluationContext::PotentiallyEvaluated, D);
15293 }
15294
15295 /// Invoked after we are finished parsing an initializer for the declaration D.
15296 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
15297   // If there is no declaration, there was an error parsing it.
15298   if (!D || D->isInvalidDecl())
15299     return;
15300
15301   if (isNonlocalVariable(D))
15302     PopExpressionEvaluationContext();
15303
15304   if (S && D->isOutOfLine())
15305     ExitDeclaratorContext(S);
15306 }
15307
15308 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
15309 /// C++ if/switch/while/for statement.
15310 /// e.g: "if (int x = f()) {...}"
15311 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
15312   // C++ 6.4p2:
15313   // The declarator shall not specify a function or an array.
15314   // The type-specifier-seq shall not contain typedef and shall not declare a
15315   // new class or enumeration.
15316   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
15317          "Parser allowed 'typedef' as storage class of condition decl.");
15318
15319   Decl *Dcl = ActOnDeclarator(S, D);
15320   if (!Dcl)
15321     return true;
15322
15323   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
15324     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
15325       << D.getSourceRange();
15326     return true;
15327   }
15328
15329   return Dcl;
15330 }
15331
15332 void Sema::LoadExternalVTableUses() {
15333   if (!ExternalSource)
15334     return;
15335
15336   SmallVector<ExternalVTableUse, 4> VTables;
15337   ExternalSource->ReadUsedVTables(VTables);
15338   SmallVector<VTableUse, 4> NewUses;
15339   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
15340     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
15341       = VTablesUsed.find(VTables[I].Record);
15342     // Even if a definition wasn't required before, it may be required now.
15343     if (Pos != VTablesUsed.end()) {
15344       if (!Pos->second && VTables[I].DefinitionRequired)
15345         Pos->second = true;
15346       continue;
15347     }
15348
15349     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
15350     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
15351   }
15352
15353   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
15354 }
15355
15356 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
15357                           bool DefinitionRequired) {
15358   // Ignore any vtable uses in unevaluated operands or for classes that do
15359   // not have a vtable.
15360   if (!Class->isDynamicClass() || Class->isDependentContext() ||
15361       CurContext->isDependentContext() || isUnevaluatedContext())
15362     return;
15363   // Do not mark as used if compiling for the device outside of the target
15364   // region.
15365   if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
15366       !isInOpenMPDeclareTargetContext() &&
15367       !isInOpenMPTargetExecutionDirective()) {
15368     if (!DefinitionRequired)
15369       MarkVirtualMembersReferenced(Loc, Class);
15370     return;
15371   }
15372
15373   // Try to insert this class into the map.
15374   LoadExternalVTableUses();
15375   Class = Class->getCanonicalDecl();
15376   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
15377     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
15378   if (!Pos.second) {
15379     // If we already had an entry, check to see if we are promoting this vtable
15380     // to require a definition. If so, we need to reappend to the VTableUses
15381     // list, since we may have already processed the first entry.
15382     if (DefinitionRequired && !Pos.first->second) {
15383       Pos.first->second = true;
15384     } else {
15385       // Otherwise, we can early exit.
15386       return;
15387     }
15388   } else {
15389     // The Microsoft ABI requires that we perform the destructor body
15390     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
15391     // the deleting destructor is emitted with the vtable, not with the
15392     // destructor definition as in the Itanium ABI.
15393     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
15394       CXXDestructorDecl *DD = Class->getDestructor();
15395       if (DD && DD->isVirtual() && !DD->isDeleted()) {
15396         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
15397           // If this is an out-of-line declaration, marking it referenced will
15398           // not do anything. Manually call CheckDestructor to look up operator
15399           // delete().
15400           ContextRAII SavedContext(*this, DD);
15401           CheckDestructor(DD);
15402         } else {
15403           MarkFunctionReferenced(Loc, Class->getDestructor());
15404         }
15405       }
15406     }
15407   }
15408
15409   // Local classes need to have their virtual members marked
15410   // immediately. For all other classes, we mark their virtual members
15411   // at the end of the translation unit.
15412   if (Class->isLocalClass())
15413     MarkVirtualMembersReferenced(Loc, Class);
15414   else
15415     VTableUses.push_back(std::make_pair(Class, Loc));
15416 }
15417
15418 bool Sema::DefineUsedVTables() {
15419   LoadExternalVTableUses();
15420   if (VTableUses.empty())
15421     return false;
15422
15423   // Note: The VTableUses vector could grow as a result of marking
15424   // the members of a class as "used", so we check the size each
15425   // time through the loop and prefer indices (which are stable) to
15426   // iterators (which are not).
15427   bool DefinedAnything = false;
15428   for (unsigned I = 0; I != VTableUses.size(); ++I) {
15429     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
15430     if (!Class)
15431       continue;
15432     TemplateSpecializationKind ClassTSK =
15433         Class->getTemplateSpecializationKind();
15434
15435     SourceLocation Loc = VTableUses[I].second;
15436
15437     bool DefineVTable = true;
15438
15439     // If this class has a key function, but that key function is
15440     // defined in another translation unit, we don't need to emit the
15441     // vtable even though we're using it.
15442     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
15443     if (KeyFunction && !KeyFunction->hasBody()) {
15444       // The key function is in another translation unit.
15445       DefineVTable = false;
15446       TemplateSpecializationKind TSK =
15447           KeyFunction->getTemplateSpecializationKind();
15448       assert(TSK != TSK_ExplicitInstantiationDefinition &&
15449              TSK != TSK_ImplicitInstantiation &&
15450              "Instantiations don't have key functions");
15451       (void)TSK;
15452     } else if (!KeyFunction) {
15453       // If we have a class with no key function that is the subject
15454       // of an explicit instantiation declaration, suppress the
15455       // vtable; it will live with the explicit instantiation
15456       // definition.
15457       bool IsExplicitInstantiationDeclaration =
15458           ClassTSK == TSK_ExplicitInstantiationDeclaration;
15459       for (auto R : Class->redecls()) {
15460         TemplateSpecializationKind TSK
15461           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
15462         if (TSK == TSK_ExplicitInstantiationDeclaration)
15463           IsExplicitInstantiationDeclaration = true;
15464         else if (TSK == TSK_ExplicitInstantiationDefinition) {
15465           IsExplicitInstantiationDeclaration = false;
15466           break;
15467         }
15468       }
15469
15470       if (IsExplicitInstantiationDeclaration)
15471         DefineVTable = false;
15472     }
15473
15474     // The exception specifications for all virtual members may be needed even
15475     // if we are not providing an authoritative form of the vtable in this TU.
15476     // We may choose to emit it available_externally anyway.
15477     if (!DefineVTable) {
15478       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
15479       continue;
15480     }
15481
15482     // Mark all of the virtual members of this class as referenced, so
15483     // that we can build a vtable. Then, tell the AST consumer that a
15484     // vtable for this class is required.
15485     DefinedAnything = true;
15486     MarkVirtualMembersReferenced(Loc, Class);
15487     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
15488     if (VTablesUsed[Canonical])
15489       Consumer.HandleVTable(Class);
15490
15491     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
15492     // no key function or the key function is inlined. Don't warn in C++ ABIs
15493     // that lack key functions, since the user won't be able to make one.
15494     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
15495         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
15496       const FunctionDecl *KeyFunctionDef = nullptr;
15497       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
15498                            KeyFunctionDef->isInlined())) {
15499         Diag(Class->getLocation(),
15500              ClassTSK == TSK_ExplicitInstantiationDefinition
15501                  ? diag::warn_weak_template_vtable
15502                  : diag::warn_weak_vtable)
15503             << Class;
15504       }
15505     }
15506   }
15507   VTableUses.clear();
15508
15509   return DefinedAnything;
15510 }
15511
15512 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
15513                                                  const CXXRecordDecl *RD) {
15514   for (const auto *I : RD->methods())
15515     if (I->isVirtual() && !I->isPure())
15516       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
15517 }
15518
15519 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
15520                                         const CXXRecordDecl *RD,
15521                                         bool ConstexprOnly) {
15522   // Mark all functions which will appear in RD's vtable as used.
15523   CXXFinalOverriderMap FinalOverriders;
15524   RD->getFinalOverriders(FinalOverriders);
15525   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
15526                                             E = FinalOverriders.end();
15527        I != E; ++I) {
15528     for (OverridingMethods::const_iterator OI = I->second.begin(),
15529                                            OE = I->second.end();
15530          OI != OE; ++OI) {
15531       assert(OI->second.size() > 0 && "no final overrider");
15532       CXXMethodDecl *Overrider = OI->second.front().Method;
15533
15534       // C++ [basic.def.odr]p2:
15535       //   [...] A virtual member function is used if it is not pure. [...]
15536       if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
15537         MarkFunctionReferenced(Loc, Overrider);
15538     }
15539   }
15540
15541   // Only classes that have virtual bases need a VTT.
15542   if (RD->getNumVBases() == 0)
15543     return;
15544
15545   for (const auto &I : RD->bases()) {
15546     const auto *Base =
15547         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
15548     if (Base->getNumVBases() == 0)
15549       continue;
15550     MarkVirtualMembersReferenced(Loc, Base);
15551   }
15552 }
15553
15554 /// SetIvarInitializers - This routine builds initialization ASTs for the
15555 /// Objective-C implementation whose ivars need be initialized.
15556 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
15557   if (!getLangOpts().CPlusPlus)
15558     return;
15559   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
15560     SmallVector<ObjCIvarDecl*, 8> ivars;
15561     CollectIvarsToConstructOrDestruct(OID, ivars);
15562     if (ivars.empty())
15563       return;
15564     SmallVector<CXXCtorInitializer*, 32> AllToInit;
15565     for (unsigned i = 0; i < ivars.size(); i++) {
15566       FieldDecl *Field = ivars[i];
15567       if (Field->isInvalidDecl())
15568         continue;
15569
15570       CXXCtorInitializer *Member;
15571       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
15572       InitializationKind InitKind =
15573         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
15574
15575       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
15576       ExprResult MemberInit =
15577         InitSeq.Perform(*this, InitEntity, InitKind, None);
15578       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
15579       // Note, MemberInit could actually come back empty if no initialization
15580       // is required (e.g., because it would call a trivial default constructor)
15581       if (!MemberInit.get() || MemberInit.isInvalid())
15582         continue;
15583
15584       Member =
15585         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
15586                                          SourceLocation(),
15587                                          MemberInit.getAs<Expr>(),
15588                                          SourceLocation());
15589       AllToInit.push_back(Member);
15590
15591       // Be sure that the destructor is accessible and is marked as referenced.
15592       if (const RecordType *RecordTy =
15593               Context.getBaseElementType(Field->getType())
15594                   ->getAs<RecordType>()) {
15595         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
15596         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
15597           MarkFunctionReferenced(Field->getLocation(), Destructor);
15598           CheckDestructorAccess(Field->getLocation(), Destructor,
15599                             PDiag(diag::err_access_dtor_ivar)
15600                               << Context.getBaseElementType(Field->getType()));
15601         }
15602       }
15603     }
15604     ObjCImplementation->setIvarInitializers(Context,
15605                                             AllToInit.data(), AllToInit.size());
15606   }
15607 }
15608
15609 static
15610 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
15611                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
15612                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
15613                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
15614                            Sema &S) {
15615   if (Ctor->isInvalidDecl())
15616     return;
15617
15618   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
15619
15620   // Target may not be determinable yet, for instance if this is a dependent
15621   // call in an uninstantiated template.
15622   if (Target) {
15623     const FunctionDecl *FNTarget = nullptr;
15624     (void)Target->hasBody(FNTarget);
15625     Target = const_cast<CXXConstructorDecl*>(
15626       cast_or_null<CXXConstructorDecl>(FNTarget));
15627   }
15628
15629   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
15630                      // Avoid dereferencing a null pointer here.
15631                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
15632
15633   if (!Current.insert(Canonical).second)
15634     return;
15635
15636   // We know that beyond here, we aren't chaining into a cycle.
15637   if (!Target || !Target->isDelegatingConstructor() ||
15638       Target->isInvalidDecl() || Valid.count(TCanonical)) {
15639     Valid.insert(Current.begin(), Current.end());
15640     Current.clear();
15641   // We've hit a cycle.
15642   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
15643              Current.count(TCanonical)) {
15644     // If we haven't diagnosed this cycle yet, do so now.
15645     if (!Invalid.count(TCanonical)) {
15646       S.Diag((*Ctor->init_begin())->getSourceLocation(),
15647              diag::warn_delegating_ctor_cycle)
15648         << Ctor;
15649
15650       // Don't add a note for a function delegating directly to itself.
15651       if (TCanonical != Canonical)
15652         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
15653
15654       CXXConstructorDecl *C = Target;
15655       while (C->getCanonicalDecl() != Canonical) {
15656         const FunctionDecl *FNTarget = nullptr;
15657         (void)C->getTargetConstructor()->hasBody(FNTarget);
15658         assert(FNTarget && "Ctor cycle through bodiless function");
15659
15660         C = const_cast<CXXConstructorDecl*>(
15661           cast<CXXConstructorDecl>(FNTarget));
15662         S.Diag(C->getLocation(), diag::note_which_delegates_to);
15663       }
15664     }
15665
15666     Invalid.insert(Current.begin(), Current.end());
15667     Current.clear();
15668   } else {
15669     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
15670   }
15671 }
15672
15673
15674 void Sema::CheckDelegatingCtorCycles() {
15675   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
15676
15677   for (DelegatingCtorDeclsType::iterator
15678          I = DelegatingCtorDecls.begin(ExternalSource),
15679          E = DelegatingCtorDecls.end();
15680        I != E; ++I)
15681     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
15682
15683   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
15684     (*CI)->setInvalidDecl();
15685 }
15686
15687 namespace {
15688   /// AST visitor that finds references to the 'this' expression.
15689   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
15690     Sema &S;
15691
15692   public:
15693     explicit FindCXXThisExpr(Sema &S) : S(S) { }
15694
15695     bool VisitCXXThisExpr(CXXThisExpr *E) {
15696       S.Diag(E->getLocation(), diag::err_this_static_member_func)
15697         << E->isImplicit();
15698       return false;
15699     }
15700   };
15701 }
15702
15703 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
15704   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15705   if (!TSInfo)
15706     return false;
15707
15708   TypeLoc TL = TSInfo->getTypeLoc();
15709   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15710   if (!ProtoTL)
15711     return false;
15712
15713   // C++11 [expr.prim.general]p3:
15714   //   [The expression this] shall not appear before the optional
15715   //   cv-qualifier-seq and it shall not appear within the declaration of a
15716   //   static member function (although its type and value category are defined
15717   //   within a static member function as they are within a non-static member
15718   //   function). [ Note: this is because declaration matching does not occur
15719   //  until the complete declarator is known. - end note ]
15720   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15721   FindCXXThisExpr Finder(*this);
15722
15723   // If the return type came after the cv-qualifier-seq, check it now.
15724   if (Proto->hasTrailingReturn() &&
15725       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
15726     return true;
15727
15728   // Check the exception specification.
15729   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
15730     return true;
15731
15732   return checkThisInStaticMemberFunctionAttributes(Method);
15733 }
15734
15735 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
15736   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15737   if (!TSInfo)
15738     return false;
15739
15740   TypeLoc TL = TSInfo->getTypeLoc();
15741   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15742   if (!ProtoTL)
15743     return false;
15744
15745   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15746   FindCXXThisExpr Finder(*this);
15747
15748   switch (Proto->getExceptionSpecType()) {
15749   case EST_Unparsed:
15750   case EST_Uninstantiated:
15751   case EST_Unevaluated:
15752   case EST_BasicNoexcept:
15753   case EST_NoThrow:
15754   case EST_DynamicNone:
15755   case EST_MSAny:
15756   case EST_None:
15757     break;
15758
15759   case EST_DependentNoexcept:
15760   case EST_NoexceptFalse:
15761   case EST_NoexceptTrue:
15762     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
15763       return true;
15764     LLVM_FALLTHROUGH;
15765
15766   case EST_Dynamic:
15767     for (const auto &E : Proto->exceptions()) {
15768       if (!Finder.TraverseType(E))
15769         return true;
15770     }
15771     break;
15772   }
15773
15774   return false;
15775 }
15776
15777 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
15778   FindCXXThisExpr Finder(*this);
15779
15780   // Check attributes.
15781   for (const auto *A : Method->attrs()) {
15782     // FIXME: This should be emitted by tblgen.
15783     Expr *Arg = nullptr;
15784     ArrayRef<Expr *> Args;
15785     if (const auto *G = dyn_cast<GuardedByAttr>(A))
15786       Arg = G->getArg();
15787     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
15788       Arg = G->getArg();
15789     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
15790       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
15791     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
15792       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
15793     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
15794       Arg = ETLF->getSuccessValue();
15795       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
15796     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
15797       Arg = STLF->getSuccessValue();
15798       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
15799     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
15800       Arg = LR->getArg();
15801     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
15802       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
15803     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
15804       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15805     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
15806       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15807     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
15808       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15809     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
15810       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15811
15812     if (Arg && !Finder.TraverseStmt(Arg))
15813       return true;
15814
15815     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
15816       if (!Finder.TraverseStmt(Args[I]))
15817         return true;
15818     }
15819   }
15820
15821   return false;
15822 }
15823
15824 void Sema::checkExceptionSpecification(
15825     bool IsTopLevel, ExceptionSpecificationType EST,
15826     ArrayRef<ParsedType> DynamicExceptions,
15827     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
15828     SmallVectorImpl<QualType> &Exceptions,
15829     FunctionProtoType::ExceptionSpecInfo &ESI) {
15830   Exceptions.clear();
15831   ESI.Type = EST;
15832   if (EST == EST_Dynamic) {
15833     Exceptions.reserve(DynamicExceptions.size());
15834     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
15835       // FIXME: Preserve type source info.
15836       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
15837
15838       if (IsTopLevel) {
15839         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
15840         collectUnexpandedParameterPacks(ET, Unexpanded);
15841         if (!Unexpanded.empty()) {
15842           DiagnoseUnexpandedParameterPacks(
15843               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
15844               Unexpanded);
15845           continue;
15846         }
15847       }
15848
15849       // Check that the type is valid for an exception spec, and
15850       // drop it if not.
15851       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
15852         Exceptions.push_back(ET);
15853     }
15854     ESI.Exceptions = Exceptions;
15855     return;
15856   }
15857
15858   if (isComputedNoexcept(EST)) {
15859     assert((NoexceptExpr->isTypeDependent() ||
15860             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
15861             Context.BoolTy) &&
15862            "Parser should have made sure that the expression is boolean");
15863     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
15864       ESI.Type = EST_BasicNoexcept;
15865       return;
15866     }
15867
15868     ESI.NoexceptExpr = NoexceptExpr;
15869     return;
15870   }
15871 }
15872
15873 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
15874              ExceptionSpecificationType EST,
15875              SourceRange SpecificationRange,
15876              ArrayRef<ParsedType> DynamicExceptions,
15877              ArrayRef<SourceRange> DynamicExceptionRanges,
15878              Expr *NoexceptExpr) {
15879   if (!MethodD)
15880     return;
15881
15882   // Dig out the method we're referring to.
15883   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
15884     MethodD = FunTmpl->getTemplatedDecl();
15885
15886   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
15887   if (!Method)
15888     return;
15889
15890   // Check the exception specification.
15891   llvm::SmallVector<QualType, 4> Exceptions;
15892   FunctionProtoType::ExceptionSpecInfo ESI;
15893   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
15894                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
15895                               ESI);
15896
15897   // Update the exception specification on the function type.
15898   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
15899
15900   if (Method->isStatic())
15901     checkThisInStaticMemberFunctionExceptionSpec(Method);
15902
15903   if (Method->isVirtual()) {
15904     // Check overrides, which we previously had to delay.
15905     for (const CXXMethodDecl *O : Method->overridden_methods())
15906       CheckOverridingFunctionExceptionSpec(Method, O);
15907   }
15908 }
15909
15910 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
15911 ///
15912 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
15913                                        SourceLocation DeclStart, Declarator &D,
15914                                        Expr *BitWidth,
15915                                        InClassInitStyle InitStyle,
15916                                        AccessSpecifier AS,
15917                                        const ParsedAttr &MSPropertyAttr) {
15918   IdentifierInfo *II = D.getIdentifier();
15919   if (!II) {
15920     Diag(DeclStart, diag::err_anonymous_property);
15921     return nullptr;
15922   }
15923   SourceLocation Loc = D.getIdentifierLoc();
15924
15925   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15926   QualType T = TInfo->getType();
15927   if (getLangOpts().CPlusPlus) {
15928     CheckExtraCXXDefaultArguments(D);
15929
15930     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15931                                         UPPC_DataMemberType)) {
15932       D.setInvalidType();
15933       T = Context.IntTy;
15934       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15935     }
15936   }
15937
15938   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15939
15940   if (D.getDeclSpec().isInlineSpecified())
15941     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15942         << getLangOpts().CPlusPlus17;
15943   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15944     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15945          diag::err_invalid_thread)
15946       << DeclSpec::getSpecifierName(TSCS);
15947
15948   // Check to see if this name was declared as a member previously
15949   NamedDecl *PrevDecl = nullptr;
15950   LookupResult Previous(*this, II, Loc, LookupMemberName,
15951                         ForVisibleRedeclaration);
15952   LookupName(Previous, S);
15953   switch (Previous.getResultKind()) {
15954   case LookupResult::Found:
15955   case LookupResult::FoundUnresolvedValue:
15956     PrevDecl = Previous.getAsSingle<NamedDecl>();
15957     break;
15958
15959   case LookupResult::FoundOverloaded:
15960     PrevDecl = Previous.getRepresentativeDecl();
15961     break;
15962
15963   case LookupResult::NotFound:
15964   case LookupResult::NotFoundInCurrentInstantiation:
15965   case LookupResult::Ambiguous:
15966     break;
15967   }
15968
15969   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15970     // Maybe we will complain about the shadowed template parameter.
15971     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15972     // Just pretend that we didn't see the previous declaration.
15973     PrevDecl = nullptr;
15974   }
15975
15976   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15977     PrevDecl = nullptr;
15978
15979   SourceLocation TSSL = D.getBeginLoc();
15980   MSPropertyDecl *NewPD =
15981       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
15982                              MSPropertyAttr.getPropertyDataGetter(),
15983                              MSPropertyAttr.getPropertyDataSetter());
15984   ProcessDeclAttributes(TUScope, NewPD, D);
15985   NewPD->setAccess(AS);
15986
15987   if (NewPD->isInvalidDecl())
15988     Record->setInvalidDecl();
15989
15990   if (D.getDeclSpec().isModulePrivateSpecified())
15991     NewPD->setModulePrivate();
15992
15993   if (NewPD->isInvalidDecl() && PrevDecl) {
15994     // Don't introduce NewFD into scope; there's already something
15995     // with the same name in the same scope.
15996   } else if (II) {
15997     PushOnScopeChains(NewPD, S);
15998   } else
15999     Record->addDecl(NewPD);
16000
16001   return NewPD;
16002 }