1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for C++ declarations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/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/PartialDiagnostic.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Lex/LiteralSupport.h"
30 #include "clang/Lex/Preprocessor.h"
31 #include "clang/Sema/CXXFieldCollector.h"
32 #include "clang/Sema/DeclSpec.h"
33 #include "clang/Sema/Initialization.h"
34 #include "clang/Sema/Lookup.h"
35 #include "clang/Sema/ParsedTemplate.h"
36 #include "clang/Sema/Scope.h"
37 #include "clang/Sema/ScopeInfo.h"
38 #include "clang/Sema/SemaInternal.h"
39 #include "clang/Sema/Template.h"
40 #include "llvm/ADT/STLExtras.h"
41 #include "llvm/ADT/SmallString.h"
42 #include "llvm/ADT/StringExtras.h"
43 #include <map>
44 #include <set>
45 
46 using namespace clang;
47 
48 //===----------------------------------------------------------------------===//
49 // CheckDefaultArgumentVisitor
50 //===----------------------------------------------------------------------===//
51 
52 namespace {
53   /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
54   /// the default argument of a parameter to determine whether it
55   /// contains any ill-formed subexpressions. For example, this will
56   /// diagnose the use of local variables or parameters within the
57   /// default argument expression.
58   class CheckDefaultArgumentVisitor
59     : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
60     Expr *DefaultArg;
61     Sema *S;
62 
63   public:
64     CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
65       : DefaultArg(defarg), S(s) {}
66 
67     bool VisitExpr(Expr *Node);
68     bool VisitDeclRefExpr(DeclRefExpr *DRE);
69     bool VisitCXXThisExpr(CXXThisExpr *ThisE);
70     bool VisitLambdaExpr(LambdaExpr *Lambda);
71     bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
72   };
73 
74   /// VisitExpr - Visit all of the children of this expression.
75   bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
76     bool IsInvalid = false;
77     for (Stmt *SubStmt : Node->children())
78       IsInvalid |= Visit(SubStmt);
79     return IsInvalid;
80   }
81 
82   /// VisitDeclRefExpr - Visit a reference to a declaration, to
83   /// determine whether this declaration can be used in the default
84   /// argument expression.
85   bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
86     NamedDecl *Decl = DRE->getDecl();
87     if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
88       // C++ [dcl.fct.default]p9
89       //   Default arguments are evaluated each time the function is
90       //   called. The order of evaluation of function arguments is
91       //   unspecified. Consequently, parameters of a function shall not
92       //   be used in default argument expressions, even if they are not
93       //   evaluated. Parameters of a function declared before a default
94       //   argument expression are in scope and can hide namespace and
95       //   class member names.
96       return S->Diag(DRE->getLocStart(),
97                      diag::err_param_default_argument_references_param)
98          << Param->getDeclName() << DefaultArg->getSourceRange();
99     } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
100       // C++ [dcl.fct.default]p7
101       //   Local variables shall not be used in default argument
102       //   expressions.
103       if (VDecl->isLocalVarDecl())
104         return S->Diag(DRE->getLocStart(),
105                        diag::err_param_default_argument_references_local)
106           << VDecl->getDeclName() << DefaultArg->getSourceRange();
107     }
108 
109     return false;
110   }
111 
112   /// VisitCXXThisExpr - Visit a C++ "this" expression.
113   bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
114     // C++ [dcl.fct.default]p8:
115     //   The keyword this shall not be used in a default argument of a
116     //   member function.
117     return S->Diag(ThisE->getLocStart(),
118                    diag::err_param_default_argument_references_this)
119                << ThisE->getSourceRange();
120   }
121 
122   bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
123     bool Invalid = false;
124     for (PseudoObjectExpr::semantics_iterator
125            i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
126       Expr *E = *i;
127 
128       // Look through bindings.
129       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
130         E = OVE->getSourceExpr();
131         assert(E && "pseudo-object binding without source expression?");
132       }
133 
134       Invalid |= Visit(E);
135     }
136     return Invalid;
137   }
138 
139   bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
140     // C++11 [expr.lambda.prim]p13:
141     //   A lambda-expression appearing in a default argument shall not
142     //   implicitly or explicitly capture any entity.
143     if (Lambda->capture_begin() == Lambda->capture_end())
144       return false;
145 
146     return S->Diag(Lambda->getLocStart(),
147                    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   switch(EST) {
171   // If this function can throw any exceptions, make a note of that.
172   case EST_MSAny:
173   case EST_None:
174     ClearExceptions();
175     ComputedEST = EST;
176     return;
177   // FIXME: If the call to this decl is using any of its default arguments, we
178   // need to search them for potentially-throwing calls.
179   // If this function has a basic noexcept, it doesn't affect the outcome.
180   case EST_BasicNoexcept:
181     return;
182   // If we're still at noexcept(true) and there's a nothrow() callee,
183   // change to that specification.
184   case EST_DynamicNone:
185     if (ComputedEST == EST_BasicNoexcept)
186       ComputedEST = EST_DynamicNone;
187     return;
188   // Check out noexcept specs.
189   case EST_ComputedNoexcept:
190   {
191     FunctionProtoType::NoexceptResult NR =
192         Proto->getNoexceptSpec(Self->Context);
193     assert(NR != FunctionProtoType::NR_NoNoexcept &&
194            "Must have noexcept result for EST_ComputedNoexcept.");
195     assert(NR != FunctionProtoType::NR_Dependent &&
196            "Should not generate implicit declarations for dependent cases, "
197            "and don't know how to handle them anyway.");
198     // noexcept(false) -> no spec on the new function
199     if (NR == FunctionProtoType::NR_Throw) {
200       ClearExceptions();
201       ComputedEST = EST_None;
202     }
203     // noexcept(true) won't change anything either.
204     return;
205   }
206   default:
207     break;
208   }
209   assert(EST == EST_Dynamic && "EST case not considered earlier.");
210   assert(ComputedEST != EST_None &&
211          "Shouldn't collect exceptions when throw-all is guaranteed.");
212   ComputedEST = EST_Dynamic;
213   // Record the exceptions in this function's exception specification.
214   for (const auto &E : Proto->exceptions())
215     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
216       Exceptions.push_back(E);
217 }
218 
219 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
220   if (!E || ComputedEST == EST_MSAny)
221     return;
222 
223   // FIXME:
224   //
225   // C++0x [except.spec]p14:
226   //   [An] implicit exception-specification specifies the type-id T if and
227   // only if T is allowed by the exception-specification of a function directly
228   // invoked by f's implicit definition; f shall allow all exceptions if any
229   // function it directly invokes allows all exceptions, and f shall allow no
230   // exceptions if every function it directly invokes allows no exceptions.
231   //
232   // Note in particular that if an implicit exception-specification is generated
233   // for a function containing a throw-expression, that specification can still
234   // be noexcept(true).
235   //
236   // Note also that 'directly invoked' is not defined in the standard, and there
237   // is no indication that we should only consider potentially-evaluated calls.
238   //
239   // Ultimately we should implement the intent of the standard: the exception
240   // specification should be the set of exceptions which can be thrown by the
241   // implicit definition. For now, we assume that any non-nothrow expression can
242   // throw any exception.
243 
244   if (Self->canThrow(E))
245     ComputedEST = EST_None;
246 }
247 
248 bool
249 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
250                               SourceLocation EqualLoc) {
251   if (RequireCompleteType(Param->getLocation(), Param->getType(),
252                           diag::err_typecheck_decl_incomplete_type)) {
253     Param->setInvalidDecl();
254     return true;
255   }
256 
257   // C++ [dcl.fct.default]p5
258   //   A default argument expression is implicitly converted (clause
259   //   4) to the parameter type. The default argument expression has
260   //   the same semantic constraints as the initializer expression in
261   //   a declaration of a variable of the parameter type, using the
262   //   copy-initialization semantics (8.5).
263   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
264                                                                     Param);
265   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
266                                                            EqualLoc);
267   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
268   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
269   if (Result.isInvalid())
270     return true;
271   Arg = Result.getAs<Expr>();
272 
273   CheckCompletedExpr(Arg, EqualLoc);
274   Arg = MaybeCreateExprWithCleanups(Arg);
275 
276   // Okay: add the default argument to the parameter
277   Param->setDefaultArg(Arg);
278 
279   // We have already instantiated this parameter; provide each of the
280   // instantiations with the uninstantiated default argument.
281   UnparsedDefaultArgInstantiationsMap::iterator InstPos
282     = UnparsedDefaultArgInstantiations.find(Param);
283   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
284     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
285       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
286 
287     // We're done tracking this parameter's instantiations.
288     UnparsedDefaultArgInstantiations.erase(InstPos);
289   }
290 
291   return false;
292 }
293 
294 /// ActOnParamDefaultArgument - Check whether the default argument
295 /// provided for a function parameter is well-formed. If so, attach it
296 /// to the parameter declaration.
297 void
298 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
299                                 Expr *DefaultArg) {
300   if (!param || !DefaultArg)
301     return;
302 
303   ParmVarDecl *Param = cast<ParmVarDecl>(param);
304   UnparsedDefaultArgLocs.erase(Param);
305 
306   // Default arguments are only permitted in C++
307   if (!getLangOpts().CPlusPlus) {
308     Diag(EqualLoc, diag::err_param_default_argument)
309       << DefaultArg->getSourceRange();
310     Param->setInvalidDecl();
311     return;
312   }
313 
314   // Check for unexpanded parameter packs.
315   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
316     Param->setInvalidDecl();
317     return;
318   }
319 
320   // C++11 [dcl.fct.default]p3
321   //   A default argument expression [...] shall not be specified for a
322   //   parameter pack.
323   if (Param->isParameterPack()) {
324     Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
325         << DefaultArg->getSourceRange();
326     return;
327   }
328 
329   // Check that the default argument is well-formed
330   CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
331   if (DefaultArgChecker.Visit(DefaultArg)) {
332     Param->setInvalidDecl();
333     return;
334   }
335 
336   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
337 }
338 
339 /// ActOnParamUnparsedDefaultArgument - We've seen a default
340 /// argument for a function parameter, but we can't parse it yet
341 /// because we're inside a class definition. Note that this default
342 /// argument will be parsed later.
343 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
344                                              SourceLocation EqualLoc,
345                                              SourceLocation ArgLoc) {
346   if (!param)
347     return;
348 
349   ParmVarDecl *Param = cast<ParmVarDecl>(param);
350   Param->setUnparsedDefaultArg();
351   UnparsedDefaultArgLocs[Param] = ArgLoc;
352 }
353 
354 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
355 /// the default argument for the parameter param failed.
356 void Sema::ActOnParamDefaultArgumentError(Decl *param,
357                                           SourceLocation EqualLoc) {
358   if (!param)
359     return;
360 
361   ParmVarDecl *Param = cast<ParmVarDecl>(param);
362   Param->setInvalidDecl();
363   UnparsedDefaultArgLocs.erase(Param);
364   Param->setDefaultArg(new(Context)
365                        OpaqueValueExpr(EqualLoc,
366                                        Param->getType().getNonReferenceType(),
367                                        VK_RValue));
368 }
369 
370 /// CheckExtraCXXDefaultArguments - Check for any extra default
371 /// arguments in the declarator, which is not a function declaration
372 /// or definition and therefore is not permitted to have default
373 /// arguments. This routine should be invoked for every declarator
374 /// that is not a function declaration or definition.
375 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
376   // C++ [dcl.fct.default]p3
377   //   A default argument expression shall be specified only in the
378   //   parameter-declaration-clause of a function declaration or in a
379   //   template-parameter (14.1). It shall not be specified for a
380   //   parameter pack. If it is specified in a
381   //   parameter-declaration-clause, it shall not occur within a
382   //   declarator or abstract-declarator of a parameter-declaration.
383   bool MightBeFunction = D.isFunctionDeclarationContext();
384   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
385     DeclaratorChunk &chunk = D.getTypeObject(i);
386     if (chunk.Kind == DeclaratorChunk::Function) {
387       if (MightBeFunction) {
388         // This is a function declaration. It can have default arguments, but
389         // keep looking in case its return type is a function type with default
390         // arguments.
391         MightBeFunction = false;
392         continue;
393       }
394       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
395            ++argIdx) {
396         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
397         if (Param->hasUnparsedDefaultArg()) {
398           CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
399           SourceRange SR;
400           if (Toks->size() > 1)
401             SR = SourceRange((*Toks)[1].getLocation(),
402                              Toks->back().getLocation());
403           else
404             SR = UnparsedDefaultArgLocs[Param];
405           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
406             << SR;
407           delete Toks;
408           chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
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       // sufficent, 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.
552       // It's important to use getInit() here;  getDefaultArg()
553       // strips off any top-level ExprWithCleanups.
554       NewParam->setHasInheritedDefaultArg();
555       if (OldParam->hasUnparsedDefaultArg())
556         NewParam->setUnparsedDefaultArg();
557       else if (OldParam->hasUninstantiatedDefaultArg())
558         NewParam->setUninstantiatedDefaultArg(
559                                       OldParam->getUninstantiatedDefaultArg());
560       else
561         NewParam->setDefaultArg(OldParam->getInit());
562     } else if (NewParamHasDfl) {
563       if (New->getDescribedFunctionTemplate()) {
564         // Paragraph 4, quoted above, only applies to non-template functions.
565         Diag(NewParam->getLocation(),
566              diag::err_param_default_argument_template_redecl)
567           << NewParam->getDefaultArgRange();
568         Diag(PrevForDefaultArgs->getLocation(),
569              diag::note_template_prev_declaration)
570             << false;
571       } else if (New->getTemplateSpecializationKind()
572                    != TSK_ImplicitInstantiation &&
573                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
574         // C++ [temp.expr.spec]p21:
575         //   Default function arguments shall not be specified in a declaration
576         //   or a definition for one of the following explicit specializations:
577         //     - the explicit specialization of a function template;
578         //     - the explicit specialization of a member function template;
579         //     - the explicit specialization of a member function of a class
580         //       template where the class template specialization to which the
581         //       member function specialization belongs is implicitly
582         //       instantiated.
583         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
584           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
585           << New->getDeclName()
586           << NewParam->getDefaultArgRange();
587       } else if (New->getDeclContext()->isDependentContext()) {
588         // C++ [dcl.fct.default]p6 (DR217):
589         //   Default arguments for a member function of a class template shall
590         //   be specified on the initial declaration of the member function
591         //   within the class template.
592         //
593         // Reading the tea leaves a bit in DR217 and its reference to DR205
594         // leads me to the conclusion that one cannot add default function
595         // arguments for an out-of-line definition of a member function of a
596         // dependent type.
597         int WhichKind = 2;
598         if (CXXRecordDecl *Record
599               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
600           if (Record->getDescribedClassTemplate())
601             WhichKind = 0;
602           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
603             WhichKind = 1;
604           else
605             WhichKind = 2;
606         }
607 
608         Diag(NewParam->getLocation(),
609              diag::err_param_default_argument_member_template_redecl)
610           << WhichKind
611           << NewParam->getDefaultArgRange();
612       }
613     }
614   }
615 
616   // DR1344: If a default argument is added outside a class definition and that
617   // default argument makes the function a special member function, the program
618   // is ill-formed. This can only happen for constructors.
619   if (isa<CXXConstructorDecl>(New) &&
620       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
621     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
622                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
623     if (NewSM != OldSM) {
624       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
625       assert(NewParam->hasDefaultArg());
626       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
627         << NewParam->getDefaultArgRange() << NewSM;
628       Diag(Old->getLocation(), diag::note_previous_declaration);
629     }
630   }
631 
632   const FunctionDecl *Def;
633   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
634   // template has a constexpr specifier then all its declarations shall
635   // contain the constexpr specifier.
636   if (New->isConstexpr() != Old->isConstexpr()) {
637     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
638       << New << New->isConstexpr();
639     Diag(Old->getLocation(), diag::note_previous_declaration);
640     Invalid = true;
641   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
642              Old->isDefined(Def)) {
643     // C++11 [dcl.fcn.spec]p4:
644     //   If the definition of a function appears in a translation unit before its
645     //   first declaration as inline, the program is ill-formed.
646     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
647     Diag(Def->getLocation(), diag::note_previous_definition);
648     Invalid = true;
649   }
650 
651   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
652   // argument expression, that declaration shall be a definition and shall be
653   // the only declaration of the function or function template in the
654   // translation unit.
655   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
656       functionDeclHasDefaultArgument(Old)) {
657     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
658     Diag(Old->getLocation(), diag::note_previous_declaration);
659     Invalid = true;
660   }
661 
662   if (CheckEquivalentExceptionSpec(Old, New))
663     Invalid = true;
664 
665   return Invalid;
666 }
667 
668 NamedDecl *
669 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
670                                    MultiTemplateParamsArg TemplateParamLists) {
671   assert(D.isDecompositionDeclarator());
672   const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
673 
674   // The syntax only allows a decomposition declarator as a simple-declaration
675   // or a for-range-declaration, but we parse it in more cases than that.
676   if (!D.mayHaveDecompositionDeclarator()) {
677     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
678       << Decomp.getSourceRange();
679     return nullptr;
680   }
681 
682   if (!TemplateParamLists.empty()) {
683     // FIXME: There's no rule against this, but there are also no rules that
684     // would actually make it usable, so we reject it for now.
685     Diag(TemplateParamLists.front()->getTemplateLoc(),
686          diag::err_decomp_decl_template);
687     return nullptr;
688   }
689 
690   Diag(Decomp.getLSquareLoc(), getLangOpts().CPlusPlus1z
691                                    ? diag::warn_cxx14_compat_decomp_decl
692                                    : diag::ext_decomp_decl)
693       << Decomp.getSourceRange();
694 
695   // The semantic context is always just the current context.
696   DeclContext *const DC = CurContext;
697 
698   // C++1z [dcl.dcl]/8:
699   //   The decl-specifier-seq shall contain only the type-specifier auto
700   //   and cv-qualifiers.
701   auto &DS = D.getDeclSpec();
702   {
703     SmallVector<StringRef, 8> BadSpecifiers;
704     SmallVector<SourceLocation, 8> BadSpecifierLocs;
705     if (auto SCS = DS.getStorageClassSpec()) {
706       BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
707       BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
708     }
709     if (auto TSCS = DS.getThreadStorageClassSpec()) {
710       BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS));
711       BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
712     }
713     if (DS.isConstexprSpecified()) {
714       BadSpecifiers.push_back("constexpr");
715       BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
716     }
717     if (DS.isInlineSpecified()) {
718       BadSpecifiers.push_back("inline");
719       BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
720     }
721     if (!BadSpecifiers.empty()) {
722       auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
723       Err << (int)BadSpecifiers.size()
724           << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
725       // Don't add FixItHints to remove the specifiers; we do still respect
726       // them when building the underlying variable.
727       for (auto Loc : BadSpecifierLocs)
728         Err << SourceRange(Loc, Loc);
729     }
730     // We can't recover from it being declared as a typedef.
731     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
732       return nullptr;
733   }
734 
735   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
736   QualType R = TInfo->getType();
737 
738   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
739                                       UPPC_DeclarationType))
740     D.setInvalidType();
741 
742   // The syntax only allows a single ref-qualifier prior to the decomposition
743   // declarator. No other declarator chunks are permitted. Also check the type
744   // specifier here.
745   if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
746       D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
747       (D.getNumTypeObjects() == 1 &&
748        D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
749     Diag(Decomp.getLSquareLoc(),
750          (D.hasGroupingParens() ||
751           (D.getNumTypeObjects() &&
752            D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
753              ? diag::err_decomp_decl_parens
754              : diag::err_decomp_decl_type)
755         << R;
756 
757     // In most cases, there's no actual problem with an explicitly-specified
758     // type, but a function type won't work here, and ActOnVariableDeclarator
759     // shouldn't be called for such a type.
760     if (R->isFunctionType())
761       D.setInvalidType();
762   }
763 
764   // Build the BindingDecls.
765   SmallVector<BindingDecl*, 8> Bindings;
766 
767   // Build the BindingDecls.
768   for (auto &B : D.getDecompositionDeclarator().bindings()) {
769     // Check for name conflicts.
770     DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
771     LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
772                           ForRedeclaration);
773     LookupName(Previous, S,
774                /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
775 
776     // It's not permitted to shadow a template parameter name.
777     if (Previous.isSingleResult() &&
778         Previous.getFoundDecl()->isTemplateParameter()) {
779       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
780                                       Previous.getFoundDecl());
781       Previous.clear();
782     }
783 
784     bool ConsiderLinkage = DC->isFunctionOrMethod() &&
785                            DS.getStorageClassSpec() == DeclSpec::SCS_extern;
786     FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
787                          /*AllowInlineNamespace*/false);
788     if (!Previous.empty()) {
789       auto *Old = Previous.getRepresentativeDecl();
790       Diag(B.NameLoc, diag::err_redefinition) << B.Name;
791       Diag(Old->getLocation(), diag::note_previous_definition);
792     }
793 
794     auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
795     PushOnScopeChains(BD, S, true);
796     Bindings.push_back(BD);
797     ParsingInitForAutoVars.insert(BD);
798   }
799 
800   // There are no prior lookup results for the variable itself, because it
801   // is unnamed.
802   DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
803                                Decomp.getLSquareLoc());
804   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
805 
806   // Build the variable that holds the non-decomposed object.
807   bool AddToScope = true;
808   NamedDecl *New =
809       ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
810                               MultiTemplateParamsArg(), AddToScope, Bindings);
811   CurContext->addHiddenDecl(New);
812 
813   if (isInOpenMPDeclareTargetContext())
814     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
815 
816   return New;
817 }
818 
819 static bool checkSimpleDecomposition(
820     Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
821     QualType DecompType, llvm::APSInt NumElems, QualType ElemType,
822     llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
823   if ((int64_t)Bindings.size() != NumElems) {
824     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
825         << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
826         << (NumElems < Bindings.size());
827     return true;
828   }
829 
830   unsigned I = 0;
831   for (auto *B : Bindings) {
832     SourceLocation Loc = B->getLocation();
833     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
834     if (E.isInvalid())
835       return true;
836     E = GetInit(Loc, E.get(), I++);
837     if (E.isInvalid())
838       return true;
839     B->setBinding(ElemType, E.get());
840   }
841 
842   return false;
843 }
844 
845 static bool checkArrayLikeDecomposition(Sema &S,
846                                         ArrayRef<BindingDecl *> Bindings,
847                                         ValueDecl *Src, QualType DecompType,
848                                         llvm::APSInt NumElems,
849                                         QualType ElemType) {
850   return checkSimpleDecomposition(
851       S, Bindings, Src, DecompType, NumElems, ElemType,
852       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
853         ExprResult E = S.ActOnIntegerConstant(Loc, I);
854         if (E.isInvalid())
855           return ExprError();
856         return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
857       });
858 }
859 
860 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
861                                     ValueDecl *Src, QualType DecompType,
862                                     const ConstantArrayType *CAT) {
863   return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
864                                      llvm::APSInt(CAT->getSize()),
865                                      CAT->getElementType());
866 }
867 
868 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
869                                      ValueDecl *Src, QualType DecompType,
870                                      const VectorType *VT) {
871   return checkArrayLikeDecomposition(
872       S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
873       S.Context.getQualifiedType(VT->getElementType(),
874                                  DecompType.getQualifiers()));
875 }
876 
877 static bool checkComplexDecomposition(Sema &S,
878                                       ArrayRef<BindingDecl *> Bindings,
879                                       ValueDecl *Src, QualType DecompType,
880                                       const ComplexType *CT) {
881   return checkSimpleDecomposition(
882       S, Bindings, Src, DecompType, llvm::APSInt::get(2),
883       S.Context.getQualifiedType(CT->getElementType(),
884                                  DecompType.getQualifiers()),
885       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
886         return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
887       });
888 }
889 
890 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
891                                      TemplateArgumentListInfo &Args) {
892   SmallString<128> SS;
893   llvm::raw_svector_ostream OS(SS);
894   bool First = true;
895   for (auto &Arg : Args.arguments()) {
896     if (!First)
897       OS << ", ";
898     Arg.getArgument().print(PrintingPolicy, OS);
899     First = false;
900   }
901   return OS.str();
902 }
903 
904 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
905                                      SourceLocation Loc, StringRef Trait,
906                                      TemplateArgumentListInfo &Args,
907                                      unsigned DiagID) {
908   auto DiagnoseMissing = [&] {
909     if (DiagID)
910       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
911                                                Args);
912     return true;
913   };
914 
915   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
916   NamespaceDecl *Std = S.getStdNamespace();
917   if (!Std)
918     return DiagnoseMissing();
919 
920   // Look up the trait itself, within namespace std. We can diagnose various
921   // problems with this lookup even if we've been asked to not diagnose a
922   // missing specialization, because this can only fail if the user has been
923   // declaring their own names in namespace std or we don't support the
924   // standard library implementation in use.
925   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
926                       Loc, Sema::LookupOrdinaryName);
927   if (!S.LookupQualifiedName(Result, Std))
928     return DiagnoseMissing();
929   if (Result.isAmbiguous())
930     return true;
931 
932   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
933   if (!TraitTD) {
934     Result.suppressDiagnostics();
935     NamedDecl *Found = *Result.begin();
936     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
937     S.Diag(Found->getLocation(), diag::note_declared_at);
938     return true;
939   }
940 
941   // Build the template-id.
942   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
943   if (TraitTy.isNull())
944     return true;
945   if (!S.isCompleteType(Loc, TraitTy)) {
946     if (DiagID)
947       S.RequireCompleteType(
948           Loc, TraitTy, DiagID,
949           printTemplateArgs(S.Context.getPrintingPolicy(), Args));
950     return true;
951   }
952 
953   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
954   assert(RD && "specialization of class template is not a class?");
955 
956   // Look up the member of the trait type.
957   S.LookupQualifiedName(TraitMemberLookup, RD);
958   return TraitMemberLookup.isAmbiguous();
959 }
960 
961 static TemplateArgumentLoc
962 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
963                                    uint64_t I) {
964   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
965   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
966 }
967 
968 static TemplateArgumentLoc
969 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
970   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
971 }
972 
973 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
974 
975 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
976                                llvm::APSInt &Size) {
977   EnterExpressionEvaluationContext ContextRAII(S, Sema::ConstantEvaluated);
978 
979   DeclarationName Value = S.PP.getIdentifierInfo("value");
980   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
981 
982   // Form template argument list for tuple_size<T>.
983   TemplateArgumentListInfo Args(Loc, Loc);
984   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
985 
986   // If there's no tuple_size specialization, it's not tuple-like.
987   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0))
988     return IsTupleLike::NotTupleLike;
989 
990   // FIXME: According to the standard, we're not supposed to diagnose if any
991   // of the steps below fail (or if lookup for ::value is ambiguous or otherwise
992   // results in an error), but this is subject to a pending CWG issue / NB
993   // comment, which says we do diagnose if tuple_size<T> is complete but
994   // tuple_size<T>::value is not an ICE.
995 
996   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
997     LookupResult &R;
998     TemplateArgumentListInfo &Args;
999     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1000         : R(R), Args(Args) {}
1001     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1002       S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1003           << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1004     }
1005   } Diagnoser(R, Args);
1006 
1007   if (R.empty()) {
1008     Diagnoser.diagnoseNotICE(S, Loc, SourceRange());
1009     return IsTupleLike::Error;
1010   }
1011 
1012   ExprResult E =
1013       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1014   if (E.isInvalid())
1015     return IsTupleLike::Error;
1016 
1017   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1018   if (E.isInvalid())
1019     return IsTupleLike::Error;
1020 
1021   return IsTupleLike::TupleLike;
1022 }
1023 
1024 /// \return std::tuple_element<I, T>::type.
1025 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1026                                         unsigned I, QualType T) {
1027   // Form template argument list for tuple_element<I, T>.
1028   TemplateArgumentListInfo Args(Loc, Loc);
1029   Args.addArgument(
1030       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1031   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1032 
1033   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1034   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1035   if (lookupStdTypeTraitMember(
1036           S, R, Loc, "tuple_element", Args,
1037           diag::err_decomp_decl_std_tuple_element_not_specialized))
1038     return QualType();
1039 
1040   auto *TD = R.getAsSingle<TypeDecl>();
1041   if (!TD) {
1042     R.suppressDiagnostics();
1043     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1044       << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1045     if (!R.empty())
1046       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1047     return QualType();
1048   }
1049 
1050   return S.Context.getTypeDeclType(TD);
1051 }
1052 
1053 namespace {
1054 struct BindingDiagnosticTrap {
1055   Sema &S;
1056   DiagnosticErrorTrap Trap;
1057   BindingDecl *BD;
1058 
1059   BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1060       : S(S), Trap(S.Diags), BD(BD) {}
1061   ~BindingDiagnosticTrap() {
1062     if (Trap.hasErrorOccurred())
1063       S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1064   }
1065 };
1066 }
1067 
1068 static bool checkTupleLikeDecomposition(Sema &S,
1069                                         ArrayRef<BindingDecl *> Bindings,
1070                                         ValueDecl *Src, QualType DecompType,
1071                                         llvm::APSInt TupleSize) {
1072   if ((int64_t)Bindings.size() != TupleSize) {
1073     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1074         << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1075         << (TupleSize < Bindings.size());
1076     return true;
1077   }
1078 
1079   if (Bindings.empty())
1080     return false;
1081 
1082   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1083 
1084   // [dcl.decomp]p3:
1085   //   The unqualified-id get is looked up in the scope of E by class member
1086   //   access lookup
1087   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1088   bool UseMemberGet = false;
1089   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1090     if (auto *RD = DecompType->getAsCXXRecordDecl())
1091       S.LookupQualifiedName(MemberGet, RD);
1092     if (MemberGet.isAmbiguous())
1093       return true;
1094     UseMemberGet = !MemberGet.empty();
1095     S.FilterAcceptableTemplateNames(MemberGet);
1096   }
1097 
1098   unsigned I = 0;
1099   for (auto *B : Bindings) {
1100     BindingDiagnosticTrap Trap(S, B);
1101     SourceLocation Loc = B->getLocation();
1102 
1103     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1104     if (E.isInvalid())
1105       return true;
1106 
1107     //   e is an lvalue if the type of the entity is an lvalue reference and
1108     //   an xvalue otherwise
1109     if (!Src->getType()->isLValueReferenceType())
1110       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1111                                    E.get(), nullptr, VK_XValue);
1112 
1113     TemplateArgumentListInfo Args(Loc, Loc);
1114     Args.addArgument(
1115         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1116 
1117     if (UseMemberGet) {
1118       //   if [lookup of member get] finds at least one declaration, the
1119       //   initializer is e.get<i-1>().
1120       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1121                                      CXXScopeSpec(), SourceLocation(), nullptr,
1122                                      MemberGet, &Args, nullptr);
1123       if (E.isInvalid())
1124         return true;
1125 
1126       E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc);
1127     } else {
1128       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1129       //   in the associated namespaces.
1130       Expr *Get = UnresolvedLookupExpr::Create(
1131           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1132           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1133           UnresolvedSetIterator(), UnresolvedSetIterator());
1134 
1135       Expr *Arg = E.get();
1136       E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc);
1137     }
1138     if (E.isInvalid())
1139       return true;
1140     Expr *Init = E.get();
1141 
1142     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1143     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1144     if (T.isNull())
1145       return true;
1146 
1147     //   each vi is a variable of type "reference to T" initialized with the
1148     //   initializer, where the reference is an lvalue reference if the
1149     //   initializer is an lvalue and an rvalue reference otherwise
1150     QualType RefType =
1151         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1152     if (RefType.isNull())
1153       return true;
1154 
1155     InitializedEntity Entity = InitializedEntity::InitializeBinding(B, RefType);
1156     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1157     InitializationSequence Seq(S, Entity, Kind, Init);
1158     E = Seq.Perform(S, Entity, Kind, Init);
1159     if (E.isInvalid())
1160       return true;
1161 
1162     B->setBinding(T, E.get());
1163     I++;
1164   }
1165 
1166   return false;
1167 }
1168 
1169 /// Find the base class to decompose in a built-in decomposition of a class type.
1170 /// This base class search is, unfortunately, not quite like any other that we
1171 /// perform anywhere else in C++.
1172 static const CXXRecordDecl *findDecomposableBaseClass(Sema &S,
1173                                                       SourceLocation Loc,
1174                                                       const CXXRecordDecl *RD,
1175                                                       CXXCastPath &BasePath) {
1176   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1177                           CXXBasePath &Path) {
1178     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1179   };
1180 
1181   const CXXRecordDecl *ClassWithFields = nullptr;
1182   if (RD->hasDirectFields())
1183     // [dcl.decomp]p4:
1184     //   Otherwise, all of E's non-static data members shall be public direct
1185     //   members of E ...
1186     ClassWithFields = RD;
1187   else {
1188     //   ... or of ...
1189     CXXBasePaths Paths;
1190     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1191     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1192       // If no classes have fields, just decompose RD itself. (This will work
1193       // if and only if zero bindings were provided.)
1194       return RD;
1195     }
1196 
1197     CXXBasePath *BestPath = nullptr;
1198     for (auto &P : Paths) {
1199       if (!BestPath)
1200         BestPath = &P;
1201       else if (!S.Context.hasSameType(P.back().Base->getType(),
1202                                       BestPath->back().Base->getType())) {
1203         //   ... the same ...
1204         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1205           << false << RD << BestPath->back().Base->getType()
1206           << P.back().Base->getType();
1207         return nullptr;
1208       } else if (P.Access < BestPath->Access) {
1209         BestPath = &P;
1210       }
1211     }
1212 
1213     //   ... unambiguous ...
1214     QualType BaseType = BestPath->back().Base->getType();
1215     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1216       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1217         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1218       return nullptr;
1219     }
1220 
1221     //   ... public base class of E.
1222     if (BestPath->Access != AS_public) {
1223       S.Diag(Loc, diag::err_decomp_decl_non_public_base)
1224         << RD << BaseType;
1225       for (auto &BS : *BestPath) {
1226         if (BS.Base->getAccessSpecifier() != AS_public) {
1227           S.Diag(BS.Base->getLocStart(), diag::note_access_constrained_by_path)
1228             << (BS.Base->getAccessSpecifier() == AS_protected)
1229             << (BS.Base->getAccessSpecifierAsWritten() == AS_none);
1230           break;
1231         }
1232       }
1233       return nullptr;
1234     }
1235 
1236     ClassWithFields = BaseType->getAsCXXRecordDecl();
1237     S.BuildBasePathArray(Paths, BasePath);
1238   }
1239 
1240   // The above search did not check whether the selected class itself has base
1241   // classes with fields, so check that now.
1242   CXXBasePaths Paths;
1243   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1244     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1245       << (ClassWithFields == RD) << RD << ClassWithFields
1246       << Paths.front().back().Base->getType();
1247     return nullptr;
1248   }
1249 
1250   return ClassWithFields;
1251 }
1252 
1253 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1254                                      ValueDecl *Src, QualType DecompType,
1255                                      const CXXRecordDecl *RD) {
1256   CXXCastPath BasePath;
1257   RD = findDecomposableBaseClass(S, Src->getLocation(), RD, BasePath);
1258   if (!RD)
1259     return true;
1260   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1261                                                  DecompType.getQualifiers());
1262 
1263   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1264     unsigned NumFields = std::distance(RD->field_begin(), RD->field_end());
1265     assert(Bindings.size() != NumFields);
1266     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1267         << DecompType << (unsigned)Bindings.size() << NumFields
1268         << (NumFields < Bindings.size());
1269     return true;
1270   };
1271 
1272   //   all of E's non-static data members shall be public [...] members,
1273   //   E shall not have an anonymous union member, ...
1274   unsigned I = 0;
1275   for (auto *FD : RD->fields()) {
1276     if (FD->isUnnamedBitfield())
1277       continue;
1278 
1279     if (FD->isAnonymousStructOrUnion()) {
1280       S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1281         << DecompType << FD->getType()->isUnionType();
1282       S.Diag(FD->getLocation(), diag::note_declared_at);
1283       return true;
1284     }
1285 
1286     // We have a real field to bind.
1287     if (I >= Bindings.size())
1288       return DiagnoseBadNumberOfBindings();
1289     auto *B = Bindings[I++];
1290 
1291     SourceLocation Loc = B->getLocation();
1292     if (FD->getAccess() != AS_public) {
1293       S.Diag(Loc, diag::err_decomp_decl_non_public_member) << FD << DecompType;
1294 
1295       // Determine whether the access specifier was explicit.
1296       bool Implicit = true;
1297       for (const auto *D : RD->decls()) {
1298         if (declaresSameEntity(D, FD))
1299           break;
1300         if (isa<AccessSpecDecl>(D)) {
1301           Implicit = false;
1302           break;
1303         }
1304       }
1305 
1306       S.Diag(FD->getLocation(), diag::note_access_natural)
1307         << (FD->getAccess() == AS_protected) << Implicit;
1308       return true;
1309     }
1310 
1311     // Initialize the binding to Src.FD.
1312     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1313     if (E.isInvalid())
1314       return true;
1315     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1316                             VK_LValue, &BasePath);
1317     if (E.isInvalid())
1318       return true;
1319     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1320                                   CXXScopeSpec(), FD,
1321                                   DeclAccessPair::make(FD, FD->getAccess()),
1322                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1323     if (E.isInvalid())
1324       return true;
1325 
1326     // If the type of the member is T, the referenced type is cv T, where cv is
1327     // the cv-qualification of the decomposition expression.
1328     //
1329     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1330     // 'const' to the type of the field.
1331     Qualifiers Q = DecompType.getQualifiers();
1332     if (FD->isMutable())
1333       Q.removeConst();
1334     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1335   }
1336 
1337   if (I != Bindings.size())
1338     return DiagnoseBadNumberOfBindings();
1339 
1340   return false;
1341 }
1342 
1343 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1344   QualType DecompType = DD->getType();
1345 
1346   // If the type of the decomposition is dependent, then so is the type of
1347   // each binding.
1348   if (DecompType->isDependentType()) {
1349     for (auto *B : DD->bindings())
1350       B->setType(Context.DependentTy);
1351     return;
1352   }
1353 
1354   DecompType = DecompType.getNonReferenceType();
1355   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1356 
1357   // C++1z [dcl.decomp]/2:
1358   //   If E is an array type [...]
1359   // As an extension, we also support decomposition of built-in complex and
1360   // vector types.
1361   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1362     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1363       DD->setInvalidDecl();
1364     return;
1365   }
1366   if (auto *VT = DecompType->getAs<VectorType>()) {
1367     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1368       DD->setInvalidDecl();
1369     return;
1370   }
1371   if (auto *CT = DecompType->getAs<ComplexType>()) {
1372     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1373       DD->setInvalidDecl();
1374     return;
1375   }
1376 
1377   // C++1z [dcl.decomp]/3:
1378   //   if the expression std::tuple_size<E>::value is a well-formed integral
1379   //   constant expression, [...]
1380   llvm::APSInt TupleSize(32);
1381   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1382   case IsTupleLike::Error:
1383     DD->setInvalidDecl();
1384     return;
1385 
1386   case IsTupleLike::TupleLike:
1387     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1388       DD->setInvalidDecl();
1389     return;
1390 
1391   case IsTupleLike::NotTupleLike:
1392     break;
1393   }
1394 
1395   // C++1z [dcl.dcl]/8:
1396   //   [E shall be of array or non-union class type]
1397   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1398   if (!RD || RD->isUnion()) {
1399     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1400         << DD << !RD << DecompType;
1401     DD->setInvalidDecl();
1402     return;
1403   }
1404 
1405   // C++1z [dcl.decomp]/4:
1406   //   all of E's non-static data members shall be [...] direct members of
1407   //   E or of the same unambiguous public base class of E, ...
1408   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1409     DD->setInvalidDecl();
1410 }
1411 
1412 /// \brief Merge the exception specifications of two variable declarations.
1413 ///
1414 /// This is called when there's a redeclaration of a VarDecl. The function
1415 /// checks if the redeclaration might have an exception specification and
1416 /// validates compatibility and merges the specs if necessary.
1417 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1418   // Shortcut if exceptions are disabled.
1419   if (!getLangOpts().CXXExceptions)
1420     return;
1421 
1422   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1423          "Should only be called if types are otherwise the same.");
1424 
1425   QualType NewType = New->getType();
1426   QualType OldType = Old->getType();
1427 
1428   // We're only interested in pointers and references to functions, as well
1429   // as pointers to member functions.
1430   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1431     NewType = R->getPointeeType();
1432     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1433   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1434     NewType = P->getPointeeType();
1435     OldType = OldType->getAs<PointerType>()->getPointeeType();
1436   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1437     NewType = M->getPointeeType();
1438     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1439   }
1440 
1441   if (!NewType->isFunctionProtoType())
1442     return;
1443 
1444   // There's lots of special cases for functions. For function pointers, system
1445   // libraries are hopefully not as broken so that we don't need these
1446   // workarounds.
1447   if (CheckEquivalentExceptionSpec(
1448         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1449         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1450     New->setInvalidDecl();
1451   }
1452 }
1453 
1454 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1455 /// function declaration are well-formed according to C++
1456 /// [dcl.fct.default].
1457 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1458   unsigned NumParams = FD->getNumParams();
1459   unsigned p;
1460 
1461   // Find first parameter with a default argument
1462   for (p = 0; p < NumParams; ++p) {
1463     ParmVarDecl *Param = FD->getParamDecl(p);
1464     if (Param->hasDefaultArg())
1465       break;
1466   }
1467 
1468   // C++11 [dcl.fct.default]p4:
1469   //   In a given function declaration, each parameter subsequent to a parameter
1470   //   with a default argument shall have a default argument supplied in this or
1471   //   a previous declaration or shall be a function parameter pack. A default
1472   //   argument shall not be redefined by a later declaration (not even to the
1473   //   same value).
1474   unsigned LastMissingDefaultArg = 0;
1475   for (; p < NumParams; ++p) {
1476     ParmVarDecl *Param = FD->getParamDecl(p);
1477     if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
1478       if (Param->isInvalidDecl())
1479         /* We already complained about this parameter. */;
1480       else if (Param->getIdentifier())
1481         Diag(Param->getLocation(),
1482              diag::err_param_default_argument_missing_name)
1483           << Param->getIdentifier();
1484       else
1485         Diag(Param->getLocation(),
1486              diag::err_param_default_argument_missing);
1487 
1488       LastMissingDefaultArg = p;
1489     }
1490   }
1491 
1492   if (LastMissingDefaultArg > 0) {
1493     // Some default arguments were missing. Clear out all of the
1494     // default arguments up to (and including) the last missing
1495     // default argument, so that we leave the function parameters
1496     // in a semantically valid state.
1497     for (p = 0; p <= LastMissingDefaultArg; ++p) {
1498       ParmVarDecl *Param = FD->getParamDecl(p);
1499       if (Param->hasDefaultArg()) {
1500         Param->setDefaultArg(nullptr);
1501       }
1502     }
1503   }
1504 }
1505 
1506 // CheckConstexprParameterTypes - Check whether a function's parameter types
1507 // are all literal types. If so, return true. If not, produce a suitable
1508 // diagnostic and return false.
1509 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1510                                          const FunctionDecl *FD) {
1511   unsigned ArgIndex = 0;
1512   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
1513   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1514                                               e = FT->param_type_end();
1515        i != e; ++i, ++ArgIndex) {
1516     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1517     SourceLocation ParamLoc = PD->getLocation();
1518     if (!(*i)->isDependentType() &&
1519         SemaRef.RequireLiteralType(ParamLoc, *i,
1520                                    diag::err_constexpr_non_literal_param,
1521                                    ArgIndex+1, PD->getSourceRange(),
1522                                    isa<CXXConstructorDecl>(FD)))
1523       return false;
1524   }
1525   return true;
1526 }
1527 
1528 /// \brief Get diagnostic %select index for tag kind for
1529 /// record diagnostic message.
1530 /// WARNING: Indexes apply to particular diagnostics only!
1531 ///
1532 /// \returns diagnostic %select index.
1533 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1534   switch (Tag) {
1535   case TTK_Struct: return 0;
1536   case TTK_Interface: return 1;
1537   case TTK_Class:  return 2;
1538   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1539   }
1540 }
1541 
1542 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
1543 // the requirements of a constexpr function definition or a constexpr
1544 // constructor definition. If so, return true. If not, produce appropriate
1545 // diagnostics and return false.
1546 //
1547 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1548 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
1549   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1550   if (MD && MD->isInstance()) {
1551     // C++11 [dcl.constexpr]p4:
1552     //  The definition of a constexpr constructor shall satisfy the following
1553     //  constraints:
1554     //  - the class shall not have any virtual base classes;
1555     const CXXRecordDecl *RD = MD->getParent();
1556     if (RD->getNumVBases()) {
1557       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1558         << isa<CXXConstructorDecl>(NewFD)
1559         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1560       for (const auto &I : RD->vbases())
1561         Diag(I.getLocStart(),
1562              diag::note_constexpr_virtual_base_here) << I.getSourceRange();
1563       return false;
1564     }
1565   }
1566 
1567   if (!isa<CXXConstructorDecl>(NewFD)) {
1568     // C++11 [dcl.constexpr]p3:
1569     //  The definition of a constexpr function shall satisfy the following
1570     //  constraints:
1571     // - it shall not be virtual;
1572     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1573     if (Method && Method->isVirtual()) {
1574       Method = Method->getCanonicalDecl();
1575       Diag(Method->getLocation(), diag::err_constexpr_virtual);
1576 
1577       // If it's not obvious why this function is virtual, find an overridden
1578       // function which uses the 'virtual' keyword.
1579       const CXXMethodDecl *WrittenVirtual = Method;
1580       while (!WrittenVirtual->isVirtualAsWritten())
1581         WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1582       if (WrittenVirtual != Method)
1583         Diag(WrittenVirtual->getLocation(),
1584              diag::note_overridden_virtual_function);
1585       return false;
1586     }
1587 
1588     // - its return type shall be a literal type;
1589     QualType RT = NewFD->getReturnType();
1590     if (!RT->isDependentType() &&
1591         RequireLiteralType(NewFD->getLocation(), RT,
1592                            diag::err_constexpr_non_literal_return))
1593       return false;
1594   }
1595 
1596   // - each of its parameter types shall be a literal type;
1597   if (!CheckConstexprParameterTypes(*this, NewFD))
1598     return false;
1599 
1600   return true;
1601 }
1602 
1603 /// Check the given declaration statement is legal within a constexpr function
1604 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1605 ///
1606 /// \return true if the body is OK (maybe only as an extension), false if we
1607 ///         have diagnosed a problem.
1608 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1609                                    DeclStmt *DS, SourceLocation &Cxx1yLoc) {
1610   // C++11 [dcl.constexpr]p3 and p4:
1611   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1612   //  contain only
1613   for (const auto *DclIt : DS->decls()) {
1614     switch (DclIt->getKind()) {
1615     case Decl::StaticAssert:
1616     case Decl::Using:
1617     case Decl::UsingShadow:
1618     case Decl::UsingDirective:
1619     case Decl::UnresolvedUsingTypename:
1620     case Decl::UnresolvedUsingValue:
1621       //   - static_assert-declarations
1622       //   - using-declarations,
1623       //   - using-directives,
1624       continue;
1625 
1626     case Decl::Typedef:
1627     case Decl::TypeAlias: {
1628       //   - typedef declarations and alias-declarations that do not define
1629       //     classes or enumerations,
1630       const auto *TN = cast<TypedefNameDecl>(DclIt);
1631       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1632         // Don't allow variably-modified types in constexpr functions.
1633         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1634         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1635           << TL.getSourceRange() << TL.getType()
1636           << isa<CXXConstructorDecl>(Dcl);
1637         return false;
1638       }
1639       continue;
1640     }
1641 
1642     case Decl::Enum:
1643     case Decl::CXXRecord:
1644       // C++1y allows types to be defined, not just declared.
1645       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
1646         SemaRef.Diag(DS->getLocStart(),
1647                      SemaRef.getLangOpts().CPlusPlus14
1648                        ? diag::warn_cxx11_compat_constexpr_type_definition
1649                        : diag::ext_constexpr_type_definition)
1650           << isa<CXXConstructorDecl>(Dcl);
1651       continue;
1652 
1653     case Decl::EnumConstant:
1654     case Decl::IndirectField:
1655     case Decl::ParmVar:
1656       // These can only appear with other declarations which are banned in
1657       // C++11 and permitted in C++1y, so ignore them.
1658       continue;
1659 
1660     case Decl::Var:
1661     case Decl::Decomposition: {
1662       // C++1y [dcl.constexpr]p3 allows anything except:
1663       //   a definition of a variable of non-literal type or of static or
1664       //   thread storage duration or for which no initialization is performed.
1665       const auto *VD = cast<VarDecl>(DclIt);
1666       if (VD->isThisDeclarationADefinition()) {
1667         if (VD->isStaticLocal()) {
1668           SemaRef.Diag(VD->getLocation(),
1669                        diag::err_constexpr_local_var_static)
1670             << isa<CXXConstructorDecl>(Dcl)
1671             << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1672           return false;
1673         }
1674         if (!VD->getType()->isDependentType() &&
1675             SemaRef.RequireLiteralType(
1676               VD->getLocation(), VD->getType(),
1677               diag::err_constexpr_local_var_non_literal_type,
1678               isa<CXXConstructorDecl>(Dcl)))
1679           return false;
1680         if (!VD->getType()->isDependentType() &&
1681             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1682           SemaRef.Diag(VD->getLocation(),
1683                        diag::err_constexpr_local_var_no_init)
1684             << isa<CXXConstructorDecl>(Dcl);
1685           return false;
1686         }
1687       }
1688       SemaRef.Diag(VD->getLocation(),
1689                    SemaRef.getLangOpts().CPlusPlus14
1690                     ? diag::warn_cxx11_compat_constexpr_local_var
1691                     : diag::ext_constexpr_local_var)
1692         << isa<CXXConstructorDecl>(Dcl);
1693       continue;
1694     }
1695 
1696     case Decl::NamespaceAlias:
1697     case Decl::Function:
1698       // These are disallowed in C++11 and permitted in C++1y. Allow them
1699       // everywhere as an extension.
1700       if (!Cxx1yLoc.isValid())
1701         Cxx1yLoc = DS->getLocStart();
1702       continue;
1703 
1704     default:
1705       SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1706         << isa<CXXConstructorDecl>(Dcl);
1707       return false;
1708     }
1709   }
1710 
1711   return true;
1712 }
1713 
1714 /// Check that the given field is initialized within a constexpr constructor.
1715 ///
1716 /// \param Dcl The constexpr constructor being checked.
1717 /// \param Field The field being checked. This may be a member of an anonymous
1718 ///        struct or union nested within the class being checked.
1719 /// \param Inits All declarations, including anonymous struct/union members and
1720 ///        indirect members, for which any initialization was provided.
1721 /// \param Diagnosed Set to true if an error is produced.
1722 static void CheckConstexprCtorInitializer(Sema &SemaRef,
1723                                           const FunctionDecl *Dcl,
1724                                           FieldDecl *Field,
1725                                           llvm::SmallSet<Decl*, 16> &Inits,
1726                                           bool &Diagnosed) {
1727   if (Field->isInvalidDecl())
1728     return;
1729 
1730   if (Field->isUnnamedBitfield())
1731     return;
1732 
1733   // Anonymous unions with no variant members and empty anonymous structs do not
1734   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1735   // indirect fields don't need initializing.
1736   if (Field->isAnonymousStructOrUnion() &&
1737       (Field->getType()->isUnionType()
1738            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1739            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1740     return;
1741 
1742   if (!Inits.count(Field)) {
1743     if (!Diagnosed) {
1744       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1745       Diagnosed = true;
1746     }
1747     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1748   } else if (Field->isAnonymousStructOrUnion()) {
1749     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1750     for (auto *I : RD->fields())
1751       // If an anonymous union contains an anonymous struct of which any member
1752       // is initialized, all members must be initialized.
1753       if (!RD->isUnion() || Inits.count(I))
1754         CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
1755   }
1756 }
1757 
1758 /// Check the provided statement is allowed in a constexpr function
1759 /// definition.
1760 static bool
1761 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1762                            SmallVectorImpl<SourceLocation> &ReturnStmts,
1763                            SourceLocation &Cxx1yLoc) {
1764   // - its function-body shall be [...] a compound-statement that contains only
1765   switch (S->getStmtClass()) {
1766   case Stmt::NullStmtClass:
1767     //   - null statements,
1768     return true;
1769 
1770   case Stmt::DeclStmtClass:
1771     //   - static_assert-declarations
1772     //   - using-declarations,
1773     //   - using-directives,
1774     //   - typedef declarations and alias-declarations that do not define
1775     //     classes or enumerations,
1776     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1777       return false;
1778     return true;
1779 
1780   case Stmt::ReturnStmtClass:
1781     //   - and exactly one return statement;
1782     if (isa<CXXConstructorDecl>(Dcl)) {
1783       // C++1y allows return statements in constexpr constructors.
1784       if (!Cxx1yLoc.isValid())
1785         Cxx1yLoc = S->getLocStart();
1786       return true;
1787     }
1788 
1789     ReturnStmts.push_back(S->getLocStart());
1790     return true;
1791 
1792   case Stmt::CompoundStmtClass: {
1793     // C++1y allows compound-statements.
1794     if (!Cxx1yLoc.isValid())
1795       Cxx1yLoc = S->getLocStart();
1796 
1797     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1798     for (auto *BodyIt : CompStmt->body()) {
1799       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1800                                       Cxx1yLoc))
1801         return false;
1802     }
1803     return true;
1804   }
1805 
1806   case Stmt::AttributedStmtClass:
1807     if (!Cxx1yLoc.isValid())
1808       Cxx1yLoc = S->getLocStart();
1809     return true;
1810 
1811   case Stmt::IfStmtClass: {
1812     // C++1y allows if-statements.
1813     if (!Cxx1yLoc.isValid())
1814       Cxx1yLoc = S->getLocStart();
1815 
1816     IfStmt *If = cast<IfStmt>(S);
1817     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1818                                     Cxx1yLoc))
1819       return false;
1820     if (If->getElse() &&
1821         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1822                                     Cxx1yLoc))
1823       return false;
1824     return true;
1825   }
1826 
1827   case Stmt::WhileStmtClass:
1828   case Stmt::DoStmtClass:
1829   case Stmt::ForStmtClass:
1830   case Stmt::CXXForRangeStmtClass:
1831   case Stmt::ContinueStmtClass:
1832     // C++1y allows all of these. We don't allow them as extensions in C++11,
1833     // because they don't make sense without variable mutation.
1834     if (!SemaRef.getLangOpts().CPlusPlus14)
1835       break;
1836     if (!Cxx1yLoc.isValid())
1837       Cxx1yLoc = S->getLocStart();
1838     for (Stmt *SubStmt : S->children())
1839       if (SubStmt &&
1840           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1841                                       Cxx1yLoc))
1842         return false;
1843     return true;
1844 
1845   case Stmt::SwitchStmtClass:
1846   case Stmt::CaseStmtClass:
1847   case Stmt::DefaultStmtClass:
1848   case Stmt::BreakStmtClass:
1849     // C++1y allows switch-statements, and since they don't need variable
1850     // mutation, we can reasonably allow them in C++11 as an extension.
1851     if (!Cxx1yLoc.isValid())
1852       Cxx1yLoc = S->getLocStart();
1853     for (Stmt *SubStmt : S->children())
1854       if (SubStmt &&
1855           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1856                                       Cxx1yLoc))
1857         return false;
1858     return true;
1859 
1860   default:
1861     if (!isa<Expr>(S))
1862       break;
1863 
1864     // C++1y allows expression-statements.
1865     if (!Cxx1yLoc.isValid())
1866       Cxx1yLoc = S->getLocStart();
1867     return true;
1868   }
1869 
1870   SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1871     << isa<CXXConstructorDecl>(Dcl);
1872   return false;
1873 }
1874 
1875 /// Check the body for the given constexpr function declaration only contains
1876 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1877 ///
1878 /// \return true if the body is OK, false if we have diagnosed a problem.
1879 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1880   if (isa<CXXTryStmt>(Body)) {
1881     // C++11 [dcl.constexpr]p3:
1882     //  The definition of a constexpr function shall satisfy the following
1883     //  constraints: [...]
1884     // - its function-body shall be = delete, = default, or a
1885     //   compound-statement
1886     //
1887     // C++11 [dcl.constexpr]p4:
1888     //  In the definition of a constexpr constructor, [...]
1889     // - its function-body shall not be a function-try-block;
1890     Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1891       << isa<CXXConstructorDecl>(Dcl);
1892     return false;
1893   }
1894 
1895   SmallVector<SourceLocation, 4> ReturnStmts;
1896 
1897   // - its function-body shall be [...] a compound-statement that contains only
1898   //   [... list of cases ...]
1899   CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1900   SourceLocation Cxx1yLoc;
1901   for (auto *BodyIt : CompBody->body()) {
1902     if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
1903       return false;
1904   }
1905 
1906   if (Cxx1yLoc.isValid())
1907     Diag(Cxx1yLoc,
1908          getLangOpts().CPlusPlus14
1909            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1910            : diag::ext_constexpr_body_invalid_stmt)
1911       << isa<CXXConstructorDecl>(Dcl);
1912 
1913   if (const CXXConstructorDecl *Constructor
1914         = dyn_cast<CXXConstructorDecl>(Dcl)) {
1915     const CXXRecordDecl *RD = Constructor->getParent();
1916     // DR1359:
1917     // - every non-variant non-static data member and base class sub-object
1918     //   shall be initialized;
1919     // DR1460:
1920     // - if the class is a union having variant members, exactly one of them
1921     //   shall be initialized;
1922     if (RD->isUnion()) {
1923       if (Constructor->getNumCtorInitializers() == 0 &&
1924           RD->hasVariantMembers()) {
1925         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1926         return false;
1927       }
1928     } else if (!Constructor->isDependentContext() &&
1929                !Constructor->isDelegatingConstructor()) {
1930       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1931 
1932       // Skip detailed checking if we have enough initializers, and we would
1933       // allow at most one initializer per member.
1934       bool AnyAnonStructUnionMembers = false;
1935       unsigned Fields = 0;
1936       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1937            E = RD->field_end(); I != E; ++I, ++Fields) {
1938         if (I->isAnonymousStructOrUnion()) {
1939           AnyAnonStructUnionMembers = true;
1940           break;
1941         }
1942       }
1943       // DR1460:
1944       // - if the class is a union-like class, but is not a union, for each of
1945       //   its anonymous union members having variant members, exactly one of
1946       //   them shall be initialized;
1947       if (AnyAnonStructUnionMembers ||
1948           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1949         // Check initialization of non-static data members. Base classes are
1950         // always initialized so do not need to be checked. Dependent bases
1951         // might not have initializers in the member initializer list.
1952         llvm::SmallSet<Decl*, 16> Inits;
1953         for (const auto *I: Constructor->inits()) {
1954           if (FieldDecl *FD = I->getMember())
1955             Inits.insert(FD);
1956           else if (IndirectFieldDecl *ID = I->getIndirectMember())
1957             Inits.insert(ID->chain_begin(), ID->chain_end());
1958         }
1959 
1960         bool Diagnosed = false;
1961         for (auto *I : RD->fields())
1962           CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
1963         if (Diagnosed)
1964           return false;
1965       }
1966     }
1967   } else {
1968     if (ReturnStmts.empty()) {
1969       // C++1y doesn't require constexpr functions to contain a 'return'
1970       // statement. We still do, unless the return type might be void, because
1971       // otherwise if there's no return statement, the function cannot
1972       // be used in a core constant expression.
1973       bool OK = getLangOpts().CPlusPlus14 &&
1974                 (Dcl->getReturnType()->isVoidType() ||
1975                  Dcl->getReturnType()->isDependentType());
1976       Diag(Dcl->getLocation(),
1977            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1978               : diag::err_constexpr_body_no_return);
1979       if (!OK)
1980         return false;
1981     } else if (ReturnStmts.size() > 1) {
1982       Diag(ReturnStmts.back(),
1983            getLangOpts().CPlusPlus14
1984              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1985              : diag::ext_constexpr_body_multiple_return);
1986       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1987         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
1988     }
1989   }
1990 
1991   // C++11 [dcl.constexpr]p5:
1992   //   if no function argument values exist such that the function invocation
1993   //   substitution would produce a constant expression, the program is
1994   //   ill-formed; no diagnostic required.
1995   // C++11 [dcl.constexpr]p3:
1996   //   - every constructor call and implicit conversion used in initializing the
1997   //     return value shall be one of those allowed in a constant expression.
1998   // C++11 [dcl.constexpr]p4:
1999   //   - every constructor involved in initializing non-static data members and
2000   //     base class sub-objects shall be a constexpr constructor.
2001   SmallVector<PartialDiagnosticAt, 8> Diags;
2002   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
2003     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
2004       << isa<CXXConstructorDecl>(Dcl);
2005     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2006       Diag(Diags[I].first, Diags[I].second);
2007     // Don't return false here: we allow this for compatibility in
2008     // system headers.
2009   }
2010 
2011   return true;
2012 }
2013 
2014 /// isCurrentClassName - Determine whether the identifier II is the
2015 /// name of the class type currently being defined. In the case of
2016 /// nested classes, this will only return true if II is the name of
2017 /// the innermost class.
2018 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
2019                               const CXXScopeSpec *SS) {
2020   assert(getLangOpts().CPlusPlus && "No class names in C!");
2021 
2022   CXXRecordDecl *CurDecl;
2023   if (SS && SS->isSet() && !SS->isInvalid()) {
2024     DeclContext *DC = computeDeclContext(*SS, true);
2025     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2026   } else
2027     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2028 
2029   if (CurDecl && CurDecl->getIdentifier())
2030     return &II == CurDecl->getIdentifier();
2031   return false;
2032 }
2033 
2034 /// \brief Determine whether the identifier II is a typo for the name of
2035 /// the class type currently being defined. If so, update it to the identifier
2036 /// that should have been used.
2037 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2038   assert(getLangOpts().CPlusPlus && "No class names in C!");
2039 
2040   if (!getLangOpts().SpellChecking)
2041     return false;
2042 
2043   CXXRecordDecl *CurDecl;
2044   if (SS && SS->isSet() && !SS->isInvalid()) {
2045     DeclContext *DC = computeDeclContext(*SS, true);
2046     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2047   } else
2048     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2049 
2050   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2051       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2052           < II->getLength()) {
2053     II = CurDecl->getIdentifier();
2054     return true;
2055   }
2056 
2057   return false;
2058 }
2059 
2060 /// \brief Determine whether the given class is a base class of the given
2061 /// class, including looking at dependent bases.
2062 static bool findCircularInheritance(const CXXRecordDecl *Class,
2063                                     const CXXRecordDecl *Current) {
2064   SmallVector<const CXXRecordDecl*, 8> Queue;
2065 
2066   Class = Class->getCanonicalDecl();
2067   while (true) {
2068     for (const auto &I : Current->bases()) {
2069       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2070       if (!Base)
2071         continue;
2072 
2073       Base = Base->getDefinition();
2074       if (!Base)
2075         continue;
2076 
2077       if (Base->getCanonicalDecl() == Class)
2078         return true;
2079 
2080       Queue.push_back(Base);
2081     }
2082 
2083     if (Queue.empty())
2084       return false;
2085 
2086     Current = Queue.pop_back_val();
2087   }
2088 
2089   return false;
2090 }
2091 
2092 /// \brief Check the validity of a C++ base class specifier.
2093 ///
2094 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2095 /// and returns NULL otherwise.
2096 CXXBaseSpecifier *
2097 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2098                          SourceRange SpecifierRange,
2099                          bool Virtual, AccessSpecifier Access,
2100                          TypeSourceInfo *TInfo,
2101                          SourceLocation EllipsisLoc) {
2102   QualType BaseType = TInfo->getType();
2103 
2104   // C++ [class.union]p1:
2105   //   A union shall not have base classes.
2106   if (Class->isUnion()) {
2107     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2108       << SpecifierRange;
2109     return nullptr;
2110   }
2111 
2112   if (EllipsisLoc.isValid() &&
2113       !TInfo->getType()->containsUnexpandedParameterPack()) {
2114     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2115       << TInfo->getTypeLoc().getSourceRange();
2116     EllipsisLoc = SourceLocation();
2117   }
2118 
2119   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2120 
2121   if (BaseType->isDependentType()) {
2122     // Make sure that we don't have circular inheritance among our dependent
2123     // bases. For non-dependent bases, the check for completeness below handles
2124     // this.
2125     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2126       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2127           ((BaseDecl = BaseDecl->getDefinition()) &&
2128            findCircularInheritance(Class, BaseDecl))) {
2129         Diag(BaseLoc, diag::err_circular_inheritance)
2130           << BaseType << Context.getTypeDeclType(Class);
2131 
2132         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2133           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2134             << BaseType;
2135 
2136         return nullptr;
2137       }
2138     }
2139 
2140     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2141                                           Class->getTagKind() == TTK_Class,
2142                                           Access, TInfo, EllipsisLoc);
2143   }
2144 
2145   // Base specifiers must be record types.
2146   if (!BaseType->isRecordType()) {
2147     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2148     return nullptr;
2149   }
2150 
2151   // C++ [class.union]p1:
2152   //   A union shall not be used as a base class.
2153   if (BaseType->isUnionType()) {
2154     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2155     return nullptr;
2156   }
2157 
2158   // For the MS ABI, propagate DLL attributes to base class templates.
2159   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2160     if (Attr *ClassAttr = getDLLAttr(Class)) {
2161       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2162               BaseType->getAsCXXRecordDecl())) {
2163         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2164                                             BaseLoc);
2165       }
2166     }
2167   }
2168 
2169   // C++ [class.derived]p2:
2170   //   The class-name in a base-specifier shall not be an incompletely
2171   //   defined class.
2172   if (RequireCompleteType(BaseLoc, BaseType,
2173                           diag::err_incomplete_base_class, SpecifierRange)) {
2174     Class->setInvalidDecl();
2175     return nullptr;
2176   }
2177 
2178   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2179   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
2180   assert(BaseDecl && "Record type has no declaration");
2181   BaseDecl = BaseDecl->getDefinition();
2182   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2183   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2184   assert(CXXBaseDecl && "Base type is not a C++ type");
2185 
2186   // A class which contains a flexible array member is not suitable for use as a
2187   // base class:
2188   //   - If the layout determines that a base comes before another base,
2189   //     the flexible array member would index into the subsequent base.
2190   //   - If the layout determines that base comes before the derived class,
2191   //     the flexible array member would index into the derived class.
2192   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2193     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2194       << CXXBaseDecl->getDeclName();
2195     return nullptr;
2196   }
2197 
2198   // C++ [class]p3:
2199   //   If a class is marked final and it appears as a base-type-specifier in
2200   //   base-clause, the program is ill-formed.
2201   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2202     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2203       << CXXBaseDecl->getDeclName()
2204       << FA->isSpelledAsSealed();
2205     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2206         << CXXBaseDecl->getDeclName() << FA->getRange();
2207     return nullptr;
2208   }
2209 
2210   if (BaseDecl->isInvalidDecl())
2211     Class->setInvalidDecl();
2212 
2213   // Create the base specifier.
2214   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2215                                         Class->getTagKind() == TTK_Class,
2216                                         Access, TInfo, EllipsisLoc);
2217 }
2218 
2219 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2220 /// one entry in the base class list of a class specifier, for
2221 /// example:
2222 ///    class foo : public bar, virtual private baz {
2223 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2224 BaseResult
2225 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2226                          ParsedAttributes &Attributes,
2227                          bool Virtual, AccessSpecifier Access,
2228                          ParsedType basetype, SourceLocation BaseLoc,
2229                          SourceLocation EllipsisLoc) {
2230   if (!classdecl)
2231     return true;
2232 
2233   AdjustDeclIfTemplate(classdecl);
2234   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2235   if (!Class)
2236     return true;
2237 
2238   // We haven't yet attached the base specifiers.
2239   Class->setIsParsingBaseSpecifiers();
2240 
2241   // We do not support any C++11 attributes on base-specifiers yet.
2242   // Diagnose any attributes we see.
2243   if (!Attributes.empty()) {
2244     for (AttributeList *Attr = Attributes.getList(); Attr;
2245          Attr = Attr->getNext()) {
2246       if (Attr->isInvalid() ||
2247           Attr->getKind() == AttributeList::IgnoredAttribute)
2248         continue;
2249       Diag(Attr->getLoc(),
2250            Attr->getKind() == AttributeList::UnknownAttribute
2251              ? diag::warn_unknown_attribute_ignored
2252              : diag::err_base_specifier_attribute)
2253         << Attr->getName();
2254     }
2255   }
2256 
2257   TypeSourceInfo *TInfo = nullptr;
2258   GetTypeFromParser(basetype, &TInfo);
2259 
2260   if (EllipsisLoc.isInvalid() &&
2261       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2262                                       UPPC_BaseType))
2263     return true;
2264 
2265   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2266                                                       Virtual, Access, TInfo,
2267                                                       EllipsisLoc))
2268     return BaseSpec;
2269   else
2270     Class->setInvalidDecl();
2271 
2272   return true;
2273 }
2274 
2275 /// Use small set to collect indirect bases.  As this is only used
2276 /// locally, there's no need to abstract the small size parameter.
2277 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2278 
2279 /// \brief Recursively add the bases of Type.  Don't add Type itself.
2280 static void
2281 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2282                   const QualType &Type)
2283 {
2284   // Even though the incoming type is a base, it might not be
2285   // a class -- it could be a template parm, for instance.
2286   if (auto Rec = Type->getAs<RecordType>()) {
2287     auto Decl = Rec->getAsCXXRecordDecl();
2288 
2289     // Iterate over its bases.
2290     for (const auto &BaseSpec : Decl->bases()) {
2291       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2292         .getUnqualifiedType();
2293       if (Set.insert(Base).second)
2294         // If we've not already seen it, recurse.
2295         NoteIndirectBases(Context, Set, Base);
2296     }
2297   }
2298 }
2299 
2300 /// \brief Performs the actual work of attaching the given base class
2301 /// specifiers to a C++ class.
2302 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2303                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2304  if (Bases.empty())
2305     return false;
2306 
2307   // Used to keep track of which base types we have already seen, so
2308   // that we can properly diagnose redundant direct base types. Note
2309   // that the key is always the unqualified canonical type of the base
2310   // class.
2311   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2312 
2313   // Used to track indirect bases so we can see if a direct base is
2314   // ambiguous.
2315   IndirectBaseSet IndirectBaseTypes;
2316 
2317   // Copy non-redundant base specifiers into permanent storage.
2318   unsigned NumGoodBases = 0;
2319   bool Invalid = false;
2320   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2321     QualType NewBaseType
2322       = Context.getCanonicalType(Bases[idx]->getType());
2323     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2324 
2325     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2326     if (KnownBase) {
2327       // C++ [class.mi]p3:
2328       //   A class shall not be specified as a direct base class of a
2329       //   derived class more than once.
2330       Diag(Bases[idx]->getLocStart(),
2331            diag::err_duplicate_base_class)
2332         << KnownBase->getType()
2333         << Bases[idx]->getSourceRange();
2334 
2335       // Delete the duplicate base class specifier; we're going to
2336       // overwrite its pointer later.
2337       Context.Deallocate(Bases[idx]);
2338 
2339       Invalid = true;
2340     } else {
2341       // Okay, add this new base class.
2342       KnownBase = Bases[idx];
2343       Bases[NumGoodBases++] = Bases[idx];
2344 
2345       // Note this base's direct & indirect bases, if there could be ambiguity.
2346       if (Bases.size() > 1)
2347         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2348 
2349       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2350         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2351         if (Class->isInterface() &&
2352               (!RD->isInterface() ||
2353                KnownBase->getAccessSpecifier() != AS_public)) {
2354           // The Microsoft extension __interface does not permit bases that
2355           // are not themselves public interfaces.
2356           Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
2357             << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
2358             << RD->getSourceRange();
2359           Invalid = true;
2360         }
2361         if (RD->hasAttr<WeakAttr>())
2362           Class->addAttr(WeakAttr::CreateImplicit(Context));
2363       }
2364     }
2365   }
2366 
2367   // Attach the remaining base class specifiers to the derived class.
2368   Class->setBases(Bases.data(), NumGoodBases);
2369 
2370   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2371     // Check whether this direct base is inaccessible due to ambiguity.
2372     QualType BaseType = Bases[idx]->getType();
2373     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2374       .getUnqualifiedType();
2375 
2376     if (IndirectBaseTypes.count(CanonicalBase)) {
2377       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2378                          /*DetectVirtual=*/true);
2379       bool found
2380         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2381       assert(found);
2382       (void)found;
2383 
2384       if (Paths.isAmbiguous(CanonicalBase))
2385         Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
2386           << BaseType << getAmbiguousPathsDisplayString(Paths)
2387           << Bases[idx]->getSourceRange();
2388       else
2389         assert(Bases[idx]->isVirtual());
2390     }
2391 
2392     // Delete the base class specifier, since its data has been copied
2393     // into the CXXRecordDecl.
2394     Context.Deallocate(Bases[idx]);
2395   }
2396 
2397   return Invalid;
2398 }
2399 
2400 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2401 /// class, after checking whether there are any duplicate base
2402 /// classes.
2403 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2404                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2405   if (!ClassDecl || Bases.empty())
2406     return;
2407 
2408   AdjustDeclIfTemplate(ClassDecl);
2409   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2410 }
2411 
2412 /// \brief Determine whether the type \p Derived is a C++ class that is
2413 /// derived from the type \p Base.
2414 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2415   if (!getLangOpts().CPlusPlus)
2416     return false;
2417 
2418   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2419   if (!DerivedRD)
2420     return false;
2421 
2422   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2423   if (!BaseRD)
2424     return false;
2425 
2426   // If either the base or the derived type is invalid, don't try to
2427   // check whether one is derived from the other.
2428   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2429     return false;
2430 
2431   // FIXME: In a modules build, do we need the entire path to be visible for us
2432   // to be able to use the inheritance relationship?
2433   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2434     return false;
2435 
2436   return DerivedRD->isDerivedFrom(BaseRD);
2437 }
2438 
2439 /// \brief Determine whether the type \p Derived is a C++ class that is
2440 /// derived from the type \p Base.
2441 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2442                          CXXBasePaths &Paths) {
2443   if (!getLangOpts().CPlusPlus)
2444     return false;
2445 
2446   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2447   if (!DerivedRD)
2448     return false;
2449 
2450   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2451   if (!BaseRD)
2452     return false;
2453 
2454   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2455     return false;
2456 
2457   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2458 }
2459 
2460 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2461                               CXXCastPath &BasePathArray) {
2462   assert(BasePathArray.empty() && "Base path array must be empty!");
2463   assert(Paths.isRecordingPaths() && "Must record paths!");
2464 
2465   const CXXBasePath &Path = Paths.front();
2466 
2467   // We first go backward and check if we have a virtual base.
2468   // FIXME: It would be better if CXXBasePath had the base specifier for
2469   // the nearest virtual base.
2470   unsigned Start = 0;
2471   for (unsigned I = Path.size(); I != 0; --I) {
2472     if (Path[I - 1].Base->isVirtual()) {
2473       Start = I - 1;
2474       break;
2475     }
2476   }
2477 
2478   // Now add all bases.
2479   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2480     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2481 }
2482 
2483 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2484 /// conversion (where Derived and Base are class types) is
2485 /// well-formed, meaning that the conversion is unambiguous (and
2486 /// that all of the base classes are accessible). Returns true
2487 /// and emits a diagnostic if the code is ill-formed, returns false
2488 /// otherwise. Loc is the location where this routine should point to
2489 /// if there is an error, and Range is the source range to highlight
2490 /// if there is an error.
2491 ///
2492 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2493 /// diagnostic for the respective type of error will be suppressed, but the
2494 /// check for ill-formed code will still be performed.
2495 bool
2496 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2497                                    unsigned InaccessibleBaseID,
2498                                    unsigned AmbigiousBaseConvID,
2499                                    SourceLocation Loc, SourceRange Range,
2500                                    DeclarationName Name,
2501                                    CXXCastPath *BasePath,
2502                                    bool IgnoreAccess) {
2503   // First, determine whether the path from Derived to Base is
2504   // ambiguous. This is slightly more expensive than checking whether
2505   // the Derived to Base conversion exists, because here we need to
2506   // explore multiple paths to determine if there is an ambiguity.
2507   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2508                      /*DetectVirtual=*/false);
2509   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2510   assert(DerivationOkay &&
2511          "Can only be used with a derived-to-base conversion");
2512   (void)DerivationOkay;
2513 
2514   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
2515     if (!IgnoreAccess) {
2516       // Check that the base class can be accessed.
2517       switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
2518                                    InaccessibleBaseID)) {
2519         case AR_inaccessible:
2520           return true;
2521         case AR_accessible:
2522         case AR_dependent:
2523         case AR_delayed:
2524           break;
2525       }
2526     }
2527 
2528     // Build a base path if necessary.
2529     if (BasePath)
2530       BuildBasePathArray(Paths, *BasePath);
2531     return false;
2532   }
2533 
2534   if (AmbigiousBaseConvID) {
2535     // We know that the derived-to-base conversion is ambiguous, and
2536     // we're going to produce a diagnostic. Perform the derived-to-base
2537     // search just one more time to compute all of the possible paths so
2538     // that we can print them out. This is more expensive than any of
2539     // the previous derived-to-base checks we've done, but at this point
2540     // performance isn't as much of an issue.
2541     Paths.clear();
2542     Paths.setRecordingPaths(true);
2543     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2544     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2545     (void)StillOkay;
2546 
2547     // Build up a textual representation of the ambiguous paths, e.g.,
2548     // D -> B -> A, that will be used to illustrate the ambiguous
2549     // conversions in the diagnostic. We only print one of the paths
2550     // to each base class subobject.
2551     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2552 
2553     Diag(Loc, AmbigiousBaseConvID)
2554     << Derived << Base << PathDisplayStr << Range << Name;
2555   }
2556   return true;
2557 }
2558 
2559 bool
2560 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2561                                    SourceLocation Loc, SourceRange Range,
2562                                    CXXCastPath *BasePath,
2563                                    bool IgnoreAccess) {
2564   return CheckDerivedToBaseConversion(
2565       Derived, Base, diag::err_upcast_to_inaccessible_base,
2566       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2567       BasePath, IgnoreAccess);
2568 }
2569 
2570 
2571 /// @brief Builds a string representing ambiguous paths from a
2572 /// specific derived class to different subobjects of the same base
2573 /// class.
2574 ///
2575 /// This function builds a string that can be used in error messages
2576 /// to show the different paths that one can take through the
2577 /// inheritance hierarchy to go from the derived class to different
2578 /// subobjects of a base class. The result looks something like this:
2579 /// @code
2580 /// struct D -> struct B -> struct A
2581 /// struct D -> struct C -> struct A
2582 /// @endcode
2583 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2584   std::string PathDisplayStr;
2585   std::set<unsigned> DisplayedPaths;
2586   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2587        Path != Paths.end(); ++Path) {
2588     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2589       // We haven't displayed a path to this particular base
2590       // class subobject yet.
2591       PathDisplayStr += "\n    ";
2592       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2593       for (CXXBasePath::const_iterator Element = Path->begin();
2594            Element != Path->end(); ++Element)
2595         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2596     }
2597   }
2598 
2599   return PathDisplayStr;
2600 }
2601 
2602 //===----------------------------------------------------------------------===//
2603 // C++ class member Handling
2604 //===----------------------------------------------------------------------===//
2605 
2606 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2607 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
2608                                 SourceLocation ASLoc,
2609                                 SourceLocation ColonLoc,
2610                                 AttributeList *Attrs) {
2611   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2612   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2613                                                   ASLoc, ColonLoc);
2614   CurContext->addHiddenDecl(ASDecl);
2615   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2616 }
2617 
2618 /// CheckOverrideControl - Check C++11 override control semantics.
2619 void Sema::CheckOverrideControl(NamedDecl *D) {
2620   if (D->isInvalidDecl())
2621     return;
2622 
2623   // We only care about "override" and "final" declarations.
2624   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2625     return;
2626 
2627   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2628 
2629   // We can't check dependent instance methods.
2630   if (MD && MD->isInstance() &&
2631       (MD->getParent()->hasAnyDependentBases() ||
2632        MD->getType()->isDependentType()))
2633     return;
2634 
2635   if (MD && !MD->isVirtual()) {
2636     // If we have a non-virtual method, check if if hides a virtual method.
2637     // (In that case, it's most likely the method has the wrong type.)
2638     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2639     FindHiddenVirtualMethods(MD, OverloadedMethods);
2640 
2641     if (!OverloadedMethods.empty()) {
2642       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2643         Diag(OA->getLocation(),
2644              diag::override_keyword_hides_virtual_member_function)
2645           << "override" << (OverloadedMethods.size() > 1);
2646       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2647         Diag(FA->getLocation(),
2648              diag::override_keyword_hides_virtual_member_function)
2649           << (FA->isSpelledAsSealed() ? "sealed" : "final")
2650           << (OverloadedMethods.size() > 1);
2651       }
2652       NoteHiddenVirtualMethods(MD, OverloadedMethods);
2653       MD->setInvalidDecl();
2654       return;
2655     }
2656     // Fall through into the general case diagnostic.
2657     // FIXME: We might want to attempt typo correction here.
2658   }
2659 
2660   if (!MD || !MD->isVirtual()) {
2661     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2662       Diag(OA->getLocation(),
2663            diag::override_keyword_only_allowed_on_virtual_member_functions)
2664         << "override" << FixItHint::CreateRemoval(OA->getLocation());
2665       D->dropAttr<OverrideAttr>();
2666     }
2667     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2668       Diag(FA->getLocation(),
2669            diag::override_keyword_only_allowed_on_virtual_member_functions)
2670         << (FA->isSpelledAsSealed() ? "sealed" : "final")
2671         << FixItHint::CreateRemoval(FA->getLocation());
2672       D->dropAttr<FinalAttr>();
2673     }
2674     return;
2675   }
2676 
2677   // C++11 [class.virtual]p5:
2678   //   If a function is marked with the virt-specifier override and
2679   //   does not override a member function of a base class, the program is
2680   //   ill-formed.
2681   bool HasOverriddenMethods =
2682     MD->begin_overridden_methods() != MD->end_overridden_methods();
2683   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2684     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2685       << MD->getDeclName();
2686 }
2687 
2688 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2689   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2690     return;
2691   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2692   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
2693       isa<CXXDestructorDecl>(MD))
2694     return;
2695 
2696   SourceLocation Loc = MD->getLocation();
2697   SourceLocation SpellingLoc = Loc;
2698   if (getSourceManager().isMacroArgExpansion(Loc))
2699     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
2700   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2701   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
2702       return;
2703 
2704   if (MD->size_overridden_methods() > 0) {
2705     Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
2706       << MD->getDeclName();
2707     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2708     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2709   }
2710 }
2711 
2712 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
2713 /// function overrides a virtual member function marked 'final', according to
2714 /// C++11 [class.virtual]p4.
2715 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2716                                                   const CXXMethodDecl *Old) {
2717   FinalAttr *FA = Old->getAttr<FinalAttr>();
2718   if (!FA)
2719     return false;
2720 
2721   Diag(New->getLocation(), diag::err_final_function_overridden)
2722     << New->getDeclName()
2723     << FA->isSpelledAsSealed();
2724   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2725   return true;
2726 }
2727 
2728 static bool InitializationHasSideEffects(const FieldDecl &FD) {
2729   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2730   // FIXME: Destruction of ObjC lifetime types has side-effects.
2731   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2732     return !RD->isCompleteDefinition() ||
2733            !RD->hasTrivialDefaultConstructor() ||
2734            !RD->hasTrivialDestructor();
2735   return false;
2736 }
2737 
2738 static AttributeList *getMSPropertyAttr(AttributeList *list) {
2739   for (AttributeList *it = list; it != nullptr; it = it->getNext())
2740     if (it->isDeclspecPropertyAttribute())
2741       return it;
2742   return nullptr;
2743 }
2744 
2745 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2746 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2747 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
2748 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2749 /// present (but parsing it has been deferred).
2750 NamedDecl *
2751 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2752                                MultiTemplateParamsArg TemplateParameterLists,
2753                                Expr *BW, const VirtSpecifiers &VS,
2754                                InClassInitStyle InitStyle) {
2755   const DeclSpec &DS = D.getDeclSpec();
2756   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2757   DeclarationName Name = NameInfo.getName();
2758   SourceLocation Loc = NameInfo.getLoc();
2759 
2760   // For anonymous bitfields, the location should point to the type.
2761   if (Loc.isInvalid())
2762     Loc = D.getLocStart();
2763 
2764   Expr *BitWidth = static_cast<Expr*>(BW);
2765 
2766   assert(isa<CXXRecordDecl>(CurContext));
2767   assert(!DS.isFriendSpecified());
2768 
2769   bool isFunc = D.isDeclarationOfFunction();
2770 
2771   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2772     // The Microsoft extension __interface only permits public member functions
2773     // and prohibits constructors, destructors, operators, non-public member
2774     // functions, static methods and data members.
2775     unsigned InvalidDecl;
2776     bool ShowDeclName = true;
2777     if (!isFunc)
2778       InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
2779     else if (AS != AS_public)
2780       InvalidDecl = 2;
2781     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2782       InvalidDecl = 3;
2783     else switch (Name.getNameKind()) {
2784       case DeclarationName::CXXConstructorName:
2785         InvalidDecl = 4;
2786         ShowDeclName = false;
2787         break;
2788 
2789       case DeclarationName::CXXDestructorName:
2790         InvalidDecl = 5;
2791         ShowDeclName = false;
2792         break;
2793 
2794       case DeclarationName::CXXOperatorName:
2795       case DeclarationName::CXXConversionFunctionName:
2796         InvalidDecl = 6;
2797         break;
2798 
2799       default:
2800         InvalidDecl = 0;
2801         break;
2802     }
2803 
2804     if (InvalidDecl) {
2805       if (ShowDeclName)
2806         Diag(Loc, diag::err_invalid_member_in_interface)
2807           << (InvalidDecl-1) << Name;
2808       else
2809         Diag(Loc, diag::err_invalid_member_in_interface)
2810           << (InvalidDecl-1) << "";
2811       return nullptr;
2812     }
2813   }
2814 
2815   // C++ 9.2p6: A member shall not be declared to have automatic storage
2816   // duration (auto, register) or with the extern storage-class-specifier.
2817   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2818   // data members and cannot be applied to names declared const or static,
2819   // and cannot be applied to reference members.
2820   switch (DS.getStorageClassSpec()) {
2821   case DeclSpec::SCS_unspecified:
2822   case DeclSpec::SCS_typedef:
2823   case DeclSpec::SCS_static:
2824     break;
2825   case DeclSpec::SCS_mutable:
2826     if (isFunc) {
2827       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2828 
2829       // FIXME: It would be nicer if the keyword was ignored only for this
2830       // declarator. Otherwise we could get follow-up errors.
2831       D.getMutableDeclSpec().ClearStorageClassSpecs();
2832     }
2833     break;
2834   default:
2835     Diag(DS.getStorageClassSpecLoc(),
2836          diag::err_storageclass_invalid_for_member);
2837     D.getMutableDeclSpec().ClearStorageClassSpecs();
2838     break;
2839   }
2840 
2841   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2842                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
2843                       !isFunc);
2844 
2845   if (DS.isConstexprSpecified() && isInstField) {
2846     SemaDiagnosticBuilder B =
2847         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2848     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2849     if (InitStyle == ICIS_NoInit) {
2850       B << 0 << 0;
2851       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2852         B << FixItHint::CreateRemoval(ConstexprLoc);
2853       else {
2854         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2855         D.getMutableDeclSpec().ClearConstexprSpec();
2856         const char *PrevSpec;
2857         unsigned DiagID;
2858         bool Failed = D.getMutableDeclSpec().SetTypeQual(
2859             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2860         (void)Failed;
2861         assert(!Failed && "Making a constexpr member const shouldn't fail");
2862       }
2863     } else {
2864       B << 1;
2865       const char *PrevSpec;
2866       unsigned DiagID;
2867       if (D.getMutableDeclSpec().SetStorageClassSpec(
2868           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2869           Context.getPrintingPolicy())) {
2870         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
2871                "This is the only DeclSpec that should fail to be applied");
2872         B << 1;
2873       } else {
2874         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2875         isInstField = false;
2876       }
2877     }
2878   }
2879 
2880   NamedDecl *Member;
2881   if (isInstField) {
2882     CXXScopeSpec &SS = D.getCXXScopeSpec();
2883 
2884     // Data members must have identifiers for names.
2885     if (!Name.isIdentifier()) {
2886       Diag(Loc, diag::err_bad_variable_name)
2887         << Name;
2888       return nullptr;
2889     }
2890 
2891     IdentifierInfo *II = Name.getAsIdentifierInfo();
2892 
2893     // Member field could not be with "template" keyword.
2894     // So TemplateParameterLists should be empty in this case.
2895     if (TemplateParameterLists.size()) {
2896       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
2897       if (TemplateParams->size()) {
2898         // There is no such thing as a member field template.
2899         Diag(D.getIdentifierLoc(), diag::err_template_member)
2900             << II
2901             << SourceRange(TemplateParams->getTemplateLoc(),
2902                 TemplateParams->getRAngleLoc());
2903       } else {
2904         // There is an extraneous 'template<>' for this member.
2905         Diag(TemplateParams->getTemplateLoc(),
2906             diag::err_template_member_noparams)
2907             << II
2908             << SourceRange(TemplateParams->getTemplateLoc(),
2909                 TemplateParams->getRAngleLoc());
2910       }
2911       return nullptr;
2912     }
2913 
2914     if (SS.isSet() && !SS.isInvalid()) {
2915       // The user provided a superfluous scope specifier inside a class
2916       // definition:
2917       //
2918       // class X {
2919       //   int X::member;
2920       // };
2921       if (DeclContext *DC = computeDeclContext(SS, false))
2922         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
2923       else
2924         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2925           << Name << SS.getRange();
2926 
2927       SS.clear();
2928     }
2929 
2930     AttributeList *MSPropertyAttr =
2931       getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
2932     if (MSPropertyAttr) {
2933       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2934                                 BitWidth, InitStyle, AS, MSPropertyAttr);
2935       if (!Member)
2936         return nullptr;
2937       isInstField = false;
2938     } else {
2939       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2940                                 BitWidth, InitStyle, AS);
2941       if (!Member)
2942         return nullptr;
2943     }
2944   } else {
2945     Member = HandleDeclarator(S, D, TemplateParameterLists);
2946     if (!Member)
2947       return nullptr;
2948 
2949     // Non-instance-fields can't have a bitfield.
2950     if (BitWidth) {
2951       if (Member->isInvalidDecl()) {
2952         // don't emit another diagnostic.
2953       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
2954         // C++ 9.6p3: A bit-field shall not be a static member.
2955         // "static member 'A' cannot be a bit-field"
2956         Diag(Loc, diag::err_static_not_bitfield)
2957           << Name << BitWidth->getSourceRange();
2958       } else if (isa<TypedefDecl>(Member)) {
2959         // "typedef member 'x' cannot be a bit-field"
2960         Diag(Loc, diag::err_typedef_not_bitfield)
2961           << Name << BitWidth->getSourceRange();
2962       } else {
2963         // A function typedef ("typedef int f(); f a;").
2964         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2965         Diag(Loc, diag::err_not_integral_type_bitfield)
2966           << Name << cast<ValueDecl>(Member)->getType()
2967           << BitWidth->getSourceRange();
2968       }
2969 
2970       BitWidth = nullptr;
2971       Member->setInvalidDecl();
2972     }
2973 
2974     Member->setAccess(AS);
2975 
2976     // If we have declared a member function template or static data member
2977     // template, set the access of the templated declaration as well.
2978     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2979       FunTmpl->getTemplatedDecl()->setAccess(AS);
2980     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2981       VarTmpl->getTemplatedDecl()->setAccess(AS);
2982   }
2983 
2984   if (VS.isOverrideSpecified())
2985     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
2986   if (VS.isFinalSpecified())
2987     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2988                                             VS.isFinalSpelledSealed()));
2989 
2990   if (VS.getLastLocation().isValid()) {
2991     // Update the end location of a method that has a virt-specifiers.
2992     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2993       MD->setRangeEnd(VS.getLastLocation());
2994   }
2995 
2996   CheckOverrideControl(Member);
2997 
2998   assert((Name || isInstField) && "No identifier for non-field ?");
2999 
3000   if (isInstField) {
3001     FieldDecl *FD = cast<FieldDecl>(Member);
3002     FieldCollector->Add(FD);
3003 
3004     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3005       // Remember all explicit private FieldDecls that have a name, no side
3006       // effects and are not part of a dependent type declaration.
3007       if (!FD->isImplicit() && FD->getDeclName() &&
3008           FD->getAccess() == AS_private &&
3009           !FD->hasAttr<UnusedAttr>() &&
3010           !FD->getParent()->isDependentContext() &&
3011           !InitializationHasSideEffects(*FD))
3012         UnusedPrivateFields.insert(FD);
3013     }
3014   }
3015 
3016   return Member;
3017 }
3018 
3019 namespace {
3020   class UninitializedFieldVisitor
3021       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3022     Sema &S;
3023     // List of Decls to generate a warning on.  Also remove Decls that become
3024     // initialized.
3025     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3026     // List of base classes of the record.  Classes are removed after their
3027     // initializers.
3028     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3029     // Vector of decls to be removed from the Decl set prior to visiting the
3030     // nodes.  These Decls may have been initialized in the prior initializer.
3031     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3032     // If non-null, add a note to the warning pointing back to the constructor.
3033     const CXXConstructorDecl *Constructor;
3034     // Variables to hold state when processing an initializer list.  When
3035     // InitList is true, special case initialization of FieldDecls matching
3036     // InitListFieldDecl.
3037     bool InitList;
3038     FieldDecl *InitListFieldDecl;
3039     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3040 
3041   public:
3042     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3043     UninitializedFieldVisitor(Sema &S,
3044                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3045                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3046       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3047         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3048 
3049     // Returns true if the use of ME is not an uninitialized use.
3050     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3051                                          bool CheckReferenceOnly) {
3052       llvm::SmallVector<FieldDecl*, 4> Fields;
3053       bool ReferenceField = false;
3054       while (ME) {
3055         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3056         if (!FD)
3057           return false;
3058         Fields.push_back(FD);
3059         if (FD->getType()->isReferenceType())
3060           ReferenceField = true;
3061         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3062       }
3063 
3064       // Binding a reference to an unintialized field is not an
3065       // uninitialized use.
3066       if (CheckReferenceOnly && !ReferenceField)
3067         return true;
3068 
3069       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3070       // Discard the first field since it is the field decl that is being
3071       // initialized.
3072       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3073         UsedFieldIndex.push_back((*I)->getFieldIndex());
3074       }
3075 
3076       for (auto UsedIter = UsedFieldIndex.begin(),
3077                 UsedEnd = UsedFieldIndex.end(),
3078                 OrigIter = InitFieldIndex.begin(),
3079                 OrigEnd = InitFieldIndex.end();
3080            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3081         if (*UsedIter < *OrigIter)
3082           return true;
3083         if (*UsedIter > *OrigIter)
3084           break;
3085       }
3086 
3087       return false;
3088     }
3089 
3090     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3091                           bool AddressOf) {
3092       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3093         return;
3094 
3095       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3096       // or union.
3097       MemberExpr *FieldME = ME;
3098 
3099       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3100 
3101       Expr *Base = ME;
3102       while (MemberExpr *SubME =
3103                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3104 
3105         if (isa<VarDecl>(SubME->getMemberDecl()))
3106           return;
3107 
3108         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3109           if (!FD->isAnonymousStructOrUnion())
3110             FieldME = SubME;
3111 
3112         if (!FieldME->getType().isPODType(S.Context))
3113           AllPODFields = false;
3114 
3115         Base = SubME->getBase();
3116       }
3117 
3118       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3119         return;
3120 
3121       if (AddressOf && AllPODFields)
3122         return;
3123 
3124       ValueDecl* FoundVD = FieldME->getMemberDecl();
3125 
3126       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3127         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3128           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3129         }
3130 
3131         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3132           QualType T = BaseCast->getType();
3133           if (T->isPointerType() &&
3134               BaseClasses.count(T->getPointeeType())) {
3135             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3136                 << T->getPointeeType() << FoundVD;
3137           }
3138         }
3139       }
3140 
3141       if (!Decls.count(FoundVD))
3142         return;
3143 
3144       const bool IsReference = FoundVD->getType()->isReferenceType();
3145 
3146       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3147         // Special checking for initializer lists.
3148         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3149           return;
3150         }
3151       } else {
3152         // Prevent double warnings on use of unbounded references.
3153         if (CheckReferenceOnly && !IsReference)
3154           return;
3155       }
3156 
3157       unsigned diag = IsReference
3158           ? diag::warn_reference_field_is_uninit
3159           : diag::warn_field_is_uninit;
3160       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3161       if (Constructor)
3162         S.Diag(Constructor->getLocation(),
3163                diag::note_uninit_in_this_constructor)
3164           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3165 
3166     }
3167 
3168     void HandleValue(Expr *E, bool AddressOf) {
3169       E = E->IgnoreParens();
3170 
3171       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3172         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3173                          AddressOf /*AddressOf*/);
3174         return;
3175       }
3176 
3177       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3178         Visit(CO->getCond());
3179         HandleValue(CO->getTrueExpr(), AddressOf);
3180         HandleValue(CO->getFalseExpr(), AddressOf);
3181         return;
3182       }
3183 
3184       if (BinaryConditionalOperator *BCO =
3185               dyn_cast<BinaryConditionalOperator>(E)) {
3186         Visit(BCO->getCond());
3187         HandleValue(BCO->getFalseExpr(), AddressOf);
3188         return;
3189       }
3190 
3191       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3192         HandleValue(OVE->getSourceExpr(), AddressOf);
3193         return;
3194       }
3195 
3196       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3197         switch (BO->getOpcode()) {
3198         default:
3199           break;
3200         case(BO_PtrMemD):
3201         case(BO_PtrMemI):
3202           HandleValue(BO->getLHS(), AddressOf);
3203           Visit(BO->getRHS());
3204           return;
3205         case(BO_Comma):
3206           Visit(BO->getLHS());
3207           HandleValue(BO->getRHS(), AddressOf);
3208           return;
3209         }
3210       }
3211 
3212       Visit(E);
3213     }
3214 
3215     void CheckInitListExpr(InitListExpr *ILE) {
3216       InitFieldIndex.push_back(0);
3217       for (auto Child : ILE->children()) {
3218         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3219           CheckInitListExpr(SubList);
3220         } else {
3221           Visit(Child);
3222         }
3223         ++InitFieldIndex.back();
3224       }
3225       InitFieldIndex.pop_back();
3226     }
3227 
3228     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3229                           FieldDecl *Field, const Type *BaseClass) {
3230       // Remove Decls that may have been initialized in the previous
3231       // initializer.
3232       for (ValueDecl* VD : DeclsToRemove)
3233         Decls.erase(VD);
3234       DeclsToRemove.clear();
3235 
3236       Constructor = FieldConstructor;
3237       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3238 
3239       if (ILE && Field) {
3240         InitList = true;
3241         InitListFieldDecl = Field;
3242         InitFieldIndex.clear();
3243         CheckInitListExpr(ILE);
3244       } else {
3245         InitList = false;
3246         Visit(E);
3247       }
3248 
3249       if (Field)
3250         Decls.erase(Field);
3251       if (BaseClass)
3252         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3253     }
3254 
3255     void VisitMemberExpr(MemberExpr *ME) {
3256       // All uses of unbounded reference fields will warn.
3257       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3258     }
3259 
3260     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3261       if (E->getCastKind() == CK_LValueToRValue) {
3262         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3263         return;
3264       }
3265 
3266       Inherited::VisitImplicitCastExpr(E);
3267     }
3268 
3269     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3270       if (E->getConstructor()->isCopyConstructor()) {
3271         Expr *ArgExpr = E->getArg(0);
3272         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3273           if (ILE->getNumInits() == 1)
3274             ArgExpr = ILE->getInit(0);
3275         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3276           if (ICE->getCastKind() == CK_NoOp)
3277             ArgExpr = ICE->getSubExpr();
3278         HandleValue(ArgExpr, false /*AddressOf*/);
3279         return;
3280       }
3281       Inherited::VisitCXXConstructExpr(E);
3282     }
3283 
3284     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3285       Expr *Callee = E->getCallee();
3286       if (isa<MemberExpr>(Callee)) {
3287         HandleValue(Callee, false /*AddressOf*/);
3288         for (auto Arg : E->arguments())
3289           Visit(Arg);
3290         return;
3291       }
3292 
3293       Inherited::VisitCXXMemberCallExpr(E);
3294     }
3295 
3296     void VisitCallExpr(CallExpr *E) {
3297       // Treat std::move as a use.
3298       if (E->getNumArgs() == 1) {
3299         if (FunctionDecl *FD = E->getDirectCallee()) {
3300           if (FD->isInStdNamespace() && FD->getIdentifier() &&
3301               FD->getIdentifier()->isStr("move")) {
3302             HandleValue(E->getArg(0), false /*AddressOf*/);
3303             return;
3304           }
3305         }
3306       }
3307 
3308       Inherited::VisitCallExpr(E);
3309     }
3310 
3311     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3312       Expr *Callee = E->getCallee();
3313 
3314       if (isa<UnresolvedLookupExpr>(Callee))
3315         return Inherited::VisitCXXOperatorCallExpr(E);
3316 
3317       Visit(Callee);
3318       for (auto Arg : E->arguments())
3319         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3320     }
3321 
3322     void VisitBinaryOperator(BinaryOperator *E) {
3323       // If a field assignment is detected, remove the field from the
3324       // uninitiailized field set.
3325       if (E->getOpcode() == BO_Assign)
3326         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3327           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3328             if (!FD->getType()->isReferenceType())
3329               DeclsToRemove.push_back(FD);
3330 
3331       if (E->isCompoundAssignmentOp()) {
3332         HandleValue(E->getLHS(), false /*AddressOf*/);
3333         Visit(E->getRHS());
3334         return;
3335       }
3336 
3337       Inherited::VisitBinaryOperator(E);
3338     }
3339 
3340     void VisitUnaryOperator(UnaryOperator *E) {
3341       if (E->isIncrementDecrementOp()) {
3342         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3343         return;
3344       }
3345       if (E->getOpcode() == UO_AddrOf) {
3346         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3347           HandleValue(ME->getBase(), true /*AddressOf*/);
3348           return;
3349         }
3350       }
3351 
3352       Inherited::VisitUnaryOperator(E);
3353     }
3354   };
3355 
3356   // Diagnose value-uses of fields to initialize themselves, e.g.
3357   //   foo(foo)
3358   // where foo is not also a parameter to the constructor.
3359   // Also diagnose across field uninitialized use such as
3360   //   x(y), y(x)
3361   // TODO: implement -Wuninitialized and fold this into that framework.
3362   static void DiagnoseUninitializedFields(
3363       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3364 
3365     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3366                                            Constructor->getLocation())) {
3367       return;
3368     }
3369 
3370     if (Constructor->isInvalidDecl())
3371       return;
3372 
3373     const CXXRecordDecl *RD = Constructor->getParent();
3374 
3375     if (RD->getDescribedClassTemplate())
3376       return;
3377 
3378     // Holds fields that are uninitialized.
3379     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3380 
3381     // At the beginning, all fields are uninitialized.
3382     for (auto *I : RD->decls()) {
3383       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3384         UninitializedFields.insert(FD);
3385       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3386         UninitializedFields.insert(IFD->getAnonField());
3387       }
3388     }
3389 
3390     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3391     for (auto I : RD->bases())
3392       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3393 
3394     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3395       return;
3396 
3397     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3398                                                    UninitializedFields,
3399                                                    UninitializedBaseClasses);
3400 
3401     for (const auto *FieldInit : Constructor->inits()) {
3402       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3403         break;
3404 
3405       Expr *InitExpr = FieldInit->getInit();
3406       if (!InitExpr)
3407         continue;
3408 
3409       if (CXXDefaultInitExpr *Default =
3410               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3411         InitExpr = Default->getExpr();
3412         if (!InitExpr)
3413           continue;
3414         // In class initializers will point to the constructor.
3415         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3416                                               FieldInit->getAnyMember(),
3417                                               FieldInit->getBaseClass());
3418       } else {
3419         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3420                                               FieldInit->getAnyMember(),
3421                                               FieldInit->getBaseClass());
3422       }
3423     }
3424   }
3425 } // namespace
3426 
3427 /// \brief Enter a new C++ default initializer scope. After calling this, the
3428 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3429 /// parsing or instantiating the initializer failed.
3430 void Sema::ActOnStartCXXInClassMemberInitializer() {
3431   // Create a synthetic function scope to represent the call to the constructor
3432   // that notionally surrounds a use of this initializer.
3433   PushFunctionScope();
3434 }
3435 
3436 /// \brief This is invoked after parsing an in-class initializer for a
3437 /// non-static C++ class member, and after instantiating an in-class initializer
3438 /// in a class template. Such actions are deferred until the class is complete.
3439 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3440                                                   SourceLocation InitLoc,
3441                                                   Expr *InitExpr) {
3442   // Pop the notional constructor scope we created earlier.
3443   PopFunctionScopeInfo(nullptr, D);
3444 
3445   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3446   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3447          "must set init style when field is created");
3448 
3449   if (!InitExpr) {
3450     D->setInvalidDecl();
3451     if (FD)
3452       FD->removeInClassInitializer();
3453     return;
3454   }
3455 
3456   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3457     FD->setInvalidDecl();
3458     FD->removeInClassInitializer();
3459     return;
3460   }
3461 
3462   ExprResult Init = InitExpr;
3463   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3464     InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
3465     InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
3466         ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
3467         : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
3468     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3469     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3470     if (Init.isInvalid()) {
3471       FD->setInvalidDecl();
3472       return;
3473     }
3474   }
3475 
3476   // C++11 [class.base.init]p7:
3477   //   The initialization of each base and member constitutes a
3478   //   full-expression.
3479   Init = ActOnFinishFullExpr(Init.get(), InitLoc);
3480   if (Init.isInvalid()) {
3481     FD->setInvalidDecl();
3482     return;
3483   }
3484 
3485   InitExpr = Init.get();
3486 
3487   FD->setInClassInitializer(InitExpr);
3488 }
3489 
3490 /// \brief Find the direct and/or virtual base specifiers that
3491 /// correspond to the given base type, for use in base initialization
3492 /// within a constructor.
3493 static bool FindBaseInitializer(Sema &SemaRef,
3494                                 CXXRecordDecl *ClassDecl,
3495                                 QualType BaseType,
3496                                 const CXXBaseSpecifier *&DirectBaseSpec,
3497                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
3498   // First, check for a direct base class.
3499   DirectBaseSpec = nullptr;
3500   for (const auto &Base : ClassDecl->bases()) {
3501     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3502       // We found a direct base of this type. That's what we're
3503       // initializing.
3504       DirectBaseSpec = &Base;
3505       break;
3506     }
3507   }
3508 
3509   // Check for a virtual base class.
3510   // FIXME: We might be able to short-circuit this if we know in advance that
3511   // there are no virtual bases.
3512   VirtualBaseSpec = nullptr;
3513   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3514     // We haven't found a base yet; search the class hierarchy for a
3515     // virtual base class.
3516     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3517                        /*DetectVirtual=*/false);
3518     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3519                               SemaRef.Context.getTypeDeclType(ClassDecl),
3520                               BaseType, Paths)) {
3521       for (CXXBasePaths::paths_iterator Path = Paths.begin();
3522            Path != Paths.end(); ++Path) {
3523         if (Path->back().Base->isVirtual()) {
3524           VirtualBaseSpec = Path->back().Base;
3525           break;
3526         }
3527       }
3528     }
3529   }
3530 
3531   return DirectBaseSpec || VirtualBaseSpec;
3532 }
3533 
3534 /// \brief Handle a C++ member initializer using braced-init-list syntax.
3535 MemInitResult
3536 Sema::ActOnMemInitializer(Decl *ConstructorD,
3537                           Scope *S,
3538                           CXXScopeSpec &SS,
3539                           IdentifierInfo *MemberOrBase,
3540                           ParsedType TemplateTypeTy,
3541                           const DeclSpec &DS,
3542                           SourceLocation IdLoc,
3543                           Expr *InitList,
3544                           SourceLocation EllipsisLoc) {
3545   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3546                              DS, IdLoc, InitList,
3547                              EllipsisLoc);
3548 }
3549 
3550 /// \brief Handle a C++ member initializer using parentheses syntax.
3551 MemInitResult
3552 Sema::ActOnMemInitializer(Decl *ConstructorD,
3553                           Scope *S,
3554                           CXXScopeSpec &SS,
3555                           IdentifierInfo *MemberOrBase,
3556                           ParsedType TemplateTypeTy,
3557                           const DeclSpec &DS,
3558                           SourceLocation IdLoc,
3559                           SourceLocation LParenLoc,
3560                           ArrayRef<Expr *> Args,
3561                           SourceLocation RParenLoc,
3562                           SourceLocation EllipsisLoc) {
3563   Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
3564                                            Args, RParenLoc);
3565   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3566                              DS, IdLoc, List, EllipsisLoc);
3567 }
3568 
3569 namespace {
3570 
3571 // Callback to only accept typo corrections that can be a valid C++ member
3572 // intializer: either a non-static field member or a base class.
3573 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
3574 public:
3575   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3576       : ClassDecl(ClassDecl) {}
3577 
3578   bool ValidateCandidate(const TypoCorrection &candidate) override {
3579     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3580       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3581         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
3582       return isa<TypeDecl>(ND);
3583     }
3584     return false;
3585   }
3586 
3587 private:
3588   CXXRecordDecl *ClassDecl;
3589 };
3590 
3591 }
3592 
3593 /// \brief Handle a C++ member initializer.
3594 MemInitResult
3595 Sema::BuildMemInitializer(Decl *ConstructorD,
3596                           Scope *S,
3597                           CXXScopeSpec &SS,
3598                           IdentifierInfo *MemberOrBase,
3599                           ParsedType TemplateTypeTy,
3600                           const DeclSpec &DS,
3601                           SourceLocation IdLoc,
3602                           Expr *Init,
3603                           SourceLocation EllipsisLoc) {
3604   ExprResult Res = CorrectDelayedTyposInExpr(Init);
3605   if (!Res.isUsable())
3606     return true;
3607   Init = Res.get();
3608 
3609   if (!ConstructorD)
3610     return true;
3611 
3612   AdjustDeclIfTemplate(ConstructorD);
3613 
3614   CXXConstructorDecl *Constructor
3615     = dyn_cast<CXXConstructorDecl>(ConstructorD);
3616   if (!Constructor) {
3617     // The user wrote a constructor initializer on a function that is
3618     // not a C++ constructor. Ignore the error for now, because we may
3619     // have more member initializers coming; we'll diagnose it just
3620     // once in ActOnMemInitializers.
3621     return true;
3622   }
3623 
3624   CXXRecordDecl *ClassDecl = Constructor->getParent();
3625 
3626   // C++ [class.base.init]p2:
3627   //   Names in a mem-initializer-id are looked up in the scope of the
3628   //   constructor's class and, if not found in that scope, are looked
3629   //   up in the scope containing the constructor's definition.
3630   //   [Note: if the constructor's class contains a member with the
3631   //   same name as a direct or virtual base class of the class, a
3632   //   mem-initializer-id naming the member or base class and composed
3633   //   of a single identifier refers to the class member. A
3634   //   mem-initializer-id for the hidden base class may be specified
3635   //   using a qualified name. ]
3636   if (!SS.getScopeRep() && !TemplateTypeTy) {
3637     // Look for a member, first.
3638     DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
3639     if (!Result.empty()) {
3640       ValueDecl *Member;
3641       if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3642           (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
3643         if (EllipsisLoc.isValid())
3644           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
3645             << MemberOrBase
3646             << SourceRange(IdLoc, Init->getSourceRange().getEnd());
3647 
3648         return BuildMemberInitializer(Member, Init, IdLoc);
3649       }
3650     }
3651   }
3652   // It didn't name a member, so see if it names a class.
3653   QualType BaseType;
3654   TypeSourceInfo *TInfo = nullptr;
3655 
3656   if (TemplateTypeTy) {
3657     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
3658   } else if (DS.getTypeSpecType() == TST_decltype) {
3659     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
3660   } else {
3661     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3662     LookupParsedName(R, S, &SS);
3663 
3664     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3665     if (!TyD) {
3666       if (R.isAmbiguous()) return true;
3667 
3668       // We don't want access-control diagnostics here.
3669       R.suppressDiagnostics();
3670 
3671       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3672         bool NotUnknownSpecialization = false;
3673         DeclContext *DC = computeDeclContext(SS, false);
3674         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3675           NotUnknownSpecialization = !Record->hasAnyDependentBases();
3676 
3677         if (!NotUnknownSpecialization) {
3678           // When the scope specifier can refer to a member of an unknown
3679           // specialization, we take it as a type name.
3680           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3681                                        SS.getWithLocInContext(Context),
3682                                        *MemberOrBase, IdLoc);
3683           if (BaseType.isNull())
3684             return true;
3685 
3686           R.clear();
3687           R.setLookupName(MemberOrBase);
3688         }
3689       }
3690 
3691       // If no results were found, try to correct typos.
3692       TypoCorrection Corr;
3693       if (R.empty() && BaseType.isNull() &&
3694           (Corr = CorrectTypo(
3695                R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3696                llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
3697                CTK_ErrorRecovery, ClassDecl))) {
3698         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
3699           // We have found a non-static data member with a similar
3700           // name to what was typed; complain and initialize that
3701           // member.
3702           diagnoseTypo(Corr,
3703                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
3704                          << MemberOrBase << true);
3705           return BuildMemberInitializer(Member, Init, IdLoc);
3706         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
3707           const CXXBaseSpecifier *DirectBaseSpec;
3708           const CXXBaseSpecifier *VirtualBaseSpec;
3709           if (FindBaseInitializer(*this, ClassDecl,
3710                                   Context.getTypeDeclType(Type),
3711                                   DirectBaseSpec, VirtualBaseSpec)) {
3712             // We have found a direct or virtual base class with a
3713             // similar name to what was typed; complain and initialize
3714             // that base class.
3715             diagnoseTypo(Corr,
3716                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
3717                            << MemberOrBase << false,
3718                          PDiag() /*Suppress note, we provide our own.*/);
3719 
3720             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3721                                                               : VirtualBaseSpec;
3722             Diag(BaseSpec->getLocStart(),
3723                  diag::note_base_class_specified_here)
3724               << BaseSpec->getType()
3725               << BaseSpec->getSourceRange();
3726 
3727             TyD = Type;
3728           }
3729         }
3730       }
3731 
3732       if (!TyD && BaseType.isNull()) {
3733         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
3734           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
3735         return true;
3736       }
3737     }
3738 
3739     if (BaseType.isNull()) {
3740       BaseType = Context.getTypeDeclType(TyD);
3741       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
3742       if (SS.isSet()) {
3743         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3744                                              BaseType);
3745         TInfo = Context.CreateTypeSourceInfo(BaseType);
3746         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3747         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3748         TL.setElaboratedKeywordLoc(SourceLocation());
3749         TL.setQualifierLoc(SS.getWithLocInContext(Context));
3750       }
3751     }
3752   }
3753 
3754   if (!TInfo)
3755     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
3756 
3757   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
3758 }
3759 
3760 /// Checks a member initializer expression for cases where reference (or
3761 /// pointer) members are bound to by-value parameters (or their addresses).
3762 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3763                                                Expr *Init,
3764                                                SourceLocation IdLoc) {
3765   QualType MemberTy = Member->getType();
3766 
3767   // We only handle pointers and references currently.
3768   // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3769   if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3770     return;
3771 
3772   const bool IsPointer = MemberTy->isPointerType();
3773   if (IsPointer) {
3774     if (const UnaryOperator *Op
3775           = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3776       // The only case we're worried about with pointers requires taking the
3777       // address.
3778       if (Op->getOpcode() != UO_AddrOf)
3779         return;
3780 
3781       Init = Op->getSubExpr();
3782     } else {
3783       // We only handle address-of expression initializers for pointers.
3784       return;
3785     }
3786   }
3787 
3788   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
3789     // We only warn when referring to a non-reference parameter declaration.
3790     const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3791     if (!Parameter || Parameter->getType()->isReferenceType())
3792       return;
3793 
3794     S.Diag(Init->getExprLoc(),
3795            IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3796                      : diag::warn_bind_ref_member_to_parameter)
3797       << Member << Parameter << Init->getSourceRange();
3798   } else {
3799     // Other initializers are fine.
3800     return;
3801   }
3802 
3803   S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3804     << (unsigned)IsPointer;
3805 }
3806 
3807 MemInitResult
3808 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3809                              SourceLocation IdLoc) {
3810   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3811   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3812   assert((DirectMember || IndirectMember) &&
3813          "Member must be a FieldDecl or IndirectFieldDecl");
3814 
3815   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3816     return true;
3817 
3818   if (Member->isInvalidDecl())
3819     return true;
3820 
3821   MultiExprArg Args;
3822   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3823     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3824   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3825     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
3826   } else {
3827     // Template instantiation doesn't reconstruct ParenListExprs for us.
3828     Args = Init;
3829   }
3830 
3831   SourceRange InitRange = Init->getSourceRange();
3832 
3833   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
3834     // Can't check initialization for a member of dependent type or when
3835     // any of the arguments are type-dependent expressions.
3836     DiscardCleanupsInEvaluationContext();
3837   } else {
3838     bool InitList = false;
3839     if (isa<InitListExpr>(Init)) {
3840       InitList = true;
3841       Args = Init;
3842     }
3843 
3844     // Initialize the member.
3845     InitializedEntity MemberEntity =
3846       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3847                    : InitializedEntity::InitializeMember(IndirectMember,
3848                                                          nullptr);
3849     InitializationKind Kind =
3850       InitList ? InitializationKind::CreateDirectList(IdLoc)
3851                : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3852                                                   InitRange.getEnd());
3853 
3854     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
3855     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3856                                             nullptr);
3857     if (MemberInit.isInvalid())
3858       return true;
3859 
3860     CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3861 
3862     // C++11 [class.base.init]p7:
3863     //   The initialization of each base and member constitutes a
3864     //   full-expression.
3865     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
3866     if (MemberInit.isInvalid())
3867       return true;
3868 
3869     Init = MemberInit.get();
3870   }
3871 
3872   if (DirectMember) {
3873     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3874                                             InitRange.getBegin(), Init,
3875                                             InitRange.getEnd());
3876   } else {
3877     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3878                                             InitRange.getBegin(), Init,
3879                                             InitRange.getEnd());
3880   }
3881 }
3882 
3883 MemInitResult
3884 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
3885                                  CXXRecordDecl *ClassDecl) {
3886   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
3887   if (!LangOpts.CPlusPlus11)
3888     return Diag(NameLoc, diag::err_delegating_ctor)
3889       << TInfo->getTypeLoc().getLocalSourceRange();
3890   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
3891 
3892   bool InitList = true;
3893   MultiExprArg Args = Init;
3894   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3895     InitList = false;
3896     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3897   }
3898 
3899   SourceRange InitRange = Init->getSourceRange();
3900   // Initialize the object.
3901   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3902                                      QualType(ClassDecl->getTypeForDecl(), 0));
3903   InitializationKind Kind =
3904     InitList ? InitializationKind::CreateDirectList(NameLoc)
3905              : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3906                                                 InitRange.getEnd());
3907   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
3908   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
3909                                               Args, nullptr);
3910   if (DelegationInit.isInvalid())
3911     return true;
3912 
3913   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3914          "Delegating constructor with no target?");
3915 
3916   // C++11 [class.base.init]p7:
3917   //   The initialization of each base and member constitutes a
3918   //   full-expression.
3919   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
3920                                        InitRange.getBegin());
3921   if (DelegationInit.isInvalid())
3922     return true;
3923 
3924   // If we are in a dependent context, template instantiation will
3925   // perform this type-checking again. Just save the arguments that we
3926   // received in a ParenListExpr.
3927   // FIXME: This isn't quite ideal, since our ASTs don't capture all
3928   // of the information that we have about the base
3929   // initializer. However, deconstructing the ASTs is a dicey process,
3930   // and this approach is far more likely to get the corner cases right.
3931   if (CurContext->isDependentContext())
3932     DelegationInit = Init;
3933 
3934   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
3935                                           DelegationInit.getAs<Expr>(),
3936                                           InitRange.getEnd());
3937 }
3938 
3939 MemInitResult
3940 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
3941                            Expr *Init, CXXRecordDecl *ClassDecl,
3942                            SourceLocation EllipsisLoc) {
3943   SourceLocation BaseLoc
3944     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
3945 
3946   if (!BaseType->isDependentType() && !BaseType->isRecordType())
3947     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
3948              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3949 
3950   // C++ [class.base.init]p2:
3951   //   [...] Unless the mem-initializer-id names a nonstatic data
3952   //   member of the constructor's class or a direct or virtual base
3953   //   of that class, the mem-initializer is ill-formed. A
3954   //   mem-initializer-list can initialize a base class using any
3955   //   name that denotes that base class type.
3956   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
3957 
3958   SourceRange InitRange = Init->getSourceRange();
3959   if (EllipsisLoc.isValid()) {
3960     // This is a pack expansion.
3961     if (!BaseType->containsUnexpandedParameterPack())  {
3962       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
3963         << SourceRange(BaseLoc, InitRange.getEnd());
3964 
3965       EllipsisLoc = SourceLocation();
3966     }
3967   } else {
3968     // Check for any unexpanded parameter packs.
3969     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
3970       return true;
3971 
3972     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3973       return true;
3974   }
3975 
3976   // Check for direct and virtual base classes.
3977   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
3978   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
3979   if (!Dependent) {
3980     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
3981                                        BaseType))
3982       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
3983 
3984     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
3985                         VirtualBaseSpec);
3986 
3987     // C++ [base.class.init]p2:
3988     // Unless the mem-initializer-id names a nonstatic data member of the
3989     // constructor's class or a direct or virtual base of that class, the
3990     // mem-initializer is ill-formed.
3991     if (!DirectBaseSpec && !VirtualBaseSpec) {
3992       // If the class has any dependent bases, then it's possible that
3993       // one of those types will resolve to the same type as
3994       // BaseType. Therefore, just treat this as a dependent base
3995       // class initialization.  FIXME: Should we try to check the
3996       // initialization anyway? It seems odd.
3997       if (ClassDecl->hasAnyDependentBases())
3998         Dependent = true;
3999       else
4000         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4001           << BaseType << Context.getTypeDeclType(ClassDecl)
4002           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4003     }
4004   }
4005 
4006   if (Dependent) {
4007     DiscardCleanupsInEvaluationContext();
4008 
4009     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4010                                             /*IsVirtual=*/false,
4011                                             InitRange.getBegin(), Init,
4012                                             InitRange.getEnd(), EllipsisLoc);
4013   }
4014 
4015   // C++ [base.class.init]p2:
4016   //   If a mem-initializer-id is ambiguous because it designates both
4017   //   a direct non-virtual base class and an inherited virtual base
4018   //   class, the mem-initializer is ill-formed.
4019   if (DirectBaseSpec && VirtualBaseSpec)
4020     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4021       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4022 
4023   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4024   if (!BaseSpec)
4025     BaseSpec = VirtualBaseSpec;
4026 
4027   // Initialize the base.
4028   bool InitList = true;
4029   MultiExprArg Args = Init;
4030   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4031     InitList = false;
4032     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4033   }
4034 
4035   InitializedEntity BaseEntity =
4036     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4037   InitializationKind Kind =
4038     InitList ? InitializationKind::CreateDirectList(BaseLoc)
4039              : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4040                                                 InitRange.getEnd());
4041   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4042   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4043   if (BaseInit.isInvalid())
4044     return true;
4045 
4046   // C++11 [class.base.init]p7:
4047   //   The initialization of each base and member constitutes a
4048   //   full-expression.
4049   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
4050   if (BaseInit.isInvalid())
4051     return true;
4052 
4053   // If we are in a dependent context, template instantiation will
4054   // perform this type-checking again. Just save the arguments that we
4055   // received in a ParenListExpr.
4056   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4057   // of the information that we have about the base
4058   // initializer. However, deconstructing the ASTs is a dicey process,
4059   // and this approach is far more likely to get the corner cases right.
4060   if (CurContext->isDependentContext())
4061     BaseInit = Init;
4062 
4063   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4064                                           BaseSpec->isVirtual(),
4065                                           InitRange.getBegin(),
4066                                           BaseInit.getAs<Expr>(),
4067                                           InitRange.getEnd(), EllipsisLoc);
4068 }
4069 
4070 // Create a static_cast\<T&&>(expr).
4071 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4072   if (T.isNull()) T = E->getType();
4073   QualType TargetType = SemaRef.BuildReferenceType(
4074       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4075   SourceLocation ExprLoc = E->getLocStart();
4076   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4077       TargetType, ExprLoc);
4078 
4079   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4080                                    SourceRange(ExprLoc, ExprLoc),
4081                                    E->getSourceRange()).get();
4082 }
4083 
4084 /// ImplicitInitializerKind - How an implicit base or member initializer should
4085 /// initialize its base or member.
4086 enum ImplicitInitializerKind {
4087   IIK_Default,
4088   IIK_Copy,
4089   IIK_Move,
4090   IIK_Inherit
4091 };
4092 
4093 static bool
4094 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4095                              ImplicitInitializerKind ImplicitInitKind,
4096                              CXXBaseSpecifier *BaseSpec,
4097                              bool IsInheritedVirtualBase,
4098                              CXXCtorInitializer *&CXXBaseInit) {
4099   InitializedEntity InitEntity
4100     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4101                                         IsInheritedVirtualBase);
4102 
4103   ExprResult BaseInit;
4104 
4105   switch (ImplicitInitKind) {
4106   case IIK_Inherit:
4107   case IIK_Default: {
4108     InitializationKind InitKind
4109       = InitializationKind::CreateDefault(Constructor->getLocation());
4110     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4111     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4112     break;
4113   }
4114 
4115   case IIK_Move:
4116   case IIK_Copy: {
4117     bool Moving = ImplicitInitKind == IIK_Move;
4118     ParmVarDecl *Param = Constructor->getParamDecl(0);
4119     QualType ParamType = Param->getType().getNonReferenceType();
4120 
4121     Expr *CopyCtorArg =
4122       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4123                           SourceLocation(), Param, false,
4124                           Constructor->getLocation(), ParamType,
4125                           VK_LValue, nullptr);
4126 
4127     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4128 
4129     // Cast to the base class to avoid ambiguities.
4130     QualType ArgTy =
4131       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4132                                        ParamType.getQualifiers());
4133 
4134     if (Moving) {
4135       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4136     }
4137 
4138     CXXCastPath BasePath;
4139     BasePath.push_back(BaseSpec);
4140     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4141                                             CK_UncheckedDerivedToBase,
4142                                             Moving ? VK_XValue : VK_LValue,
4143                                             &BasePath).get();
4144 
4145     InitializationKind InitKind
4146       = InitializationKind::CreateDirect(Constructor->getLocation(),
4147                                          SourceLocation(), SourceLocation());
4148     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4149     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4150     break;
4151   }
4152   }
4153 
4154   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4155   if (BaseInit.isInvalid())
4156     return true;
4157 
4158   CXXBaseInit =
4159     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4160                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4161                                                         SourceLocation()),
4162                                              BaseSpec->isVirtual(),
4163                                              SourceLocation(),
4164                                              BaseInit.getAs<Expr>(),
4165                                              SourceLocation(),
4166                                              SourceLocation());
4167 
4168   return false;
4169 }
4170 
4171 static bool RefersToRValueRef(Expr *MemRef) {
4172   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4173   return Referenced->getType()->isRValueReferenceType();
4174 }
4175 
4176 static bool
4177 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4178                                ImplicitInitializerKind ImplicitInitKind,
4179                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4180                                CXXCtorInitializer *&CXXMemberInit) {
4181   if (Field->isInvalidDecl())
4182     return true;
4183 
4184   SourceLocation Loc = Constructor->getLocation();
4185 
4186   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4187     bool Moving = ImplicitInitKind == IIK_Move;
4188     ParmVarDecl *Param = Constructor->getParamDecl(0);
4189     QualType ParamType = Param->getType().getNonReferenceType();
4190 
4191     // Suppress copying zero-width bitfields.
4192     if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
4193       return false;
4194 
4195     Expr *MemberExprBase =
4196       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4197                           SourceLocation(), Param, false,
4198                           Loc, ParamType, VK_LValue, nullptr);
4199 
4200     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4201 
4202     if (Moving) {
4203       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4204     }
4205 
4206     // Build a reference to this field within the parameter.
4207     CXXScopeSpec SS;
4208     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4209                               Sema::LookupMemberName);
4210     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4211                                   : cast<ValueDecl>(Field), AS_public);
4212     MemberLookup.resolveKind();
4213     ExprResult CtorArg
4214       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4215                                          ParamType, Loc,
4216                                          /*IsArrow=*/false,
4217                                          SS,
4218                                          /*TemplateKWLoc=*/SourceLocation(),
4219                                          /*FirstQualifierInScope=*/nullptr,
4220                                          MemberLookup,
4221                                          /*TemplateArgs=*/nullptr,
4222                                          /*S*/nullptr);
4223     if (CtorArg.isInvalid())
4224       return true;
4225 
4226     // C++11 [class.copy]p15:
4227     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4228     //     with static_cast<T&&>(x.m);
4229     if (RefersToRValueRef(CtorArg.get())) {
4230       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4231     }
4232 
4233     // When the field we are copying is an array, create index variables for
4234     // each dimension of the array. We use these index variables to subscript
4235     // the source array, and other clients (e.g., CodeGen) will perform the
4236     // necessary iteration with these index variables.
4237     SmallVector<VarDecl *, 4> IndexVariables;
4238     QualType BaseType = Field->getType();
4239     QualType SizeType = SemaRef.Context.getSizeType();
4240     bool InitializingArray = false;
4241     while (const ConstantArrayType *Array
4242                           = SemaRef.Context.getAsConstantArrayType(BaseType)) {
4243       InitializingArray = true;
4244       // Create the iteration variable for this array index.
4245       IdentifierInfo *IterationVarName = nullptr;
4246       {
4247         SmallString<8> Str;
4248         llvm::raw_svector_ostream OS(Str);
4249         OS << "__i" << IndexVariables.size();
4250         IterationVarName = &SemaRef.Context.Idents.get(OS.str());
4251       }
4252       VarDecl *IterationVar
4253         = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
4254                           IterationVarName, SizeType,
4255                         SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
4256                           SC_None);
4257       IndexVariables.push_back(IterationVar);
4258 
4259       // Create a reference to the iteration variable.
4260       ExprResult IterationVarRef
4261         = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
4262       assert(!IterationVarRef.isInvalid() &&
4263              "Reference to invented variable cannot fail!");
4264       IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
4265       assert(!IterationVarRef.isInvalid() &&
4266              "Conversion of invented variable cannot fail!");
4267 
4268       // Subscript the array with this iteration variable.
4269       CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
4270                                                         IterationVarRef.get(),
4271                                                         Loc);
4272       if (CtorArg.isInvalid())
4273         return true;
4274 
4275       BaseType = Array->getElementType();
4276     }
4277 
4278     // The array subscript expression is an lvalue, which is wrong for moving.
4279     if (Moving && InitializingArray)
4280       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4281 
4282     // Construct the entity that we will be initializing. For an array, this
4283     // will be first element in the array, which may require several levels
4284     // of array-subscript entities.
4285     SmallVector<InitializedEntity, 4> Entities;
4286     Entities.reserve(1 + IndexVariables.size());
4287     if (Indirect)
4288       Entities.push_back(InitializedEntity::InitializeMember(Indirect));
4289     else
4290       Entities.push_back(InitializedEntity::InitializeMember(Field));
4291     for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
4292       Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
4293                                                               0,
4294                                                               Entities.back()));
4295 
4296     // Direct-initialize to use the copy constructor.
4297     InitializationKind InitKind =
4298       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4299 
4300     Expr *CtorArgE = CtorArg.getAs<Expr>();
4301     InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
4302                                    CtorArgE);
4303 
4304     ExprResult MemberInit
4305       = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
4306                         MultiExprArg(&CtorArgE, 1));
4307     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4308     if (MemberInit.isInvalid())
4309       return true;
4310 
4311     if (Indirect) {
4312       assert(IndexVariables.size() == 0 &&
4313              "Indirect field improperly initialized");
4314       CXXMemberInit
4315         = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
4316                                                    Loc, Loc,
4317                                                    MemberInit.getAs<Expr>(),
4318                                                    Loc);
4319     } else
4320       CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
4321                                                  Loc, MemberInit.getAs<Expr>(),
4322                                                  Loc,
4323                                                  IndexVariables.data(),
4324                                                  IndexVariables.size());
4325     return false;
4326   }
4327 
4328   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4329          "Unhandled implicit init kind!");
4330 
4331   QualType FieldBaseElementType =
4332     SemaRef.Context.getBaseElementType(Field->getType());
4333 
4334   if (FieldBaseElementType->isRecordType()) {
4335     InitializedEntity InitEntity
4336       = Indirect? InitializedEntity::InitializeMember(Indirect)
4337                 : InitializedEntity::InitializeMember(Field);
4338     InitializationKind InitKind =
4339       InitializationKind::CreateDefault(Loc);
4340 
4341     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4342     ExprResult MemberInit =
4343       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4344 
4345     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4346     if (MemberInit.isInvalid())
4347       return true;
4348 
4349     if (Indirect)
4350       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4351                                                                Indirect, Loc,
4352                                                                Loc,
4353                                                                MemberInit.get(),
4354                                                                Loc);
4355     else
4356       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4357                                                                Field, Loc, Loc,
4358                                                                MemberInit.get(),
4359                                                                Loc);
4360     return false;
4361   }
4362 
4363   if (!Field->getParent()->isUnion()) {
4364     if (FieldBaseElementType->isReferenceType()) {
4365       SemaRef.Diag(Constructor->getLocation(),
4366                    diag::err_uninitialized_member_in_ctor)
4367       << (int)Constructor->isImplicit()
4368       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4369       << 0 << Field->getDeclName();
4370       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4371       return true;
4372     }
4373 
4374     if (FieldBaseElementType.isConstQualified()) {
4375       SemaRef.Diag(Constructor->getLocation(),
4376                    diag::err_uninitialized_member_in_ctor)
4377       << (int)Constructor->isImplicit()
4378       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4379       << 1 << Field->getDeclName();
4380       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4381       return true;
4382     }
4383   }
4384 
4385   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
4386       FieldBaseElementType->isObjCRetainableType() &&
4387       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
4388       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
4389     // ARC:
4390     //   Default-initialize Objective-C pointers to NULL.
4391     CXXMemberInit
4392       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4393                                                  Loc, Loc,
4394                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4395                                                  Loc);
4396     return false;
4397   }
4398 
4399   // Nothing to initialize.
4400   CXXMemberInit = nullptr;
4401   return false;
4402 }
4403 
4404 namespace {
4405 struct BaseAndFieldInfo {
4406   Sema &S;
4407   CXXConstructorDecl *Ctor;
4408   bool AnyErrorsInInits;
4409   ImplicitInitializerKind IIK;
4410   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4411   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4412   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4413 
4414   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4415     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4416     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4417     if (Ctor->getInheritedConstructor())
4418       IIK = IIK_Inherit;
4419     else if (Generated && Ctor->isCopyConstructor())
4420       IIK = IIK_Copy;
4421     else if (Generated && Ctor->isMoveConstructor())
4422       IIK = IIK_Move;
4423     else
4424       IIK = IIK_Default;
4425   }
4426 
4427   bool isImplicitCopyOrMove() const {
4428     switch (IIK) {
4429     case IIK_Copy:
4430     case IIK_Move:
4431       return true;
4432 
4433     case IIK_Default:
4434     case IIK_Inherit:
4435       return false;
4436     }
4437 
4438     llvm_unreachable("Invalid ImplicitInitializerKind!");
4439   }
4440 
4441   bool addFieldInitializer(CXXCtorInitializer *Init) {
4442     AllToInit.push_back(Init);
4443 
4444     // Check whether this initializer makes the field "used".
4445     if (Init->getInit()->HasSideEffects(S.Context))
4446       S.UnusedPrivateFields.remove(Init->getAnyMember());
4447 
4448     return false;
4449   }
4450 
4451   bool isInactiveUnionMember(FieldDecl *Field) {
4452     RecordDecl *Record = Field->getParent();
4453     if (!Record->isUnion())
4454       return false;
4455 
4456     if (FieldDecl *Active =
4457             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4458       return Active != Field->getCanonicalDecl();
4459 
4460     // In an implicit copy or move constructor, ignore any in-class initializer.
4461     if (isImplicitCopyOrMove())
4462       return true;
4463 
4464     // If there's no explicit initialization, the field is active only if it
4465     // has an in-class initializer...
4466     if (Field->hasInClassInitializer())
4467       return false;
4468     // ... or it's an anonymous struct or union whose class has an in-class
4469     // initializer.
4470     if (!Field->isAnonymousStructOrUnion())
4471       return true;
4472     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4473     return !FieldRD->hasInClassInitializer();
4474   }
4475 
4476   /// \brief Determine whether the given field is, or is within, a union member
4477   /// that is inactive (because there was an initializer given for a different
4478   /// member of the union, or because the union was not initialized at all).
4479   bool isWithinInactiveUnionMember(FieldDecl *Field,
4480                                    IndirectFieldDecl *Indirect) {
4481     if (!Indirect)
4482       return isInactiveUnionMember(Field);
4483 
4484     for (auto *C : Indirect->chain()) {
4485       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4486       if (Field && isInactiveUnionMember(Field))
4487         return true;
4488     }
4489     return false;
4490   }
4491 };
4492 }
4493 
4494 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
4495 /// array type.
4496 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4497   if (T->isIncompleteArrayType())
4498     return true;
4499 
4500   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4501     if (!ArrayT->getSize())
4502       return true;
4503 
4504     T = ArrayT->getElementType();
4505   }
4506 
4507   return false;
4508 }
4509 
4510 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4511                                     FieldDecl *Field,
4512                                     IndirectFieldDecl *Indirect = nullptr) {
4513   if (Field->isInvalidDecl())
4514     return false;
4515 
4516   // Overwhelmingly common case: we have a direct initializer for this field.
4517   if (CXXCtorInitializer *Init =
4518           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4519     return Info.addFieldInitializer(Init);
4520 
4521   // C++11 [class.base.init]p8:
4522   //   if the entity is a non-static data member that has a
4523   //   brace-or-equal-initializer and either
4524   //   -- the constructor's class is a union and no other variant member of that
4525   //      union is designated by a mem-initializer-id or
4526   //   -- the constructor's class is not a union, and, if the entity is a member
4527   //      of an anonymous union, no other member of that union is designated by
4528   //      a mem-initializer-id,
4529   //   the entity is initialized as specified in [dcl.init].
4530   //
4531   // We also apply the same rules to handle anonymous structs within anonymous
4532   // unions.
4533   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4534     return false;
4535 
4536   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4537     ExprResult DIE =
4538         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4539     if (DIE.isInvalid())
4540       return true;
4541     CXXCtorInitializer *Init;
4542     if (Indirect)
4543       Init = new (SemaRef.Context)
4544           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4545                              SourceLocation(), DIE.get(), SourceLocation());
4546     else
4547       Init = new (SemaRef.Context)
4548           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4549                              SourceLocation(), DIE.get(), SourceLocation());
4550     return Info.addFieldInitializer(Init);
4551   }
4552 
4553   // Don't initialize incomplete or zero-length arrays.
4554   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4555     return false;
4556 
4557   // Don't try to build an implicit initializer if there were semantic
4558   // errors in any of the initializers (and therefore we might be
4559   // missing some that the user actually wrote).
4560   if (Info.AnyErrorsInInits)
4561     return false;
4562 
4563   CXXCtorInitializer *Init = nullptr;
4564   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4565                                      Indirect, Init))
4566     return true;
4567 
4568   if (!Init)
4569     return false;
4570 
4571   return Info.addFieldInitializer(Init);
4572 }
4573 
4574 bool
4575 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4576                                CXXCtorInitializer *Initializer) {
4577   assert(Initializer->isDelegatingInitializer());
4578   Constructor->setNumCtorInitializers(1);
4579   CXXCtorInitializer **initializer =
4580     new (Context) CXXCtorInitializer*[1];
4581   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4582   Constructor->setCtorInitializers(initializer);
4583 
4584   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4585     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4586     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4587   }
4588 
4589   DelegatingCtorDecls.push_back(Constructor);
4590 
4591   DiagnoseUninitializedFields(*this, Constructor);
4592 
4593   return false;
4594 }
4595 
4596 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4597                                ArrayRef<CXXCtorInitializer *> Initializers) {
4598   if (Constructor->isDependentContext()) {
4599     // Just store the initializers as written, they will be checked during
4600     // instantiation.
4601     if (!Initializers.empty()) {
4602       Constructor->setNumCtorInitializers(Initializers.size());
4603       CXXCtorInitializer **baseOrMemberInitializers =
4604         new (Context) CXXCtorInitializer*[Initializers.size()];
4605       memcpy(baseOrMemberInitializers, Initializers.data(),
4606              Initializers.size() * sizeof(CXXCtorInitializer*));
4607       Constructor->setCtorInitializers(baseOrMemberInitializers);
4608     }
4609 
4610     // Let template instantiation know whether we had errors.
4611     if (AnyErrors)
4612       Constructor->setInvalidDecl();
4613 
4614     return false;
4615   }
4616 
4617   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4618 
4619   // We need to build the initializer AST according to order of construction
4620   // and not what user specified in the Initializers list.
4621   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4622   if (!ClassDecl)
4623     return true;
4624 
4625   bool HadError = false;
4626 
4627   for (unsigned i = 0; i < Initializers.size(); i++) {
4628     CXXCtorInitializer *Member = Initializers[i];
4629 
4630     if (Member->isBaseInitializer())
4631       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4632     else {
4633       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4634 
4635       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4636         for (auto *C : F->chain()) {
4637           FieldDecl *FD = dyn_cast<FieldDecl>(C);
4638           if (FD && FD->getParent()->isUnion())
4639             Info.ActiveUnionMember.insert(std::make_pair(
4640                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4641         }
4642       } else if (FieldDecl *FD = Member->getMember()) {
4643         if (FD->getParent()->isUnion())
4644           Info.ActiveUnionMember.insert(std::make_pair(
4645               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4646       }
4647     }
4648   }
4649 
4650   // Keep track of the direct virtual bases.
4651   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4652   for (auto &I : ClassDecl->bases()) {
4653     if (I.isVirtual())
4654       DirectVBases.insert(&I);
4655   }
4656 
4657   // Push virtual bases before others.
4658   for (auto &VBase : ClassDecl->vbases()) {
4659     if (CXXCtorInitializer *Value
4660         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
4661       // [class.base.init]p7, per DR257:
4662       //   A mem-initializer where the mem-initializer-id names a virtual base
4663       //   class is ignored during execution of a constructor of any class that
4664       //   is not the most derived class.
4665       if (ClassDecl->isAbstract()) {
4666         // FIXME: Provide a fixit to remove the base specifier. This requires
4667         // tracking the location of the associated comma for a base specifier.
4668         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
4669           << VBase.getType() << ClassDecl;
4670         DiagnoseAbstractType(ClassDecl);
4671       }
4672 
4673       Info.AllToInit.push_back(Value);
4674     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4675       // [class.base.init]p8, per DR257:
4676       //   If a given [...] base class is not named by a mem-initializer-id
4677       //   [...] and the entity is not a virtual base class of an abstract
4678       //   class, then [...] the entity is default-initialized.
4679       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
4680       CXXCtorInitializer *CXXBaseInit;
4681       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4682                                        &VBase, IsInheritedVirtualBase,
4683                                        CXXBaseInit)) {
4684         HadError = true;
4685         continue;
4686       }
4687 
4688       Info.AllToInit.push_back(CXXBaseInit);
4689     }
4690   }
4691 
4692   // Non-virtual bases.
4693   for (auto &Base : ClassDecl->bases()) {
4694     // Virtuals are in the virtual base list and already constructed.
4695     if (Base.isVirtual())
4696       continue;
4697 
4698     if (CXXCtorInitializer *Value
4699           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
4700       Info.AllToInit.push_back(Value);
4701     } else if (!AnyErrors) {
4702       CXXCtorInitializer *CXXBaseInit;
4703       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4704                                        &Base, /*IsInheritedVirtualBase=*/false,
4705                                        CXXBaseInit)) {
4706         HadError = true;
4707         continue;
4708       }
4709 
4710       Info.AllToInit.push_back(CXXBaseInit);
4711     }
4712   }
4713 
4714   // Fields.
4715   for (auto *Mem : ClassDecl->decls()) {
4716     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
4717       // C++ [class.bit]p2:
4718       //   A declaration for a bit-field that omits the identifier declares an
4719       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
4720       //   initialized.
4721       if (F->isUnnamedBitfield())
4722         continue;
4723 
4724       // If we're not generating the implicit copy/move constructor, then we'll
4725       // handle anonymous struct/union fields based on their individual
4726       // indirect fields.
4727       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4728         continue;
4729 
4730       if (CollectFieldInitializer(*this, Info, F))
4731         HadError = true;
4732       continue;
4733     }
4734 
4735     // Beyond this point, we only consider default initialization.
4736     if (Info.isImplicitCopyOrMove())
4737       continue;
4738 
4739     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4740       if (F->getType()->isIncompleteArrayType()) {
4741         assert(ClassDecl->hasFlexibleArrayMember() &&
4742                "Incomplete array type is not valid");
4743         continue;
4744       }
4745 
4746       // Initialize each field of an anonymous struct individually.
4747       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4748         HadError = true;
4749 
4750       continue;
4751     }
4752   }
4753 
4754   unsigned NumInitializers = Info.AllToInit.size();
4755   if (NumInitializers > 0) {
4756     Constructor->setNumCtorInitializers(NumInitializers);
4757     CXXCtorInitializer **baseOrMemberInitializers =
4758       new (Context) CXXCtorInitializer*[NumInitializers];
4759     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4760            NumInitializers * sizeof(CXXCtorInitializer*));
4761     Constructor->setCtorInitializers(baseOrMemberInitializers);
4762 
4763     // Constructors implicitly reference the base and member
4764     // destructors.
4765     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4766                                            Constructor->getParent());
4767   }
4768 
4769   return HadError;
4770 }
4771 
4772 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4773   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4774     const RecordDecl *RD = RT->getDecl();
4775     if (RD->isAnonymousStructOrUnion()) {
4776       for (auto *Field : RD->fields())
4777         PopulateKeysForFields(Field, IdealInits);
4778       return;
4779     }
4780   }
4781   IdealInits.push_back(Field->getCanonicalDecl());
4782 }
4783 
4784 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4785   return Context.getCanonicalType(BaseType).getTypePtr();
4786 }
4787 
4788 static const void *GetKeyForMember(ASTContext &Context,
4789                                    CXXCtorInitializer *Member) {
4790   if (!Member->isAnyMemberInitializer())
4791     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4792 
4793   return Member->getAnyMember()->getCanonicalDecl();
4794 }
4795 
4796 static void DiagnoseBaseOrMemInitializerOrder(
4797     Sema &SemaRef, const CXXConstructorDecl *Constructor,
4798     ArrayRef<CXXCtorInitializer *> Inits) {
4799   if (Constructor->getDeclContext()->isDependentContext())
4800     return;
4801 
4802   // Don't check initializers order unless the warning is enabled at the
4803   // location of at least one initializer.
4804   bool ShouldCheckOrder = false;
4805   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4806     CXXCtorInitializer *Init = Inits[InitIndex];
4807     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4808                                  Init->getSourceLocation())) {
4809       ShouldCheckOrder = true;
4810       break;
4811     }
4812   }
4813   if (!ShouldCheckOrder)
4814     return;
4815 
4816   // Build the list of bases and members in the order that they'll
4817   // actually be initialized.  The explicit initializers should be in
4818   // this same order but may be missing things.
4819   SmallVector<const void*, 32> IdealInitKeys;
4820 
4821   const CXXRecordDecl *ClassDecl = Constructor->getParent();
4822 
4823   // 1. Virtual bases.
4824   for (const auto &VBase : ClassDecl->vbases())
4825     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4826 
4827   // 2. Non-virtual bases.
4828   for (const auto &Base : ClassDecl->bases()) {
4829     if (Base.isVirtual())
4830       continue;
4831     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4832   }
4833 
4834   // 3. Direct fields.
4835   for (auto *Field : ClassDecl->fields()) {
4836     if (Field->isUnnamedBitfield())
4837       continue;
4838 
4839     PopulateKeysForFields(Field, IdealInitKeys);
4840   }
4841 
4842   unsigned NumIdealInits = IdealInitKeys.size();
4843   unsigned IdealIndex = 0;
4844 
4845   CXXCtorInitializer *PrevInit = nullptr;
4846   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4847     CXXCtorInitializer *Init = Inits[InitIndex];
4848     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4849 
4850     // Scan forward to try to find this initializer in the idealized
4851     // initializers list.
4852     for (; IdealIndex != NumIdealInits; ++IdealIndex)
4853       if (InitKey == IdealInitKeys[IdealIndex])
4854         break;
4855 
4856     // If we didn't find this initializer, it must be because we
4857     // scanned past it on a previous iteration.  That can only
4858     // happen if we're out of order;  emit a warning.
4859     if (IdealIndex == NumIdealInits && PrevInit) {
4860       Sema::SemaDiagnosticBuilder D =
4861         SemaRef.Diag(PrevInit->getSourceLocation(),
4862                      diag::warn_initializer_out_of_order);
4863 
4864       if (PrevInit->isAnyMemberInitializer())
4865         D << 0 << PrevInit->getAnyMember()->getDeclName();
4866       else
4867         D << 1 << PrevInit->getTypeSourceInfo()->getType();
4868 
4869       if (Init->isAnyMemberInitializer())
4870         D << 0 << Init->getAnyMember()->getDeclName();
4871       else
4872         D << 1 << Init->getTypeSourceInfo()->getType();
4873 
4874       // Move back to the initializer's location in the ideal list.
4875       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4876         if (InitKey == IdealInitKeys[IdealIndex])
4877           break;
4878 
4879       assert(IdealIndex < NumIdealInits &&
4880              "initializer not found in initializer list");
4881     }
4882 
4883     PrevInit = Init;
4884   }
4885 }
4886 
4887 namespace {
4888 bool CheckRedundantInit(Sema &S,
4889                         CXXCtorInitializer *Init,
4890                         CXXCtorInitializer *&PrevInit) {
4891   if (!PrevInit) {
4892     PrevInit = Init;
4893     return false;
4894   }
4895 
4896   if (FieldDecl *Field = Init->getAnyMember())
4897     S.Diag(Init->getSourceLocation(),
4898            diag::err_multiple_mem_initialization)
4899       << Field->getDeclName()
4900       << Init->getSourceRange();
4901   else {
4902     const Type *BaseClass = Init->getBaseClass();
4903     assert(BaseClass && "neither field nor base");
4904     S.Diag(Init->getSourceLocation(),
4905            diag::err_multiple_base_initialization)
4906       << QualType(BaseClass, 0)
4907       << Init->getSourceRange();
4908   }
4909   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4910     << 0 << PrevInit->getSourceRange();
4911 
4912   return true;
4913 }
4914 
4915 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
4916 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4917 
4918 bool CheckRedundantUnionInit(Sema &S,
4919                              CXXCtorInitializer *Init,
4920                              RedundantUnionMap &Unions) {
4921   FieldDecl *Field = Init->getAnyMember();
4922   RecordDecl *Parent = Field->getParent();
4923   NamedDecl *Child = Field;
4924 
4925   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
4926     if (Parent->isUnion()) {
4927       UnionEntry &En = Unions[Parent];
4928       if (En.first && En.first != Child) {
4929         S.Diag(Init->getSourceLocation(),
4930                diag::err_multiple_mem_union_initialization)
4931           << Field->getDeclName()
4932           << Init->getSourceRange();
4933         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4934           << 0 << En.second->getSourceRange();
4935         return true;
4936       }
4937       if (!En.first) {
4938         En.first = Child;
4939         En.second = Init;
4940       }
4941       if (!Parent->isAnonymousStructOrUnion())
4942         return false;
4943     }
4944 
4945     Child = Parent;
4946     Parent = cast<RecordDecl>(Parent->getDeclContext());
4947   }
4948 
4949   return false;
4950 }
4951 }
4952 
4953 /// ActOnMemInitializers - Handle the member initializers for a constructor.
4954 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
4955                                 SourceLocation ColonLoc,
4956                                 ArrayRef<CXXCtorInitializer*> MemInits,
4957                                 bool AnyErrors) {
4958   if (!ConstructorDecl)
4959     return;
4960 
4961   AdjustDeclIfTemplate(ConstructorDecl);
4962 
4963   CXXConstructorDecl *Constructor
4964     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
4965 
4966   if (!Constructor) {
4967     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4968     return;
4969   }
4970 
4971   // Mapping for the duplicate initializers check.
4972   // For member initializers, this is keyed with a FieldDecl*.
4973   // For base initializers, this is keyed with a Type*.
4974   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
4975 
4976   // Mapping for the inconsistent anonymous-union initializers check.
4977   RedundantUnionMap MemberUnions;
4978 
4979   bool HadError = false;
4980   for (unsigned i = 0; i < MemInits.size(); i++) {
4981     CXXCtorInitializer *Init = MemInits[i];
4982 
4983     // Set the source order index.
4984     Init->setSourceOrder(i);
4985 
4986     if (Init->isAnyMemberInitializer()) {
4987       const void *Key = GetKeyForMember(Context, Init);
4988       if (CheckRedundantInit(*this, Init, Members[Key]) ||
4989           CheckRedundantUnionInit(*this, Init, MemberUnions))
4990         HadError = true;
4991     } else if (Init->isBaseInitializer()) {
4992       const void *Key = GetKeyForMember(Context, Init);
4993       if (CheckRedundantInit(*this, Init, Members[Key]))
4994         HadError = true;
4995     } else {
4996       assert(Init->isDelegatingInitializer());
4997       // This must be the only initializer
4998       if (MemInits.size() != 1) {
4999         Diag(Init->getSourceLocation(),
5000              diag::err_delegating_initializer_alone)
5001           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5002         // We will treat this as being the only initializer.
5003       }
5004       SetDelegatingInitializer(Constructor, MemInits[i]);
5005       // Return immediately as the initializer is set.
5006       return;
5007     }
5008   }
5009 
5010   if (HadError)
5011     return;
5012 
5013   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5014 
5015   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5016 
5017   DiagnoseUninitializedFields(*this, Constructor);
5018 }
5019 
5020 void
5021 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5022                                              CXXRecordDecl *ClassDecl) {
5023   // Ignore dependent contexts. Also ignore unions, since their members never
5024   // have destructors implicitly called.
5025   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5026     return;
5027 
5028   // FIXME: all the access-control diagnostics are positioned on the
5029   // field/base declaration.  That's probably good; that said, the
5030   // user might reasonably want to know why the destructor is being
5031   // emitted, and we currently don't say.
5032 
5033   // Non-static data members.
5034   for (auto *Field : ClassDecl->fields()) {
5035     if (Field->isInvalidDecl())
5036       continue;
5037 
5038     // Don't destroy incomplete or zero-length arrays.
5039     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5040       continue;
5041 
5042     QualType FieldType = Context.getBaseElementType(Field->getType());
5043 
5044     const RecordType* RT = FieldType->getAs<RecordType>();
5045     if (!RT)
5046       continue;
5047 
5048     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5049     if (FieldClassDecl->isInvalidDecl())
5050       continue;
5051     if (FieldClassDecl->hasIrrelevantDestructor())
5052       continue;
5053     // The destructor for an implicit anonymous union member is never invoked.
5054     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5055       continue;
5056 
5057     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5058     assert(Dtor && "No dtor found for FieldClassDecl!");
5059     CheckDestructorAccess(Field->getLocation(), Dtor,
5060                           PDiag(diag::err_access_dtor_field)
5061                             << Field->getDeclName()
5062                             << FieldType);
5063 
5064     MarkFunctionReferenced(Location, Dtor);
5065     DiagnoseUseOfDecl(Dtor, Location);
5066   }
5067 
5068   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5069 
5070   // Bases.
5071   for (const auto &Base : ClassDecl->bases()) {
5072     // Bases are always records in a well-formed non-dependent class.
5073     const RecordType *RT = Base.getType()->getAs<RecordType>();
5074 
5075     // Remember direct virtual bases.
5076     if (Base.isVirtual())
5077       DirectVirtualBases.insert(RT);
5078 
5079     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5080     // If our base class is invalid, we probably can't get its dtor anyway.
5081     if (BaseClassDecl->isInvalidDecl())
5082       continue;
5083     if (BaseClassDecl->hasIrrelevantDestructor())
5084       continue;
5085 
5086     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5087     assert(Dtor && "No dtor found for BaseClassDecl!");
5088 
5089     // FIXME: caret should be on the start of the class name
5090     CheckDestructorAccess(Base.getLocStart(), Dtor,
5091                           PDiag(diag::err_access_dtor_base)
5092                             << Base.getType()
5093                             << Base.getSourceRange(),
5094                           Context.getTypeDeclType(ClassDecl));
5095 
5096     MarkFunctionReferenced(Location, Dtor);
5097     DiagnoseUseOfDecl(Dtor, Location);
5098   }
5099 
5100   // Virtual bases.
5101   for (const auto &VBase : ClassDecl->vbases()) {
5102     // Bases are always records in a well-formed non-dependent class.
5103     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5104 
5105     // Ignore direct virtual bases.
5106     if (DirectVirtualBases.count(RT))
5107       continue;
5108 
5109     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5110     // If our base class is invalid, we probably can't get its dtor anyway.
5111     if (BaseClassDecl->isInvalidDecl())
5112       continue;
5113     if (BaseClassDecl->hasIrrelevantDestructor())
5114       continue;
5115 
5116     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5117     assert(Dtor && "No dtor found for BaseClassDecl!");
5118     if (CheckDestructorAccess(
5119             ClassDecl->getLocation(), Dtor,
5120             PDiag(diag::err_access_dtor_vbase)
5121                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5122             Context.getTypeDeclType(ClassDecl)) ==
5123         AR_accessible) {
5124       CheckDerivedToBaseConversion(
5125           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5126           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5127           SourceRange(), DeclarationName(), nullptr);
5128     }
5129 
5130     MarkFunctionReferenced(Location, Dtor);
5131     DiagnoseUseOfDecl(Dtor, Location);
5132   }
5133 }
5134 
5135 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5136   if (!CDtorDecl)
5137     return;
5138 
5139   if (CXXConstructorDecl *Constructor
5140       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5141     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5142     DiagnoseUninitializedFields(*this, Constructor);
5143   }
5144 }
5145 
5146 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5147   if (!getLangOpts().CPlusPlus)
5148     return false;
5149 
5150   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5151   if (!RD)
5152     return false;
5153 
5154   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5155   // class template specialization here, but doing so breaks a lot of code.
5156 
5157   // We can't answer whether something is abstract until it has a
5158   // definition. If it's currently being defined, we'll walk back
5159   // over all the declarations when we have a full definition.
5160   const CXXRecordDecl *Def = RD->getDefinition();
5161   if (!Def || Def->isBeingDefined())
5162     return false;
5163 
5164   return RD->isAbstract();
5165 }
5166 
5167 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5168                                   TypeDiagnoser &Diagnoser) {
5169   if (!isAbstractType(Loc, T))
5170     return false;
5171 
5172   T = Context.getBaseElementType(T);
5173   Diagnoser.diagnose(*this, Loc, T);
5174   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5175   return true;
5176 }
5177 
5178 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5179   // Check if we've already emitted the list of pure virtual functions
5180   // for this class.
5181   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5182     return;
5183 
5184   // If the diagnostic is suppressed, don't emit the notes. We're only
5185   // going to emit them once, so try to attach them to a diagnostic we're
5186   // actually going to show.
5187   if (Diags.isLastDiagnosticIgnored())
5188     return;
5189 
5190   CXXFinalOverriderMap FinalOverriders;
5191   RD->getFinalOverriders(FinalOverriders);
5192 
5193   // Keep a set of seen pure methods so we won't diagnose the same method
5194   // more than once.
5195   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5196 
5197   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5198                                    MEnd = FinalOverriders.end();
5199        M != MEnd;
5200        ++M) {
5201     for (OverridingMethods::iterator SO = M->second.begin(),
5202                                   SOEnd = M->second.end();
5203          SO != SOEnd; ++SO) {
5204       // C++ [class.abstract]p4:
5205       //   A class is abstract if it contains or inherits at least one
5206       //   pure virtual function for which the final overrider is pure
5207       //   virtual.
5208 
5209       //
5210       if (SO->second.size() != 1)
5211         continue;
5212 
5213       if (!SO->second.front().Method->isPure())
5214         continue;
5215 
5216       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5217         continue;
5218 
5219       Diag(SO->second.front().Method->getLocation(),
5220            diag::note_pure_virtual_function)
5221         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5222     }
5223   }
5224 
5225   if (!PureVirtualClassDiagSet)
5226     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5227   PureVirtualClassDiagSet->insert(RD);
5228 }
5229 
5230 namespace {
5231 struct AbstractUsageInfo {
5232   Sema &S;
5233   CXXRecordDecl *Record;
5234   CanQualType AbstractType;
5235   bool Invalid;
5236 
5237   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5238     : S(S), Record(Record),
5239       AbstractType(S.Context.getCanonicalType(
5240                    S.Context.getTypeDeclType(Record))),
5241       Invalid(false) {}
5242 
5243   void DiagnoseAbstractType() {
5244     if (Invalid) return;
5245     S.DiagnoseAbstractType(Record);
5246     Invalid = true;
5247   }
5248 
5249   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5250 };
5251 
5252 struct CheckAbstractUsage {
5253   AbstractUsageInfo &Info;
5254   const NamedDecl *Ctx;
5255 
5256   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5257     : Info(Info), Ctx(Ctx) {}
5258 
5259   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5260     switch (TL.getTypeLocClass()) {
5261 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5262 #define TYPELOC(CLASS, PARENT) \
5263     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5264 #include "clang/AST/TypeLocNodes.def"
5265     }
5266   }
5267 
5268   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5269     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5270     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5271       if (!TL.getParam(I))
5272         continue;
5273 
5274       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5275       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5276     }
5277   }
5278 
5279   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5280     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5281   }
5282 
5283   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5284     // Visit the type parameters from a permissive context.
5285     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5286       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5287       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5288         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5289           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5290       // TODO: other template argument types?
5291     }
5292   }
5293 
5294   // Visit pointee types from a permissive context.
5295 #define CheckPolymorphic(Type) \
5296   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5297     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5298   }
5299   CheckPolymorphic(PointerTypeLoc)
5300   CheckPolymorphic(ReferenceTypeLoc)
5301   CheckPolymorphic(MemberPointerTypeLoc)
5302   CheckPolymorphic(BlockPointerTypeLoc)
5303   CheckPolymorphic(AtomicTypeLoc)
5304 
5305   /// Handle all the types we haven't given a more specific
5306   /// implementation for above.
5307   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5308     // Every other kind of type that we haven't called out already
5309     // that has an inner type is either (1) sugar or (2) contains that
5310     // inner type in some way as a subobject.
5311     if (TypeLoc Next = TL.getNextTypeLoc())
5312       return Visit(Next, Sel);
5313 
5314     // If there's no inner type and we're in a permissive context,
5315     // don't diagnose.
5316     if (Sel == Sema::AbstractNone) return;
5317 
5318     // Check whether the type matches the abstract type.
5319     QualType T = TL.getType();
5320     if (T->isArrayType()) {
5321       Sel = Sema::AbstractArrayType;
5322       T = Info.S.Context.getBaseElementType(T);
5323     }
5324     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5325     if (CT != Info.AbstractType) return;
5326 
5327     // It matched; do some magic.
5328     if (Sel == Sema::AbstractArrayType) {
5329       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5330         << T << TL.getSourceRange();
5331     } else {
5332       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5333         << Sel << T << TL.getSourceRange();
5334     }
5335     Info.DiagnoseAbstractType();
5336   }
5337 };
5338 
5339 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5340                                   Sema::AbstractDiagSelID Sel) {
5341   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5342 }
5343 
5344 }
5345 
5346 /// Check for invalid uses of an abstract type in a method declaration.
5347 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5348                                     CXXMethodDecl *MD) {
5349   // No need to do the check on definitions, which require that
5350   // the return/param types be complete.
5351   if (MD->doesThisDeclarationHaveABody())
5352     return;
5353 
5354   // For safety's sake, just ignore it if we don't have type source
5355   // information.  This should never happen for non-implicit methods,
5356   // but...
5357   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5358     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5359 }
5360 
5361 /// Check for invalid uses of an abstract type within a class definition.
5362 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5363                                     CXXRecordDecl *RD) {
5364   for (auto *D : RD->decls()) {
5365     if (D->isImplicit()) continue;
5366 
5367     // Methods and method templates.
5368     if (isa<CXXMethodDecl>(D)) {
5369       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5370     } else if (isa<FunctionTemplateDecl>(D)) {
5371       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5372       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5373 
5374     // Fields and static variables.
5375     } else if (isa<FieldDecl>(D)) {
5376       FieldDecl *FD = cast<FieldDecl>(D);
5377       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5378         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5379     } else if (isa<VarDecl>(D)) {
5380       VarDecl *VD = cast<VarDecl>(D);
5381       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5382         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5383 
5384     // Nested classes and class templates.
5385     } else if (isa<CXXRecordDecl>(D)) {
5386       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5387     } else if (isa<ClassTemplateDecl>(D)) {
5388       CheckAbstractClassUsage(Info,
5389                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5390     }
5391   }
5392 }
5393 
5394 static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) {
5395   Attr *ClassAttr = getDLLAttr(Class);
5396   if (!ClassAttr)
5397     return;
5398 
5399   assert(ClassAttr->getKind() == attr::DLLExport);
5400 
5401   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5402 
5403   if (TSK == TSK_ExplicitInstantiationDeclaration)
5404     // Don't go any further if this is just an explicit instantiation
5405     // declaration.
5406     return;
5407 
5408   for (Decl *Member : Class->decls()) {
5409     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5410     if (!MD)
5411       continue;
5412 
5413     if (Member->getAttr<DLLExportAttr>()) {
5414       if (MD->isUserProvided()) {
5415         // Instantiate non-default class member functions ...
5416 
5417         // .. except for certain kinds of template specializations.
5418         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5419           continue;
5420 
5421         S.MarkFunctionReferenced(Class->getLocation(), MD);
5422 
5423         // The function will be passed to the consumer when its definition is
5424         // encountered.
5425       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5426                  MD->isCopyAssignmentOperator() ||
5427                  MD->isMoveAssignmentOperator()) {
5428         // Synthesize and instantiate non-trivial implicit methods, explicitly
5429         // defaulted methods, and the copy and move assignment operators. The
5430         // latter are exported even if they are trivial, because the address of
5431         // an operator can be taken and should compare equal accross libraries.
5432         DiagnosticErrorTrap Trap(S.Diags);
5433         S.MarkFunctionReferenced(Class->getLocation(), MD);
5434         if (Trap.hasErrorOccurred()) {
5435           S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5436               << Class->getName() << !S.getLangOpts().CPlusPlus11;
5437           break;
5438         }
5439 
5440         // There is no later point when we will see the definition of this
5441         // function, so pass it to the consumer now.
5442         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5443       }
5444     }
5445   }
5446 }
5447 
5448 /// \brief Check class-level dllimport/dllexport attribute.
5449 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
5450   Attr *ClassAttr = getDLLAttr(Class);
5451 
5452   // MSVC inherits DLL attributes to partial class template specializations.
5453   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5454     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5455       if (Attr *TemplateAttr =
5456               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5457         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5458         A->setInherited(true);
5459         ClassAttr = A;
5460       }
5461     }
5462   }
5463 
5464   if (!ClassAttr)
5465     return;
5466 
5467   if (!Class->isExternallyVisible()) {
5468     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5469         << Class << ClassAttr;
5470     return;
5471   }
5472 
5473   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5474       !ClassAttr->isInherited()) {
5475     // Diagnose dll attributes on members of class with dll attribute.
5476     for (Decl *Member : Class->decls()) {
5477       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5478         continue;
5479       InheritableAttr *MemberAttr = getDLLAttr(Member);
5480       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5481         continue;
5482 
5483       Diag(MemberAttr->getLocation(),
5484              diag::err_attribute_dll_member_of_dll_class)
5485           << MemberAttr << ClassAttr;
5486       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5487       Member->setInvalidDecl();
5488     }
5489   }
5490 
5491   if (Class->getDescribedClassTemplate())
5492     // Don't inherit dll attribute until the template is instantiated.
5493     return;
5494 
5495   // The class is either imported or exported.
5496   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5497 
5498   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5499 
5500   // Ignore explicit dllexport on explicit class template instantiation declarations.
5501   if (ClassExported && !ClassAttr->isInherited() &&
5502       TSK == TSK_ExplicitInstantiationDeclaration) {
5503     Class->dropAttr<DLLExportAttr>();
5504     return;
5505   }
5506 
5507   // Force declaration of implicit members so they can inherit the attribute.
5508   ForceDeclarationOfImplicitMembers(Class);
5509 
5510   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5511   // seem to be true in practice?
5512 
5513   for (Decl *Member : Class->decls()) {
5514     VarDecl *VD = dyn_cast<VarDecl>(Member);
5515     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5516 
5517     // Only methods and static fields inherit the attributes.
5518     if (!VD && !MD)
5519       continue;
5520 
5521     if (MD) {
5522       // Don't process deleted methods.
5523       if (MD->isDeleted())
5524         continue;
5525 
5526       if (MD->isInlined()) {
5527         // MinGW does not import or export inline methods.
5528         if (!Context.getTargetInfo().getCXXABI().isMicrosoft())
5529           continue;
5530 
5531         // MSVC versions before 2015 don't export the move assignment operators
5532         // and move constructor, so don't attempt to import/export them if
5533         // we have a definition.
5534         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5535         if ((MD->isMoveAssignmentOperator() ||
5536              (Ctor && Ctor->isMoveConstructor())) &&
5537             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5538           continue;
5539 
5540         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5541         // operator is exported anyway.
5542         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5543             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5544           continue;
5545       }
5546     }
5547 
5548     if (!cast<NamedDecl>(Member)->isExternallyVisible())
5549       continue;
5550 
5551     if (!getDLLAttr(Member)) {
5552       auto *NewAttr =
5553           cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5554       NewAttr->setInherited(true);
5555       Member->addAttr(NewAttr);
5556     }
5557   }
5558 
5559   if (ClassExported)
5560     DelayedDllExportClasses.push_back(Class);
5561 }
5562 
5563 /// \brief Perform propagation of DLL attributes from a derived class to a
5564 /// templated base class for MS compatibility.
5565 void Sema::propagateDLLAttrToBaseClassTemplate(
5566     CXXRecordDecl *Class, Attr *ClassAttr,
5567     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5568   if (getDLLAttr(
5569           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5570     // If the base class template has a DLL attribute, don't try to change it.
5571     return;
5572   }
5573 
5574   auto TSK = BaseTemplateSpec->getSpecializationKind();
5575   if (!getDLLAttr(BaseTemplateSpec) &&
5576       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5577        TSK == TSK_ImplicitInstantiation)) {
5578     // The template hasn't been instantiated yet (or it has, but only as an
5579     // explicit instantiation declaration or implicit instantiation, which means
5580     // we haven't codegenned any members yet), so propagate the attribute.
5581     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5582     NewAttr->setInherited(true);
5583     BaseTemplateSpec->addAttr(NewAttr);
5584 
5585     // If the template is already instantiated, checkDLLAttributeRedeclaration()
5586     // needs to be run again to work see the new attribute. Otherwise this will
5587     // get run whenever the template is instantiated.
5588     if (TSK != TSK_Undeclared)
5589       checkClassLevelDLLAttribute(BaseTemplateSpec);
5590 
5591     return;
5592   }
5593 
5594   if (getDLLAttr(BaseTemplateSpec)) {
5595     // The template has already been specialized or instantiated with an
5596     // attribute, explicitly or through propagation. We should not try to change
5597     // it.
5598     return;
5599   }
5600 
5601   // The template was previously instantiated or explicitly specialized without
5602   // a dll attribute, It's too late for us to add an attribute, so warn that
5603   // this is unsupported.
5604   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5605       << BaseTemplateSpec->isExplicitSpecialization();
5606   Diag(ClassAttr->getLocation(), diag::note_attribute);
5607   if (BaseTemplateSpec->isExplicitSpecialization()) {
5608     Diag(BaseTemplateSpec->getLocation(),
5609            diag::note_template_class_explicit_specialization_was_here)
5610         << BaseTemplateSpec;
5611   } else {
5612     Diag(BaseTemplateSpec->getPointOfInstantiation(),
5613            diag::note_template_class_instantiation_was_here)
5614         << BaseTemplateSpec;
5615   }
5616 }
5617 
5618 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5619                                         SourceLocation DefaultLoc) {
5620   switch (S.getSpecialMember(MD)) {
5621   case Sema::CXXDefaultConstructor:
5622     S.DefineImplicitDefaultConstructor(DefaultLoc,
5623                                        cast<CXXConstructorDecl>(MD));
5624     break;
5625   case Sema::CXXCopyConstructor:
5626     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5627     break;
5628   case Sema::CXXCopyAssignment:
5629     S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5630     break;
5631   case Sema::CXXDestructor:
5632     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5633     break;
5634   case Sema::CXXMoveConstructor:
5635     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5636     break;
5637   case Sema::CXXMoveAssignment:
5638     S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5639     break;
5640   case Sema::CXXInvalid:
5641     llvm_unreachable("Invalid special member.");
5642   }
5643 }
5644 
5645 /// \brief Perform semantic checks on a class definition that has been
5646 /// completing, introducing implicitly-declared members, checking for
5647 /// abstract types, etc.
5648 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
5649   if (!Record)
5650     return;
5651 
5652   if (Record->isAbstract() && !Record->isInvalidDecl()) {
5653     AbstractUsageInfo Info(*this, Record);
5654     CheckAbstractClassUsage(Info, Record);
5655   }
5656 
5657   // If this is not an aggregate type and has no user-declared constructor,
5658   // complain about any non-static data members of reference or const scalar
5659   // type, since they will never get initializers.
5660   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
5661       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
5662       !Record->isLambda()) {
5663     bool Complained = false;
5664     for (const auto *F : Record->fields()) {
5665       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
5666         continue;
5667 
5668       if (F->getType()->isReferenceType() ||
5669           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
5670         if (!Complained) {
5671           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
5672             << Record->getTagKind() << Record;
5673           Complained = true;
5674         }
5675 
5676         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
5677           << F->getType()->isReferenceType()
5678           << F->getDeclName();
5679       }
5680     }
5681   }
5682 
5683   if (Record->getIdentifier()) {
5684     // C++ [class.mem]p13:
5685     //   If T is the name of a class, then each of the following shall have a
5686     //   name different from T:
5687     //     - every member of every anonymous union that is a member of class T.
5688     //
5689     // C++ [class.mem]p14:
5690     //   In addition, if class T has a user-declared constructor (12.1), every
5691     //   non-static data member of class T shall have a name different from T.
5692     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
5693     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
5694          ++I) {
5695       NamedDecl *D = *I;
5696       if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
5697           isa<IndirectFieldDecl>(D)) {
5698         Diag(D->getLocation(), diag::err_member_name_of_class)
5699           << D->getDeclName();
5700         break;
5701       }
5702     }
5703   }
5704 
5705   // Warn if the class has virtual methods but non-virtual public destructor.
5706   if (Record->isPolymorphic() && !Record->isDependentType()) {
5707     CXXDestructorDecl *dtor = Record->getDestructor();
5708     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
5709         !Record->hasAttr<FinalAttr>())
5710       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
5711            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
5712   }
5713 
5714   if (Record->isAbstract()) {
5715     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
5716       Diag(Record->getLocation(), diag::warn_abstract_final_class)
5717         << FA->isSpelledAsSealed();
5718       DiagnoseAbstractType(Record);
5719     }
5720   }
5721 
5722   bool HasMethodWithOverrideControl = false,
5723        HasOverridingMethodWithoutOverrideControl = false;
5724   if (!Record->isDependentType()) {
5725     for (auto *M : Record->methods()) {
5726       // See if a method overloads virtual methods in a base
5727       // class without overriding any.
5728       if (!M->isStatic())
5729         DiagnoseHiddenVirtualMethods(M);
5730       if (M->hasAttr<OverrideAttr>())
5731         HasMethodWithOverrideControl = true;
5732       else if (M->size_overridden_methods() > 0)
5733         HasOverridingMethodWithoutOverrideControl = true;
5734       // Check whether the explicitly-defaulted special members are valid.
5735       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
5736         CheckExplicitlyDefaultedSpecialMember(M);
5737 
5738       // For an explicitly defaulted or deleted special member, we defer
5739       // determining triviality until the class is complete. That time is now!
5740       CXXSpecialMember CSM = getSpecialMember(M);
5741       if (!M->isImplicit() && !M->isUserProvided()) {
5742         if (CSM != CXXInvalid) {
5743           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
5744 
5745           // Inform the class that we've finished declaring this member.
5746           Record->finishedDefaultedOrDeletedMember(M);
5747         }
5748       }
5749 
5750       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
5751           M->hasAttr<DLLExportAttr>()) {
5752         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5753             M->isTrivial() &&
5754             (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
5755              CSM == CXXDestructor))
5756           M->dropAttr<DLLExportAttr>();
5757 
5758         if (M->hasAttr<DLLExportAttr>()) {
5759           DefineImplicitSpecialMember(*this, M, M->getLocation());
5760           ActOnFinishInlineFunctionDef(M);
5761         }
5762       }
5763     }
5764   }
5765 
5766   if (HasMethodWithOverrideControl &&
5767       HasOverridingMethodWithoutOverrideControl) {
5768     // At least one method has the 'override' control declared.
5769     // Diagnose all other overridden methods which do not have 'override' specified on them.
5770     for (auto *M : Record->methods())
5771       DiagnoseAbsenceOfOverrideControl(M);
5772   }
5773 
5774   // ms_struct is a request to use the same ABI rules as MSVC.  Check
5775   // whether this class uses any C++ features that are implemented
5776   // completely differently in MSVC, and if so, emit a diagnostic.
5777   // That diagnostic defaults to an error, but we allow projects to
5778   // map it down to a warning (or ignore it).  It's a fairly common
5779   // practice among users of the ms_struct pragma to mass-annotate
5780   // headers, sweeping up a bunch of types that the project doesn't
5781   // really rely on MSVC-compatible layout for.  We must therefore
5782   // support "ms_struct except for C++ stuff" as a secondary ABI.
5783   if (Record->isMsStruct(Context) &&
5784       (Record->isPolymorphic() || Record->getNumBases())) {
5785     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
5786   }
5787 
5788   checkClassLevelDLLAttribute(Record);
5789 }
5790 
5791 /// Look up the special member function that would be called by a special
5792 /// member function for a subobject of class type.
5793 ///
5794 /// \param Class The class type of the subobject.
5795 /// \param CSM The kind of special member function.
5796 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
5797 /// \param ConstRHS True if this is a copy operation with a const object
5798 ///        on its RHS, that is, if the argument to the outer special member
5799 ///        function is 'const' and this is not a field marked 'mutable'.
5800 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
5801     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
5802     unsigned FieldQuals, bool ConstRHS) {
5803   unsigned LHSQuals = 0;
5804   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
5805     LHSQuals = FieldQuals;
5806 
5807   unsigned RHSQuals = FieldQuals;
5808   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
5809     RHSQuals = 0;
5810   else if (ConstRHS)
5811     RHSQuals |= Qualifiers::Const;
5812 
5813   return S.LookupSpecialMember(Class, CSM,
5814                                RHSQuals & Qualifiers::Const,
5815                                RHSQuals & Qualifiers::Volatile,
5816                                false,
5817                                LHSQuals & Qualifiers::Const,
5818                                LHSQuals & Qualifiers::Volatile);
5819 }
5820 
5821 class Sema::InheritedConstructorInfo {
5822   Sema &S;
5823   SourceLocation UseLoc;
5824 
5825   /// A mapping from the base classes through which the constructor was
5826   /// inherited to the using shadow declaration in that base class (or a null
5827   /// pointer if the constructor was declared in that base class).
5828   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
5829       InheritedFromBases;
5830 
5831 public:
5832   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
5833                            ConstructorUsingShadowDecl *Shadow)
5834       : S(S), UseLoc(UseLoc) {
5835     bool DiagnosedMultipleConstructedBases = false;
5836     CXXRecordDecl *ConstructedBase = nullptr;
5837     UsingDecl *ConstructedBaseUsing = nullptr;
5838 
5839     // Find the set of such base class subobjects and check that there's a
5840     // unique constructed subobject.
5841     for (auto *D : Shadow->redecls()) {
5842       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
5843       auto *DNominatedBase = DShadow->getNominatedBaseClass();
5844       auto *DConstructedBase = DShadow->getConstructedBaseClass();
5845 
5846       InheritedFromBases.insert(
5847           std::make_pair(DNominatedBase->getCanonicalDecl(),
5848                          DShadow->getNominatedBaseClassShadowDecl()));
5849       if (DShadow->constructsVirtualBase())
5850         InheritedFromBases.insert(
5851             std::make_pair(DConstructedBase->getCanonicalDecl(),
5852                            DShadow->getConstructedBaseClassShadowDecl()));
5853       else
5854         assert(DNominatedBase == DConstructedBase);
5855 
5856       // [class.inhctor.init]p2:
5857       //   If the constructor was inherited from multiple base class subobjects
5858       //   of type B, the program is ill-formed.
5859       if (!ConstructedBase) {
5860         ConstructedBase = DConstructedBase;
5861         ConstructedBaseUsing = D->getUsingDecl();
5862       } else if (ConstructedBase != DConstructedBase &&
5863                  !Shadow->isInvalidDecl()) {
5864         if (!DiagnosedMultipleConstructedBases) {
5865           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
5866               << Shadow->getTargetDecl();
5867           S.Diag(ConstructedBaseUsing->getLocation(),
5868                diag::note_ambiguous_inherited_constructor_using)
5869               << ConstructedBase;
5870           DiagnosedMultipleConstructedBases = true;
5871         }
5872         S.Diag(D->getUsingDecl()->getLocation(),
5873                diag::note_ambiguous_inherited_constructor_using)
5874             << DConstructedBase;
5875       }
5876     }
5877 
5878     if (DiagnosedMultipleConstructedBases)
5879       Shadow->setInvalidDecl();
5880   }
5881 
5882   /// Find the constructor to use for inherited construction of a base class,
5883   /// and whether that base class constructor inherits the constructor from a
5884   /// virtual base class (in which case it won't actually invoke it).
5885   std::pair<CXXConstructorDecl *, bool>
5886   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
5887     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
5888     if (It == InheritedFromBases.end())
5889       return std::make_pair(nullptr, false);
5890 
5891     // This is an intermediary class.
5892     if (It->second)
5893       return std::make_pair(
5894           S.findInheritingConstructor(UseLoc, Ctor, It->second),
5895           It->second->constructsVirtualBase());
5896 
5897     // This is the base class from which the constructor was inherited.
5898     return std::make_pair(Ctor, false);
5899   }
5900 };
5901 
5902 /// Is the special member function which would be selected to perform the
5903 /// specified operation on the specified class type a constexpr constructor?
5904 static bool
5905 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5906                          Sema::CXXSpecialMember CSM, unsigned Quals,
5907                          bool ConstRHS,
5908                          CXXConstructorDecl *InheritedCtor = nullptr,
5909                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
5910   // If we're inheriting a constructor, see if we need to call it for this base
5911   // class.
5912   if (InheritedCtor) {
5913     assert(CSM == Sema::CXXDefaultConstructor);
5914     auto BaseCtor =
5915         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
5916     if (BaseCtor)
5917       return BaseCtor->isConstexpr();
5918   }
5919 
5920   if (CSM == Sema::CXXDefaultConstructor)
5921     return ClassDecl->hasConstexprDefaultConstructor();
5922 
5923   Sema::SpecialMemberOverloadResult *SMOR =
5924       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
5925   if (!SMOR || !SMOR->getMethod())
5926     // A constructor we wouldn't select can't be "involved in initializing"
5927     // anything.
5928     return true;
5929   return SMOR->getMethod()->isConstexpr();
5930 }
5931 
5932 /// Determine whether the specified special member function would be constexpr
5933 /// if it were implicitly defined.
5934 static bool defaultedSpecialMemberIsConstexpr(
5935     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
5936     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
5937     Sema::InheritedConstructorInfo *Inherited = nullptr) {
5938   if (!S.getLangOpts().CPlusPlus11)
5939     return false;
5940 
5941   // C++11 [dcl.constexpr]p4:
5942   // In the definition of a constexpr constructor [...]
5943   bool Ctor = true;
5944   switch (CSM) {
5945   case Sema::CXXDefaultConstructor:
5946     if (Inherited)
5947       break;
5948     // Since default constructor lookup is essentially trivial (and cannot
5949     // involve, for instance, template instantiation), we compute whether a
5950     // defaulted default constructor is constexpr directly within CXXRecordDecl.
5951     //
5952     // This is important for performance; we need to know whether the default
5953     // constructor is constexpr to determine whether the type is a literal type.
5954     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
5955 
5956   case Sema::CXXCopyConstructor:
5957   case Sema::CXXMoveConstructor:
5958     // For copy or move constructors, we need to perform overload resolution.
5959     break;
5960 
5961   case Sema::CXXCopyAssignment:
5962   case Sema::CXXMoveAssignment:
5963     if (!S.getLangOpts().CPlusPlus14)
5964       return false;
5965     // In C++1y, we need to perform overload resolution.
5966     Ctor = false;
5967     break;
5968 
5969   case Sema::CXXDestructor:
5970   case Sema::CXXInvalid:
5971     return false;
5972   }
5973 
5974   //   -- if the class is a non-empty union, or for each non-empty anonymous
5975   //      union member of a non-union class, exactly one non-static data member
5976   //      shall be initialized; [DR1359]
5977   //
5978   // If we squint, this is guaranteed, since exactly one non-static data member
5979   // will be initialized (if the constructor isn't deleted), we just don't know
5980   // which one.
5981   if (Ctor && ClassDecl->isUnion())
5982     return CSM == Sema::CXXDefaultConstructor
5983                ? ClassDecl->hasInClassInitializer() ||
5984                      !ClassDecl->hasVariantMembers()
5985                : true;
5986 
5987   //   -- the class shall not have any virtual base classes;
5988   if (Ctor && ClassDecl->getNumVBases())
5989     return false;
5990 
5991   // C++1y [class.copy]p26:
5992   //   -- [the class] is a literal type, and
5993   if (!Ctor && !ClassDecl->isLiteral())
5994     return false;
5995 
5996   //   -- every constructor involved in initializing [...] base class
5997   //      sub-objects shall be a constexpr constructor;
5998   //   -- the assignment operator selected to copy/move each direct base
5999   //      class is a constexpr function, and
6000   for (const auto &B : ClassDecl->bases()) {
6001     const RecordType *BaseType = B.getType()->getAs<RecordType>();
6002     if (!BaseType) continue;
6003 
6004     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6005     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6006                                   InheritedCtor, Inherited))
6007       return false;
6008   }
6009 
6010   //   -- every constructor involved in initializing non-static data members
6011   //      [...] shall be a constexpr constructor;
6012   //   -- every non-static data member and base class sub-object shall be
6013   //      initialized
6014   //   -- for each non-static data member of X that is of class type (or array
6015   //      thereof), the assignment operator selected to copy/move that member is
6016   //      a constexpr function
6017   for (const auto *F : ClassDecl->fields()) {
6018     if (F->isInvalidDecl())
6019       continue;
6020     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6021       continue;
6022     QualType BaseType = S.Context.getBaseElementType(F->getType());
6023     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
6024       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6025       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6026                                     BaseType.getCVRQualifiers(),
6027                                     ConstArg && !F->isMutable()))
6028         return false;
6029     } else if (CSM == Sema::CXXDefaultConstructor) {
6030       return false;
6031     }
6032   }
6033 
6034   // All OK, it's constexpr!
6035   return true;
6036 }
6037 
6038 static Sema::ImplicitExceptionSpecification
6039 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6040   switch (S.getSpecialMember(MD)) {
6041   case Sema::CXXDefaultConstructor:
6042     return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
6043   case Sema::CXXCopyConstructor:
6044     return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
6045   case Sema::CXXCopyAssignment:
6046     return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
6047   case Sema::CXXMoveConstructor:
6048     return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
6049   case Sema::CXXMoveAssignment:
6050     return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
6051   case Sema::CXXDestructor:
6052     return S.ComputeDefaultedDtorExceptionSpec(MD);
6053   case Sema::CXXInvalid:
6054     break;
6055   }
6056   assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
6057          "only special members have implicit exception specs");
6058   return S.ComputeInheritingCtorExceptionSpec(Loc,
6059                                               cast<CXXConstructorDecl>(MD));
6060 }
6061 
6062 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6063                                                             CXXMethodDecl *MD) {
6064   FunctionProtoType::ExtProtoInfo EPI;
6065 
6066   // Build an exception specification pointing back at this member.
6067   EPI.ExceptionSpec.Type = EST_Unevaluated;
6068   EPI.ExceptionSpec.SourceDecl = MD;
6069 
6070   // Set the calling convention to the default for C++ instance methods.
6071   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6072       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6073                                             /*IsCXXMethod=*/true));
6074   return EPI;
6075 }
6076 
6077 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6078   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6079   if (FPT->getExceptionSpecType() != EST_Unevaluated)
6080     return;
6081 
6082   // Evaluate the exception specification.
6083   auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
6084 
6085   // Update the type of the special member to use it.
6086   UpdateExceptionSpec(MD, ESI);
6087 
6088   // A user-provided destructor can be defined outside the class. When that
6089   // happens, be sure to update the exception specification on both
6090   // declarations.
6091   const FunctionProtoType *CanonicalFPT =
6092     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6093   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
6094     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
6095 }
6096 
6097 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6098   CXXRecordDecl *RD = MD->getParent();
6099   CXXSpecialMember CSM = getSpecialMember(MD);
6100 
6101   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6102          "not an explicitly-defaulted special member");
6103 
6104   // Whether this was the first-declared instance of the constructor.
6105   // This affects whether we implicitly add an exception spec and constexpr.
6106   bool First = MD == MD->getCanonicalDecl();
6107 
6108   bool HadError = false;
6109 
6110   // C++11 [dcl.fct.def.default]p1:
6111   //   A function that is explicitly defaulted shall
6112   //     -- be a special member function (checked elsewhere),
6113   //     -- have the same type (except for ref-qualifiers, and except that a
6114   //        copy operation can take a non-const reference) as an implicit
6115   //        declaration, and
6116   //     -- not have default arguments.
6117   unsigned ExpectedParams = 1;
6118   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6119     ExpectedParams = 0;
6120   if (MD->getNumParams() != ExpectedParams) {
6121     // This also checks for default arguments: a copy or move constructor with a
6122     // default argument is classified as a default constructor, and assignment
6123     // operations and destructors can't have default arguments.
6124     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6125       << CSM << MD->getSourceRange();
6126     HadError = true;
6127   } else if (MD->isVariadic()) {
6128     Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6129       << CSM << MD->getSourceRange();
6130     HadError = true;
6131   }
6132 
6133   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
6134 
6135   bool CanHaveConstParam = false;
6136   if (CSM == CXXCopyConstructor)
6137     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
6138   else if (CSM == CXXCopyAssignment)
6139     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
6140 
6141   QualType ReturnType = Context.VoidTy;
6142   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6143     // Check for return type matching.
6144     ReturnType = Type->getReturnType();
6145     QualType ExpectedReturnType =
6146         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
6147     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6148       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6149         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6150       HadError = true;
6151     }
6152 
6153     // A defaulted special member cannot have cv-qualifiers.
6154     if (Type->getTypeQuals()) {
6155       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
6156         << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
6157       HadError = true;
6158     }
6159   }
6160 
6161   // Check for parameter type matching.
6162   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
6163   bool HasConstParam = false;
6164   if (ExpectedParams && ArgType->isReferenceType()) {
6165     // Argument must be reference to possibly-const T.
6166     QualType ReferentType = ArgType->getPointeeType();
6167     HasConstParam = ReferentType.isConstQualified();
6168 
6169     if (ReferentType.isVolatileQualified()) {
6170       Diag(MD->getLocation(),
6171            diag::err_defaulted_special_member_volatile_param) << CSM;
6172       HadError = true;
6173     }
6174 
6175     if (HasConstParam && !CanHaveConstParam) {
6176       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6177         Diag(MD->getLocation(),
6178              diag::err_defaulted_special_member_copy_const_param)
6179           << (CSM == CXXCopyAssignment);
6180         // FIXME: Explain why this special member can't be const.
6181       } else {
6182         Diag(MD->getLocation(),
6183              diag::err_defaulted_special_member_move_const_param)
6184           << (CSM == CXXMoveAssignment);
6185       }
6186       HadError = true;
6187     }
6188   } else if (ExpectedParams) {
6189     // A copy assignment operator can take its argument by value, but a
6190     // defaulted one cannot.
6191     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
6192     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
6193     HadError = true;
6194   }
6195 
6196   // C++11 [dcl.fct.def.default]p2:
6197   //   An explicitly-defaulted function may be declared constexpr only if it
6198   //   would have been implicitly declared as constexpr,
6199   // Do not apply this rule to members of class templates, since core issue 1358
6200   // makes such functions always instantiate to constexpr functions. For
6201   // functions which cannot be constexpr (for non-constructors in C++11 and for
6202   // destructors in C++1y), this is checked elsewhere.
6203   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6204                                                      HasConstParam);
6205   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
6206                                  : isa<CXXConstructorDecl>(MD)) &&
6207       MD->isConstexpr() && !Constexpr &&
6208       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6209     Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
6210     // FIXME: Explain why the special member can't be constexpr.
6211     HadError = true;
6212   }
6213 
6214   //   and may have an explicit exception-specification only if it is compatible
6215   //   with the exception-specification on the implicit declaration.
6216   if (Type->hasExceptionSpec()) {
6217     // Delay the check if this is the first declaration of the special member,
6218     // since we may not have parsed some necessary in-class initializers yet.
6219     if (First) {
6220       // If the exception specification needs to be instantiated, do so now,
6221       // before we clobber it with an EST_Unevaluated specification below.
6222       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
6223         InstantiateExceptionSpec(MD->getLocStart(), MD);
6224         Type = MD->getType()->getAs<FunctionProtoType>();
6225       }
6226       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
6227     } else
6228       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
6229   }
6230 
6231   //   If a function is explicitly defaulted on its first declaration,
6232   if (First) {
6233     //  -- it is implicitly considered to be constexpr if the implicit
6234     //     definition would be,
6235     MD->setConstexpr(Constexpr);
6236 
6237     //  -- it is implicitly considered to have the same exception-specification
6238     //     as if it had been implicitly declared,
6239     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
6240     EPI.ExceptionSpec.Type = EST_Unevaluated;
6241     EPI.ExceptionSpec.SourceDecl = MD;
6242     MD->setType(Context.getFunctionType(ReturnType,
6243                                         llvm::makeArrayRef(&ArgType,
6244                                                            ExpectedParams),
6245                                         EPI));
6246   }
6247 
6248   if (ShouldDeleteSpecialMember(MD, CSM)) {
6249     if (First) {
6250       SetDeclDeleted(MD, MD->getLocation());
6251     } else {
6252       // C++11 [dcl.fct.def.default]p4:
6253       //   [For a] user-provided explicitly-defaulted function [...] if such a
6254       //   function is implicitly defined as deleted, the program is ill-formed.
6255       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
6256       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6257       HadError = true;
6258     }
6259   }
6260 
6261   if (HadError)
6262     MD->setInvalidDecl();
6263 }
6264 
6265 /// Check whether the exception specification provided for an
6266 /// explicitly-defaulted special member matches the exception specification
6267 /// that would have been generated for an implicit special member, per
6268 /// C++11 [dcl.fct.def.default]p2.
6269 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
6270     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
6271   // If the exception specification was explicitly specified but hadn't been
6272   // parsed when the method was defaulted, grab it now.
6273   if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
6274     SpecifiedType =
6275         MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
6276 
6277   // Compute the implicit exception specification.
6278   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6279                                                        /*IsCXXMethod=*/true);
6280   FunctionProtoType::ExtProtoInfo EPI(CC);
6281   EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
6282                           .getExceptionSpec();
6283   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
6284     Context.getFunctionType(Context.VoidTy, None, EPI));
6285 
6286   // Ensure that it matches.
6287   CheckEquivalentExceptionSpec(
6288     PDiag(diag::err_incorrect_defaulted_exception_spec)
6289       << getSpecialMember(MD), PDiag(),
6290     ImplicitType, SourceLocation(),
6291     SpecifiedType, MD->getLocation());
6292 }
6293 
6294 void Sema::CheckDelayedMemberExceptionSpecs() {
6295   decltype(DelayedExceptionSpecChecks) Checks;
6296   decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
6297 
6298   std::swap(Checks, DelayedExceptionSpecChecks);
6299   std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
6300 
6301   // Perform any deferred checking of exception specifications for virtual
6302   // destructors.
6303   for (auto &Check : Checks)
6304     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
6305 
6306   // Check that any explicitly-defaulted methods have exception specifications
6307   // compatible with their implicit exception specifications.
6308   for (auto &Spec : Specs)
6309     CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
6310 }
6311 
6312 namespace {
6313 struct SpecialMemberDeletionInfo {
6314   Sema &S;
6315   CXXMethodDecl *MD;
6316   Sema::CXXSpecialMember CSM;
6317   Sema::InheritedConstructorInfo *ICI;
6318   bool Diagnose;
6319 
6320   // Properties of the special member, computed for convenience.
6321   bool IsConstructor, IsAssignment, IsMove, ConstArg;
6322   SourceLocation Loc;
6323 
6324   bool AllFieldsAreConst;
6325 
6326   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
6327                             Sema::CXXSpecialMember CSM,
6328                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
6329       : S(S), MD(MD), CSM(CSM), ICI(ICI), Diagnose(Diagnose),
6330         IsConstructor(false), IsAssignment(false), IsMove(false),
6331         ConstArg(false), Loc(MD->getLocation()), AllFieldsAreConst(true) {
6332     switch (CSM) {
6333       case Sema::CXXDefaultConstructor:
6334       case Sema::CXXCopyConstructor:
6335         IsConstructor = true;
6336         break;
6337       case Sema::CXXMoveConstructor:
6338         IsConstructor = true;
6339         IsMove = true;
6340         break;
6341       case Sema::CXXCopyAssignment:
6342         IsAssignment = true;
6343         break;
6344       case Sema::CXXMoveAssignment:
6345         IsAssignment = true;
6346         IsMove = true;
6347         break;
6348       case Sema::CXXDestructor:
6349         break;
6350       case Sema::CXXInvalid:
6351         llvm_unreachable("invalid special member kind");
6352     }
6353 
6354     if (MD->getNumParams()) {
6355       if (const ReferenceType *RT =
6356               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6357         ConstArg = RT->getPointeeType().isConstQualified();
6358     }
6359   }
6360 
6361   bool inUnion() const { return MD->getParent()->isUnion(); }
6362 
6363   Sema::CXXSpecialMember getEffectiveCSM() {
6364     return ICI ? Sema::CXXInvalid : CSM;
6365   }
6366 
6367   /// Look up the corresponding special member in the given class.
6368   Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
6369                                               unsigned Quals, bool IsMutable) {
6370     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6371                                        ConstArg && !IsMutable);
6372   }
6373 
6374   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6375 
6376   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
6377   bool shouldDeleteForField(FieldDecl *FD);
6378   bool shouldDeleteForAllConstMembers();
6379 
6380   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6381                                      unsigned Quals);
6382   bool shouldDeleteForSubobjectCall(Subobject Subobj,
6383                                     Sema::SpecialMemberOverloadResult *SMOR,
6384                                     bool IsDtorCallInCtor);
6385 
6386   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
6387 };
6388 }
6389 
6390 /// Is the given special member inaccessible when used on the given
6391 /// sub-object.
6392 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6393                                              CXXMethodDecl *target) {
6394   /// If we're operating on a base class, the object type is the
6395   /// type of this special member.
6396   QualType objectTy;
6397   AccessSpecifier access = target->getAccess();
6398   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6399     objectTy = S.Context.getTypeDeclType(MD->getParent());
6400     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6401 
6402   // If we're operating on a field, the object type is the type of the field.
6403   } else {
6404     objectTy = S.Context.getTypeDeclType(target->getParent());
6405   }
6406 
6407   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6408 }
6409 
6410 /// Check whether we should delete a special member due to the implicit
6411 /// definition containing a call to a special member of a subobject.
6412 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
6413     Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
6414     bool IsDtorCallInCtor) {
6415   CXXMethodDecl *Decl = SMOR->getMethod();
6416   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6417 
6418   int DiagKind = -1;
6419 
6420   if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
6421     DiagKind = !Decl ? 0 : 1;
6422   else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6423     DiagKind = 2;
6424   else if (!isAccessible(Subobj, Decl))
6425     DiagKind = 3;
6426   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6427            !Decl->isTrivial()) {
6428     // A member of a union must have a trivial corresponding special member.
6429     // As a weird special case, a destructor call from a union's constructor
6430     // must be accessible and non-deleted, but need not be trivial. Such a
6431     // destructor is never actually called, but is semantically checked as
6432     // if it were.
6433     DiagKind = 4;
6434   }
6435 
6436   if (DiagKind == -1)
6437     return false;
6438 
6439   if (Diagnose) {
6440     if (Field) {
6441       S.Diag(Field->getLocation(),
6442              diag::note_deleted_special_member_class_subobject)
6443         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
6444         << Field << DiagKind << IsDtorCallInCtor;
6445     } else {
6446       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6447       S.Diag(Base->getLocStart(),
6448              diag::note_deleted_special_member_class_subobject)
6449         << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6450         << Base->getType() << DiagKind << IsDtorCallInCtor;
6451     }
6452 
6453     if (DiagKind == 1)
6454       S.NoteDeletedFunction(Decl);
6455     // FIXME: Explain inaccessibility if DiagKind == 3.
6456   }
6457 
6458   return true;
6459 }
6460 
6461 /// Check whether we should delete a special member function due to having a
6462 /// direct or virtual base class or non-static data member of class type M.
6463 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
6464     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
6465   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6466   bool IsMutable = Field && Field->isMutable();
6467 
6468   // C++11 [class.ctor]p5:
6469   // -- any direct or virtual base class, or non-static data member with no
6470   //    brace-or-equal-initializer, has class type M (or array thereof) and
6471   //    either M has no default constructor or overload resolution as applied
6472   //    to M's default constructor results in an ambiguity or in a function
6473   //    that is deleted or inaccessible
6474   // C++11 [class.copy]p11, C++11 [class.copy]p23:
6475   // -- a direct or virtual base class B that cannot be copied/moved because
6476   //    overload resolution, as applied to B's corresponding special member,
6477   //    results in an ambiguity or a function that is deleted or inaccessible
6478   //    from the defaulted special member
6479   // C++11 [class.dtor]p5:
6480   // -- any direct or virtual base class [...] has a type with a destructor
6481   //    that is deleted or inaccessible
6482   if (!(CSM == Sema::CXXDefaultConstructor &&
6483         Field && Field->hasInClassInitializer()) &&
6484       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
6485                                    false))
6486     return true;
6487 
6488   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
6489   // -- any direct or virtual base class or non-static data member has a
6490   //    type with a destructor that is deleted or inaccessible
6491   if (IsConstructor) {
6492     Sema::SpecialMemberOverloadResult *SMOR =
6493         S.LookupSpecialMember(Class, Sema::CXXDestructor,
6494                               false, false, false, false, false);
6495     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
6496       return true;
6497   }
6498 
6499   return false;
6500 }
6501 
6502 /// Check whether we should delete a special member function due to the class
6503 /// having a particular direct or virtual base class.
6504 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
6505   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
6506   // If program is correct, BaseClass cannot be null, but if it is, the error
6507   // must be reported elsewhere.
6508   if (!BaseClass)
6509     return false;
6510   // If we have an inheriting constructor, check whether we're calling an
6511   // inherited constructor instead of a default constructor.
6512   if (ICI) {
6513     assert(CSM == Sema::CXXDefaultConstructor);
6514     auto *BaseCtor =
6515         ICI->findConstructorForBase(BaseClass, cast<CXXConstructorDecl>(MD)
6516                                                    ->getInheritedConstructor()
6517                                                    .getConstructor())
6518             .first;
6519     if (BaseCtor) {
6520       if (BaseCtor->isDeleted() && Diagnose) {
6521         S.Diag(Base->getLocStart(),
6522                diag::note_deleted_special_member_class_subobject)
6523           << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6524           << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false;
6525         S.NoteDeletedFunction(BaseCtor);
6526       }
6527       return BaseCtor->isDeleted();
6528     }
6529   }
6530   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
6531 }
6532 
6533 /// Check whether we should delete a special member function due to the class
6534 /// having a particular non-static data member.
6535 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
6536   QualType FieldType = S.Context.getBaseElementType(FD->getType());
6537   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
6538 
6539   if (CSM == Sema::CXXDefaultConstructor) {
6540     // For a default constructor, all references must be initialized in-class
6541     // and, if a union, it must have a non-const member.
6542     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
6543       if (Diagnose)
6544         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
6545           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
6546       return true;
6547     }
6548     // C++11 [class.ctor]p5: any non-variant non-static data member of
6549     // const-qualified type (or array thereof) with no
6550     // brace-or-equal-initializer does not have a user-provided default
6551     // constructor.
6552     if (!inUnion() && FieldType.isConstQualified() &&
6553         !FD->hasInClassInitializer() &&
6554         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
6555       if (Diagnose)
6556         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
6557           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
6558       return true;
6559     }
6560 
6561     if (inUnion() && !FieldType.isConstQualified())
6562       AllFieldsAreConst = false;
6563   } else if (CSM == Sema::CXXCopyConstructor) {
6564     // For a copy constructor, data members must not be of rvalue reference
6565     // type.
6566     if (FieldType->isRValueReferenceType()) {
6567       if (Diagnose)
6568         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
6569           << MD->getParent() << FD << FieldType;
6570       return true;
6571     }
6572   } else if (IsAssignment) {
6573     // For an assignment operator, data members must not be of reference type.
6574     if (FieldType->isReferenceType()) {
6575       if (Diagnose)
6576         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
6577           << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
6578       return true;
6579     }
6580     if (!FieldRecord && FieldType.isConstQualified()) {
6581       // C++11 [class.copy]p23:
6582       // -- a non-static data member of const non-class type (or array thereof)
6583       if (Diagnose)
6584         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
6585           << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
6586       return true;
6587     }
6588   }
6589 
6590   if (FieldRecord) {
6591     // Some additional restrictions exist on the variant members.
6592     if (!inUnion() && FieldRecord->isUnion() &&
6593         FieldRecord->isAnonymousStructOrUnion()) {
6594       bool AllVariantFieldsAreConst = true;
6595 
6596       // FIXME: Handle anonymous unions declared within anonymous unions.
6597       for (auto *UI : FieldRecord->fields()) {
6598         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
6599 
6600         if (!UnionFieldType.isConstQualified())
6601           AllVariantFieldsAreConst = false;
6602 
6603         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
6604         if (UnionFieldRecord &&
6605             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
6606                                           UnionFieldType.getCVRQualifiers()))
6607           return true;
6608       }
6609 
6610       // At least one member in each anonymous union must be non-const
6611       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
6612           !FieldRecord->field_empty()) {
6613         if (Diagnose)
6614           S.Diag(FieldRecord->getLocation(),
6615                  diag::note_deleted_default_ctor_all_const)
6616             << !!ICI << MD->getParent() << /*anonymous union*/1;
6617         return true;
6618       }
6619 
6620       // Don't check the implicit member of the anonymous union type.
6621       // This is technically non-conformant, but sanity demands it.
6622       return false;
6623     }
6624 
6625     if (shouldDeleteForClassSubobject(FieldRecord, FD,
6626                                       FieldType.getCVRQualifiers()))
6627       return true;
6628   }
6629 
6630   return false;
6631 }
6632 
6633 /// C++11 [class.ctor] p5:
6634 ///   A defaulted default constructor for a class X is defined as deleted if
6635 /// X is a union and all of its variant members are of const-qualified type.
6636 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
6637   // This is a silly definition, because it gives an empty union a deleted
6638   // default constructor. Don't do that.
6639   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
6640       !MD->getParent()->field_empty()) {
6641     if (Diagnose)
6642       S.Diag(MD->getParent()->getLocation(),
6643              diag::note_deleted_default_ctor_all_const)
6644         << !!ICI << MD->getParent() << /*not anonymous union*/0;
6645     return true;
6646   }
6647   return false;
6648 }
6649 
6650 /// Determine whether a defaulted special member function should be defined as
6651 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
6652 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
6653 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
6654                                      InheritedConstructorInfo *ICI,
6655                                      bool Diagnose) {
6656   if (MD->isInvalidDecl())
6657     return false;
6658   CXXRecordDecl *RD = MD->getParent();
6659   assert(!RD->isDependentType() && "do deletion after instantiation");
6660   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
6661     return false;
6662 
6663   // C++11 [expr.lambda.prim]p19:
6664   //   The closure type associated with a lambda-expression has a
6665   //   deleted (8.4.3) default constructor and a deleted copy
6666   //   assignment operator.
6667   if (RD->isLambda() &&
6668       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
6669     if (Diagnose)
6670       Diag(RD->getLocation(), diag::note_lambda_decl);
6671     return true;
6672   }
6673 
6674   // For an anonymous struct or union, the copy and assignment special members
6675   // will never be used, so skip the check. For an anonymous union declared at
6676   // namespace scope, the constructor and destructor are used.
6677   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
6678       RD->isAnonymousStructOrUnion())
6679     return false;
6680 
6681   // C++11 [class.copy]p7, p18:
6682   //   If the class definition declares a move constructor or move assignment
6683   //   operator, an implicitly declared copy constructor or copy assignment
6684   //   operator is defined as deleted.
6685   if (MD->isImplicit() &&
6686       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
6687     CXXMethodDecl *UserDeclaredMove = nullptr;
6688 
6689     // In Microsoft mode, a user-declared move only causes the deletion of the
6690     // corresponding copy operation, not both copy operations.
6691     if (RD->hasUserDeclaredMoveConstructor() &&
6692         (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
6693       if (!Diagnose) return true;
6694 
6695       // Find any user-declared move constructor.
6696       for (auto *I : RD->ctors()) {
6697         if (I->isMoveConstructor()) {
6698           UserDeclaredMove = I;
6699           break;
6700         }
6701       }
6702       assert(UserDeclaredMove);
6703     } else if (RD->hasUserDeclaredMoveAssignment() &&
6704                (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
6705       if (!Diagnose) return true;
6706 
6707       // Find any user-declared move assignment operator.
6708       for (auto *I : RD->methods()) {
6709         if (I->isMoveAssignmentOperator()) {
6710           UserDeclaredMove = I;
6711           break;
6712         }
6713       }
6714       assert(UserDeclaredMove);
6715     }
6716 
6717     if (UserDeclaredMove) {
6718       Diag(UserDeclaredMove->getLocation(),
6719            diag::note_deleted_copy_user_declared_move)
6720         << (CSM == CXXCopyAssignment) << RD
6721         << UserDeclaredMove->isMoveAssignmentOperator();
6722       return true;
6723     }
6724   }
6725 
6726   // Do access control from the special member function
6727   ContextRAII MethodContext(*this, MD);
6728 
6729   // C++11 [class.dtor]p5:
6730   // -- for a virtual destructor, lookup of the non-array deallocation function
6731   //    results in an ambiguity or in a function that is deleted or inaccessible
6732   if (CSM == CXXDestructor && MD->isVirtual()) {
6733     FunctionDecl *OperatorDelete = nullptr;
6734     DeclarationName Name =
6735       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6736     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
6737                                  OperatorDelete, false)) {
6738       if (Diagnose)
6739         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
6740       return true;
6741     }
6742   }
6743 
6744   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
6745 
6746   for (auto &BI : RD->bases())
6747     if (!BI.isVirtual() &&
6748         SMI.shouldDeleteForBase(&BI))
6749       return true;
6750 
6751   // Per DR1611, do not consider virtual bases of constructors of abstract
6752   // classes, since we are not going to construct them.
6753   if (!RD->isAbstract() || !SMI.IsConstructor) {
6754     for (auto &BI : RD->vbases())
6755       if (SMI.shouldDeleteForBase(&BI))
6756         return true;
6757   }
6758 
6759   for (auto *FI : RD->fields())
6760     if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
6761         SMI.shouldDeleteForField(FI))
6762       return true;
6763 
6764   if (SMI.shouldDeleteForAllConstMembers())
6765     return true;
6766 
6767   if (getLangOpts().CUDA) {
6768     // We should delete the special member in CUDA mode if target inference
6769     // failed.
6770     return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
6771                                                    Diagnose);
6772   }
6773 
6774   return false;
6775 }
6776 
6777 /// Perform lookup for a special member of the specified kind, and determine
6778 /// whether it is trivial. If the triviality can be determined without the
6779 /// lookup, skip it. This is intended for use when determining whether a
6780 /// special member of a containing object is trivial, and thus does not ever
6781 /// perform overload resolution for default constructors.
6782 ///
6783 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
6784 /// member that was most likely to be intended to be trivial, if any.
6785 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
6786                                      Sema::CXXSpecialMember CSM, unsigned Quals,
6787                                      bool ConstRHS, CXXMethodDecl **Selected) {
6788   if (Selected)
6789     *Selected = nullptr;
6790 
6791   switch (CSM) {
6792   case Sema::CXXInvalid:
6793     llvm_unreachable("not a special member");
6794 
6795   case Sema::CXXDefaultConstructor:
6796     // C++11 [class.ctor]p5:
6797     //   A default constructor is trivial if:
6798     //    - all the [direct subobjects] have trivial default constructors
6799     //
6800     // Note, no overload resolution is performed in this case.
6801     if (RD->hasTrivialDefaultConstructor())
6802       return true;
6803 
6804     if (Selected) {
6805       // If there's a default constructor which could have been trivial, dig it
6806       // out. Otherwise, if there's any user-provided default constructor, point
6807       // to that as an example of why there's not a trivial one.
6808       CXXConstructorDecl *DefCtor = nullptr;
6809       if (RD->needsImplicitDefaultConstructor())
6810         S.DeclareImplicitDefaultConstructor(RD);
6811       for (auto *CI : RD->ctors()) {
6812         if (!CI->isDefaultConstructor())
6813           continue;
6814         DefCtor = CI;
6815         if (!DefCtor->isUserProvided())
6816           break;
6817       }
6818 
6819       *Selected = DefCtor;
6820     }
6821 
6822     return false;
6823 
6824   case Sema::CXXDestructor:
6825     // C++11 [class.dtor]p5:
6826     //   A destructor is trivial if:
6827     //    - all the direct [subobjects] have trivial destructors
6828     if (RD->hasTrivialDestructor())
6829       return true;
6830 
6831     if (Selected) {
6832       if (RD->needsImplicitDestructor())
6833         S.DeclareImplicitDestructor(RD);
6834       *Selected = RD->getDestructor();
6835     }
6836 
6837     return false;
6838 
6839   case Sema::CXXCopyConstructor:
6840     // C++11 [class.copy]p12:
6841     //   A copy constructor is trivial if:
6842     //    - the constructor selected to copy each direct [subobject] is trivial
6843     if (RD->hasTrivialCopyConstructor()) {
6844       if (Quals == Qualifiers::Const)
6845         // We must either select the trivial copy constructor or reach an
6846         // ambiguity; no need to actually perform overload resolution.
6847         return true;
6848     } else if (!Selected) {
6849       return false;
6850     }
6851     // In C++98, we are not supposed to perform overload resolution here, but we
6852     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
6853     // cases like B as having a non-trivial copy constructor:
6854     //   struct A { template<typename T> A(T&); };
6855     //   struct B { mutable A a; };
6856     goto NeedOverloadResolution;
6857 
6858   case Sema::CXXCopyAssignment:
6859     // C++11 [class.copy]p25:
6860     //   A copy assignment operator is trivial if:
6861     //    - the assignment operator selected to copy each direct [subobject] is
6862     //      trivial
6863     if (RD->hasTrivialCopyAssignment()) {
6864       if (Quals == Qualifiers::Const)
6865         return true;
6866     } else if (!Selected) {
6867       return false;
6868     }
6869     // In C++98, we are not supposed to perform overload resolution here, but we
6870     // treat that as a language defect.
6871     goto NeedOverloadResolution;
6872 
6873   case Sema::CXXMoveConstructor:
6874   case Sema::CXXMoveAssignment:
6875   NeedOverloadResolution:
6876     Sema::SpecialMemberOverloadResult *SMOR =
6877         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
6878 
6879     // The standard doesn't describe how to behave if the lookup is ambiguous.
6880     // We treat it as not making the member non-trivial, just like the standard
6881     // mandates for the default constructor. This should rarely matter, because
6882     // the member will also be deleted.
6883     if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6884       return true;
6885 
6886     if (!SMOR->getMethod()) {
6887       assert(SMOR->getKind() ==
6888              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
6889       return false;
6890     }
6891 
6892     // We deliberately don't check if we found a deleted special member. We're
6893     // not supposed to!
6894     if (Selected)
6895       *Selected = SMOR->getMethod();
6896     return SMOR->getMethod()->isTrivial();
6897   }
6898 
6899   llvm_unreachable("unknown special method kind");
6900 }
6901 
6902 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
6903   for (auto *CI : RD->ctors())
6904     if (!CI->isImplicit())
6905       return CI;
6906 
6907   // Look for constructor templates.
6908   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
6909   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
6910     if (CXXConstructorDecl *CD =
6911           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
6912       return CD;
6913   }
6914 
6915   return nullptr;
6916 }
6917 
6918 /// The kind of subobject we are checking for triviality. The values of this
6919 /// enumeration are used in diagnostics.
6920 enum TrivialSubobjectKind {
6921   /// The subobject is a base class.
6922   TSK_BaseClass,
6923   /// The subobject is a non-static data member.
6924   TSK_Field,
6925   /// The object is actually the complete object.
6926   TSK_CompleteObject
6927 };
6928 
6929 /// Check whether the special member selected for a given type would be trivial.
6930 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
6931                                       QualType SubType, bool ConstRHS,
6932                                       Sema::CXXSpecialMember CSM,
6933                                       TrivialSubobjectKind Kind,
6934                                       bool Diagnose) {
6935   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
6936   if (!SubRD)
6937     return true;
6938 
6939   CXXMethodDecl *Selected;
6940   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
6941                                ConstRHS, Diagnose ? &Selected : nullptr))
6942     return true;
6943 
6944   if (Diagnose) {
6945     if (ConstRHS)
6946       SubType.addConst();
6947 
6948     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
6949       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
6950         << Kind << SubType.getUnqualifiedType();
6951       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
6952         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
6953     } else if (!Selected)
6954       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
6955         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
6956     else if (Selected->isUserProvided()) {
6957       if (Kind == TSK_CompleteObject)
6958         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
6959           << Kind << SubType.getUnqualifiedType() << CSM;
6960       else {
6961         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
6962           << Kind << SubType.getUnqualifiedType() << CSM;
6963         S.Diag(Selected->getLocation(), diag::note_declared_at);
6964       }
6965     } else {
6966       if (Kind != TSK_CompleteObject)
6967         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
6968           << Kind << SubType.getUnqualifiedType() << CSM;
6969 
6970       // Explain why the defaulted or deleted special member isn't trivial.
6971       S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
6972     }
6973   }
6974 
6975   return false;
6976 }
6977 
6978 /// Check whether the members of a class type allow a special member to be
6979 /// trivial.
6980 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
6981                                      Sema::CXXSpecialMember CSM,
6982                                      bool ConstArg, bool Diagnose) {
6983   for (const auto *FI : RD->fields()) {
6984     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
6985       continue;
6986 
6987     QualType FieldType = S.Context.getBaseElementType(FI->getType());
6988 
6989     // Pretend anonymous struct or union members are members of this class.
6990     if (FI->isAnonymousStructOrUnion()) {
6991       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
6992                                     CSM, ConstArg, Diagnose))
6993         return false;
6994       continue;
6995     }
6996 
6997     // C++11 [class.ctor]p5:
6998     //   A default constructor is trivial if [...]
6999     //    -- no non-static data member of its class has a
7000     //       brace-or-equal-initializer
7001     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7002       if (Diagnose)
7003         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
7004       return false;
7005     }
7006 
7007     // Objective C ARC 4.3.5:
7008     //   [...] nontrivally ownership-qualified types are [...] not trivially
7009     //   default constructible, copy constructible, move constructible, copy
7010     //   assignable, move assignable, or destructible [...]
7011     if (S.getLangOpts().ObjCAutoRefCount &&
7012         FieldType.hasNonTrivialObjCLifetime()) {
7013       if (Diagnose)
7014         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7015           << RD << FieldType.getObjCLifetime();
7016       return false;
7017     }
7018 
7019     bool ConstRHS = ConstArg && !FI->isMutable();
7020     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7021                                    CSM, TSK_Field, Diagnose))
7022       return false;
7023   }
7024 
7025   return true;
7026 }
7027 
7028 /// Diagnose why the specified class does not have a trivial special member of
7029 /// the given kind.
7030 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7031   QualType Ty = Context.getRecordType(RD);
7032 
7033   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7034   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
7035                             TSK_CompleteObject, /*Diagnose*/true);
7036 }
7037 
7038 /// Determine whether a defaulted or deleted special member function is trivial,
7039 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7040 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7041 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7042                                   bool Diagnose) {
7043   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7044 
7045   CXXRecordDecl *RD = MD->getParent();
7046 
7047   bool ConstArg = false;
7048 
7049   // C++11 [class.copy]p12, p25: [DR1593]
7050   //   A [special member] is trivial if [...] its parameter-type-list is
7051   //   equivalent to the parameter-type-list of an implicit declaration [...]
7052   switch (CSM) {
7053   case CXXDefaultConstructor:
7054   case CXXDestructor:
7055     // Trivial default constructors and destructors cannot have parameters.
7056     break;
7057 
7058   case CXXCopyConstructor:
7059   case CXXCopyAssignment: {
7060     // Trivial copy operations always have const, non-volatile parameter types.
7061     ConstArg = true;
7062     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7063     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7064     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7065       if (Diagnose)
7066         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7067           << Param0->getSourceRange() << Param0->getType()
7068           << Context.getLValueReferenceType(
7069                Context.getRecordType(RD).withConst());
7070       return false;
7071     }
7072     break;
7073   }
7074 
7075   case CXXMoveConstructor:
7076   case CXXMoveAssignment: {
7077     // Trivial move operations always have non-cv-qualified parameters.
7078     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7079     const RValueReferenceType *RT =
7080       Param0->getType()->getAs<RValueReferenceType>();
7081     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7082       if (Diagnose)
7083         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7084           << Param0->getSourceRange() << Param0->getType()
7085           << Context.getRValueReferenceType(Context.getRecordType(RD));
7086       return false;
7087     }
7088     break;
7089   }
7090 
7091   case CXXInvalid:
7092     llvm_unreachable("not a special member");
7093   }
7094 
7095   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7096     if (Diagnose)
7097       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7098            diag::note_nontrivial_default_arg)
7099         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7100     return false;
7101   }
7102   if (MD->isVariadic()) {
7103     if (Diagnose)
7104       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7105     return false;
7106   }
7107 
7108   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7109   //   A copy/move [constructor or assignment operator] is trivial if
7110   //    -- the [member] selected to copy/move each direct base class subobject
7111   //       is trivial
7112   //
7113   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7114   //   A [default constructor or destructor] is trivial if
7115   //    -- all the direct base classes have trivial [default constructors or
7116   //       destructors]
7117   for (const auto &BI : RD->bases())
7118     if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
7119                                    ConstArg, CSM, TSK_BaseClass, Diagnose))
7120       return false;
7121 
7122   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7123   //   A copy/move [constructor or assignment operator] for a class X is
7124   //   trivial if
7125   //    -- for each non-static data member of X that is of class type (or array
7126   //       thereof), the constructor selected to copy/move that member is
7127   //       trivial
7128   //
7129   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7130   //   A [default constructor or destructor] is trivial if
7131   //    -- for all of the non-static data members of its class that are of class
7132   //       type (or array thereof), each such class has a trivial [default
7133   //       constructor or destructor]
7134   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
7135     return false;
7136 
7137   // C++11 [class.dtor]p5:
7138   //   A destructor is trivial if [...]
7139   //    -- the destructor is not virtual
7140   if (CSM == CXXDestructor && MD->isVirtual()) {
7141     if (Diagnose)
7142       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7143     return false;
7144   }
7145 
7146   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7147   //   A [special member] for class X is trivial if [...]
7148   //    -- class X has no virtual functions and no virtual base classes
7149   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7150     if (!Diagnose)
7151       return false;
7152 
7153     if (RD->getNumVBases()) {
7154       // Check for virtual bases. We already know that the corresponding
7155       // member in all bases is trivial, so vbases must all be direct.
7156       CXXBaseSpecifier &BS = *RD->vbases_begin();
7157       assert(BS.isVirtual());
7158       Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
7159       return false;
7160     }
7161 
7162     // Must have a virtual method.
7163     for (const auto *MI : RD->methods()) {
7164       if (MI->isVirtual()) {
7165         SourceLocation MLoc = MI->getLocStart();
7166         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7167         return false;
7168       }
7169     }
7170 
7171     llvm_unreachable("dynamic class with no vbases and no virtual functions");
7172   }
7173 
7174   // Looks like it's trivial!
7175   return true;
7176 }
7177 
7178 namespace {
7179 struct FindHiddenVirtualMethod {
7180   Sema *S;
7181   CXXMethodDecl *Method;
7182   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7183   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7184 
7185 private:
7186   /// Check whether any most overriden method from MD in Methods
7187   static bool CheckMostOverridenMethods(
7188       const CXXMethodDecl *MD,
7189       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7190     if (MD->size_overridden_methods() == 0)
7191       return Methods.count(MD->getCanonicalDecl());
7192     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7193                                         E = MD->end_overridden_methods();
7194          I != E; ++I)
7195       if (CheckMostOverridenMethods(*I, Methods))
7196         return true;
7197     return false;
7198   }
7199 
7200 public:
7201   /// Member lookup function that determines whether a given C++
7202   /// method overloads virtual methods in a base class without overriding any,
7203   /// to be used with CXXRecordDecl::lookupInBases().
7204   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7205     RecordDecl *BaseRecord =
7206         Specifier->getType()->getAs<RecordType>()->getDecl();
7207 
7208     DeclarationName Name = Method->getDeclName();
7209     assert(Name.getNameKind() == DeclarationName::Identifier);
7210 
7211     bool foundSameNameMethod = false;
7212     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7213     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7214          Path.Decls = Path.Decls.slice(1)) {
7215       NamedDecl *D = Path.Decls.front();
7216       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7217         MD = MD->getCanonicalDecl();
7218         foundSameNameMethod = true;
7219         // Interested only in hidden virtual methods.
7220         if (!MD->isVirtual())
7221           continue;
7222         // If the method we are checking overrides a method from its base
7223         // don't warn about the other overloaded methods. Clang deviates from
7224         // GCC by only diagnosing overloads of inherited virtual functions that
7225         // do not override any other virtual functions in the base. GCC's
7226         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7227         // function from a base class. These cases may be better served by a
7228         // warning (not specific to virtual functions) on call sites when the
7229         // call would select a different function from the base class, were it
7230         // visible.
7231         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7232         if (!S->IsOverload(Method, MD, false))
7233           return true;
7234         // Collect the overload only if its hidden.
7235         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7236           overloadedMethods.push_back(MD);
7237       }
7238     }
7239 
7240     if (foundSameNameMethod)
7241       OverloadedMethods.append(overloadedMethods.begin(),
7242                                overloadedMethods.end());
7243     return foundSameNameMethod;
7244   }
7245 };
7246 } // end anonymous namespace
7247 
7248 /// \brief Add the most overriden methods from MD to Methods
7249 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
7250                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
7251   if (MD->size_overridden_methods() == 0)
7252     Methods.insert(MD->getCanonicalDecl());
7253   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7254                                       E = MD->end_overridden_methods();
7255        I != E; ++I)
7256     AddMostOverridenMethods(*I, Methods);
7257 }
7258 
7259 /// \brief Check if a method overloads virtual methods in a base class without
7260 /// overriding any.
7261 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7262                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7263   if (!MD->getDeclName().isIdentifier())
7264     return;
7265 
7266   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7267                      /*bool RecordPaths=*/false,
7268                      /*bool DetectVirtual=*/false);
7269   FindHiddenVirtualMethod FHVM;
7270   FHVM.Method = MD;
7271   FHVM.S = this;
7272 
7273   // Keep the base methods that were overriden or introduced in the subclass
7274   // by 'using' in a set. A base method not in this set is hidden.
7275   CXXRecordDecl *DC = MD->getParent();
7276   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7277   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7278     NamedDecl *ND = *I;
7279     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
7280       ND = shad->getTargetDecl();
7281     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7282       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
7283   }
7284 
7285   if (DC->lookupInBases(FHVM, Paths))
7286     OverloadedMethods = FHVM.OverloadedMethods;
7287 }
7288 
7289 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7290                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7291   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7292     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7293     PartialDiagnostic PD = PDiag(
7294          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7295     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7296     Diag(overloadedMD->getLocation(), PD);
7297   }
7298 }
7299 
7300 /// \brief Diagnose methods which overload virtual methods in a base class
7301 /// without overriding any.
7302 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7303   if (MD->isInvalidDecl())
7304     return;
7305 
7306   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
7307     return;
7308 
7309   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7310   FindHiddenVirtualMethods(MD, OverloadedMethods);
7311   if (!OverloadedMethods.empty()) {
7312     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7313       << MD << (OverloadedMethods.size() > 1);
7314 
7315     NoteHiddenVirtualMethods(MD, OverloadedMethods);
7316   }
7317 }
7318 
7319 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
7320                                              Decl *TagDecl,
7321                                              SourceLocation LBrac,
7322                                              SourceLocation RBrac,
7323                                              AttributeList *AttrList) {
7324   if (!TagDecl)
7325     return;
7326 
7327   AdjustDeclIfTemplate(TagDecl);
7328 
7329   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
7330     if (l->getKind() != AttributeList::AT_Visibility)
7331       continue;
7332     l->setInvalid();
7333     Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
7334       l->getName();
7335   }
7336 
7337   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
7338               // strict aliasing violation!
7339               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
7340               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
7341 
7342   CheckCompletedCXXClass(
7343                         dyn_cast_or_null<CXXRecordDecl>(TagDecl));
7344 }
7345 
7346 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7347 /// special functions, such as the default constructor, copy
7348 /// constructor, or destructor, to the given C++ class (C++
7349 /// [special]p1).  This routine can only be executed just before the
7350 /// definition of the class is complete.
7351 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
7352   if (ClassDecl->needsImplicitDefaultConstructor()) {
7353     ++ASTContext::NumImplicitDefaultConstructors;
7354 
7355     if (ClassDecl->hasInheritedConstructor())
7356       DeclareImplicitDefaultConstructor(ClassDecl);
7357   }
7358 
7359   if (ClassDecl->needsImplicitCopyConstructor()) {
7360     ++ASTContext::NumImplicitCopyConstructors;
7361 
7362     // If the properties or semantics of the copy constructor couldn't be
7363     // determined while the class was being declared, force a declaration
7364     // of it now.
7365     if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7366         ClassDecl->hasInheritedConstructor())
7367       DeclareImplicitCopyConstructor(ClassDecl);
7368   }
7369 
7370   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
7371     ++ASTContext::NumImplicitMoveConstructors;
7372 
7373     if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7374         ClassDecl->hasInheritedConstructor())
7375       DeclareImplicitMoveConstructor(ClassDecl);
7376   }
7377 
7378   if (ClassDecl->needsImplicitCopyAssignment()) {
7379     ++ASTContext::NumImplicitCopyAssignmentOperators;
7380 
7381     // If we have a dynamic class, then the copy assignment operator may be
7382     // virtual, so we have to declare it immediately. This ensures that, e.g.,
7383     // it shows up in the right place in the vtable and that we diagnose
7384     // problems with the implicit exception specification.
7385     if (ClassDecl->isDynamicClass() ||
7386         ClassDecl->needsOverloadResolutionForCopyAssignment() ||
7387         ClassDecl->hasInheritedAssignment())
7388       DeclareImplicitCopyAssignment(ClassDecl);
7389   }
7390 
7391   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
7392     ++ASTContext::NumImplicitMoveAssignmentOperators;
7393 
7394     // Likewise for the move assignment operator.
7395     if (ClassDecl->isDynamicClass() ||
7396         ClassDecl->needsOverloadResolutionForMoveAssignment() ||
7397         ClassDecl->hasInheritedAssignment())
7398       DeclareImplicitMoveAssignment(ClassDecl);
7399   }
7400 
7401   if (ClassDecl->needsImplicitDestructor()) {
7402     ++ASTContext::NumImplicitDestructors;
7403 
7404     // If we have a dynamic class, then the destructor may be virtual, so we
7405     // have to declare the destructor immediately. This ensures that, e.g., it
7406     // shows up in the right place in the vtable and that we diagnose problems
7407     // with the implicit exception specification.
7408     if (ClassDecl->isDynamicClass() ||
7409         ClassDecl->needsOverloadResolutionForDestructor())
7410       DeclareImplicitDestructor(ClassDecl);
7411   }
7412 }
7413 
7414 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
7415   if (!D)
7416     return 0;
7417 
7418   // The order of template parameters is not important here. All names
7419   // get added to the same scope.
7420   SmallVector<TemplateParameterList *, 4> ParameterLists;
7421 
7422   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
7423     D = TD->getTemplatedDecl();
7424 
7425   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
7426     ParameterLists.push_back(PSD->getTemplateParameters());
7427 
7428   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
7429     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
7430       ParameterLists.push_back(DD->getTemplateParameterList(i));
7431 
7432     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7433       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
7434         ParameterLists.push_back(FTD->getTemplateParameters());
7435     }
7436   }
7437 
7438   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
7439     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
7440       ParameterLists.push_back(TD->getTemplateParameterList(i));
7441 
7442     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
7443       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
7444         ParameterLists.push_back(CTD->getTemplateParameters());
7445     }
7446   }
7447 
7448   unsigned Count = 0;
7449   for (TemplateParameterList *Params : ParameterLists) {
7450     if (Params->size() > 0)
7451       // Ignore explicit specializations; they don't contribute to the template
7452       // depth.
7453       ++Count;
7454     for (NamedDecl *Param : *Params) {
7455       if (Param->getDeclName()) {
7456         S->AddDecl(Param);
7457         IdResolver.AddDecl(Param);
7458       }
7459     }
7460   }
7461 
7462   return Count;
7463 }
7464 
7465 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7466   if (!RecordD) return;
7467   AdjustDeclIfTemplate(RecordD);
7468   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
7469   PushDeclContext(S, Record);
7470 }
7471 
7472 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7473   if (!RecordD) return;
7474   PopDeclContext();
7475 }
7476 
7477 /// This is used to implement the constant expression evaluation part of the
7478 /// attribute enable_if extension. There is nothing in standard C++ which would
7479 /// require reentering parameters.
7480 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
7481   if (!Param)
7482     return;
7483 
7484   S->AddDecl(Param);
7485   if (Param->getDeclName())
7486     IdResolver.AddDecl(Param);
7487 }
7488 
7489 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
7490 /// parsing a top-level (non-nested) C++ class, and we are now
7491 /// parsing those parts of the given Method declaration that could
7492 /// not be parsed earlier (C++ [class.mem]p2), such as default
7493 /// arguments. This action should enter the scope of the given
7494 /// Method declaration as if we had just parsed the qualified method
7495 /// name. However, it should not bring the parameters into scope;
7496 /// that will be performed by ActOnDelayedCXXMethodParameter.
7497 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
7498 }
7499 
7500 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
7501 /// C++ method declaration. We're (re-)introducing the given
7502 /// function parameter into scope for use in parsing later parts of
7503 /// the method declaration. For example, we could see an
7504 /// ActOnParamDefaultArgument event for this parameter.
7505 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
7506   if (!ParamD)
7507     return;
7508 
7509   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
7510 
7511   // If this parameter has an unparsed default argument, clear it out
7512   // to make way for the parsed default argument.
7513   if (Param->hasUnparsedDefaultArg())
7514     Param->setDefaultArg(nullptr);
7515 
7516   S->AddDecl(Param);
7517   if (Param->getDeclName())
7518     IdResolver.AddDecl(Param);
7519 }
7520 
7521 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
7522 /// processing the delayed method declaration for Method. The method
7523 /// declaration is now considered finished. There may be a separate
7524 /// ActOnStartOfFunctionDef action later (not necessarily
7525 /// immediately!) for this method, if it was also defined inside the
7526 /// class body.
7527 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
7528   if (!MethodD)
7529     return;
7530 
7531   AdjustDeclIfTemplate(MethodD);
7532 
7533   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
7534 
7535   // Now that we have our default arguments, check the constructor
7536   // again. It could produce additional diagnostics or affect whether
7537   // the class has implicitly-declared destructors, among other
7538   // things.
7539   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
7540     CheckConstructor(Constructor);
7541 
7542   // Check the default arguments, which we may have added.
7543   if (!Method->isInvalidDecl())
7544     CheckCXXDefaultArguments(Method);
7545 }
7546 
7547 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
7548 /// the well-formedness of the constructor declarator @p D with type @p
7549 /// R. If there are any errors in the declarator, this routine will
7550 /// emit diagnostics and set the invalid bit to true.  In any case, the type
7551 /// will be updated to reflect a well-formed type for the constructor and
7552 /// returned.
7553 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
7554                                           StorageClass &SC) {
7555   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7556 
7557   // C++ [class.ctor]p3:
7558   //   A constructor shall not be virtual (10.3) or static (9.4). A
7559   //   constructor can be invoked for a const, volatile or const
7560   //   volatile object. A constructor shall not be declared const,
7561   //   volatile, or const volatile (9.3.2).
7562   if (isVirtual) {
7563     if (!D.isInvalidType())
7564       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7565         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
7566         << SourceRange(D.getIdentifierLoc());
7567     D.setInvalidType();
7568   }
7569   if (SC == SC_Static) {
7570     if (!D.isInvalidType())
7571       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7572         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7573         << SourceRange(D.getIdentifierLoc());
7574     D.setInvalidType();
7575     SC = SC_None;
7576   }
7577 
7578   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7579     diagnoseIgnoredQualifiers(
7580         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
7581         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
7582         D.getDeclSpec().getRestrictSpecLoc(),
7583         D.getDeclSpec().getAtomicSpecLoc());
7584     D.setInvalidType();
7585   }
7586 
7587   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7588   if (FTI.TypeQuals != 0) {
7589     if (FTI.TypeQuals & Qualifiers::Const)
7590       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7591         << "const" << SourceRange(D.getIdentifierLoc());
7592     if (FTI.TypeQuals & Qualifiers::Volatile)
7593       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7594         << "volatile" << SourceRange(D.getIdentifierLoc());
7595     if (FTI.TypeQuals & Qualifiers::Restrict)
7596       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7597         << "restrict" << SourceRange(D.getIdentifierLoc());
7598     D.setInvalidType();
7599   }
7600 
7601   // C++0x [class.ctor]p4:
7602   //   A constructor shall not be declared with a ref-qualifier.
7603   if (FTI.hasRefQualifier()) {
7604     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
7605       << FTI.RefQualifierIsLValueRef
7606       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7607     D.setInvalidType();
7608   }
7609 
7610   // Rebuild the function type "R" without any type qualifiers (in
7611   // case any of the errors above fired) and with "void" as the
7612   // return type, since constructors don't have return types.
7613   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
7614   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
7615     return R;
7616 
7617   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
7618   EPI.TypeQuals = 0;
7619   EPI.RefQualifier = RQ_None;
7620 
7621   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
7622 }
7623 
7624 /// CheckConstructor - Checks a fully-formed constructor for
7625 /// well-formedness, issuing any diagnostics required. Returns true if
7626 /// the constructor declarator is invalid.
7627 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
7628   CXXRecordDecl *ClassDecl
7629     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
7630   if (!ClassDecl)
7631     return Constructor->setInvalidDecl();
7632 
7633   // C++ [class.copy]p3:
7634   //   A declaration of a constructor for a class X is ill-formed if
7635   //   its first parameter is of type (optionally cv-qualified) X and
7636   //   either there are no other parameters or else all other
7637   //   parameters have default arguments.
7638   if (!Constructor->isInvalidDecl() &&
7639       ((Constructor->getNumParams() == 1) ||
7640        (Constructor->getNumParams() > 1 &&
7641         Constructor->getParamDecl(1)->hasDefaultArg())) &&
7642       Constructor->getTemplateSpecializationKind()
7643                                               != TSK_ImplicitInstantiation) {
7644     QualType ParamType = Constructor->getParamDecl(0)->getType();
7645     QualType ClassTy = Context.getTagDeclType(ClassDecl);
7646     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
7647       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
7648       const char *ConstRef
7649         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
7650                                                         : " const &";
7651       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
7652         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
7653 
7654       // FIXME: Rather that making the constructor invalid, we should endeavor
7655       // to fix the type.
7656       Constructor->setInvalidDecl();
7657     }
7658   }
7659 }
7660 
7661 /// CheckDestructor - Checks a fully-formed destructor definition for
7662 /// well-formedness, issuing any diagnostics required.  Returns true
7663 /// on error.
7664 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
7665   CXXRecordDecl *RD = Destructor->getParent();
7666 
7667   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
7668     SourceLocation Loc;
7669 
7670     if (!Destructor->isImplicit())
7671       Loc = Destructor->getLocation();
7672     else
7673       Loc = RD->getLocation();
7674 
7675     // If we have a virtual destructor, look up the deallocation function
7676     FunctionDecl *OperatorDelete = nullptr;
7677     DeclarationName Name =
7678     Context.DeclarationNames.getCXXOperatorName(OO_Delete);
7679     if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
7680       return true;
7681     // If there's no class-specific operator delete, look up the global
7682     // non-array delete.
7683     if (!OperatorDelete)
7684       OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
7685 
7686     MarkFunctionReferenced(Loc, OperatorDelete);
7687 
7688     Destructor->setOperatorDelete(OperatorDelete);
7689   }
7690 
7691   return false;
7692 }
7693 
7694 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
7695 /// the well-formednes of the destructor declarator @p D with type @p
7696 /// R. If there are any errors in the declarator, this routine will
7697 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
7698 /// will be updated to reflect a well-formed type for the destructor and
7699 /// returned.
7700 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
7701                                          StorageClass& SC) {
7702   // C++ [class.dtor]p1:
7703   //   [...] A typedef-name that names a class is a class-name
7704   //   (7.1.3); however, a typedef-name that names a class shall not
7705   //   be used as the identifier in the declarator for a destructor
7706   //   declaration.
7707   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
7708   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
7709     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
7710       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
7711   else if (const TemplateSpecializationType *TST =
7712              DeclaratorType->getAs<TemplateSpecializationType>())
7713     if (TST->isTypeAlias())
7714       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
7715         << DeclaratorType << 1;
7716 
7717   // C++ [class.dtor]p2:
7718   //   A destructor is used to destroy objects of its class type. A
7719   //   destructor takes no parameters, and no return type can be
7720   //   specified for it (not even void). The address of a destructor
7721   //   shall not be taken. A destructor shall not be static. A
7722   //   destructor can be invoked for a const, volatile or const
7723   //   volatile object. A destructor shall not be declared const,
7724   //   volatile or const volatile (9.3.2).
7725   if (SC == SC_Static) {
7726     if (!D.isInvalidType())
7727       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
7728         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7729         << SourceRange(D.getIdentifierLoc())
7730         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7731 
7732     SC = SC_None;
7733   }
7734   if (!D.isInvalidType()) {
7735     // Destructors don't have return types, but the parser will
7736     // happily parse something like:
7737     //
7738     //   class X {
7739     //     float ~X();
7740     //   };
7741     //
7742     // The return type will be eliminated later.
7743     if (D.getDeclSpec().hasTypeSpecifier())
7744       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
7745         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7746         << SourceRange(D.getIdentifierLoc());
7747     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7748       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
7749                                 SourceLocation(),
7750                                 D.getDeclSpec().getConstSpecLoc(),
7751                                 D.getDeclSpec().getVolatileSpecLoc(),
7752                                 D.getDeclSpec().getRestrictSpecLoc(),
7753                                 D.getDeclSpec().getAtomicSpecLoc());
7754       D.setInvalidType();
7755     }
7756   }
7757 
7758   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7759   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
7760     if (FTI.TypeQuals & Qualifiers::Const)
7761       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7762         << "const" << SourceRange(D.getIdentifierLoc());
7763     if (FTI.TypeQuals & Qualifiers::Volatile)
7764       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7765         << "volatile" << SourceRange(D.getIdentifierLoc());
7766     if (FTI.TypeQuals & Qualifiers::Restrict)
7767       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7768         << "restrict" << SourceRange(D.getIdentifierLoc());
7769     D.setInvalidType();
7770   }
7771 
7772   // C++0x [class.dtor]p2:
7773   //   A destructor shall not be declared with a ref-qualifier.
7774   if (FTI.hasRefQualifier()) {
7775     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
7776       << FTI.RefQualifierIsLValueRef
7777       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7778     D.setInvalidType();
7779   }
7780 
7781   // Make sure we don't have any parameters.
7782   if (FTIHasNonVoidParameters(FTI)) {
7783     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
7784 
7785     // Delete the parameters.
7786     FTI.freeParams();
7787     D.setInvalidType();
7788   }
7789 
7790   // Make sure the destructor isn't variadic.
7791   if (FTI.isVariadic) {
7792     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
7793     D.setInvalidType();
7794   }
7795 
7796   // Rebuild the function type "R" without any type qualifiers or
7797   // parameters (in case any of the errors above fired) and with
7798   // "void" as the return type, since destructors don't have return
7799   // types.
7800   if (!D.isInvalidType())
7801     return R;
7802 
7803   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
7804   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
7805   EPI.Variadic = false;
7806   EPI.TypeQuals = 0;
7807   EPI.RefQualifier = RQ_None;
7808   return Context.getFunctionType(Context.VoidTy, None, EPI);
7809 }
7810 
7811 static void extendLeft(SourceRange &R, SourceRange Before) {
7812   if (Before.isInvalid())
7813     return;
7814   R.setBegin(Before.getBegin());
7815   if (R.getEnd().isInvalid())
7816     R.setEnd(Before.getEnd());
7817 }
7818 
7819 static void extendRight(SourceRange &R, SourceRange After) {
7820   if (After.isInvalid())
7821     return;
7822   if (R.getBegin().isInvalid())
7823     R.setBegin(After.getBegin());
7824   R.setEnd(After.getEnd());
7825 }
7826 
7827 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
7828 /// well-formednes of the conversion function declarator @p D with
7829 /// type @p R. If there are any errors in the declarator, this routine
7830 /// will emit diagnostics and return true. Otherwise, it will return
7831 /// false. Either way, the type @p R will be updated to reflect a
7832 /// well-formed type for the conversion operator.
7833 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
7834                                      StorageClass& SC) {
7835   // C++ [class.conv.fct]p1:
7836   //   Neither parameter types nor return type can be specified. The
7837   //   type of a conversion function (8.3.5) is "function taking no
7838   //   parameter returning conversion-type-id."
7839   if (SC == SC_Static) {
7840     if (!D.isInvalidType())
7841       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
7842         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7843         << D.getName().getSourceRange();
7844     D.setInvalidType();
7845     SC = SC_None;
7846   }
7847 
7848   TypeSourceInfo *ConvTSI = nullptr;
7849   QualType ConvType =
7850       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
7851 
7852   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
7853     // Conversion functions don't have return types, but the parser will
7854     // happily parse something like:
7855     //
7856     //   class X {
7857     //     float operator bool();
7858     //   };
7859     //
7860     // The return type will be changed later anyway.
7861     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
7862       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7863       << SourceRange(D.getIdentifierLoc());
7864     D.setInvalidType();
7865   }
7866 
7867   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
7868 
7869   // Make sure we don't have any parameters.
7870   if (Proto->getNumParams() > 0) {
7871     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
7872 
7873     // Delete the parameters.
7874     D.getFunctionTypeInfo().freeParams();
7875     D.setInvalidType();
7876   } else if (Proto->isVariadic()) {
7877     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
7878     D.setInvalidType();
7879   }
7880 
7881   // Diagnose "&operator bool()" and other such nonsense.  This
7882   // is actually a gcc extension which we don't support.
7883   if (Proto->getReturnType() != ConvType) {
7884     bool NeedsTypedef = false;
7885     SourceRange Before, After;
7886 
7887     // Walk the chunks and extract information on them for our diagnostic.
7888     bool PastFunctionChunk = false;
7889     for (auto &Chunk : D.type_objects()) {
7890       switch (Chunk.Kind) {
7891       case DeclaratorChunk::Function:
7892         if (!PastFunctionChunk) {
7893           if (Chunk.Fun.HasTrailingReturnType) {
7894             TypeSourceInfo *TRT = nullptr;
7895             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
7896             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
7897           }
7898           PastFunctionChunk = true;
7899           break;
7900         }
7901         // Fall through.
7902       case DeclaratorChunk::Array:
7903         NeedsTypedef = true;
7904         extendRight(After, Chunk.getSourceRange());
7905         break;
7906 
7907       case DeclaratorChunk::Pointer:
7908       case DeclaratorChunk::BlockPointer:
7909       case DeclaratorChunk::Reference:
7910       case DeclaratorChunk::MemberPointer:
7911       case DeclaratorChunk::Pipe:
7912         extendLeft(Before, Chunk.getSourceRange());
7913         break;
7914 
7915       case DeclaratorChunk::Paren:
7916         extendLeft(Before, Chunk.Loc);
7917         extendRight(After, Chunk.EndLoc);
7918         break;
7919       }
7920     }
7921 
7922     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
7923                          After.isValid()  ? After.getBegin() :
7924                                             D.getIdentifierLoc();
7925     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
7926     DB << Before << After;
7927 
7928     if (!NeedsTypedef) {
7929       DB << /*don't need a typedef*/0;
7930 
7931       // If we can provide a correct fix-it hint, do so.
7932       if (After.isInvalid() && ConvTSI) {
7933         SourceLocation InsertLoc =
7934             getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
7935         DB << FixItHint::CreateInsertion(InsertLoc, " ")
7936            << FixItHint::CreateInsertionFromRange(
7937                   InsertLoc, CharSourceRange::getTokenRange(Before))
7938            << FixItHint::CreateRemoval(Before);
7939       }
7940     } else if (!Proto->getReturnType()->isDependentType()) {
7941       DB << /*typedef*/1 << Proto->getReturnType();
7942     } else if (getLangOpts().CPlusPlus11) {
7943       DB << /*alias template*/2 << Proto->getReturnType();
7944     } else {
7945       DB << /*might not be fixable*/3;
7946     }
7947 
7948     // Recover by incorporating the other type chunks into the result type.
7949     // Note, this does *not* change the name of the function. This is compatible
7950     // with the GCC extension:
7951     //   struct S { &operator int(); } s;
7952     //   int &r = s.operator int(); // ok in GCC
7953     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
7954     ConvType = Proto->getReturnType();
7955   }
7956 
7957   // C++ [class.conv.fct]p4:
7958   //   The conversion-type-id shall not represent a function type nor
7959   //   an array type.
7960   if (ConvType->isArrayType()) {
7961     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
7962     ConvType = Context.getPointerType(ConvType);
7963     D.setInvalidType();
7964   } else if (ConvType->isFunctionType()) {
7965     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
7966     ConvType = Context.getPointerType(ConvType);
7967     D.setInvalidType();
7968   }
7969 
7970   // Rebuild the function type "R" without any parameters (in case any
7971   // of the errors above fired) and with the conversion type as the
7972   // return type.
7973   if (D.isInvalidType())
7974     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
7975 
7976   // C++0x explicit conversion operators.
7977   if (D.getDeclSpec().isExplicitSpecified())
7978     Diag(D.getDeclSpec().getExplicitSpecLoc(),
7979          getLangOpts().CPlusPlus11 ?
7980            diag::warn_cxx98_compat_explicit_conversion_functions :
7981            diag::ext_explicit_conversion_functions)
7982       << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
7983 }
7984 
7985 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
7986 /// the declaration of the given C++ conversion function. This routine
7987 /// is responsible for recording the conversion function in the C++
7988 /// class, if possible.
7989 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
7990   assert(Conversion && "Expected to receive a conversion function declaration");
7991 
7992   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
7993 
7994   // Make sure we aren't redeclaring the conversion function.
7995   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
7996 
7997   // C++ [class.conv.fct]p1:
7998   //   [...] A conversion function is never used to convert a
7999   //   (possibly cv-qualified) object to the (possibly cv-qualified)
8000   //   same object type (or a reference to it), to a (possibly
8001   //   cv-qualified) base class of that type (or a reference to it),
8002   //   or to (possibly cv-qualified) void.
8003   // FIXME: Suppress this warning if the conversion function ends up being a
8004   // virtual function that overrides a virtual function in a base class.
8005   QualType ClassType
8006     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8007   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
8008     ConvType = ConvTypeRef->getPointeeType();
8009   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8010       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
8011     /* Suppress diagnostics for instantiations. */;
8012   else if (ConvType->isRecordType()) {
8013     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8014     if (ConvType == ClassType)
8015       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
8016         << ClassType;
8017     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
8018       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
8019         <<  ClassType << ConvType;
8020   } else if (ConvType->isVoidType()) {
8021     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
8022       << ClassType << ConvType;
8023   }
8024 
8025   if (FunctionTemplateDecl *ConversionTemplate
8026                                 = Conversion->getDescribedFunctionTemplate())
8027     return ConversionTemplate;
8028 
8029   return Conversion;
8030 }
8031 
8032 //===----------------------------------------------------------------------===//
8033 // Namespace Handling
8034 //===----------------------------------------------------------------------===//
8035 
8036 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
8037 /// reopened.
8038 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8039                                             SourceLocation Loc,
8040                                             IdentifierInfo *II, bool *IsInline,
8041                                             NamespaceDecl *PrevNS) {
8042   assert(*IsInline != PrevNS->isInline());
8043 
8044   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8045   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8046   // inline namespaces, with the intention of bringing names into namespace std.
8047   //
8048   // We support this just well enough to get that case working; this is not
8049   // sufficient to support reopening namespaces as inline in general.
8050   if (*IsInline && II && II->getName().startswith("__atomic") &&
8051       S.getSourceManager().isInSystemHeader(Loc)) {
8052     // Mark all prior declarations of the namespace as inline.
8053     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8054          NS = NS->getPreviousDecl())
8055       NS->setInline(*IsInline);
8056     // Patch up the lookup table for the containing namespace. This isn't really
8057     // correct, but it's good enough for this particular case.
8058     for (auto *I : PrevNS->decls())
8059       if (auto *ND = dyn_cast<NamedDecl>(I))
8060         PrevNS->getParent()->makeDeclVisibleInContext(ND);
8061     return;
8062   }
8063 
8064   if (PrevNS->isInline())
8065     // The user probably just forgot the 'inline', so suggest that it
8066     // be added back.
8067     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8068       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8069   else
8070     S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
8071 
8072   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8073   *IsInline = PrevNS->isInline();
8074 }
8075 
8076 /// ActOnStartNamespaceDef - This is called at the start of a namespace
8077 /// definition.
8078 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
8079                                    SourceLocation InlineLoc,
8080                                    SourceLocation NamespaceLoc,
8081                                    SourceLocation IdentLoc,
8082                                    IdentifierInfo *II,
8083                                    SourceLocation LBrace,
8084                                    AttributeList *AttrList,
8085                                    UsingDirectiveDecl *&UD) {
8086   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8087   // For anonymous namespace, take the location of the left brace.
8088   SourceLocation Loc = II ? IdentLoc : LBrace;
8089   bool IsInline = InlineLoc.isValid();
8090   bool IsInvalid = false;
8091   bool IsStd = false;
8092   bool AddToKnown = false;
8093   Scope *DeclRegionScope = NamespcScope->getParent();
8094 
8095   NamespaceDecl *PrevNS = nullptr;
8096   if (II) {
8097     // C++ [namespace.def]p2:
8098     //   The identifier in an original-namespace-definition shall not
8099     //   have been previously defined in the declarative region in
8100     //   which the original-namespace-definition appears. The
8101     //   identifier in an original-namespace-definition is the name of
8102     //   the namespace. Subsequently in that declarative region, it is
8103     //   treated as an original-namespace-name.
8104     //
8105     // Since namespace names are unique in their scope, and we don't
8106     // look through using directives, just look for any ordinary names
8107     // as if by qualified name lookup.
8108     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, ForRedeclaration);
8109     LookupQualifiedName(R, CurContext->getRedeclContext());
8110     NamedDecl *PrevDecl =
8111         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
8112     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
8113 
8114     if (PrevNS) {
8115       // This is an extended namespace definition.
8116       if (IsInline != PrevNS->isInline())
8117         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8118                                         &IsInline, PrevNS);
8119     } else if (PrevDecl) {
8120       // This is an invalid name redefinition.
8121       Diag(Loc, diag::err_redefinition_different_kind)
8122         << II;
8123       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8124       IsInvalid = true;
8125       // Continue on to push Namespc as current DeclContext and return it.
8126     } else if (II->isStr("std") &&
8127                CurContext->getRedeclContext()->isTranslationUnit()) {
8128       // This is the first "real" definition of the namespace "std", so update
8129       // our cache of the "std" namespace to point at this definition.
8130       PrevNS = getStdNamespace();
8131       IsStd = true;
8132       AddToKnown = !IsInline;
8133     } else {
8134       // We've seen this namespace for the first time.
8135       AddToKnown = !IsInline;
8136     }
8137   } else {
8138     // Anonymous namespaces.
8139 
8140     // Determine whether the parent already has an anonymous namespace.
8141     DeclContext *Parent = CurContext->getRedeclContext();
8142     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8143       PrevNS = TU->getAnonymousNamespace();
8144     } else {
8145       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
8146       PrevNS = ND->getAnonymousNamespace();
8147     }
8148 
8149     if (PrevNS && IsInline != PrevNS->isInline())
8150       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8151                                       &IsInline, PrevNS);
8152   }
8153 
8154   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8155                                                  StartLoc, Loc, II, PrevNS);
8156   if (IsInvalid)
8157     Namespc->setInvalidDecl();
8158 
8159   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
8160 
8161   // FIXME: Should we be merging attributes?
8162   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
8163     PushNamespaceVisibilityAttr(Attr, Loc);
8164 
8165   if (IsStd)
8166     StdNamespace = Namespc;
8167   if (AddToKnown)
8168     KnownNamespaces[Namespc] = false;
8169 
8170   if (II) {
8171     PushOnScopeChains(Namespc, DeclRegionScope);
8172   } else {
8173     // Link the anonymous namespace into its parent.
8174     DeclContext *Parent = CurContext->getRedeclContext();
8175     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8176       TU->setAnonymousNamespace(Namespc);
8177     } else {
8178       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
8179     }
8180 
8181     CurContext->addDecl(Namespc);
8182 
8183     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
8184     //   behaves as if it were replaced by
8185     //     namespace unique { /* empty body */ }
8186     //     using namespace unique;
8187     //     namespace unique { namespace-body }
8188     //   where all occurrences of 'unique' in a translation unit are
8189     //   replaced by the same identifier and this identifier differs
8190     //   from all other identifiers in the entire program.
8191 
8192     // We just create the namespace with an empty name and then add an
8193     // implicit using declaration, just like the standard suggests.
8194     //
8195     // CodeGen enforces the "universally unique" aspect by giving all
8196     // declarations semantically contained within an anonymous
8197     // namespace internal linkage.
8198 
8199     if (!PrevNS) {
8200       UD = UsingDirectiveDecl::Create(Context, Parent,
8201                                       /* 'using' */ LBrace,
8202                                       /* 'namespace' */ SourceLocation(),
8203                                       /* qualifier */ NestedNameSpecifierLoc(),
8204                                       /* identifier */ SourceLocation(),
8205                                       Namespc,
8206                                       /* Ancestor */ Parent);
8207       UD->setImplicit();
8208       Parent->addDecl(UD);
8209     }
8210   }
8211 
8212   ActOnDocumentableDecl(Namespc);
8213 
8214   // Although we could have an invalid decl (i.e. the namespace name is a
8215   // redefinition), push it as current DeclContext and try to continue parsing.
8216   // FIXME: We should be able to push Namespc here, so that the each DeclContext
8217   // for the namespace has the declarations that showed up in that particular
8218   // namespace definition.
8219   PushDeclContext(NamespcScope, Namespc);
8220   return Namespc;
8221 }
8222 
8223 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
8224 /// is a namespace alias, returns the namespace it points to.
8225 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
8226   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
8227     return AD->getNamespace();
8228   return dyn_cast_or_null<NamespaceDecl>(D);
8229 }
8230 
8231 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
8232 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
8233 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
8234   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
8235   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
8236   Namespc->setRBraceLoc(RBrace);
8237   PopDeclContext();
8238   if (Namespc->hasAttr<VisibilityAttr>())
8239     PopPragmaVisibility(true, RBrace);
8240 }
8241 
8242 CXXRecordDecl *Sema::getStdBadAlloc() const {
8243   return cast_or_null<CXXRecordDecl>(
8244                                   StdBadAlloc.get(Context.getExternalSource()));
8245 }
8246 
8247 NamespaceDecl *Sema::getStdNamespace() const {
8248   return cast_or_null<NamespaceDecl>(
8249                                  StdNamespace.get(Context.getExternalSource()));
8250 }
8251 
8252 /// \brief Retrieve the special "std" namespace, which may require us to
8253 /// implicitly define the namespace.
8254 NamespaceDecl *Sema::getOrCreateStdNamespace() {
8255   if (!StdNamespace) {
8256     // The "std" namespace has not yet been defined, so build one implicitly.
8257     StdNamespace = NamespaceDecl::Create(Context,
8258                                          Context.getTranslationUnitDecl(),
8259                                          /*Inline=*/false,
8260                                          SourceLocation(), SourceLocation(),
8261                                          &PP.getIdentifierTable().get("std"),
8262                                          /*PrevDecl=*/nullptr);
8263     getStdNamespace()->setImplicit(true);
8264   }
8265 
8266   return getStdNamespace();
8267 }
8268 
8269 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
8270   assert(getLangOpts().CPlusPlus &&
8271          "Looking for std::initializer_list outside of C++.");
8272 
8273   // We're looking for implicit instantiations of
8274   // template <typename E> class std::initializer_list.
8275 
8276   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
8277     return false;
8278 
8279   ClassTemplateDecl *Template = nullptr;
8280   const TemplateArgument *Arguments = nullptr;
8281 
8282   if (const RecordType *RT = Ty->getAs<RecordType>()) {
8283 
8284     ClassTemplateSpecializationDecl *Specialization =
8285         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
8286     if (!Specialization)
8287       return false;
8288 
8289     Template = Specialization->getSpecializedTemplate();
8290     Arguments = Specialization->getTemplateArgs().data();
8291   } else if (const TemplateSpecializationType *TST =
8292                  Ty->getAs<TemplateSpecializationType>()) {
8293     Template = dyn_cast_or_null<ClassTemplateDecl>(
8294         TST->getTemplateName().getAsTemplateDecl());
8295     Arguments = TST->getArgs();
8296   }
8297   if (!Template)
8298     return false;
8299 
8300   if (!StdInitializerList) {
8301     // Haven't recognized std::initializer_list yet, maybe this is it.
8302     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
8303     if (TemplateClass->getIdentifier() !=
8304             &PP.getIdentifierTable().get("initializer_list") ||
8305         !getStdNamespace()->InEnclosingNamespaceSetOf(
8306             TemplateClass->getDeclContext()))
8307       return false;
8308     // This is a template called std::initializer_list, but is it the right
8309     // template?
8310     TemplateParameterList *Params = Template->getTemplateParameters();
8311     if (Params->getMinRequiredArguments() != 1)
8312       return false;
8313     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
8314       return false;
8315 
8316     // It's the right template.
8317     StdInitializerList = Template;
8318   }
8319 
8320   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
8321     return false;
8322 
8323   // This is an instance of std::initializer_list. Find the argument type.
8324   if (Element)
8325     *Element = Arguments[0].getAsType();
8326   return true;
8327 }
8328 
8329 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
8330   NamespaceDecl *Std = S.getStdNamespace();
8331   if (!Std) {
8332     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
8333     return nullptr;
8334   }
8335 
8336   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
8337                       Loc, Sema::LookupOrdinaryName);
8338   if (!S.LookupQualifiedName(Result, Std)) {
8339     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
8340     return nullptr;
8341   }
8342   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
8343   if (!Template) {
8344     Result.suppressDiagnostics();
8345     // We found something weird. Complain about the first thing we found.
8346     NamedDecl *Found = *Result.begin();
8347     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
8348     return nullptr;
8349   }
8350 
8351   // We found some template called std::initializer_list. Now verify that it's
8352   // correct.
8353   TemplateParameterList *Params = Template->getTemplateParameters();
8354   if (Params->getMinRequiredArguments() != 1 ||
8355       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
8356     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
8357     return nullptr;
8358   }
8359 
8360   return Template;
8361 }
8362 
8363 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
8364   if (!StdInitializerList) {
8365     StdInitializerList = LookupStdInitializerList(*this, Loc);
8366     if (!StdInitializerList)
8367       return QualType();
8368   }
8369 
8370   TemplateArgumentListInfo Args(Loc, Loc);
8371   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
8372                                        Context.getTrivialTypeSourceInfo(Element,
8373                                                                         Loc)));
8374   return Context.getCanonicalType(
8375       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
8376 }
8377 
8378 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
8379   // C++ [dcl.init.list]p2:
8380   //   A constructor is an initializer-list constructor if its first parameter
8381   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
8382   //   std::initializer_list<E> for some type E, and either there are no other
8383   //   parameters or else all other parameters have default arguments.
8384   if (Ctor->getNumParams() < 1 ||
8385       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
8386     return false;
8387 
8388   QualType ArgType = Ctor->getParamDecl(0)->getType();
8389   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
8390     ArgType = RT->getPointeeType().getUnqualifiedType();
8391 
8392   return isStdInitializerList(ArgType, nullptr);
8393 }
8394 
8395 /// \brief Determine whether a using statement is in a context where it will be
8396 /// apply in all contexts.
8397 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
8398   switch (CurContext->getDeclKind()) {
8399     case Decl::TranslationUnit:
8400       return true;
8401     case Decl::LinkageSpec:
8402       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
8403     default:
8404       return false;
8405   }
8406 }
8407 
8408 namespace {
8409 
8410 // Callback to only accept typo corrections that are namespaces.
8411 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
8412 public:
8413   bool ValidateCandidate(const TypoCorrection &candidate) override {
8414     if (NamedDecl *ND = candidate.getCorrectionDecl())
8415       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
8416     return false;
8417   }
8418 };
8419 
8420 }
8421 
8422 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
8423                                        CXXScopeSpec &SS,
8424                                        SourceLocation IdentLoc,
8425                                        IdentifierInfo *Ident) {
8426   R.clear();
8427   if (TypoCorrection Corrected =
8428           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
8429                         llvm::make_unique<NamespaceValidatorCCC>(),
8430                         Sema::CTK_ErrorRecovery)) {
8431     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
8432       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
8433       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
8434                               Ident->getName().equals(CorrectedStr);
8435       S.diagnoseTypo(Corrected,
8436                      S.PDiag(diag::err_using_directive_member_suggest)
8437                        << Ident << DC << DroppedSpecifier << SS.getRange(),
8438                      S.PDiag(diag::note_namespace_defined_here));
8439     } else {
8440       S.diagnoseTypo(Corrected,
8441                      S.PDiag(diag::err_using_directive_suggest) << Ident,
8442                      S.PDiag(diag::note_namespace_defined_here));
8443     }
8444     R.addDecl(Corrected.getFoundDecl());
8445     return true;
8446   }
8447   return false;
8448 }
8449 
8450 Decl *Sema::ActOnUsingDirective(Scope *S,
8451                                           SourceLocation UsingLoc,
8452                                           SourceLocation NamespcLoc,
8453                                           CXXScopeSpec &SS,
8454                                           SourceLocation IdentLoc,
8455                                           IdentifierInfo *NamespcName,
8456                                           AttributeList *AttrList) {
8457   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
8458   assert(NamespcName && "Invalid NamespcName.");
8459   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
8460 
8461   // This can only happen along a recovery path.
8462   while (S->isTemplateParamScope())
8463     S = S->getParent();
8464   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
8465 
8466   UsingDirectiveDecl *UDir = nullptr;
8467   NestedNameSpecifier *Qualifier = nullptr;
8468   if (SS.isSet())
8469     Qualifier = SS.getScopeRep();
8470 
8471   // Lookup namespace name.
8472   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
8473   LookupParsedName(R, S, &SS);
8474   if (R.isAmbiguous())
8475     return nullptr;
8476 
8477   if (R.empty()) {
8478     R.clear();
8479     // Allow "using namespace std;" or "using namespace ::std;" even if
8480     // "std" hasn't been defined yet, for GCC compatibility.
8481     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
8482         NamespcName->isStr("std")) {
8483       Diag(IdentLoc, diag::ext_using_undefined_std);
8484       R.addDecl(getOrCreateStdNamespace());
8485       R.resolveKind();
8486     }
8487     // Otherwise, attempt typo correction.
8488     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
8489   }
8490 
8491   if (!R.empty()) {
8492     NamedDecl *Named = R.getRepresentativeDecl();
8493     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
8494     assert(NS && "expected namespace decl");
8495 
8496     // The use of a nested name specifier may trigger deprecation warnings.
8497     DiagnoseUseOfDecl(Named, IdentLoc);
8498 
8499     // C++ [namespace.udir]p1:
8500     //   A using-directive specifies that the names in the nominated
8501     //   namespace can be used in the scope in which the
8502     //   using-directive appears after the using-directive. During
8503     //   unqualified name lookup (3.4.1), the names appear as if they
8504     //   were declared in the nearest enclosing namespace which
8505     //   contains both the using-directive and the nominated
8506     //   namespace. [Note: in this context, "contains" means "contains
8507     //   directly or indirectly". ]
8508 
8509     // Find enclosing context containing both using-directive and
8510     // nominated namespace.
8511     DeclContext *CommonAncestor = cast<DeclContext>(NS);
8512     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
8513       CommonAncestor = CommonAncestor->getParent();
8514 
8515     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
8516                                       SS.getWithLocInContext(Context),
8517                                       IdentLoc, Named, CommonAncestor);
8518 
8519     if (IsUsingDirectiveInToplevelContext(CurContext) &&
8520         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
8521       Diag(IdentLoc, diag::warn_using_directive_in_header);
8522     }
8523 
8524     PushUsingDirective(S, UDir);
8525   } else {
8526     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
8527   }
8528 
8529   if (UDir)
8530     ProcessDeclAttributeList(S, UDir, AttrList);
8531 
8532   return UDir;
8533 }
8534 
8535 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
8536   // If the scope has an associated entity and the using directive is at
8537   // namespace or translation unit scope, add the UsingDirectiveDecl into
8538   // its lookup structure so qualified name lookup can find it.
8539   DeclContext *Ctx = S->getEntity();
8540   if (Ctx && !Ctx->isFunctionOrMethod())
8541     Ctx->addDecl(UDir);
8542   else
8543     // Otherwise, it is at block scope. The using-directives will affect lookup
8544     // only to the end of the scope.
8545     S->PushUsingDirective(UDir);
8546 }
8547 
8548 
8549 Decl *Sema::ActOnUsingDeclaration(Scope *S,
8550                                   AccessSpecifier AS,
8551                                   bool HasUsingKeyword,
8552                                   SourceLocation UsingLoc,
8553                                   CXXScopeSpec &SS,
8554                                   UnqualifiedId &Name,
8555                                   AttributeList *AttrList,
8556                                   bool HasTypenameKeyword,
8557                                   SourceLocation TypenameLoc) {
8558   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
8559 
8560   switch (Name.getKind()) {
8561   case UnqualifiedId::IK_ImplicitSelfParam:
8562   case UnqualifiedId::IK_Identifier:
8563   case UnqualifiedId::IK_OperatorFunctionId:
8564   case UnqualifiedId::IK_LiteralOperatorId:
8565   case UnqualifiedId::IK_ConversionFunctionId:
8566     break;
8567 
8568   case UnqualifiedId::IK_ConstructorName:
8569   case UnqualifiedId::IK_ConstructorTemplateId:
8570     // C++11 inheriting constructors.
8571     Diag(Name.getLocStart(),
8572          getLangOpts().CPlusPlus11 ?
8573            diag::warn_cxx98_compat_using_decl_constructor :
8574            diag::err_using_decl_constructor)
8575       << SS.getRange();
8576 
8577     if (getLangOpts().CPlusPlus11) break;
8578 
8579     return nullptr;
8580 
8581   case UnqualifiedId::IK_DestructorName:
8582     Diag(Name.getLocStart(), diag::err_using_decl_destructor)
8583       << SS.getRange();
8584     return nullptr;
8585 
8586   case UnqualifiedId::IK_TemplateId:
8587     Diag(Name.getLocStart(), diag::err_using_decl_template_id)
8588       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
8589     return nullptr;
8590   }
8591 
8592   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
8593   DeclarationName TargetName = TargetNameInfo.getName();
8594   if (!TargetName)
8595     return nullptr;
8596 
8597   // Warn about access declarations.
8598   if (!HasUsingKeyword) {
8599     Diag(Name.getLocStart(),
8600          getLangOpts().CPlusPlus11 ? diag::err_access_decl
8601                                    : diag::warn_access_decl_deprecated)
8602       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
8603   }
8604 
8605   if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
8606       DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
8607     return nullptr;
8608 
8609   NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
8610                                         TargetNameInfo, AttrList,
8611                                         /* IsInstantiation */ false,
8612                                         HasTypenameKeyword, TypenameLoc);
8613   if (UD)
8614     PushOnScopeChains(UD, S, /*AddToContext*/ false);
8615 
8616   return UD;
8617 }
8618 
8619 /// \brief Determine whether a using declaration considers the given
8620 /// declarations as "equivalent", e.g., if they are redeclarations of
8621 /// the same entity or are both typedefs of the same type.
8622 static bool
8623 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
8624   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
8625     return true;
8626 
8627   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
8628     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
8629       return Context.hasSameType(TD1->getUnderlyingType(),
8630                                  TD2->getUnderlyingType());
8631 
8632   return false;
8633 }
8634 
8635 
8636 /// Determines whether to create a using shadow decl for a particular
8637 /// decl, given the set of decls existing prior to this using lookup.
8638 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
8639                                 const LookupResult &Previous,
8640                                 UsingShadowDecl *&PrevShadow) {
8641   // Diagnose finding a decl which is not from a base class of the
8642   // current class.  We do this now because there are cases where this
8643   // function will silently decide not to build a shadow decl, which
8644   // will pre-empt further diagnostics.
8645   //
8646   // We don't need to do this in C++11 because we do the check once on
8647   // the qualifier.
8648   //
8649   // FIXME: diagnose the following if we care enough:
8650   //   struct A { int foo; };
8651   //   struct B : A { using A::foo; };
8652   //   template <class T> struct C : A {};
8653   //   template <class T> struct D : C<T> { using B::foo; } // <---
8654   // This is invalid (during instantiation) in C++03 because B::foo
8655   // resolves to the using decl in B, which is not a base class of D<T>.
8656   // We can't diagnose it immediately because C<T> is an unknown
8657   // specialization.  The UsingShadowDecl in D<T> then points directly
8658   // to A::foo, which will look well-formed when we instantiate.
8659   // The right solution is to not collapse the shadow-decl chain.
8660   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
8661     DeclContext *OrigDC = Orig->getDeclContext();
8662 
8663     // Handle enums and anonymous structs.
8664     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
8665     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
8666     while (OrigRec->isAnonymousStructOrUnion())
8667       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
8668 
8669     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
8670       if (OrigDC == CurContext) {
8671         Diag(Using->getLocation(),
8672              diag::err_using_decl_nested_name_specifier_is_current_class)
8673           << Using->getQualifierLoc().getSourceRange();
8674         Diag(Orig->getLocation(), diag::note_using_decl_target);
8675         return true;
8676       }
8677 
8678       Diag(Using->getQualifierLoc().getBeginLoc(),
8679            diag::err_using_decl_nested_name_specifier_is_not_base_class)
8680         << Using->getQualifier()
8681         << cast<CXXRecordDecl>(CurContext)
8682         << Using->getQualifierLoc().getSourceRange();
8683       Diag(Orig->getLocation(), diag::note_using_decl_target);
8684       return true;
8685     }
8686   }
8687 
8688   if (Previous.empty()) return false;
8689 
8690   NamedDecl *Target = Orig;
8691   if (isa<UsingShadowDecl>(Target))
8692     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
8693 
8694   // If the target happens to be one of the previous declarations, we
8695   // don't have a conflict.
8696   //
8697   // FIXME: but we might be increasing its access, in which case we
8698   // should redeclare it.
8699   NamedDecl *NonTag = nullptr, *Tag = nullptr;
8700   bool FoundEquivalentDecl = false;
8701   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8702          I != E; ++I) {
8703     NamedDecl *D = (*I)->getUnderlyingDecl();
8704     // We can have UsingDecls in our Previous results because we use the same
8705     // LookupResult for checking whether the UsingDecl itself is a valid
8706     // redeclaration.
8707     if (isa<UsingDecl>(D))
8708       continue;
8709 
8710     if (IsEquivalentForUsingDecl(Context, D, Target)) {
8711       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
8712         PrevShadow = Shadow;
8713       FoundEquivalentDecl = true;
8714     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
8715       // We don't conflict with an existing using shadow decl of an equivalent
8716       // declaration, but we're not a redeclaration of it.
8717       FoundEquivalentDecl = true;
8718     }
8719 
8720     if (isVisible(D))
8721       (isa<TagDecl>(D) ? Tag : NonTag) = D;
8722   }
8723 
8724   if (FoundEquivalentDecl)
8725     return false;
8726 
8727   if (FunctionDecl *FD = Target->getAsFunction()) {
8728     NamedDecl *OldDecl = nullptr;
8729     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
8730                           /*IsForUsingDecl*/ true)) {
8731     case Ovl_Overload:
8732       return false;
8733 
8734     case Ovl_NonFunction:
8735       Diag(Using->getLocation(), diag::err_using_decl_conflict);
8736       break;
8737 
8738     // We found a decl with the exact signature.
8739     case Ovl_Match:
8740       // If we're in a record, we want to hide the target, so we
8741       // return true (without a diagnostic) to tell the caller not to
8742       // build a shadow decl.
8743       if (CurContext->isRecord())
8744         return true;
8745 
8746       // If we're not in a record, this is an error.
8747       Diag(Using->getLocation(), diag::err_using_decl_conflict);
8748       break;
8749     }
8750 
8751     Diag(Target->getLocation(), diag::note_using_decl_target);
8752     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
8753     return true;
8754   }
8755 
8756   // Target is not a function.
8757 
8758   if (isa<TagDecl>(Target)) {
8759     // No conflict between a tag and a non-tag.
8760     if (!Tag) return false;
8761 
8762     Diag(Using->getLocation(), diag::err_using_decl_conflict);
8763     Diag(Target->getLocation(), diag::note_using_decl_target);
8764     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
8765     return true;
8766   }
8767 
8768   // No conflict between a tag and a non-tag.
8769   if (!NonTag) return false;
8770 
8771   Diag(Using->getLocation(), diag::err_using_decl_conflict);
8772   Diag(Target->getLocation(), diag::note_using_decl_target);
8773   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
8774   return true;
8775 }
8776 
8777 /// Determine whether a direct base class is a virtual base class.
8778 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
8779   if (!Derived->getNumVBases())
8780     return false;
8781   for (auto &B : Derived->bases())
8782     if (B.getType()->getAsCXXRecordDecl() == Base)
8783       return B.isVirtual();
8784   llvm_unreachable("not a direct base class");
8785 }
8786 
8787 /// Builds a shadow declaration corresponding to a 'using' declaration.
8788 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
8789                                             UsingDecl *UD,
8790                                             NamedDecl *Orig,
8791                                             UsingShadowDecl *PrevDecl) {
8792   // If we resolved to another shadow declaration, just coalesce them.
8793   NamedDecl *Target = Orig;
8794   if (isa<UsingShadowDecl>(Target)) {
8795     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
8796     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
8797   }
8798 
8799   NamedDecl *NonTemplateTarget = Target;
8800   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
8801     NonTemplateTarget = TargetTD->getTemplatedDecl();
8802 
8803   UsingShadowDecl *Shadow;
8804   if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
8805     bool IsVirtualBase =
8806         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
8807                             UD->getQualifier()->getAsRecordDecl());
8808     Shadow = ConstructorUsingShadowDecl::Create(
8809         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
8810   } else {
8811     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
8812                                      Target);
8813   }
8814   UD->addShadowDecl(Shadow);
8815 
8816   Shadow->setAccess(UD->getAccess());
8817   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
8818     Shadow->setInvalidDecl();
8819 
8820   Shadow->setPreviousDecl(PrevDecl);
8821 
8822   if (S)
8823     PushOnScopeChains(Shadow, S);
8824   else
8825     CurContext->addDecl(Shadow);
8826 
8827 
8828   return Shadow;
8829 }
8830 
8831 /// Hides a using shadow declaration.  This is required by the current
8832 /// using-decl implementation when a resolvable using declaration in a
8833 /// class is followed by a declaration which would hide or override
8834 /// one or more of the using decl's targets; for example:
8835 ///
8836 ///   struct Base { void foo(int); };
8837 ///   struct Derived : Base {
8838 ///     using Base::foo;
8839 ///     void foo(int);
8840 ///   };
8841 ///
8842 /// The governing language is C++03 [namespace.udecl]p12:
8843 ///
8844 ///   When a using-declaration brings names from a base class into a
8845 ///   derived class scope, member functions in the derived class
8846 ///   override and/or hide member functions with the same name and
8847 ///   parameter types in a base class (rather than conflicting).
8848 ///
8849 /// There are two ways to implement this:
8850 ///   (1) optimistically create shadow decls when they're not hidden
8851 ///       by existing declarations, or
8852 ///   (2) don't create any shadow decls (or at least don't make them
8853 ///       visible) until we've fully parsed/instantiated the class.
8854 /// The problem with (1) is that we might have to retroactively remove
8855 /// a shadow decl, which requires several O(n) operations because the
8856 /// decl structures are (very reasonably) not designed for removal.
8857 /// (2) avoids this but is very fiddly and phase-dependent.
8858 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
8859   if (Shadow->getDeclName().getNameKind() ==
8860         DeclarationName::CXXConversionFunctionName)
8861     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
8862 
8863   // Remove it from the DeclContext...
8864   Shadow->getDeclContext()->removeDecl(Shadow);
8865 
8866   // ...and the scope, if applicable...
8867   if (S) {
8868     S->RemoveDecl(Shadow);
8869     IdResolver.RemoveDecl(Shadow);
8870   }
8871 
8872   // ...and the using decl.
8873   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
8874 
8875   // TODO: complain somehow if Shadow was used.  It shouldn't
8876   // be possible for this to happen, because...?
8877 }
8878 
8879 /// Find the base specifier for a base class with the given type.
8880 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
8881                                                 QualType DesiredBase,
8882                                                 bool &AnyDependentBases) {
8883   // Check whether the named type is a direct base class.
8884   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
8885   for (auto &Base : Derived->bases()) {
8886     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
8887     if (CanonicalDesiredBase == BaseType)
8888       return &Base;
8889     if (BaseType->isDependentType())
8890       AnyDependentBases = true;
8891   }
8892   return nullptr;
8893 }
8894 
8895 namespace {
8896 class UsingValidatorCCC : public CorrectionCandidateCallback {
8897 public:
8898   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
8899                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
8900       : HasTypenameKeyword(HasTypenameKeyword),
8901         IsInstantiation(IsInstantiation), OldNNS(NNS),
8902         RequireMemberOf(RequireMemberOf) {}
8903 
8904   bool ValidateCandidate(const TypoCorrection &Candidate) override {
8905     NamedDecl *ND = Candidate.getCorrectionDecl();
8906 
8907     // Keywords are not valid here.
8908     if (!ND || isa<NamespaceDecl>(ND))
8909       return false;
8910 
8911     // Completely unqualified names are invalid for a 'using' declaration.
8912     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
8913       return false;
8914 
8915     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
8916     // reject.
8917 
8918     if (RequireMemberOf) {
8919       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
8920       if (FoundRecord && FoundRecord->isInjectedClassName()) {
8921         // No-one ever wants a using-declaration to name an injected-class-name
8922         // of a base class, unless they're declaring an inheriting constructor.
8923         ASTContext &Ctx = ND->getASTContext();
8924         if (!Ctx.getLangOpts().CPlusPlus11)
8925           return false;
8926         QualType FoundType = Ctx.getRecordType(FoundRecord);
8927 
8928         // Check that the injected-class-name is named as a member of its own
8929         // type; we don't want to suggest 'using Derived::Base;', since that
8930         // means something else.
8931         NestedNameSpecifier *Specifier =
8932             Candidate.WillReplaceSpecifier()
8933                 ? Candidate.getCorrectionSpecifier()
8934                 : OldNNS;
8935         if (!Specifier->getAsType() ||
8936             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
8937           return false;
8938 
8939         // Check that this inheriting constructor declaration actually names a
8940         // direct base class of the current class.
8941         bool AnyDependentBases = false;
8942         if (!findDirectBaseWithType(RequireMemberOf,
8943                                     Ctx.getRecordType(FoundRecord),
8944                                     AnyDependentBases) &&
8945             !AnyDependentBases)
8946           return false;
8947       } else {
8948         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
8949         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
8950           return false;
8951 
8952         // FIXME: Check that the base class member is accessible?
8953       }
8954     } else {
8955       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
8956       if (FoundRecord && FoundRecord->isInjectedClassName())
8957         return false;
8958     }
8959 
8960     if (isa<TypeDecl>(ND))
8961       return HasTypenameKeyword || !IsInstantiation;
8962 
8963     return !HasTypenameKeyword;
8964   }
8965 
8966 private:
8967   bool HasTypenameKeyword;
8968   bool IsInstantiation;
8969   NestedNameSpecifier *OldNNS;
8970   CXXRecordDecl *RequireMemberOf;
8971 };
8972 } // end anonymous namespace
8973 
8974 /// Builds a using declaration.
8975 ///
8976 /// \param IsInstantiation - Whether this call arises from an
8977 ///   instantiation of an unresolved using declaration.  We treat
8978 ///   the lookup differently for these declarations.
8979 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
8980                                        SourceLocation UsingLoc,
8981                                        CXXScopeSpec &SS,
8982                                        DeclarationNameInfo NameInfo,
8983                                        AttributeList *AttrList,
8984                                        bool IsInstantiation,
8985                                        bool HasTypenameKeyword,
8986                                        SourceLocation TypenameLoc) {
8987   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
8988   SourceLocation IdentLoc = NameInfo.getLoc();
8989   assert(IdentLoc.isValid() && "Invalid TargetName location.");
8990 
8991   // FIXME: We ignore attributes for now.
8992 
8993   if (SS.isEmpty()) {
8994     Diag(IdentLoc, diag::err_using_requires_qualname);
8995     return nullptr;
8996   }
8997 
8998   // For an inheriting constructor declaration, the name of the using
8999   // declaration is the name of a constructor in this class, not in the
9000   // base class.
9001   DeclarationNameInfo UsingName = NameInfo;
9002   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9003     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9004       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9005           Context.getCanonicalType(Context.getRecordType(RD))));
9006 
9007   // Do the redeclaration lookup in the current scope.
9008   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
9009                         ForRedeclaration);
9010   Previous.setHideTags(false);
9011   if (S) {
9012     LookupName(Previous, S);
9013 
9014     // It is really dumb that we have to do this.
9015     LookupResult::Filter F = Previous.makeFilter();
9016     while (F.hasNext()) {
9017       NamedDecl *D = F.next();
9018       if (!isDeclInScope(D, CurContext, S))
9019         F.erase();
9020       // If we found a local extern declaration that's not ordinarily visible,
9021       // and this declaration is being added to a non-block scope, ignore it.
9022       // We're only checking for scope conflicts here, not also for violations
9023       // of the linkage rules.
9024       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
9025                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
9026         F.erase();
9027     }
9028     F.done();
9029   } else {
9030     assert(IsInstantiation && "no scope in non-instantiation");
9031     assert(CurContext->isRecord() && "scope not record in instantiation");
9032     LookupQualifiedName(Previous, CurContext);
9033   }
9034 
9035   // Check for invalid redeclarations.
9036   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
9037                                   SS, IdentLoc, Previous))
9038     return nullptr;
9039 
9040   // Check for bad qualifiers.
9041   if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
9042     return nullptr;
9043 
9044   DeclContext *LookupContext = computeDeclContext(SS);
9045   NamedDecl *D;
9046   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9047   if (!LookupContext) {
9048     if (HasTypenameKeyword) {
9049       // FIXME: not all declaration name kinds are legal here
9050       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
9051                                               UsingLoc, TypenameLoc,
9052                                               QualifierLoc,
9053                                               IdentLoc, NameInfo.getName());
9054     } else {
9055       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
9056                                            QualifierLoc, NameInfo);
9057     }
9058     D->setAccess(AS);
9059     CurContext->addDecl(D);
9060     return D;
9061   }
9062 
9063   auto Build = [&](bool Invalid) {
9064     UsingDecl *UD =
9065         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
9066                           UsingName, HasTypenameKeyword);
9067     UD->setAccess(AS);
9068     CurContext->addDecl(UD);
9069     UD->setInvalidDecl(Invalid);
9070     return UD;
9071   };
9072   auto BuildInvalid = [&]{ return Build(true); };
9073   auto BuildValid = [&]{ return Build(false); };
9074 
9075   if (RequireCompleteDeclContext(SS, LookupContext))
9076     return BuildInvalid();
9077 
9078   // Look up the target name.
9079   LookupResult R(*this, NameInfo, LookupOrdinaryName);
9080 
9081   // Unlike most lookups, we don't always want to hide tag
9082   // declarations: tag names are visible through the using declaration
9083   // even if hidden by ordinary names, *except* in a dependent context
9084   // where it's important for the sanity of two-phase lookup.
9085   if (!IsInstantiation)
9086     R.setHideTags(false);
9087 
9088   // For the purposes of this lookup, we have a base object type
9089   // equal to that of the current context.
9090   if (CurContext->isRecord()) {
9091     R.setBaseObjectType(
9092                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
9093   }
9094 
9095   LookupQualifiedName(R, LookupContext);
9096 
9097   // Try to correct typos if possible. If constructor name lookup finds no
9098   // results, that means the named class has no explicit constructors, and we
9099   // suppressed declaring implicit ones (probably because it's dependent or
9100   // invalid).
9101   if (R.empty() &&
9102       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
9103     if (TypoCorrection Corrected = CorrectTypo(
9104             R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
9105             llvm::make_unique<UsingValidatorCCC>(
9106                 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
9107                 dyn_cast<CXXRecordDecl>(CurContext)),
9108             CTK_ErrorRecovery)) {
9109       // We reject any correction for which ND would be NULL.
9110       NamedDecl *ND = Corrected.getCorrectionDecl();
9111 
9112       // We reject candidates where DroppedSpecifier == true, hence the
9113       // literal '0' below.
9114       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
9115                                 << NameInfo.getName() << LookupContext << 0
9116                                 << SS.getRange());
9117 
9118       // If we corrected to an inheriting constructor, handle it as one.
9119       auto *RD = dyn_cast<CXXRecordDecl>(ND);
9120       if (RD && RD->isInjectedClassName()) {
9121         // The parent of the injected class name is the class itself.
9122         RD = cast<CXXRecordDecl>(RD->getParent());
9123 
9124         // Fix up the information we'll use to build the using declaration.
9125         if (Corrected.WillReplaceSpecifier()) {
9126           NestedNameSpecifierLocBuilder Builder;
9127           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
9128                               QualifierLoc.getSourceRange());
9129           QualifierLoc = Builder.getWithLocInContext(Context);
9130         }
9131 
9132         // In this case, the name we introduce is the name of a derived class
9133         // constructor.
9134         auto *CurClass = cast<CXXRecordDecl>(CurContext);
9135         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9136             Context.getCanonicalType(Context.getRecordType(CurClass))));
9137         UsingName.setNamedTypeInfo(nullptr);
9138         for (auto *Ctor : LookupConstructors(RD))
9139           R.addDecl(Ctor);
9140         R.resolveKind();
9141       } else {
9142         // FIXME: Pick up all the declarations if we found an overloaded
9143         // function.
9144         UsingName.setName(ND->getDeclName());
9145         R.addDecl(ND);
9146       }
9147     } else {
9148       Diag(IdentLoc, diag::err_no_member)
9149         << NameInfo.getName() << LookupContext << SS.getRange();
9150       return BuildInvalid();
9151     }
9152   }
9153 
9154   if (R.isAmbiguous())
9155     return BuildInvalid();
9156 
9157   if (HasTypenameKeyword) {
9158     // If we asked for a typename and got a non-type decl, error out.
9159     if (!R.getAsSingle<TypeDecl>()) {
9160       Diag(IdentLoc, diag::err_using_typename_non_type);
9161       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9162         Diag((*I)->getUnderlyingDecl()->getLocation(),
9163              diag::note_using_decl_target);
9164       return BuildInvalid();
9165     }
9166   } else {
9167     // If we asked for a non-typename and we got a type, error out,
9168     // but only if this is an instantiation of an unresolved using
9169     // decl.  Otherwise just silently find the type name.
9170     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
9171       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
9172       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
9173       return BuildInvalid();
9174     }
9175   }
9176 
9177   // C++14 [namespace.udecl]p6:
9178   // A using-declaration shall not name a namespace.
9179   if (R.getAsSingle<NamespaceDecl>()) {
9180     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
9181       << SS.getRange();
9182     return BuildInvalid();
9183   }
9184 
9185   // C++14 [namespace.udecl]p7:
9186   // A using-declaration shall not name a scoped enumerator.
9187   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
9188     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
9189       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
9190         << SS.getRange();
9191       return BuildInvalid();
9192     }
9193   }
9194 
9195   UsingDecl *UD = BuildValid();
9196 
9197   // Some additional rules apply to inheriting constructors.
9198   if (UsingName.getName().getNameKind() ==
9199         DeclarationName::CXXConstructorName) {
9200     // Suppress access diagnostics; the access check is instead performed at the
9201     // point of use for an inheriting constructor.
9202     R.suppressDiagnostics();
9203     if (CheckInheritingConstructorUsingDecl(UD))
9204       return UD;
9205   }
9206 
9207   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
9208     UsingShadowDecl *PrevDecl = nullptr;
9209     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
9210       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
9211   }
9212 
9213   return UD;
9214 }
9215 
9216 /// Additional checks for a using declaration referring to a constructor name.
9217 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
9218   assert(!UD->hasTypename() && "expecting a constructor name");
9219 
9220   const Type *SourceType = UD->getQualifier()->getAsType();
9221   assert(SourceType &&
9222          "Using decl naming constructor doesn't have type in scope spec.");
9223   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
9224 
9225   // Check whether the named type is a direct base class.
9226   bool AnyDependentBases = false;
9227   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
9228                                       AnyDependentBases);
9229   if (!Base && !AnyDependentBases) {
9230     Diag(UD->getUsingLoc(),
9231          diag::err_using_decl_constructor_not_in_direct_base)
9232       << UD->getNameInfo().getSourceRange()
9233       << QualType(SourceType, 0) << TargetClass;
9234     UD->setInvalidDecl();
9235     return true;
9236   }
9237 
9238   if (Base)
9239     Base->setInheritConstructors();
9240 
9241   return false;
9242 }
9243 
9244 /// Checks that the given using declaration is not an invalid
9245 /// redeclaration.  Note that this is checking only for the using decl
9246 /// itself, not for any ill-formedness among the UsingShadowDecls.
9247 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
9248                                        bool HasTypenameKeyword,
9249                                        const CXXScopeSpec &SS,
9250                                        SourceLocation NameLoc,
9251                                        const LookupResult &Prev) {
9252   // C++03 [namespace.udecl]p8:
9253   // C++0x [namespace.udecl]p10:
9254   //   A using-declaration is a declaration and can therefore be used
9255   //   repeatedly where (and only where) multiple declarations are
9256   //   allowed.
9257   //
9258   // That's in non-member contexts.
9259   if (!CurContext->getRedeclContext()->isRecord())
9260     return false;
9261 
9262   NestedNameSpecifier *Qual = SS.getScopeRep();
9263 
9264   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
9265     NamedDecl *D = *I;
9266 
9267     bool DTypename;
9268     NestedNameSpecifier *DQual;
9269     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
9270       DTypename = UD->hasTypename();
9271       DQual = UD->getQualifier();
9272     } else if (UnresolvedUsingValueDecl *UD
9273                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
9274       DTypename = false;
9275       DQual = UD->getQualifier();
9276     } else if (UnresolvedUsingTypenameDecl *UD
9277                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
9278       DTypename = true;
9279       DQual = UD->getQualifier();
9280     } else continue;
9281 
9282     // using decls differ if one says 'typename' and the other doesn't.
9283     // FIXME: non-dependent using decls?
9284     if (HasTypenameKeyword != DTypename) continue;
9285 
9286     // using decls differ if they name different scopes (but note that
9287     // template instantiation can cause this check to trigger when it
9288     // didn't before instantiation).
9289     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
9290         Context.getCanonicalNestedNameSpecifier(DQual))
9291       continue;
9292 
9293     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
9294     Diag(D->getLocation(), diag::note_using_decl) << 1;
9295     return true;
9296   }
9297 
9298   return false;
9299 }
9300 
9301 
9302 /// Checks that the given nested-name qualifier used in a using decl
9303 /// in the current context is appropriately related to the current
9304 /// scope.  If an error is found, diagnoses it and returns true.
9305 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
9306                                    const CXXScopeSpec &SS,
9307                                    const DeclarationNameInfo &NameInfo,
9308                                    SourceLocation NameLoc) {
9309   DeclContext *NamedContext = computeDeclContext(SS);
9310 
9311   if (!CurContext->isRecord()) {
9312     // C++03 [namespace.udecl]p3:
9313     // C++0x [namespace.udecl]p8:
9314     //   A using-declaration for a class member shall be a member-declaration.
9315 
9316     // If we weren't able to compute a valid scope, it must be a
9317     // dependent class scope.
9318     if (!NamedContext || NamedContext->getRedeclContext()->isRecord()) {
9319       auto *RD = NamedContext
9320                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
9321                      : nullptr;
9322       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
9323         RD = nullptr;
9324 
9325       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
9326         << SS.getRange();
9327 
9328       // If we have a complete, non-dependent source type, try to suggest a
9329       // way to get the same effect.
9330       if (!RD)
9331         return true;
9332 
9333       // Find what this using-declaration was referring to.
9334       LookupResult R(*this, NameInfo, LookupOrdinaryName);
9335       R.setHideTags(false);
9336       R.suppressDiagnostics();
9337       LookupQualifiedName(R, RD);
9338 
9339       if (R.getAsSingle<TypeDecl>()) {
9340         if (getLangOpts().CPlusPlus11) {
9341           // Convert 'using X::Y;' to 'using Y = X::Y;'.
9342           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
9343             << 0 // alias declaration
9344             << FixItHint::CreateInsertion(SS.getBeginLoc(),
9345                                           NameInfo.getName().getAsString() +
9346                                               " = ");
9347         } else {
9348           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
9349           SourceLocation InsertLoc =
9350               getLocForEndOfToken(NameInfo.getLocEnd());
9351           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
9352             << 1 // typedef declaration
9353             << FixItHint::CreateReplacement(UsingLoc, "typedef")
9354             << FixItHint::CreateInsertion(
9355                    InsertLoc, " " + NameInfo.getName().getAsString());
9356         }
9357       } else if (R.getAsSingle<VarDecl>()) {
9358         // Don't provide a fixit outside C++11 mode; we don't want to suggest
9359         // repeating the type of the static data member here.
9360         FixItHint FixIt;
9361         if (getLangOpts().CPlusPlus11) {
9362           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
9363           FixIt = FixItHint::CreateReplacement(
9364               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
9365         }
9366 
9367         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
9368           << 2 // reference declaration
9369           << FixIt;
9370       } else if (R.getAsSingle<EnumConstantDecl>()) {
9371         // Don't provide a fixit outside C++11 mode; we don't want to suggest
9372         // repeating the type of the enumeration here, and we can't do so if
9373         // the type is anonymous.
9374         FixItHint FixIt;
9375         if (getLangOpts().CPlusPlus11) {
9376           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
9377           FixIt = FixItHint::CreateReplacement(
9378               UsingLoc, "constexpr auto " + NameInfo.getName().getAsString() + " = ");
9379         }
9380 
9381         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
9382           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
9383           << FixIt;
9384       }
9385       return true;
9386     }
9387 
9388     // Otherwise, everything is known to be fine.
9389     return false;
9390   }
9391 
9392   // The current scope is a record.
9393 
9394   // If the named context is dependent, we can't decide much.
9395   if (!NamedContext) {
9396     // FIXME: in C++0x, we can diagnose if we can prove that the
9397     // nested-name-specifier does not refer to a base class, which is
9398     // still possible in some cases.
9399 
9400     // Otherwise we have to conservatively report that things might be
9401     // okay.
9402     return false;
9403   }
9404 
9405   if (!NamedContext->isRecord()) {
9406     // Ideally this would point at the last name in the specifier,
9407     // but we don't have that level of source info.
9408     Diag(SS.getRange().getBegin(),
9409          diag::err_using_decl_nested_name_specifier_is_not_class)
9410       << SS.getScopeRep() << SS.getRange();
9411     return true;
9412   }
9413 
9414   if (!NamedContext->isDependentContext() &&
9415       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
9416     return true;
9417 
9418   if (getLangOpts().CPlusPlus11) {
9419     // C++11 [namespace.udecl]p3:
9420     //   In a using-declaration used as a member-declaration, the
9421     //   nested-name-specifier shall name a base class of the class
9422     //   being defined.
9423 
9424     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
9425                                  cast<CXXRecordDecl>(NamedContext))) {
9426       if (CurContext == NamedContext) {
9427         Diag(NameLoc,
9428              diag::err_using_decl_nested_name_specifier_is_current_class)
9429           << SS.getRange();
9430         return true;
9431       }
9432 
9433       Diag(SS.getRange().getBegin(),
9434            diag::err_using_decl_nested_name_specifier_is_not_base_class)
9435         << SS.getScopeRep()
9436         << cast<CXXRecordDecl>(CurContext)
9437         << SS.getRange();
9438       return true;
9439     }
9440 
9441     return false;
9442   }
9443 
9444   // C++03 [namespace.udecl]p4:
9445   //   A using-declaration used as a member-declaration shall refer
9446   //   to a member of a base class of the class being defined [etc.].
9447 
9448   // Salient point: SS doesn't have to name a base class as long as
9449   // lookup only finds members from base classes.  Therefore we can
9450   // diagnose here only if we can prove that that can't happen,
9451   // i.e. if the class hierarchies provably don't intersect.
9452 
9453   // TODO: it would be nice if "definitely valid" results were cached
9454   // in the UsingDecl and UsingShadowDecl so that these checks didn't
9455   // need to be repeated.
9456 
9457   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
9458   auto Collect = [&Bases](const CXXRecordDecl *Base) {
9459     Bases.insert(Base);
9460     return true;
9461   };
9462 
9463   // Collect all bases. Return false if we find a dependent base.
9464   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
9465     return false;
9466 
9467   // Returns true if the base is dependent or is one of the accumulated base
9468   // classes.
9469   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
9470     return !Bases.count(Base);
9471   };
9472 
9473   // Return false if the class has a dependent base or if it or one
9474   // of its bases is present in the base set of the current context.
9475   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
9476       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
9477     return false;
9478 
9479   Diag(SS.getRange().getBegin(),
9480        diag::err_using_decl_nested_name_specifier_is_not_base_class)
9481     << SS.getScopeRep()
9482     << cast<CXXRecordDecl>(CurContext)
9483     << SS.getRange();
9484 
9485   return true;
9486 }
9487 
9488 Decl *Sema::ActOnAliasDeclaration(Scope *S,
9489                                   AccessSpecifier AS,
9490                                   MultiTemplateParamsArg TemplateParamLists,
9491                                   SourceLocation UsingLoc,
9492                                   UnqualifiedId &Name,
9493                                   AttributeList *AttrList,
9494                                   TypeResult Type,
9495                                   Decl *DeclFromDeclSpec) {
9496   // Skip up to the relevant declaration scope.
9497   while (S->isTemplateParamScope())
9498     S = S->getParent();
9499   assert((S->getFlags() & Scope::DeclScope) &&
9500          "got alias-declaration outside of declaration scope");
9501 
9502   if (Type.isInvalid())
9503     return nullptr;
9504 
9505   bool Invalid = false;
9506   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
9507   TypeSourceInfo *TInfo = nullptr;
9508   GetTypeFromParser(Type.get(), &TInfo);
9509 
9510   if (DiagnoseClassNameShadow(CurContext, NameInfo))
9511     return nullptr;
9512 
9513   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
9514                                       UPPC_DeclarationType)) {
9515     Invalid = true;
9516     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9517                                              TInfo->getTypeLoc().getBeginLoc());
9518   }
9519 
9520   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
9521   LookupName(Previous, S);
9522 
9523   // Warn about shadowing the name of a template parameter.
9524   if (Previous.isSingleResult() &&
9525       Previous.getFoundDecl()->isTemplateParameter()) {
9526     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
9527     Previous.clear();
9528   }
9529 
9530   assert(Name.Kind == UnqualifiedId::IK_Identifier &&
9531          "name in alias declaration must be an identifier");
9532   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
9533                                                Name.StartLocation,
9534                                                Name.Identifier, TInfo);
9535 
9536   NewTD->setAccess(AS);
9537 
9538   if (Invalid)
9539     NewTD->setInvalidDecl();
9540 
9541   ProcessDeclAttributeList(S, NewTD, AttrList);
9542 
9543   CheckTypedefForVariablyModifiedType(S, NewTD);
9544   Invalid |= NewTD->isInvalidDecl();
9545 
9546   bool Redeclaration = false;
9547 
9548   NamedDecl *NewND;
9549   if (TemplateParamLists.size()) {
9550     TypeAliasTemplateDecl *OldDecl = nullptr;
9551     TemplateParameterList *OldTemplateParams = nullptr;
9552 
9553     if (TemplateParamLists.size() != 1) {
9554       Diag(UsingLoc, diag::err_alias_template_extra_headers)
9555         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
9556          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
9557     }
9558     TemplateParameterList *TemplateParams = TemplateParamLists[0];
9559 
9560     // Check that we can declare a template here.
9561     if (CheckTemplateDeclScope(S, TemplateParams))
9562       return nullptr;
9563 
9564     // Only consider previous declarations in the same scope.
9565     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
9566                          /*ExplicitInstantiationOrSpecialization*/false);
9567     if (!Previous.empty()) {
9568       Redeclaration = true;
9569 
9570       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
9571       if (!OldDecl && !Invalid) {
9572         Diag(UsingLoc, diag::err_redefinition_different_kind)
9573           << Name.Identifier;
9574 
9575         NamedDecl *OldD = Previous.getRepresentativeDecl();
9576         if (OldD->getLocation().isValid())
9577           Diag(OldD->getLocation(), diag::note_previous_definition);
9578 
9579         Invalid = true;
9580       }
9581 
9582       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
9583         if (TemplateParameterListsAreEqual(TemplateParams,
9584                                            OldDecl->getTemplateParameters(),
9585                                            /*Complain=*/true,
9586                                            TPL_TemplateMatch))
9587           OldTemplateParams = OldDecl->getTemplateParameters();
9588         else
9589           Invalid = true;
9590 
9591         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
9592         if (!Invalid &&
9593             !Context.hasSameType(OldTD->getUnderlyingType(),
9594                                  NewTD->getUnderlyingType())) {
9595           // FIXME: The C++0x standard does not clearly say this is ill-formed,
9596           // but we can't reasonably accept it.
9597           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
9598             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
9599           if (OldTD->getLocation().isValid())
9600             Diag(OldTD->getLocation(), diag::note_previous_definition);
9601           Invalid = true;
9602         }
9603       }
9604     }
9605 
9606     // Merge any previous default template arguments into our parameters,
9607     // and check the parameter list.
9608     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
9609                                    TPC_TypeAliasTemplate))
9610       return nullptr;
9611 
9612     TypeAliasTemplateDecl *NewDecl =
9613       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
9614                                     Name.Identifier, TemplateParams,
9615                                     NewTD);
9616     NewTD->setDescribedAliasTemplate(NewDecl);
9617 
9618     NewDecl->setAccess(AS);
9619 
9620     if (Invalid)
9621       NewDecl->setInvalidDecl();
9622     else if (OldDecl)
9623       NewDecl->setPreviousDecl(OldDecl);
9624 
9625     NewND = NewDecl;
9626   } else {
9627     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
9628       setTagNameForLinkagePurposes(TD, NewTD);
9629       handleTagNumbering(TD, S);
9630     }
9631     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
9632     NewND = NewTD;
9633   }
9634 
9635   PushOnScopeChains(NewND, S);
9636   ActOnDocumentableDecl(NewND);
9637   return NewND;
9638 }
9639 
9640 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
9641                                    SourceLocation AliasLoc,
9642                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
9643                                    SourceLocation IdentLoc,
9644                                    IdentifierInfo *Ident) {
9645 
9646   // Lookup the namespace name.
9647   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
9648   LookupParsedName(R, S, &SS);
9649 
9650   if (R.isAmbiguous())
9651     return nullptr;
9652 
9653   if (R.empty()) {
9654     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
9655       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
9656       return nullptr;
9657     }
9658   }
9659   assert(!R.isAmbiguous() && !R.empty());
9660   NamedDecl *ND = R.getRepresentativeDecl();
9661 
9662   // Check if we have a previous declaration with the same name.
9663   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
9664                      ForRedeclaration);
9665   LookupName(PrevR, S);
9666 
9667   // Check we're not shadowing a template parameter.
9668   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
9669     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
9670     PrevR.clear();
9671   }
9672 
9673   // Filter out any other lookup result from an enclosing scope.
9674   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
9675                        /*AllowInlineNamespace*/false);
9676 
9677   // Find the previous declaration and check that we can redeclare it.
9678   NamespaceAliasDecl *Prev = nullptr;
9679   if (PrevR.isSingleResult()) {
9680     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
9681     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
9682       // We already have an alias with the same name that points to the same
9683       // namespace; check that it matches.
9684       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
9685         Prev = AD;
9686       } else if (isVisible(PrevDecl)) {
9687         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
9688           << Alias;
9689         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
9690           << AD->getNamespace();
9691         return nullptr;
9692       }
9693     } else if (isVisible(PrevDecl)) {
9694       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
9695                             ? diag::err_redefinition
9696                             : diag::err_redefinition_different_kind;
9697       Diag(AliasLoc, DiagID) << Alias;
9698       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
9699       return nullptr;
9700     }
9701   }
9702 
9703   // The use of a nested name specifier may trigger deprecation warnings.
9704   DiagnoseUseOfDecl(ND, IdentLoc);
9705 
9706   NamespaceAliasDecl *AliasDecl =
9707     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
9708                                Alias, SS.getWithLocInContext(Context),
9709                                IdentLoc, ND);
9710   if (Prev)
9711     AliasDecl->setPreviousDecl(Prev);
9712 
9713   PushOnScopeChains(AliasDecl, S);
9714   return AliasDecl;
9715 }
9716 
9717 Sema::ImplicitExceptionSpecification
9718 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
9719                                                CXXMethodDecl *MD) {
9720   CXXRecordDecl *ClassDecl = MD->getParent();
9721 
9722   // C++ [except.spec]p14:
9723   //   An implicitly declared special member function (Clause 12) shall have an
9724   //   exception-specification. [...]
9725   ImplicitExceptionSpecification ExceptSpec(*this);
9726   if (ClassDecl->isInvalidDecl())
9727     return ExceptSpec;
9728 
9729   // Direct base-class constructors.
9730   for (const auto &B : ClassDecl->bases()) {
9731     if (B.isVirtual()) // Handled below.
9732       continue;
9733 
9734     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
9735       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
9736       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
9737       // If this is a deleted function, add it anyway. This might be conformant
9738       // with the standard. This might not. I'm not sure. It might not matter.
9739       if (Constructor)
9740         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
9741     }
9742   }
9743 
9744   // Virtual base-class constructors.
9745   for (const auto &B : ClassDecl->vbases()) {
9746     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
9747       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
9748       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
9749       // If this is a deleted function, add it anyway. This might be conformant
9750       // with the standard. This might not. I'm not sure. It might not matter.
9751       if (Constructor)
9752         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
9753     }
9754   }
9755 
9756   // Field constructors.
9757   for (const auto *F : ClassDecl->fields()) {
9758     if (F->hasInClassInitializer()) {
9759       if (Expr *E = F->getInClassInitializer())
9760         ExceptSpec.CalledExpr(E);
9761     } else if (const RecordType *RecordTy
9762               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
9763       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9764       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
9765       // If this is a deleted function, add it anyway. This might be conformant
9766       // with the standard. This might not. I'm not sure. It might not matter.
9767       // In particular, the problem is that this function never gets called. It
9768       // might just be ill-formed because this function attempts to refer to
9769       // a deleted function here.
9770       if (Constructor)
9771         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
9772     }
9773   }
9774 
9775   return ExceptSpec;
9776 }
9777 
9778 Sema::ImplicitExceptionSpecification
9779 Sema::ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
9780                                          CXXConstructorDecl *CD) {
9781   CXXRecordDecl *ClassDecl = CD->getParent();
9782 
9783   // C++ [except.spec]p14:
9784   //   An inheriting constructor [...] shall have an exception-specification. [...]
9785   ImplicitExceptionSpecification ExceptSpec(*this);
9786   if (ClassDecl->isInvalidDecl())
9787     return ExceptSpec;
9788 
9789   auto Inherited = CD->getInheritedConstructor();
9790   InheritedConstructorInfo ICI(*this, Loc, Inherited.getShadowDecl());
9791 
9792   // Direct and virtual base-class constructors.
9793   for (bool VBase : {false, true}) {
9794     for (CXXBaseSpecifier &B :
9795          VBase ? ClassDecl->vbases() : ClassDecl->bases()) {
9796       // Don't visit direct vbases twice.
9797       if (B.isVirtual() != VBase)
9798         continue;
9799 
9800       CXXRecordDecl *BaseClass = B.getType()->getAsCXXRecordDecl();
9801       if (!BaseClass)
9802         continue;
9803 
9804       CXXConstructorDecl *Constructor =
9805           ICI.findConstructorForBase(BaseClass, Inherited.getConstructor())
9806               .first;
9807       if (!Constructor)
9808         Constructor = LookupDefaultConstructor(BaseClass);
9809       if (Constructor)
9810         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
9811     }
9812   }
9813 
9814   // Field constructors.
9815   for (const auto *F : ClassDecl->fields()) {
9816     if (F->hasInClassInitializer()) {
9817       if (Expr *E = F->getInClassInitializer())
9818         ExceptSpec.CalledExpr(E);
9819     } else if (const RecordType *RecordTy
9820               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
9821       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9822       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
9823       if (Constructor)
9824         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
9825     }
9826   }
9827 
9828   return ExceptSpec;
9829 }
9830 
9831 namespace {
9832 /// RAII object to register a special member as being currently declared.
9833 struct DeclaringSpecialMember {
9834   Sema &S;
9835   Sema::SpecialMemberDecl D;
9836   Sema::ContextRAII SavedContext;
9837   bool WasAlreadyBeingDeclared;
9838 
9839   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
9840     : S(S), D(RD, CSM), SavedContext(S, RD) {
9841     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
9842     if (WasAlreadyBeingDeclared)
9843       // This almost never happens, but if it does, ensure that our cache
9844       // doesn't contain a stale result.
9845       S.SpecialMemberCache.clear();
9846 
9847     // FIXME: Register a note to be produced if we encounter an error while
9848     // declaring the special member.
9849   }
9850   ~DeclaringSpecialMember() {
9851     if (!WasAlreadyBeingDeclared)
9852       S.SpecialMembersBeingDeclared.erase(D);
9853   }
9854 
9855   /// \brief Are we already trying to declare this special member?
9856   bool isAlreadyBeingDeclared() const {
9857     return WasAlreadyBeingDeclared;
9858   }
9859 };
9860 }
9861 
9862 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
9863   // Look up any existing declarations, but don't trigger declaration of all
9864   // implicit special members with this name.
9865   DeclarationName Name = FD->getDeclName();
9866   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
9867                  ForRedeclaration);
9868   for (auto *D : FD->getParent()->lookup(Name))
9869     if (auto *Acceptable = R.getAcceptableDecl(D))
9870       R.addDecl(Acceptable);
9871   R.resolveKind();
9872   R.suppressDiagnostics();
9873 
9874   CheckFunctionDeclaration(S, FD, R, /*IsExplicitSpecialization*/false);
9875 }
9876 
9877 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
9878                                                      CXXRecordDecl *ClassDecl) {
9879   // C++ [class.ctor]p5:
9880   //   A default constructor for a class X is a constructor of class X
9881   //   that can be called without an argument. If there is no
9882   //   user-declared constructor for class X, a default constructor is
9883   //   implicitly declared. An implicitly-declared default constructor
9884   //   is an inline public member of its class.
9885   assert(ClassDecl->needsImplicitDefaultConstructor() &&
9886          "Should not build implicit default constructor!");
9887 
9888   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
9889   if (DSM.isAlreadyBeingDeclared())
9890     return nullptr;
9891 
9892   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9893                                                      CXXDefaultConstructor,
9894                                                      false);
9895 
9896   // Create the actual constructor declaration.
9897   CanQualType ClassType
9898     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
9899   SourceLocation ClassLoc = ClassDecl->getLocation();
9900   DeclarationName Name
9901     = Context.DeclarationNames.getCXXConstructorName(ClassType);
9902   DeclarationNameInfo NameInfo(Name, ClassLoc);
9903   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
9904       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
9905       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
9906       /*isImplicitlyDeclared=*/true, Constexpr);
9907   DefaultCon->setAccess(AS_public);
9908   DefaultCon->setDefaulted();
9909 
9910   if (getLangOpts().CUDA) {
9911     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
9912                                             DefaultCon,
9913                                             /* ConstRHS */ false,
9914                                             /* Diagnose */ false);
9915   }
9916 
9917   // Build an exception specification pointing back at this constructor.
9918   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
9919   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9920 
9921   // We don't need to use SpecialMemberIsTrivial here; triviality for default
9922   // constructors is easy to compute.
9923   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
9924 
9925   // Note that we have declared this constructor.
9926   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
9927 
9928   Scope *S = getScopeForContext(ClassDecl);
9929   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
9930 
9931   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
9932     SetDeclDeleted(DefaultCon, ClassLoc);
9933 
9934   if (S)
9935     PushOnScopeChains(DefaultCon, S, false);
9936   ClassDecl->addDecl(DefaultCon);
9937 
9938   return DefaultCon;
9939 }
9940 
9941 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
9942                                             CXXConstructorDecl *Constructor) {
9943   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
9944           !Constructor->doesThisDeclarationHaveABody() &&
9945           !Constructor->isDeleted()) &&
9946     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
9947 
9948   CXXRecordDecl *ClassDecl = Constructor->getParent();
9949   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
9950 
9951   SynthesizedFunctionScope Scope(*this, Constructor);
9952   DiagnosticErrorTrap Trap(Diags);
9953   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
9954       Trap.hasErrorOccurred()) {
9955     Diag(CurrentLocation, diag::note_member_synthesized_at)
9956       << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
9957     Constructor->setInvalidDecl();
9958     return;
9959   }
9960 
9961   // The exception specification is needed because we are defining the
9962   // function.
9963   ResolveExceptionSpec(CurrentLocation,
9964                        Constructor->getType()->castAs<FunctionProtoType>());
9965 
9966   SourceLocation Loc = Constructor->getLocEnd().isValid()
9967                            ? Constructor->getLocEnd()
9968                            : Constructor->getLocation();
9969   Constructor->setBody(new (Context) CompoundStmt(Loc));
9970 
9971   Constructor->markUsed(Context);
9972   MarkVTableUsed(CurrentLocation, ClassDecl);
9973 
9974   if (ASTMutationListener *L = getASTMutationListener()) {
9975     L->CompletedImplicitDefinition(Constructor);
9976   }
9977 
9978   DiagnoseUninitializedFields(*this, Constructor);
9979 }
9980 
9981 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
9982   // Perform any delayed checks on exception specifications.
9983   CheckDelayedMemberExceptionSpecs();
9984 }
9985 
9986 /// Find or create the fake constructor we synthesize to model constructing an
9987 /// object of a derived class via a constructor of a base class.
9988 CXXConstructorDecl *
9989 Sema::findInheritingConstructor(SourceLocation Loc,
9990                                 CXXConstructorDecl *BaseCtor,
9991                                 ConstructorUsingShadowDecl *Shadow) {
9992   CXXRecordDecl *Derived = Shadow->getParent();
9993   SourceLocation UsingLoc = Shadow->getLocation();
9994 
9995   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
9996   // For now we use the name of the base class constructor as a member of the
9997   // derived class to indicate a (fake) inherited constructor name.
9998   DeclarationName Name = BaseCtor->getDeclName();
9999 
10000   // Check to see if we already have a fake constructor for this inherited
10001   // constructor call.
10002   for (NamedDecl *Ctor : Derived->lookup(Name))
10003     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
10004                                ->getInheritedConstructor()
10005                                .getConstructor(),
10006                            BaseCtor))
10007       return cast<CXXConstructorDecl>(Ctor);
10008 
10009   DeclarationNameInfo NameInfo(Name, UsingLoc);
10010   TypeSourceInfo *TInfo =
10011       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
10012   FunctionProtoTypeLoc ProtoLoc =
10013       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
10014 
10015   // Check the inherited constructor is valid and find the list of base classes
10016   // from which it was inherited.
10017   InheritedConstructorInfo ICI(*this, Loc, Shadow);
10018 
10019   bool Constexpr =
10020       BaseCtor->isConstexpr() &&
10021       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
10022                                         false, BaseCtor, &ICI);
10023 
10024   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
10025       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
10026       BaseCtor->isExplicit(), /*Inline=*/true,
10027       /*ImplicitlyDeclared=*/true, Constexpr,
10028       InheritedConstructor(Shadow, BaseCtor));
10029   if (Shadow->isInvalidDecl())
10030     DerivedCtor->setInvalidDecl();
10031 
10032   // Build an unevaluated exception specification for this fake constructor.
10033   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
10034   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10035   EPI.ExceptionSpec.Type = EST_Unevaluated;
10036   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
10037   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
10038                                                FPT->getParamTypes(), EPI));
10039 
10040   // Build the parameter declarations.
10041   SmallVector<ParmVarDecl *, 16> ParamDecls;
10042   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
10043     TypeSourceInfo *TInfo =
10044         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
10045     ParmVarDecl *PD = ParmVarDecl::Create(
10046         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
10047         FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
10048     PD->setScopeInfo(0, I);
10049     PD->setImplicit();
10050     // Ensure attributes are propagated onto parameters (this matters for
10051     // format, pass_object_size, ...).
10052     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
10053     ParamDecls.push_back(PD);
10054     ProtoLoc.setParam(I, PD);
10055   }
10056 
10057   // Set up the new constructor.
10058   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
10059   DerivedCtor->setAccess(BaseCtor->getAccess());
10060   DerivedCtor->setParams(ParamDecls);
10061   Derived->addDecl(DerivedCtor);
10062 
10063   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
10064     SetDeclDeleted(DerivedCtor, UsingLoc);
10065 
10066   return DerivedCtor;
10067 }
10068 
10069 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
10070   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
10071                                Ctor->getInheritedConstructor().getShadowDecl());
10072   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
10073                             /*Diagnose*/true);
10074 }
10075 
10076 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
10077                                        CXXConstructorDecl *Constructor) {
10078   CXXRecordDecl *ClassDecl = Constructor->getParent();
10079   assert(Constructor->getInheritedConstructor() &&
10080          !Constructor->doesThisDeclarationHaveABody() &&
10081          !Constructor->isDeleted());
10082   if (Constructor->isInvalidDecl())
10083     return;
10084 
10085   ConstructorUsingShadowDecl *Shadow =
10086       Constructor->getInheritedConstructor().getShadowDecl();
10087   CXXConstructorDecl *InheritedCtor =
10088       Constructor->getInheritedConstructor().getConstructor();
10089 
10090   // [class.inhctor.init]p1:
10091   //   initialization proceeds as if a defaulted default constructor is used to
10092   //   initialize the D object and each base class subobject from which the
10093   //   constructor was inherited
10094 
10095   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
10096   CXXRecordDecl *RD = Shadow->getParent();
10097   SourceLocation InitLoc = Shadow->getLocation();
10098 
10099   // Initializations are performed "as if by a defaulted default constructor",
10100   // so enter the appropriate scope.
10101   SynthesizedFunctionScope Scope(*this, Constructor);
10102   DiagnosticErrorTrap Trap(Diags);
10103 
10104   // Build explicit initializers for all base classes from which the
10105   // constructor was inherited.
10106   SmallVector<CXXCtorInitializer*, 8> Inits;
10107   for (bool VBase : {false, true}) {
10108     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
10109       if (B.isVirtual() != VBase)
10110         continue;
10111 
10112       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
10113       if (!BaseRD)
10114         continue;
10115 
10116       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
10117       if (!BaseCtor.first)
10118         continue;
10119 
10120       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
10121       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
10122           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
10123 
10124       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
10125       Inits.push_back(new (Context) CXXCtorInitializer(
10126           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
10127           SourceLocation()));
10128     }
10129   }
10130 
10131   // We now proceed as if for a defaulted default constructor, with the relevant
10132   // initializers replaced.
10133 
10134   bool HadError = SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits);
10135   if (HadError || Trap.hasErrorOccurred()) {
10136     Diag(CurrentLocation, diag::note_inhctor_synthesized_at) << RD;
10137     Constructor->setInvalidDecl();
10138     return;
10139   }
10140 
10141   // The exception specification is needed because we are defining the
10142   // function.
10143   ResolveExceptionSpec(CurrentLocation,
10144                        Constructor->getType()->castAs<FunctionProtoType>());
10145 
10146   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
10147 
10148   Constructor->markUsed(Context);
10149   MarkVTableUsed(CurrentLocation, ClassDecl);
10150 
10151   if (ASTMutationListener *L = getASTMutationListener()) {
10152     L->CompletedImplicitDefinition(Constructor);
10153   }
10154 
10155   DiagnoseUninitializedFields(*this, Constructor);
10156 }
10157 
10158 Sema::ImplicitExceptionSpecification
10159 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
10160   CXXRecordDecl *ClassDecl = MD->getParent();
10161 
10162   // C++ [except.spec]p14:
10163   //   An implicitly declared special member function (Clause 12) shall have
10164   //   an exception-specification.
10165   ImplicitExceptionSpecification ExceptSpec(*this);
10166   if (ClassDecl->isInvalidDecl())
10167     return ExceptSpec;
10168 
10169   // Direct base-class destructors.
10170   for (const auto &B : ClassDecl->bases()) {
10171     if (B.isVirtual()) // Handled below.
10172       continue;
10173 
10174     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
10175       ExceptSpec.CalledDecl(B.getLocStart(),
10176                    LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
10177   }
10178 
10179   // Virtual base-class destructors.
10180   for (const auto &B : ClassDecl->vbases()) {
10181     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
10182       ExceptSpec.CalledDecl(B.getLocStart(),
10183                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
10184   }
10185 
10186   // Field destructors.
10187   for (const auto *F : ClassDecl->fields()) {
10188     if (const RecordType *RecordTy
10189         = Context.getBaseElementType(F->getType())->getAs<RecordType>())
10190       ExceptSpec.CalledDecl(F->getLocation(),
10191                   LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
10192   }
10193 
10194   return ExceptSpec;
10195 }
10196 
10197 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
10198   // C++ [class.dtor]p2:
10199   //   If a class has no user-declared destructor, a destructor is
10200   //   declared implicitly. An implicitly-declared destructor is an
10201   //   inline public member of its class.
10202   assert(ClassDecl->needsImplicitDestructor());
10203 
10204   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
10205   if (DSM.isAlreadyBeingDeclared())
10206     return nullptr;
10207 
10208   // Create the actual destructor declaration.
10209   CanQualType ClassType
10210     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10211   SourceLocation ClassLoc = ClassDecl->getLocation();
10212   DeclarationName Name
10213     = Context.DeclarationNames.getCXXDestructorName(ClassType);
10214   DeclarationNameInfo NameInfo(Name, ClassLoc);
10215   CXXDestructorDecl *Destructor
10216       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
10217                                   QualType(), nullptr, /*isInline=*/true,
10218                                   /*isImplicitlyDeclared=*/true);
10219   Destructor->setAccess(AS_public);
10220   Destructor->setDefaulted();
10221 
10222   if (getLangOpts().CUDA) {
10223     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
10224                                             Destructor,
10225                                             /* ConstRHS */ false,
10226                                             /* Diagnose */ false);
10227   }
10228 
10229   // Build an exception specification pointing back at this destructor.
10230   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
10231   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10232 
10233   // We don't need to use SpecialMemberIsTrivial here; triviality for
10234   // destructors is easy to compute.
10235   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
10236 
10237   // Note that we have declared this destructor.
10238   ++ASTContext::NumImplicitDestructorsDeclared;
10239 
10240   Scope *S = getScopeForContext(ClassDecl);
10241   CheckImplicitSpecialMemberDeclaration(S, Destructor);
10242 
10243   if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
10244     SetDeclDeleted(Destructor, ClassLoc);
10245 
10246   // Introduce this destructor into its scope.
10247   if (S)
10248     PushOnScopeChains(Destructor, S, false);
10249   ClassDecl->addDecl(Destructor);
10250 
10251   return Destructor;
10252 }
10253 
10254 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
10255                                     CXXDestructorDecl *Destructor) {
10256   assert((Destructor->isDefaulted() &&
10257           !Destructor->doesThisDeclarationHaveABody() &&
10258           !Destructor->isDeleted()) &&
10259          "DefineImplicitDestructor - call it for implicit default dtor");
10260   CXXRecordDecl *ClassDecl = Destructor->getParent();
10261   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
10262 
10263   if (Destructor->isInvalidDecl())
10264     return;
10265 
10266   SynthesizedFunctionScope Scope(*this, Destructor);
10267 
10268   DiagnosticErrorTrap Trap(Diags);
10269   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
10270                                          Destructor->getParent());
10271 
10272   if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
10273     Diag(CurrentLocation, diag::note_member_synthesized_at)
10274       << CXXDestructor << Context.getTagDeclType(ClassDecl);
10275 
10276     Destructor->setInvalidDecl();
10277     return;
10278   }
10279 
10280   // The exception specification is needed because we are defining the
10281   // function.
10282   ResolveExceptionSpec(CurrentLocation,
10283                        Destructor->getType()->castAs<FunctionProtoType>());
10284 
10285   SourceLocation Loc = Destructor->getLocEnd().isValid()
10286                            ? Destructor->getLocEnd()
10287                            : Destructor->getLocation();
10288   Destructor->setBody(new (Context) CompoundStmt(Loc));
10289   Destructor->markUsed(Context);
10290   MarkVTableUsed(CurrentLocation, ClassDecl);
10291 
10292   if (ASTMutationListener *L = getASTMutationListener()) {
10293     L->CompletedImplicitDefinition(Destructor);
10294   }
10295 }
10296 
10297 /// \brief Perform any semantic analysis which needs to be delayed until all
10298 /// pending class member declarations have been parsed.
10299 void Sema::ActOnFinishCXXMemberDecls() {
10300   // If the context is an invalid C++ class, just suppress these checks.
10301   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
10302     if (Record->isInvalidDecl()) {
10303       DelayedDefaultedMemberExceptionSpecs.clear();
10304       DelayedExceptionSpecChecks.clear();
10305       return;
10306     }
10307   }
10308 }
10309 
10310 static void getDefaultArgExprsForConstructors(Sema &S, CXXRecordDecl *Class) {
10311   // Don't do anything for template patterns.
10312   if (Class->getDescribedClassTemplate())
10313     return;
10314 
10315   CallingConv ExpectedCallingConv = S.Context.getDefaultCallingConvention(
10316       /*IsVariadic=*/false, /*IsCXXMethod=*/true);
10317 
10318   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
10319   for (Decl *Member : Class->decls()) {
10320     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
10321     if (!CD) {
10322       // Recurse on nested classes.
10323       if (auto *NestedRD = dyn_cast<CXXRecordDecl>(Member))
10324         getDefaultArgExprsForConstructors(S, NestedRD);
10325       continue;
10326     } else if (!CD->isDefaultConstructor() || !CD->hasAttr<DLLExportAttr>()) {
10327       continue;
10328     }
10329 
10330     CallingConv ActualCallingConv =
10331         CD->getType()->getAs<FunctionProtoType>()->getCallConv();
10332 
10333     // Skip default constructors with typical calling conventions and no default
10334     // arguments.
10335     unsigned NumParams = CD->getNumParams();
10336     if (ExpectedCallingConv == ActualCallingConv && NumParams == 0)
10337       continue;
10338 
10339     if (LastExportedDefaultCtor) {
10340       S.Diag(LastExportedDefaultCtor->getLocation(),
10341              diag::err_attribute_dll_ambiguous_default_ctor) << Class;
10342       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
10343           << CD->getDeclName();
10344       return;
10345     }
10346     LastExportedDefaultCtor = CD;
10347 
10348     for (unsigned I = 0; I != NumParams; ++I) {
10349       // Skip any default arguments that we've already instantiated.
10350       if (S.Context.getDefaultArgExprForConstructor(CD, I))
10351         continue;
10352 
10353       Expr *DefaultArg = S.BuildCXXDefaultArgExpr(Class->getLocation(), CD,
10354                                                   CD->getParamDecl(I)).get();
10355       S.DiscardCleanupsInEvaluationContext();
10356       S.Context.addDefaultArgExprForConstructor(CD, I, DefaultArg);
10357     }
10358   }
10359 }
10360 
10361 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
10362   auto *RD = dyn_cast<CXXRecordDecl>(D);
10363 
10364   // Default constructors that are annotated with __declspec(dllexport) which
10365   // have default arguments or don't use the standard calling convention are
10366   // wrapped with a thunk called the default constructor closure.
10367   if (RD && Context.getTargetInfo().getCXXABI().isMicrosoft())
10368     getDefaultArgExprsForConstructors(*this, RD);
10369 
10370   referenceDLLExportedClassMethods();
10371 }
10372 
10373 void Sema::referenceDLLExportedClassMethods() {
10374   if (!DelayedDllExportClasses.empty()) {
10375     // Calling ReferenceDllExportedMethods might cause the current function to
10376     // be called again, so use a local copy of DelayedDllExportClasses.
10377     SmallVector<CXXRecordDecl *, 4> WorkList;
10378     std::swap(DelayedDllExportClasses, WorkList);
10379     for (CXXRecordDecl *Class : WorkList)
10380       ReferenceDllExportedMethods(*this, Class);
10381   }
10382 }
10383 
10384 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
10385                                          CXXDestructorDecl *Destructor) {
10386   assert(getLangOpts().CPlusPlus11 &&
10387          "adjusting dtor exception specs was introduced in c++11");
10388 
10389   // C++11 [class.dtor]p3:
10390   //   A declaration of a destructor that does not have an exception-
10391   //   specification is implicitly considered to have the same exception-
10392   //   specification as an implicit declaration.
10393   const FunctionProtoType *DtorType = Destructor->getType()->
10394                                         getAs<FunctionProtoType>();
10395   if (DtorType->hasExceptionSpec())
10396     return;
10397 
10398   // Replace the destructor's type, building off the existing one. Fortunately,
10399   // the only thing of interest in the destructor type is its extended info.
10400   // The return and arguments are fixed.
10401   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
10402   EPI.ExceptionSpec.Type = EST_Unevaluated;
10403   EPI.ExceptionSpec.SourceDecl = Destructor;
10404   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10405 
10406   // FIXME: If the destructor has a body that could throw, and the newly created
10407   // spec doesn't allow exceptions, we should emit a warning, because this
10408   // change in behavior can break conforming C++03 programs at runtime.
10409   // However, we don't have a body or an exception specification yet, so it
10410   // needs to be done somewhere else.
10411 }
10412 
10413 namespace {
10414 /// \brief An abstract base class for all helper classes used in building the
10415 //  copy/move operators. These classes serve as factory functions and help us
10416 //  avoid using the same Expr* in the AST twice.
10417 class ExprBuilder {
10418   ExprBuilder(const ExprBuilder&) = delete;
10419   ExprBuilder &operator=(const ExprBuilder&) = delete;
10420 
10421 protected:
10422   static Expr *assertNotNull(Expr *E) {
10423     assert(E && "Expression construction must not fail.");
10424     return E;
10425   }
10426 
10427 public:
10428   ExprBuilder() {}
10429   virtual ~ExprBuilder() {}
10430 
10431   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
10432 };
10433 
10434 class RefBuilder: public ExprBuilder {
10435   VarDecl *Var;
10436   QualType VarType;
10437 
10438 public:
10439   Expr *build(Sema &S, SourceLocation Loc) const override {
10440     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
10441   }
10442 
10443   RefBuilder(VarDecl *Var, QualType VarType)
10444       : Var(Var), VarType(VarType) {}
10445 };
10446 
10447 class ThisBuilder: public ExprBuilder {
10448 public:
10449   Expr *build(Sema &S, SourceLocation Loc) const override {
10450     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
10451   }
10452 };
10453 
10454 class CastBuilder: public ExprBuilder {
10455   const ExprBuilder &Builder;
10456   QualType Type;
10457   ExprValueKind Kind;
10458   const CXXCastPath &Path;
10459 
10460 public:
10461   Expr *build(Sema &S, SourceLocation Loc) const override {
10462     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
10463                                              CK_UncheckedDerivedToBase, Kind,
10464                                              &Path).get());
10465   }
10466 
10467   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
10468               const CXXCastPath &Path)
10469       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
10470 };
10471 
10472 class DerefBuilder: public ExprBuilder {
10473   const ExprBuilder &Builder;
10474 
10475 public:
10476   Expr *build(Sema &S, SourceLocation Loc) const override {
10477     return assertNotNull(
10478         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
10479   }
10480 
10481   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10482 };
10483 
10484 class MemberBuilder: public ExprBuilder {
10485   const ExprBuilder &Builder;
10486   QualType Type;
10487   CXXScopeSpec SS;
10488   bool IsArrow;
10489   LookupResult &MemberLookup;
10490 
10491 public:
10492   Expr *build(Sema &S, SourceLocation Loc) const override {
10493     return assertNotNull(S.BuildMemberReferenceExpr(
10494         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
10495         nullptr, MemberLookup, nullptr, nullptr).get());
10496   }
10497 
10498   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
10499                 LookupResult &MemberLookup)
10500       : Builder(Builder), Type(Type), IsArrow(IsArrow),
10501         MemberLookup(MemberLookup) {}
10502 };
10503 
10504 class MoveCastBuilder: public ExprBuilder {
10505   const ExprBuilder &Builder;
10506 
10507 public:
10508   Expr *build(Sema &S, SourceLocation Loc) const override {
10509     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
10510   }
10511 
10512   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10513 };
10514 
10515 class LvalueConvBuilder: public ExprBuilder {
10516   const ExprBuilder &Builder;
10517 
10518 public:
10519   Expr *build(Sema &S, SourceLocation Loc) const override {
10520     return assertNotNull(
10521         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
10522   }
10523 
10524   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10525 };
10526 
10527 class SubscriptBuilder: public ExprBuilder {
10528   const ExprBuilder &Base;
10529   const ExprBuilder &Index;
10530 
10531 public:
10532   Expr *build(Sema &S, SourceLocation Loc) const override {
10533     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
10534         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
10535   }
10536 
10537   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
10538       : Base(Base), Index(Index) {}
10539 };
10540 
10541 } // end anonymous namespace
10542 
10543 /// When generating a defaulted copy or move assignment operator, if a field
10544 /// should be copied with __builtin_memcpy rather than via explicit assignments,
10545 /// do so. This optimization only applies for arrays of scalars, and for arrays
10546 /// of class type where the selected copy/move-assignment operator is trivial.
10547 static StmtResult
10548 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
10549                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
10550   // Compute the size of the memory buffer to be copied.
10551   QualType SizeType = S.Context.getSizeType();
10552   llvm::APInt Size(S.Context.getTypeSize(SizeType),
10553                    S.Context.getTypeSizeInChars(T).getQuantity());
10554 
10555   // Take the address of the field references for "from" and "to". We
10556   // directly construct UnaryOperators here because semantic analysis
10557   // does not permit us to take the address of an xvalue.
10558   Expr *From = FromB.build(S, Loc);
10559   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
10560                          S.Context.getPointerType(From->getType()),
10561                          VK_RValue, OK_Ordinary, Loc);
10562   Expr *To = ToB.build(S, Loc);
10563   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
10564                        S.Context.getPointerType(To->getType()),
10565                        VK_RValue, OK_Ordinary, Loc);
10566 
10567   const Type *E = T->getBaseElementTypeUnsafe();
10568   bool NeedsCollectableMemCpy =
10569     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
10570 
10571   // Create a reference to the __builtin_objc_memmove_collectable function
10572   StringRef MemCpyName = NeedsCollectableMemCpy ?
10573     "__builtin_objc_memmove_collectable" :
10574     "__builtin_memcpy";
10575   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
10576                  Sema::LookupOrdinaryName);
10577   S.LookupName(R, S.TUScope, true);
10578 
10579   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
10580   if (!MemCpy)
10581     // Something went horribly wrong earlier, and we will have complained
10582     // about it.
10583     return StmtError();
10584 
10585   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
10586                                             VK_RValue, Loc, nullptr);
10587   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
10588 
10589   Expr *CallArgs[] = {
10590     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
10591   };
10592   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
10593                                     Loc, CallArgs, Loc);
10594 
10595   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
10596   return Call.getAs<Stmt>();
10597 }
10598 
10599 /// \brief Builds a statement that copies/moves the given entity from \p From to
10600 /// \c To.
10601 ///
10602 /// This routine is used to copy/move the members of a class with an
10603 /// implicitly-declared copy/move assignment operator. When the entities being
10604 /// copied are arrays, this routine builds for loops to copy them.
10605 ///
10606 /// \param S The Sema object used for type-checking.
10607 ///
10608 /// \param Loc The location where the implicit copy/move is being generated.
10609 ///
10610 /// \param T The type of the expressions being copied/moved. Both expressions
10611 /// must have this type.
10612 ///
10613 /// \param To The expression we are copying/moving to.
10614 ///
10615 /// \param From The expression we are copying/moving from.
10616 ///
10617 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
10618 /// Otherwise, it's a non-static member subobject.
10619 ///
10620 /// \param Copying Whether we're copying or moving.
10621 ///
10622 /// \param Depth Internal parameter recording the depth of the recursion.
10623 ///
10624 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
10625 /// if a memcpy should be used instead.
10626 static StmtResult
10627 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
10628                                  const ExprBuilder &To, const ExprBuilder &From,
10629                                  bool CopyingBaseSubobject, bool Copying,
10630                                  unsigned Depth = 0) {
10631   // C++11 [class.copy]p28:
10632   //   Each subobject is assigned in the manner appropriate to its type:
10633   //
10634   //     - if the subobject is of class type, as if by a call to operator= with
10635   //       the subobject as the object expression and the corresponding
10636   //       subobject of x as a single function argument (as if by explicit
10637   //       qualification; that is, ignoring any possible virtual overriding
10638   //       functions in more derived classes);
10639   //
10640   // C++03 [class.copy]p13:
10641   //     - if the subobject is of class type, the copy assignment operator for
10642   //       the class is used (as if by explicit qualification; that is,
10643   //       ignoring any possible virtual overriding functions in more derived
10644   //       classes);
10645   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
10646     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
10647 
10648     // Look for operator=.
10649     DeclarationName Name
10650       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10651     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
10652     S.LookupQualifiedName(OpLookup, ClassDecl, false);
10653 
10654     // Prior to C++11, filter out any result that isn't a copy/move-assignment
10655     // operator.
10656     if (!S.getLangOpts().CPlusPlus11) {
10657       LookupResult::Filter F = OpLookup.makeFilter();
10658       while (F.hasNext()) {
10659         NamedDecl *D = F.next();
10660         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
10661           if (Method->isCopyAssignmentOperator() ||
10662               (!Copying && Method->isMoveAssignmentOperator()))
10663             continue;
10664 
10665         F.erase();
10666       }
10667       F.done();
10668     }
10669 
10670     // Suppress the protected check (C++ [class.protected]) for each of the
10671     // assignment operators we found. This strange dance is required when
10672     // we're assigning via a base classes's copy-assignment operator. To
10673     // ensure that we're getting the right base class subobject (without
10674     // ambiguities), we need to cast "this" to that subobject type; to
10675     // ensure that we don't go through the virtual call mechanism, we need
10676     // to qualify the operator= name with the base class (see below). However,
10677     // this means that if the base class has a protected copy assignment
10678     // operator, the protected member access check will fail. So, we
10679     // rewrite "protected" access to "public" access in this case, since we
10680     // know by construction that we're calling from a derived class.
10681     if (CopyingBaseSubobject) {
10682       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
10683            L != LEnd; ++L) {
10684         if (L.getAccess() == AS_protected)
10685           L.setAccess(AS_public);
10686       }
10687     }
10688 
10689     // Create the nested-name-specifier that will be used to qualify the
10690     // reference to operator=; this is required to suppress the virtual
10691     // call mechanism.
10692     CXXScopeSpec SS;
10693     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
10694     SS.MakeTrivial(S.Context,
10695                    NestedNameSpecifier::Create(S.Context, nullptr, false,
10696                                                CanonicalT),
10697                    Loc);
10698 
10699     // Create the reference to operator=.
10700     ExprResult OpEqualRef
10701       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
10702                                    SS, /*TemplateKWLoc=*/SourceLocation(),
10703                                    /*FirstQualifierInScope=*/nullptr,
10704                                    OpLookup,
10705                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
10706                                    /*SuppressQualifierCheck=*/true);
10707     if (OpEqualRef.isInvalid())
10708       return StmtError();
10709 
10710     // Build the call to the assignment operator.
10711 
10712     Expr *FromInst = From.build(S, Loc);
10713     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
10714                                                   OpEqualRef.getAs<Expr>(),
10715                                                   Loc, FromInst, Loc);
10716     if (Call.isInvalid())
10717       return StmtError();
10718 
10719     // If we built a call to a trivial 'operator=' while copying an array,
10720     // bail out. We'll replace the whole shebang with a memcpy.
10721     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
10722     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
10723       return StmtResult((Stmt*)nullptr);
10724 
10725     // Convert to an expression-statement, and clean up any produced
10726     // temporaries.
10727     return S.ActOnExprStmt(Call);
10728   }
10729 
10730   //     - if the subobject is of scalar type, the built-in assignment
10731   //       operator is used.
10732   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
10733   if (!ArrayTy) {
10734     ExprResult Assignment = S.CreateBuiltinBinOp(
10735         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
10736     if (Assignment.isInvalid())
10737       return StmtError();
10738     return S.ActOnExprStmt(Assignment);
10739   }
10740 
10741   //     - if the subobject is an array, each element is assigned, in the
10742   //       manner appropriate to the element type;
10743 
10744   // Construct a loop over the array bounds, e.g.,
10745   //
10746   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
10747   //
10748   // that will copy each of the array elements.
10749   QualType SizeType = S.Context.getSizeType();
10750 
10751   // Create the iteration variable.
10752   IdentifierInfo *IterationVarName = nullptr;
10753   {
10754     SmallString<8> Str;
10755     llvm::raw_svector_ostream OS(Str);
10756     OS << "__i" << Depth;
10757     IterationVarName = &S.Context.Idents.get(OS.str());
10758   }
10759   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10760                                           IterationVarName, SizeType,
10761                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10762                                           SC_None);
10763 
10764   // Initialize the iteration variable to zero.
10765   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
10766   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
10767 
10768   // Creates a reference to the iteration variable.
10769   RefBuilder IterationVarRef(IterationVar, SizeType);
10770   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
10771 
10772   // Create the DeclStmt that holds the iteration variable.
10773   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
10774 
10775   // Subscript the "from" and "to" expressions with the iteration variable.
10776   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
10777   MoveCastBuilder FromIndexMove(FromIndexCopy);
10778   const ExprBuilder *FromIndex;
10779   if (Copying)
10780     FromIndex = &FromIndexCopy;
10781   else
10782     FromIndex = &FromIndexMove;
10783 
10784   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
10785 
10786   // Build the copy/move for an individual element of the array.
10787   StmtResult Copy =
10788     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
10789                                      ToIndex, *FromIndex, CopyingBaseSubobject,
10790                                      Copying, Depth + 1);
10791   // Bail out if copying fails or if we determined that we should use memcpy.
10792   if (Copy.isInvalid() || !Copy.get())
10793     return Copy;
10794 
10795   // Create the comparison against the array bound.
10796   llvm::APInt Upper
10797     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
10798   Expr *Comparison
10799     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
10800                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
10801                                      BO_NE, S.Context.BoolTy,
10802                                      VK_RValue, OK_Ordinary, Loc, false);
10803 
10804   // Create the pre-increment of the iteration variable.
10805   Expr *Increment
10806     = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
10807                                     SizeType, VK_LValue, OK_Ordinary, Loc);
10808 
10809   // Construct the loop that copies all elements of this array.
10810   return S.ActOnForStmt(
10811       Loc, Loc, InitStmt,
10812       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
10813       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
10814 }
10815 
10816 static StmtResult
10817 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
10818                       const ExprBuilder &To, const ExprBuilder &From,
10819                       bool CopyingBaseSubobject, bool Copying) {
10820   // Maybe we should use a memcpy?
10821   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
10822       T.isTriviallyCopyableType(S.Context))
10823     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
10824 
10825   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
10826                                                      CopyingBaseSubobject,
10827                                                      Copying, 0));
10828 
10829   // If we ended up picking a trivial assignment operator for an array of a
10830   // non-trivially-copyable class type, just emit a memcpy.
10831   if (!Result.isInvalid() && !Result.get())
10832     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
10833 
10834   return Result;
10835 }
10836 
10837 Sema::ImplicitExceptionSpecification
10838 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
10839   CXXRecordDecl *ClassDecl = MD->getParent();
10840 
10841   ImplicitExceptionSpecification ExceptSpec(*this);
10842   if (ClassDecl->isInvalidDecl())
10843     return ExceptSpec;
10844 
10845   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
10846   assert(T->getNumParams() == 1 && "not a copy assignment op");
10847   unsigned ArgQuals =
10848       T->getParamType(0).getNonReferenceType().getCVRQualifiers();
10849 
10850   // C++ [except.spec]p14:
10851   //   An implicitly declared special member function (Clause 12) shall have an
10852   //   exception-specification. [...]
10853 
10854   // It is unspecified whether or not an implicit copy assignment operator
10855   // attempts to deduplicate calls to assignment operators of virtual bases are
10856   // made. As such, this exception specification is effectively unspecified.
10857   // Based on a similar decision made for constness in C++0x, we're erring on
10858   // the side of assuming such calls to be made regardless of whether they
10859   // actually happen.
10860   for (const auto &Base : ClassDecl->bases()) {
10861     if (Base.isVirtual())
10862       continue;
10863 
10864     CXXRecordDecl *BaseClassDecl
10865       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10866     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
10867                                                             ArgQuals, false, 0))
10868       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
10869   }
10870 
10871   for (const auto &Base : ClassDecl->vbases()) {
10872     CXXRecordDecl *BaseClassDecl
10873       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10874     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
10875                                                             ArgQuals, false, 0))
10876       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
10877   }
10878 
10879   for (const auto *Field : ClassDecl->fields()) {
10880     QualType FieldType = Context.getBaseElementType(Field->getType());
10881     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10882       if (CXXMethodDecl *CopyAssign =
10883           LookupCopyingAssignment(FieldClassDecl,
10884                                   ArgQuals | FieldType.getCVRQualifiers(),
10885                                   false, 0))
10886         ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
10887     }
10888   }
10889 
10890   return ExceptSpec;
10891 }
10892 
10893 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
10894   // Note: The following rules are largely analoguous to the copy
10895   // constructor rules. Note that virtual bases are not taken into account
10896   // for determining the argument type of the operator. Note also that
10897   // operators taking an object instead of a reference are allowed.
10898   assert(ClassDecl->needsImplicitCopyAssignment());
10899 
10900   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
10901   if (DSM.isAlreadyBeingDeclared())
10902     return nullptr;
10903 
10904   QualType ArgType = Context.getTypeDeclType(ClassDecl);
10905   QualType RetType = Context.getLValueReferenceType(ArgType);
10906   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
10907   if (Const)
10908     ArgType = ArgType.withConst();
10909   ArgType = Context.getLValueReferenceType(ArgType);
10910 
10911   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10912                                                      CXXCopyAssignment,
10913                                                      Const);
10914 
10915   //   An implicitly-declared copy assignment operator is an inline public
10916   //   member of its class.
10917   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10918   SourceLocation ClassLoc = ClassDecl->getLocation();
10919   DeclarationNameInfo NameInfo(Name, ClassLoc);
10920   CXXMethodDecl *CopyAssignment =
10921       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
10922                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10923                             /*isInline=*/true, Constexpr, SourceLocation());
10924   CopyAssignment->setAccess(AS_public);
10925   CopyAssignment->setDefaulted();
10926   CopyAssignment->setImplicit();
10927 
10928   if (getLangOpts().CUDA) {
10929     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
10930                                             CopyAssignment,
10931                                             /* ConstRHS */ Const,
10932                                             /* Diagnose */ false);
10933   }
10934 
10935   // Build an exception specification pointing back at this member.
10936   FunctionProtoType::ExtProtoInfo EPI =
10937       getImplicitMethodEPI(*this, CopyAssignment);
10938   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
10939 
10940   // Add the parameter to the operator.
10941   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
10942                                                ClassLoc, ClassLoc,
10943                                                /*Id=*/nullptr, ArgType,
10944                                                /*TInfo=*/nullptr, SC_None,
10945                                                nullptr);
10946   CopyAssignment->setParams(FromParam);
10947 
10948   CopyAssignment->setTrivial(
10949     ClassDecl->needsOverloadResolutionForCopyAssignment()
10950       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
10951       : ClassDecl->hasTrivialCopyAssignment());
10952 
10953   // Note that we have added this copy-assignment operator.
10954   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
10955 
10956   Scope *S = getScopeForContext(ClassDecl);
10957   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
10958 
10959   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
10960     SetDeclDeleted(CopyAssignment, ClassLoc);
10961 
10962   if (S)
10963     PushOnScopeChains(CopyAssignment, S, false);
10964   ClassDecl->addDecl(CopyAssignment);
10965 
10966   return CopyAssignment;
10967 }
10968 
10969 /// Diagnose an implicit copy operation for a class which is odr-used, but
10970 /// which is deprecated because the class has a user-declared copy constructor,
10971 /// copy assignment operator, or destructor.
10972 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
10973                                             SourceLocation UseLoc) {
10974   assert(CopyOp->isImplicit());
10975 
10976   CXXRecordDecl *RD = CopyOp->getParent();
10977   CXXMethodDecl *UserDeclaredOperation = nullptr;
10978 
10979   // In Microsoft mode, assignment operations don't affect constructors and
10980   // vice versa.
10981   if (RD->hasUserDeclaredDestructor()) {
10982     UserDeclaredOperation = RD->getDestructor();
10983   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
10984              RD->hasUserDeclaredCopyConstructor() &&
10985              !S.getLangOpts().MSVCCompat) {
10986     // Find any user-declared copy constructor.
10987     for (auto *I : RD->ctors()) {
10988       if (I->isCopyConstructor()) {
10989         UserDeclaredOperation = I;
10990         break;
10991       }
10992     }
10993     assert(UserDeclaredOperation);
10994   } else if (isa<CXXConstructorDecl>(CopyOp) &&
10995              RD->hasUserDeclaredCopyAssignment() &&
10996              !S.getLangOpts().MSVCCompat) {
10997     // Find any user-declared move assignment operator.
10998     for (auto *I : RD->methods()) {
10999       if (I->isCopyAssignmentOperator()) {
11000         UserDeclaredOperation = I;
11001         break;
11002       }
11003     }
11004     assert(UserDeclaredOperation);
11005   }
11006 
11007   if (UserDeclaredOperation) {
11008     S.Diag(UserDeclaredOperation->getLocation(),
11009          diag::warn_deprecated_copy_operation)
11010       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
11011       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
11012     S.Diag(UseLoc, diag::note_member_synthesized_at)
11013       << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
11014                                           : Sema::CXXCopyAssignment)
11015       << RD;
11016   }
11017 }
11018 
11019 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
11020                                         CXXMethodDecl *CopyAssignOperator) {
11021   assert((CopyAssignOperator->isDefaulted() &&
11022           CopyAssignOperator->isOverloadedOperator() &&
11023           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
11024           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
11025           !CopyAssignOperator->isDeleted()) &&
11026          "DefineImplicitCopyAssignment called for wrong function");
11027 
11028   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
11029 
11030   if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
11031     CopyAssignOperator->setInvalidDecl();
11032     return;
11033   }
11034 
11035   // C++11 [class.copy]p18:
11036   //   The [definition of an implicitly declared copy assignment operator] is
11037   //   deprecated if the class has a user-declared copy constructor or a
11038   //   user-declared destructor.
11039   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
11040     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
11041 
11042   CopyAssignOperator->markUsed(Context);
11043 
11044   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
11045   DiagnosticErrorTrap Trap(Diags);
11046 
11047   // C++0x [class.copy]p30:
11048   //   The implicitly-defined or explicitly-defaulted copy assignment operator
11049   //   for a non-union class X performs memberwise copy assignment of its
11050   //   subobjects. The direct base classes of X are assigned first, in the
11051   //   order of their declaration in the base-specifier-list, and then the
11052   //   immediate non-static data members of X are assigned, in the order in
11053   //   which they were declared in the class definition.
11054 
11055   // The statements that form the synthesized function body.
11056   SmallVector<Stmt*, 8> Statements;
11057 
11058   // The parameter for the "other" object, which we are copying from.
11059   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
11060   Qualifiers OtherQuals = Other->getType().getQualifiers();
11061   QualType OtherRefType = Other->getType();
11062   if (const LValueReferenceType *OtherRef
11063                                 = OtherRefType->getAs<LValueReferenceType>()) {
11064     OtherRefType = OtherRef->getPointeeType();
11065     OtherQuals = OtherRefType.getQualifiers();
11066   }
11067 
11068   // Our location for everything implicitly-generated.
11069   SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
11070                            ? CopyAssignOperator->getLocEnd()
11071                            : CopyAssignOperator->getLocation();
11072 
11073   // Builds a DeclRefExpr for the "other" object.
11074   RefBuilder OtherRef(Other, OtherRefType);
11075 
11076   // Builds the "this" pointer.
11077   ThisBuilder This;
11078 
11079   // Assign base classes.
11080   bool Invalid = false;
11081   for (auto &Base : ClassDecl->bases()) {
11082     // Form the assignment:
11083     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
11084     QualType BaseType = Base.getType().getUnqualifiedType();
11085     if (!BaseType->isRecordType()) {
11086       Invalid = true;
11087       continue;
11088     }
11089 
11090     CXXCastPath BasePath;
11091     BasePath.push_back(&Base);
11092 
11093     // Construct the "from" expression, which is an implicit cast to the
11094     // appropriately-qualified base type.
11095     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
11096                      VK_LValue, BasePath);
11097 
11098     // Dereference "this".
11099     DerefBuilder DerefThis(This);
11100     CastBuilder To(DerefThis,
11101                    Context.getCVRQualifiedType(
11102                        BaseType, CopyAssignOperator->getTypeQualifiers()),
11103                    VK_LValue, BasePath);
11104 
11105     // Build the copy.
11106     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
11107                                             To, From,
11108                                             /*CopyingBaseSubobject=*/true,
11109                                             /*Copying=*/true);
11110     if (Copy.isInvalid()) {
11111       Diag(CurrentLocation, diag::note_member_synthesized_at)
11112         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11113       CopyAssignOperator->setInvalidDecl();
11114       return;
11115     }
11116 
11117     // Success! Record the copy.
11118     Statements.push_back(Copy.getAs<Expr>());
11119   }
11120 
11121   // Assign non-static members.
11122   for (auto *Field : ClassDecl->fields()) {
11123     // FIXME: We should form some kind of AST representation for the implied
11124     // memcpy in a union copy operation.
11125     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
11126       continue;
11127 
11128     if (Field->isInvalidDecl()) {
11129       Invalid = true;
11130       continue;
11131     }
11132 
11133     // Check for members of reference type; we can't copy those.
11134     if (Field->getType()->isReferenceType()) {
11135       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11136         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11137       Diag(Field->getLocation(), diag::note_declared_at);
11138       Diag(CurrentLocation, diag::note_member_synthesized_at)
11139         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11140       Invalid = true;
11141       continue;
11142     }
11143 
11144     // Check for members of const-qualified, non-class type.
11145     QualType BaseType = Context.getBaseElementType(Field->getType());
11146     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11147       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11148         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11149       Diag(Field->getLocation(), diag::note_declared_at);
11150       Diag(CurrentLocation, diag::note_member_synthesized_at)
11151         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11152       Invalid = true;
11153       continue;
11154     }
11155 
11156     // Suppress assigning zero-width bitfields.
11157     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
11158       continue;
11159 
11160     QualType FieldType = Field->getType().getNonReferenceType();
11161     if (FieldType->isIncompleteArrayType()) {
11162       assert(ClassDecl->hasFlexibleArrayMember() &&
11163              "Incomplete array type is not valid");
11164       continue;
11165     }
11166 
11167     // Build references to the field in the object we're copying from and to.
11168     CXXScopeSpec SS; // Intentionally empty
11169     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11170                               LookupMemberName);
11171     MemberLookup.addDecl(Field);
11172     MemberLookup.resolveKind();
11173 
11174     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
11175 
11176     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
11177 
11178     // Build the copy of this field.
11179     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
11180                                             To, From,
11181                                             /*CopyingBaseSubobject=*/false,
11182                                             /*Copying=*/true);
11183     if (Copy.isInvalid()) {
11184       Diag(CurrentLocation, diag::note_member_synthesized_at)
11185         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11186       CopyAssignOperator->setInvalidDecl();
11187       return;
11188     }
11189 
11190     // Success! Record the copy.
11191     Statements.push_back(Copy.getAs<Stmt>());
11192   }
11193 
11194   if (!Invalid) {
11195     // Add a "return *this;"
11196     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
11197 
11198     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
11199     if (Return.isInvalid())
11200       Invalid = true;
11201     else {
11202       Statements.push_back(Return.getAs<Stmt>());
11203 
11204       if (Trap.hasErrorOccurred()) {
11205         Diag(CurrentLocation, diag::note_member_synthesized_at)
11206           << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11207         Invalid = true;
11208       }
11209     }
11210   }
11211 
11212   // The exception specification is needed because we are defining the
11213   // function.
11214   ResolveExceptionSpec(CurrentLocation,
11215                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
11216 
11217   if (Invalid) {
11218     CopyAssignOperator->setInvalidDecl();
11219     return;
11220   }
11221 
11222   StmtResult Body;
11223   {
11224     CompoundScopeRAII CompoundScope(*this);
11225     Body = ActOnCompoundStmt(Loc, Loc, Statements,
11226                              /*isStmtExpr=*/false);
11227     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11228   }
11229   CopyAssignOperator->setBody(Body.getAs<Stmt>());
11230 
11231   if (ASTMutationListener *L = getASTMutationListener()) {
11232     L->CompletedImplicitDefinition(CopyAssignOperator);
11233   }
11234 }
11235 
11236 Sema::ImplicitExceptionSpecification
11237 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
11238   CXXRecordDecl *ClassDecl = MD->getParent();
11239 
11240   ImplicitExceptionSpecification ExceptSpec(*this);
11241   if (ClassDecl->isInvalidDecl())
11242     return ExceptSpec;
11243 
11244   // C++0x [except.spec]p14:
11245   //   An implicitly declared special member function (Clause 12) shall have an
11246   //   exception-specification. [...]
11247 
11248   // It is unspecified whether or not an implicit move assignment operator
11249   // attempts to deduplicate calls to assignment operators of virtual bases are
11250   // made. As such, this exception specification is effectively unspecified.
11251   // Based on a similar decision made for constness in C++0x, we're erring on
11252   // the side of assuming such calls to be made regardless of whether they
11253   // actually happen.
11254   // Note that a move constructor is not implicitly declared when there are
11255   // virtual bases, but it can still be user-declared and explicitly defaulted.
11256   for (const auto &Base : ClassDecl->bases()) {
11257     if (Base.isVirtual())
11258       continue;
11259 
11260     CXXRecordDecl *BaseClassDecl
11261       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
11262     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
11263                                                            0, false, 0))
11264       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
11265   }
11266 
11267   for (const auto &Base : ClassDecl->vbases()) {
11268     CXXRecordDecl *BaseClassDecl
11269       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
11270     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
11271                                                            0, false, 0))
11272       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
11273   }
11274 
11275   for (const auto *Field : ClassDecl->fields()) {
11276     QualType FieldType = Context.getBaseElementType(Field->getType());
11277     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
11278       if (CXXMethodDecl *MoveAssign =
11279               LookupMovingAssignment(FieldClassDecl,
11280                                      FieldType.getCVRQualifiers(),
11281                                      false, 0))
11282         ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
11283     }
11284   }
11285 
11286   return ExceptSpec;
11287 }
11288 
11289 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
11290   assert(ClassDecl->needsImplicitMoveAssignment());
11291 
11292   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
11293   if (DSM.isAlreadyBeingDeclared())
11294     return nullptr;
11295 
11296   // Note: The following rules are largely analoguous to the move
11297   // constructor rules.
11298 
11299   QualType ArgType = Context.getTypeDeclType(ClassDecl);
11300   QualType RetType = Context.getLValueReferenceType(ArgType);
11301   ArgType = Context.getRValueReferenceType(ArgType);
11302 
11303   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11304                                                      CXXMoveAssignment,
11305                                                      false);
11306 
11307   //   An implicitly-declared move assignment operator is an inline public
11308   //   member of its class.
11309   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11310   SourceLocation ClassLoc = ClassDecl->getLocation();
11311   DeclarationNameInfo NameInfo(Name, ClassLoc);
11312   CXXMethodDecl *MoveAssignment =
11313       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11314                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11315                             /*isInline=*/true, Constexpr, SourceLocation());
11316   MoveAssignment->setAccess(AS_public);
11317   MoveAssignment->setDefaulted();
11318   MoveAssignment->setImplicit();
11319 
11320   if (getLangOpts().CUDA) {
11321     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
11322                                             MoveAssignment,
11323                                             /* ConstRHS */ false,
11324                                             /* Diagnose */ false);
11325   }
11326 
11327   // Build an exception specification pointing back at this member.
11328   FunctionProtoType::ExtProtoInfo EPI =
11329       getImplicitMethodEPI(*this, MoveAssignment);
11330   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
11331 
11332   // Add the parameter to the operator.
11333   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
11334                                                ClassLoc, ClassLoc,
11335                                                /*Id=*/nullptr, ArgType,
11336                                                /*TInfo=*/nullptr, SC_None,
11337                                                nullptr);
11338   MoveAssignment->setParams(FromParam);
11339 
11340   MoveAssignment->setTrivial(
11341     ClassDecl->needsOverloadResolutionForMoveAssignment()
11342       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
11343       : ClassDecl->hasTrivialMoveAssignment());
11344 
11345   // Note that we have added this copy-assignment operator.
11346   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
11347 
11348   Scope *S = getScopeForContext(ClassDecl);
11349   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
11350 
11351   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
11352     ClassDecl->setImplicitMoveAssignmentIsDeleted();
11353     SetDeclDeleted(MoveAssignment, ClassLoc);
11354   }
11355 
11356   if (S)
11357     PushOnScopeChains(MoveAssignment, S, false);
11358   ClassDecl->addDecl(MoveAssignment);
11359 
11360   return MoveAssignment;
11361 }
11362 
11363 /// Check if we're implicitly defining a move assignment operator for a class
11364 /// with virtual bases. Such a move assignment might move-assign the virtual
11365 /// base multiple times.
11366 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
11367                                                SourceLocation CurrentLocation) {
11368   assert(!Class->isDependentContext() && "should not define dependent move");
11369 
11370   // Only a virtual base could get implicitly move-assigned multiple times.
11371   // Only a non-trivial move assignment can observe this. We only want to
11372   // diagnose if we implicitly define an assignment operator that assigns
11373   // two base classes, both of which move-assign the same virtual base.
11374   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
11375       Class->getNumBases() < 2)
11376     return;
11377 
11378   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
11379   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
11380   VBaseMap VBases;
11381 
11382   for (auto &BI : Class->bases()) {
11383     Worklist.push_back(&BI);
11384     while (!Worklist.empty()) {
11385       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
11386       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
11387 
11388       // If the base has no non-trivial move assignment operators,
11389       // we don't care about moves from it.
11390       if (!Base->hasNonTrivialMoveAssignment())
11391         continue;
11392 
11393       // If there's nothing virtual here, skip it.
11394       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
11395         continue;
11396 
11397       // If we're not actually going to call a move assignment for this base,
11398       // or the selected move assignment is trivial, skip it.
11399       Sema::SpecialMemberOverloadResult *SMOR =
11400         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
11401                               /*ConstArg*/false, /*VolatileArg*/false,
11402                               /*RValueThis*/true, /*ConstThis*/false,
11403                               /*VolatileThis*/false);
11404       if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
11405           !SMOR->getMethod()->isMoveAssignmentOperator())
11406         continue;
11407 
11408       if (BaseSpec->isVirtual()) {
11409         // We're going to move-assign this virtual base, and its move
11410         // assignment operator is not trivial. If this can happen for
11411         // multiple distinct direct bases of Class, diagnose it. (If it
11412         // only happens in one base, we'll diagnose it when synthesizing
11413         // that base class's move assignment operator.)
11414         CXXBaseSpecifier *&Existing =
11415             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
11416                 .first->second;
11417         if (Existing && Existing != &BI) {
11418           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
11419             << Class << Base;
11420           S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
11421             << (Base->getCanonicalDecl() ==
11422                 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
11423             << Base << Existing->getType() << Existing->getSourceRange();
11424           S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
11425             << (Base->getCanonicalDecl() ==
11426                 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
11427             << Base << BI.getType() << BaseSpec->getSourceRange();
11428 
11429           // Only diagnose each vbase once.
11430           Existing = nullptr;
11431         }
11432       } else {
11433         // Only walk over bases that have defaulted move assignment operators.
11434         // We assume that any user-provided move assignment operator handles
11435         // the multiple-moves-of-vbase case itself somehow.
11436         if (!SMOR->getMethod()->isDefaulted())
11437           continue;
11438 
11439         // We're going to move the base classes of Base. Add them to the list.
11440         for (auto &BI : Base->bases())
11441           Worklist.push_back(&BI);
11442       }
11443     }
11444   }
11445 }
11446 
11447 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
11448                                         CXXMethodDecl *MoveAssignOperator) {
11449   assert((MoveAssignOperator->isDefaulted() &&
11450           MoveAssignOperator->isOverloadedOperator() &&
11451           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
11452           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
11453           !MoveAssignOperator->isDeleted()) &&
11454          "DefineImplicitMoveAssignment called for wrong function");
11455 
11456   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
11457 
11458   if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
11459     MoveAssignOperator->setInvalidDecl();
11460     return;
11461   }
11462 
11463   MoveAssignOperator->markUsed(Context);
11464 
11465   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
11466   DiagnosticErrorTrap Trap(Diags);
11467 
11468   // C++0x [class.copy]p28:
11469   //   The implicitly-defined or move assignment operator for a non-union class
11470   //   X performs memberwise move assignment of its subobjects. The direct base
11471   //   classes of X are assigned first, in the order of their declaration in the
11472   //   base-specifier-list, and then the immediate non-static data members of X
11473   //   are assigned, in the order in which they were declared in the class
11474   //   definition.
11475 
11476   // Issue a warning if our implicit move assignment operator will move
11477   // from a virtual base more than once.
11478   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
11479 
11480   // The statements that form the synthesized function body.
11481   SmallVector<Stmt*, 8> Statements;
11482 
11483   // The parameter for the "other" object, which we are move from.
11484   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
11485   QualType OtherRefType = Other->getType()->
11486       getAs<RValueReferenceType>()->getPointeeType();
11487   assert(!OtherRefType.getQualifiers() &&
11488          "Bad argument type of defaulted move assignment");
11489 
11490   // Our location for everything implicitly-generated.
11491   SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
11492                            ? MoveAssignOperator->getLocEnd()
11493                            : MoveAssignOperator->getLocation();
11494 
11495   // Builds a reference to the "other" object.
11496   RefBuilder OtherRef(Other, OtherRefType);
11497   // Cast to rvalue.
11498   MoveCastBuilder MoveOther(OtherRef);
11499 
11500   // Builds the "this" pointer.
11501   ThisBuilder This;
11502 
11503   // Assign base classes.
11504   bool Invalid = false;
11505   for (auto &Base : ClassDecl->bases()) {
11506     // C++11 [class.copy]p28:
11507     //   It is unspecified whether subobjects representing virtual base classes
11508     //   are assigned more than once by the implicitly-defined copy assignment
11509     //   operator.
11510     // FIXME: Do not assign to a vbase that will be assigned by some other base
11511     // class. For a move-assignment, this can result in the vbase being moved
11512     // multiple times.
11513 
11514     // Form the assignment:
11515     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
11516     QualType BaseType = Base.getType().getUnqualifiedType();
11517     if (!BaseType->isRecordType()) {
11518       Invalid = true;
11519       continue;
11520     }
11521 
11522     CXXCastPath BasePath;
11523     BasePath.push_back(&Base);
11524 
11525     // Construct the "from" expression, which is an implicit cast to the
11526     // appropriately-qualified base type.
11527     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
11528 
11529     // Dereference "this".
11530     DerefBuilder DerefThis(This);
11531 
11532     // Implicitly cast "this" to the appropriately-qualified base type.
11533     CastBuilder To(DerefThis,
11534                    Context.getCVRQualifiedType(
11535                        BaseType, MoveAssignOperator->getTypeQualifiers()),
11536                    VK_LValue, BasePath);
11537 
11538     // Build the move.
11539     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
11540                                             To, From,
11541                                             /*CopyingBaseSubobject=*/true,
11542                                             /*Copying=*/false);
11543     if (Move.isInvalid()) {
11544       Diag(CurrentLocation, diag::note_member_synthesized_at)
11545         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11546       MoveAssignOperator->setInvalidDecl();
11547       return;
11548     }
11549 
11550     // Success! Record the move.
11551     Statements.push_back(Move.getAs<Expr>());
11552   }
11553 
11554   // Assign non-static members.
11555   for (auto *Field : ClassDecl->fields()) {
11556     // FIXME: We should form some kind of AST representation for the implied
11557     // memcpy in a union copy operation.
11558     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
11559       continue;
11560 
11561     if (Field->isInvalidDecl()) {
11562       Invalid = true;
11563       continue;
11564     }
11565 
11566     // Check for members of reference type; we can't move those.
11567     if (Field->getType()->isReferenceType()) {
11568       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11569         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11570       Diag(Field->getLocation(), diag::note_declared_at);
11571       Diag(CurrentLocation, diag::note_member_synthesized_at)
11572         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11573       Invalid = true;
11574       continue;
11575     }
11576 
11577     // Check for members of const-qualified, non-class type.
11578     QualType BaseType = Context.getBaseElementType(Field->getType());
11579     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11580       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11581         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11582       Diag(Field->getLocation(), diag::note_declared_at);
11583       Diag(CurrentLocation, diag::note_member_synthesized_at)
11584         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11585       Invalid = true;
11586       continue;
11587     }
11588 
11589     // Suppress assigning zero-width bitfields.
11590     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
11591       continue;
11592 
11593     QualType FieldType = Field->getType().getNonReferenceType();
11594     if (FieldType->isIncompleteArrayType()) {
11595       assert(ClassDecl->hasFlexibleArrayMember() &&
11596              "Incomplete array type is not valid");
11597       continue;
11598     }
11599 
11600     // Build references to the field in the object we're copying from and to.
11601     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11602                               LookupMemberName);
11603     MemberLookup.addDecl(Field);
11604     MemberLookup.resolveKind();
11605     MemberBuilder From(MoveOther, OtherRefType,
11606                        /*IsArrow=*/false, MemberLookup);
11607     MemberBuilder To(This, getCurrentThisType(),
11608                      /*IsArrow=*/true, MemberLookup);
11609 
11610     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
11611         "Member reference with rvalue base must be rvalue except for reference "
11612         "members, which aren't allowed for move assignment.");
11613 
11614     // Build the move of this field.
11615     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
11616                                             To, From,
11617                                             /*CopyingBaseSubobject=*/false,
11618                                             /*Copying=*/false);
11619     if (Move.isInvalid()) {
11620       Diag(CurrentLocation, diag::note_member_synthesized_at)
11621         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11622       MoveAssignOperator->setInvalidDecl();
11623       return;
11624     }
11625 
11626     // Success! Record the copy.
11627     Statements.push_back(Move.getAs<Stmt>());
11628   }
11629 
11630   if (!Invalid) {
11631     // Add a "return *this;"
11632     ExprResult ThisObj =
11633         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
11634 
11635     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
11636     if (Return.isInvalid())
11637       Invalid = true;
11638     else {
11639       Statements.push_back(Return.getAs<Stmt>());
11640 
11641       if (Trap.hasErrorOccurred()) {
11642         Diag(CurrentLocation, diag::note_member_synthesized_at)
11643           << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11644         Invalid = true;
11645       }
11646     }
11647   }
11648 
11649   // The exception specification is needed because we are defining the
11650   // function.
11651   ResolveExceptionSpec(CurrentLocation,
11652                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
11653 
11654   if (Invalid) {
11655     MoveAssignOperator->setInvalidDecl();
11656     return;
11657   }
11658 
11659   StmtResult Body;
11660   {
11661     CompoundScopeRAII CompoundScope(*this);
11662     Body = ActOnCompoundStmt(Loc, Loc, Statements,
11663                              /*isStmtExpr=*/false);
11664     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11665   }
11666   MoveAssignOperator->setBody(Body.getAs<Stmt>());
11667 
11668   if (ASTMutationListener *L = getASTMutationListener()) {
11669     L->CompletedImplicitDefinition(MoveAssignOperator);
11670   }
11671 }
11672 
11673 Sema::ImplicitExceptionSpecification
11674 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
11675   CXXRecordDecl *ClassDecl = MD->getParent();
11676 
11677   ImplicitExceptionSpecification ExceptSpec(*this);
11678   if (ClassDecl->isInvalidDecl())
11679     return ExceptSpec;
11680 
11681   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
11682   assert(T->getNumParams() >= 1 && "not a copy ctor");
11683   unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
11684 
11685   // C++ [except.spec]p14:
11686   //   An implicitly declared special member function (Clause 12) shall have an
11687   //   exception-specification. [...]
11688   for (const auto &Base : ClassDecl->bases()) {
11689     // Virtual bases are handled below.
11690     if (Base.isVirtual())
11691       continue;
11692 
11693     CXXRecordDecl *BaseClassDecl
11694       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
11695     if (CXXConstructorDecl *CopyConstructor =
11696           LookupCopyingConstructor(BaseClassDecl, Quals))
11697       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
11698   }
11699   for (const auto &Base : ClassDecl->vbases()) {
11700     CXXRecordDecl *BaseClassDecl
11701       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
11702     if (CXXConstructorDecl *CopyConstructor =
11703           LookupCopyingConstructor(BaseClassDecl, Quals))
11704       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
11705   }
11706   for (const auto *Field : ClassDecl->fields()) {
11707     QualType FieldType = Context.getBaseElementType(Field->getType());
11708     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
11709       if (CXXConstructorDecl *CopyConstructor =
11710               LookupCopyingConstructor(FieldClassDecl,
11711                                        Quals | FieldType.getCVRQualifiers()))
11712       ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
11713     }
11714   }
11715 
11716   return ExceptSpec;
11717 }
11718 
11719 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
11720                                                     CXXRecordDecl *ClassDecl) {
11721   // C++ [class.copy]p4:
11722   //   If the class definition does not explicitly declare a copy
11723   //   constructor, one is declared implicitly.
11724   assert(ClassDecl->needsImplicitCopyConstructor());
11725 
11726   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
11727   if (DSM.isAlreadyBeingDeclared())
11728     return nullptr;
11729 
11730   QualType ClassType = Context.getTypeDeclType(ClassDecl);
11731   QualType ArgType = ClassType;
11732   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
11733   if (Const)
11734     ArgType = ArgType.withConst();
11735   ArgType = Context.getLValueReferenceType(ArgType);
11736 
11737   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11738                                                      CXXCopyConstructor,
11739                                                      Const);
11740 
11741   DeclarationName Name
11742     = Context.DeclarationNames.getCXXConstructorName(
11743                                            Context.getCanonicalType(ClassType));
11744   SourceLocation ClassLoc = ClassDecl->getLocation();
11745   DeclarationNameInfo NameInfo(Name, ClassLoc);
11746 
11747   //   An implicitly-declared copy constructor is an inline public
11748   //   member of its class.
11749   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
11750       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
11751       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
11752       Constexpr);
11753   CopyConstructor->setAccess(AS_public);
11754   CopyConstructor->setDefaulted();
11755 
11756   if (getLangOpts().CUDA) {
11757     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
11758                                             CopyConstructor,
11759                                             /* ConstRHS */ Const,
11760                                             /* Diagnose */ false);
11761   }
11762 
11763   // Build an exception specification pointing back at this member.
11764   FunctionProtoType::ExtProtoInfo EPI =
11765       getImplicitMethodEPI(*this, CopyConstructor);
11766   CopyConstructor->setType(
11767       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
11768 
11769   // Add the parameter to the constructor.
11770   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
11771                                                ClassLoc, ClassLoc,
11772                                                /*IdentifierInfo=*/nullptr,
11773                                                ArgType, /*TInfo=*/nullptr,
11774                                                SC_None, nullptr);
11775   CopyConstructor->setParams(FromParam);
11776 
11777   CopyConstructor->setTrivial(
11778     ClassDecl->needsOverloadResolutionForCopyConstructor()
11779       ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
11780       : ClassDecl->hasTrivialCopyConstructor());
11781 
11782   // Note that we have declared this constructor.
11783   ++ASTContext::NumImplicitCopyConstructorsDeclared;
11784 
11785   Scope *S = getScopeForContext(ClassDecl);
11786   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
11787 
11788   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
11789     SetDeclDeleted(CopyConstructor, ClassLoc);
11790 
11791   if (S)
11792     PushOnScopeChains(CopyConstructor, S, false);
11793   ClassDecl->addDecl(CopyConstructor);
11794 
11795   return CopyConstructor;
11796 }
11797 
11798 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
11799                                    CXXConstructorDecl *CopyConstructor) {
11800   assert((CopyConstructor->isDefaulted() &&
11801           CopyConstructor->isCopyConstructor() &&
11802           !CopyConstructor->doesThisDeclarationHaveABody() &&
11803           !CopyConstructor->isDeleted()) &&
11804          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
11805 
11806   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
11807   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
11808 
11809   // C++11 [class.copy]p7:
11810   //   The [definition of an implicitly declared copy constructor] is
11811   //   deprecated if the class has a user-declared copy assignment operator
11812   //   or a user-declared destructor.
11813   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
11814     diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
11815 
11816   SynthesizedFunctionScope Scope(*this, CopyConstructor);
11817   DiagnosticErrorTrap Trap(Diags);
11818 
11819   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
11820       Trap.hasErrorOccurred()) {
11821     Diag(CurrentLocation, diag::note_member_synthesized_at)
11822       << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
11823     CopyConstructor->setInvalidDecl();
11824   }  else {
11825     SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
11826                              ? CopyConstructor->getLocEnd()
11827                              : CopyConstructor->getLocation();
11828     Sema::CompoundScopeRAII CompoundScope(*this);
11829     CopyConstructor->setBody(
11830         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
11831   }
11832 
11833   // The exception specification is needed because we are defining the
11834   // function.
11835   ResolveExceptionSpec(CurrentLocation,
11836                        CopyConstructor->getType()->castAs<FunctionProtoType>());
11837 
11838   CopyConstructor->markUsed(Context);
11839   MarkVTableUsed(CurrentLocation, ClassDecl);
11840 
11841   if (ASTMutationListener *L = getASTMutationListener()) {
11842     L->CompletedImplicitDefinition(CopyConstructor);
11843   }
11844 }
11845 
11846 Sema::ImplicitExceptionSpecification
11847 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
11848   CXXRecordDecl *ClassDecl = MD->getParent();
11849 
11850   // C++ [except.spec]p14:
11851   //   An implicitly declared special member function (Clause 12) shall have an
11852   //   exception-specification. [...]
11853   ImplicitExceptionSpecification ExceptSpec(*this);
11854   if (ClassDecl->isInvalidDecl())
11855     return ExceptSpec;
11856 
11857   // Direct base-class constructors.
11858   for (const auto &B : ClassDecl->bases()) {
11859     if (B.isVirtual()) // Handled below.
11860       continue;
11861 
11862     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
11863       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
11864       CXXConstructorDecl *Constructor =
11865           LookupMovingConstructor(BaseClassDecl, 0);
11866       // If this is a deleted function, add it anyway. This might be conformant
11867       // with the standard. This might not. I'm not sure. It might not matter.
11868       if (Constructor)
11869         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
11870     }
11871   }
11872 
11873   // Virtual base-class constructors.
11874   for (const auto &B : ClassDecl->vbases()) {
11875     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
11876       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
11877       CXXConstructorDecl *Constructor =
11878           LookupMovingConstructor(BaseClassDecl, 0);
11879       // If this is a deleted function, add it anyway. This might be conformant
11880       // with the standard. This might not. I'm not sure. It might not matter.
11881       if (Constructor)
11882         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
11883     }
11884   }
11885 
11886   // Field constructors.
11887   for (const auto *F : ClassDecl->fields()) {
11888     QualType FieldType = Context.getBaseElementType(F->getType());
11889     if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
11890       CXXConstructorDecl *Constructor =
11891           LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
11892       // If this is a deleted function, add it anyway. This might be conformant
11893       // with the standard. This might not. I'm not sure. It might not matter.
11894       // In particular, the problem is that this function never gets called. It
11895       // might just be ill-formed because this function attempts to refer to
11896       // a deleted function here.
11897       if (Constructor)
11898         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
11899     }
11900   }
11901 
11902   return ExceptSpec;
11903 }
11904 
11905 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
11906                                                     CXXRecordDecl *ClassDecl) {
11907   assert(ClassDecl->needsImplicitMoveConstructor());
11908 
11909   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
11910   if (DSM.isAlreadyBeingDeclared())
11911     return nullptr;
11912 
11913   QualType ClassType = Context.getTypeDeclType(ClassDecl);
11914   QualType ArgType = Context.getRValueReferenceType(ClassType);
11915 
11916   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11917                                                      CXXMoveConstructor,
11918                                                      false);
11919 
11920   DeclarationName Name
11921     = Context.DeclarationNames.getCXXConstructorName(
11922                                            Context.getCanonicalType(ClassType));
11923   SourceLocation ClassLoc = ClassDecl->getLocation();
11924   DeclarationNameInfo NameInfo(Name, ClassLoc);
11925 
11926   // C++11 [class.copy]p11:
11927   //   An implicitly-declared copy/move constructor is an inline public
11928   //   member of its class.
11929   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
11930       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
11931       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
11932       Constexpr);
11933   MoveConstructor->setAccess(AS_public);
11934   MoveConstructor->setDefaulted();
11935 
11936   if (getLangOpts().CUDA) {
11937     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
11938                                             MoveConstructor,
11939                                             /* ConstRHS */ false,
11940                                             /* Diagnose */ false);
11941   }
11942 
11943   // Build an exception specification pointing back at this member.
11944   FunctionProtoType::ExtProtoInfo EPI =
11945       getImplicitMethodEPI(*this, MoveConstructor);
11946   MoveConstructor->setType(
11947       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
11948 
11949   // Add the parameter to the constructor.
11950   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
11951                                                ClassLoc, ClassLoc,
11952                                                /*IdentifierInfo=*/nullptr,
11953                                                ArgType, /*TInfo=*/nullptr,
11954                                                SC_None, nullptr);
11955   MoveConstructor->setParams(FromParam);
11956 
11957   MoveConstructor->setTrivial(
11958     ClassDecl->needsOverloadResolutionForMoveConstructor()
11959       ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
11960       : ClassDecl->hasTrivialMoveConstructor());
11961 
11962   // Note that we have declared this constructor.
11963   ++ASTContext::NumImplicitMoveConstructorsDeclared;
11964 
11965   Scope *S = getScopeForContext(ClassDecl);
11966   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
11967 
11968   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
11969     ClassDecl->setImplicitMoveConstructorIsDeleted();
11970     SetDeclDeleted(MoveConstructor, ClassLoc);
11971   }
11972 
11973   if (S)
11974     PushOnScopeChains(MoveConstructor, S, false);
11975   ClassDecl->addDecl(MoveConstructor);
11976 
11977   return MoveConstructor;
11978 }
11979 
11980 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
11981                                    CXXConstructorDecl *MoveConstructor) {
11982   assert((MoveConstructor->isDefaulted() &&
11983           MoveConstructor->isMoveConstructor() &&
11984           !MoveConstructor->doesThisDeclarationHaveABody() &&
11985           !MoveConstructor->isDeleted()) &&
11986          "DefineImplicitMoveConstructor - call it for implicit move ctor");
11987 
11988   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
11989   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
11990 
11991   SynthesizedFunctionScope Scope(*this, MoveConstructor);
11992   DiagnosticErrorTrap Trap(Diags);
11993 
11994   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
11995       Trap.hasErrorOccurred()) {
11996     Diag(CurrentLocation, diag::note_member_synthesized_at)
11997       << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
11998     MoveConstructor->setInvalidDecl();
11999   }  else {
12000     SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
12001                              ? MoveConstructor->getLocEnd()
12002                              : MoveConstructor->getLocation();
12003     Sema::CompoundScopeRAII CompoundScope(*this);
12004     MoveConstructor->setBody(ActOnCompoundStmt(
12005         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
12006   }
12007 
12008   // The exception specification is needed because we are defining the
12009   // function.
12010   ResolveExceptionSpec(CurrentLocation,
12011                        MoveConstructor->getType()->castAs<FunctionProtoType>());
12012 
12013   MoveConstructor->markUsed(Context);
12014   MarkVTableUsed(CurrentLocation, ClassDecl);
12015 
12016   if (ASTMutationListener *L = getASTMutationListener()) {
12017     L->CompletedImplicitDefinition(MoveConstructor);
12018   }
12019 }
12020 
12021 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
12022   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
12023 }
12024 
12025 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
12026                             SourceLocation CurrentLocation,
12027                             CXXConversionDecl *Conv) {
12028   CXXRecordDecl *Lambda = Conv->getParent();
12029   CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
12030   // If we are defining a specialization of a conversion to function-ptr
12031   // cache the deduced template arguments for this specialization
12032   // so that we can use them to retrieve the corresponding call-operator
12033   // and static-invoker.
12034   const TemplateArgumentList *DeducedTemplateArgs = nullptr;
12035 
12036   // Retrieve the corresponding call-operator specialization.
12037   if (Lambda->isGenericLambda()) {
12038     assert(Conv->isFunctionTemplateSpecialization());
12039     FunctionTemplateDecl *CallOpTemplate =
12040         CallOp->getDescribedFunctionTemplate();
12041     DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
12042     void *InsertPos = nullptr;
12043     FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
12044                                                 DeducedTemplateArgs->asArray(),
12045                                                 InsertPos);
12046     assert(CallOpSpec &&
12047           "Conversion operator must have a corresponding call operator");
12048     CallOp = cast<CXXMethodDecl>(CallOpSpec);
12049   }
12050   // Mark the call operator referenced (and add to pending instantiations
12051   // if necessary).
12052   // For both the conversion and static-invoker template specializations
12053   // we construct their body's in this function, so no need to add them
12054   // to the PendingInstantiations.
12055   MarkFunctionReferenced(CurrentLocation, CallOp);
12056 
12057   SynthesizedFunctionScope Scope(*this, Conv);
12058   DiagnosticErrorTrap Trap(Diags);
12059 
12060   // Retrieve the static invoker...
12061   CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
12062   // ... and get the corresponding specialization for a generic lambda.
12063   if (Lambda->isGenericLambda()) {
12064     assert(DeducedTemplateArgs &&
12065       "Must have deduced template arguments from Conversion Operator");
12066     FunctionTemplateDecl *InvokeTemplate =
12067                           Invoker->getDescribedFunctionTemplate();
12068     void *InsertPos = nullptr;
12069     FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
12070                                                 DeducedTemplateArgs->asArray(),
12071                                                 InsertPos);
12072     assert(InvokeSpec &&
12073       "Must have a corresponding static invoker specialization");
12074     Invoker = cast<CXXMethodDecl>(InvokeSpec);
12075   }
12076   // Construct the body of the conversion function { return __invoke; }.
12077   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
12078                                         VK_LValue, Conv->getLocation()).get();
12079    assert(FunctionRef && "Can't refer to __invoke function?");
12080    Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
12081    Conv->setBody(new (Context) CompoundStmt(Context, Return,
12082                                             Conv->getLocation(),
12083                                             Conv->getLocation()));
12084 
12085   Conv->markUsed(Context);
12086   Conv->setReferenced();
12087 
12088   // Fill in the __invoke function with a dummy implementation. IR generation
12089   // will fill in the actual details.
12090   Invoker->markUsed(Context);
12091   Invoker->setReferenced();
12092   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12093 
12094   if (ASTMutationListener *L = getASTMutationListener()) {
12095     L->CompletedImplicitDefinition(Conv);
12096     L->CompletedImplicitDefinition(Invoker);
12097    }
12098 }
12099 
12100 
12101 
12102 void Sema::DefineImplicitLambdaToBlockPointerConversion(
12103        SourceLocation CurrentLocation,
12104        CXXConversionDecl *Conv)
12105 {
12106   assert(!Conv->getParent()->isGenericLambda());
12107 
12108   Conv->markUsed(Context);
12109 
12110   SynthesizedFunctionScope Scope(*this, Conv);
12111   DiagnosticErrorTrap Trap(Diags);
12112 
12113   // Copy-initialize the lambda object as needed to capture it.
12114   Expr *This = ActOnCXXThis(CurrentLocation).get();
12115   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
12116 
12117   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12118                                                         Conv->getLocation(),
12119                                                         Conv, DerefThis);
12120 
12121   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12122   // behavior.  Note that only the general conversion function does this
12123   // (since it's unusable otherwise); in the case where we inline the
12124   // block literal, it has block literal lifetime semantics.
12125   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
12126     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12127                                           CK_CopyAndAutoreleaseBlockObject,
12128                                           BuildBlock.get(), nullptr, VK_RValue);
12129 
12130   if (BuildBlock.isInvalid()) {
12131     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12132     Conv->setInvalidDecl();
12133     return;
12134   }
12135 
12136   // Create the return statement that returns the block from the conversion
12137   // function.
12138   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
12139   if (Return.isInvalid()) {
12140     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12141     Conv->setInvalidDecl();
12142     return;
12143   }
12144 
12145   // Set the body of the conversion function.
12146   Stmt *ReturnS = Return.get();
12147   Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
12148                                            Conv->getLocation(),
12149                                            Conv->getLocation()));
12150 
12151   // We're done; notify the mutation listener, if any.
12152   if (ASTMutationListener *L = getASTMutationListener()) {
12153     L->CompletedImplicitDefinition(Conv);
12154   }
12155 }
12156 
12157 /// \brief Determine whether the given list arguments contains exactly one
12158 /// "real" (non-default) argument.
12159 static bool hasOneRealArgument(MultiExprArg Args) {
12160   switch (Args.size()) {
12161   case 0:
12162     return false;
12163 
12164   default:
12165     if (!Args[1]->isDefaultArgument())
12166       return false;
12167 
12168     // fall through
12169   case 1:
12170     return !Args[0]->isDefaultArgument();
12171   }
12172 
12173   return false;
12174 }
12175 
12176 ExprResult
12177 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12178                             NamedDecl *FoundDecl,
12179                             CXXConstructorDecl *Constructor,
12180                             MultiExprArg ExprArgs,
12181                             bool HadMultipleCandidates,
12182                             bool IsListInitialization,
12183                             bool IsStdInitListInitialization,
12184                             bool RequiresZeroInit,
12185                             unsigned ConstructKind,
12186                             SourceRange ParenRange) {
12187   bool Elidable = false;
12188 
12189   // C++0x [class.copy]p34:
12190   //   When certain criteria are met, an implementation is allowed to
12191   //   omit the copy/move construction of a class object, even if the
12192   //   copy/move constructor and/or destructor for the object have
12193   //   side effects. [...]
12194   //     - when a temporary class object that has not been bound to a
12195   //       reference (12.2) would be copied/moved to a class object
12196   //       with the same cv-unqualified type, the copy/move operation
12197   //       can be omitted by constructing the temporary object
12198   //       directly into the target of the omitted copy/move
12199   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
12200       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
12201     Expr *SubExpr = ExprArgs[0];
12202     Elidable = SubExpr->isTemporaryObject(
12203         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
12204   }
12205 
12206   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
12207                                FoundDecl, Constructor,
12208                                Elidable, ExprArgs, HadMultipleCandidates,
12209                                IsListInitialization,
12210                                IsStdInitListInitialization, RequiresZeroInit,
12211                                ConstructKind, ParenRange);
12212 }
12213 
12214 ExprResult
12215 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12216                             NamedDecl *FoundDecl,
12217                             CXXConstructorDecl *Constructor,
12218                             bool Elidable,
12219                             MultiExprArg ExprArgs,
12220                             bool HadMultipleCandidates,
12221                             bool IsListInitialization,
12222                             bool IsStdInitListInitialization,
12223                             bool RequiresZeroInit,
12224                             unsigned ConstructKind,
12225                             SourceRange ParenRange) {
12226   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
12227     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
12228     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
12229       return ExprError();
12230   }
12231 
12232   return BuildCXXConstructExpr(
12233       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
12234       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
12235       RequiresZeroInit, ConstructKind, ParenRange);
12236 }
12237 
12238 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
12239 /// including handling of its default argument expressions.
12240 ExprResult
12241 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12242                             CXXConstructorDecl *Constructor,
12243                             bool Elidable,
12244                             MultiExprArg ExprArgs,
12245                             bool HadMultipleCandidates,
12246                             bool IsListInitialization,
12247                             bool IsStdInitListInitialization,
12248                             bool RequiresZeroInit,
12249                             unsigned ConstructKind,
12250                             SourceRange ParenRange) {
12251   assert(declaresSameEntity(
12252              Constructor->getParent(),
12253              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
12254          "given constructor for wrong type");
12255   MarkFunctionReferenced(ConstructLoc, Constructor);
12256 
12257   return CXXConstructExpr::Create(
12258       Context, DeclInitType, ConstructLoc, Constructor, Elidable,
12259       ExprArgs, HadMultipleCandidates, IsListInitialization,
12260       IsStdInitListInitialization, RequiresZeroInit,
12261       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
12262       ParenRange);
12263 }
12264 
12265 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
12266   assert(Field->hasInClassInitializer());
12267 
12268   // If we already have the in-class initializer nothing needs to be done.
12269   if (Field->getInClassInitializer())
12270     return CXXDefaultInitExpr::Create(Context, Loc, Field);
12271 
12272   // Maybe we haven't instantiated the in-class initializer. Go check the
12273   // pattern FieldDecl to see if it has one.
12274   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
12275 
12276   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
12277     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
12278     DeclContext::lookup_result Lookup =
12279         ClassPattern->lookup(Field->getDeclName());
12280 
12281     // Lookup can return at most two results: the pattern for the field, or the
12282     // injected class name of the parent record. No other member can have the
12283     // same name as the field.
12284     assert(!Lookup.empty() && Lookup.size() <= 2 &&
12285            "more than two lookup results for field name");
12286     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
12287     if (!Pattern) {
12288       assert(isa<CXXRecordDecl>(Lookup[0]) &&
12289              "cannot have other non-field member with same name");
12290       Pattern = cast<FieldDecl>(Lookup[1]);
12291     }
12292 
12293     if (InstantiateInClassInitializer(Loc, Field, Pattern,
12294                                       getTemplateInstantiationArgs(Field)))
12295       return ExprError();
12296     return CXXDefaultInitExpr::Create(Context, Loc, Field);
12297   }
12298 
12299   // DR1351:
12300   //   If the brace-or-equal-initializer of a non-static data member
12301   //   invokes a defaulted default constructor of its class or of an
12302   //   enclosing class in a potentially evaluated subexpression, the
12303   //   program is ill-formed.
12304   //
12305   // This resolution is unworkable: the exception specification of the
12306   // default constructor can be needed in an unevaluated context, in
12307   // particular, in the operand of a noexcept-expression, and we can be
12308   // unable to compute an exception specification for an enclosed class.
12309   //
12310   // Any attempt to resolve the exception specification of a defaulted default
12311   // constructor before the initializer is lexically complete will ultimately
12312   // come here at which point we can diagnose it.
12313   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
12314   if (OutermostClass == ParentRD) {
12315     Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
12316         << ParentRD << Field;
12317   } else {
12318     Diag(Field->getLocEnd(),
12319          diag::err_in_class_initializer_not_yet_parsed_outer_class)
12320         << ParentRD << OutermostClass << Field;
12321   }
12322 
12323   return ExprError();
12324 }
12325 
12326 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
12327   if (VD->isInvalidDecl()) return;
12328 
12329   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
12330   if (ClassDecl->isInvalidDecl()) return;
12331   if (ClassDecl->hasIrrelevantDestructor()) return;
12332   if (ClassDecl->isDependentContext()) return;
12333 
12334   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12335   MarkFunctionReferenced(VD->getLocation(), Destructor);
12336   CheckDestructorAccess(VD->getLocation(), Destructor,
12337                         PDiag(diag::err_access_dtor_var)
12338                         << VD->getDeclName()
12339                         << VD->getType());
12340   DiagnoseUseOfDecl(Destructor, VD->getLocation());
12341 
12342   if (Destructor->isTrivial()) return;
12343   if (!VD->hasGlobalStorage()) return;
12344 
12345   // Emit warning for non-trivial dtor in global scope (a real global,
12346   // class-static, function-static).
12347   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
12348 
12349   // TODO: this should be re-enabled for static locals by !CXAAtExit
12350   if (!VD->isStaticLocal())
12351     Diag(VD->getLocation(), diag::warn_global_destructor);
12352 }
12353 
12354 /// \brief Given a constructor and the set of arguments provided for the
12355 /// constructor, convert the arguments and add any required default arguments
12356 /// to form a proper call to this constructor.
12357 ///
12358 /// \returns true if an error occurred, false otherwise.
12359 bool
12360 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
12361                               MultiExprArg ArgsPtr,
12362                               SourceLocation Loc,
12363                               SmallVectorImpl<Expr*> &ConvertedArgs,
12364                               bool AllowExplicit,
12365                               bool IsListInitialization) {
12366   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
12367   unsigned NumArgs = ArgsPtr.size();
12368   Expr **Args = ArgsPtr.data();
12369 
12370   const FunctionProtoType *Proto
12371     = Constructor->getType()->getAs<FunctionProtoType>();
12372   assert(Proto && "Constructor without a prototype?");
12373   unsigned NumParams = Proto->getNumParams();
12374 
12375   // If too few arguments are available, we'll fill in the rest with defaults.
12376   if (NumArgs < NumParams)
12377     ConvertedArgs.reserve(NumParams);
12378   else
12379     ConvertedArgs.reserve(NumArgs);
12380 
12381   VariadicCallType CallType =
12382     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
12383   SmallVector<Expr *, 8> AllArgs;
12384   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
12385                                         Proto, 0,
12386                                         llvm::makeArrayRef(Args, NumArgs),
12387                                         AllArgs,
12388                                         CallType, AllowExplicit,
12389                                         IsListInitialization);
12390   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
12391 
12392   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
12393 
12394   CheckConstructorCall(Constructor,
12395                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
12396                        Proto, Loc);
12397 
12398   return Invalid;
12399 }
12400 
12401 static inline bool
12402 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
12403                                        const FunctionDecl *FnDecl) {
12404   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
12405   if (isa<NamespaceDecl>(DC)) {
12406     return SemaRef.Diag(FnDecl->getLocation(),
12407                         diag::err_operator_new_delete_declared_in_namespace)
12408       << FnDecl->getDeclName();
12409   }
12410 
12411   if (isa<TranslationUnitDecl>(DC) &&
12412       FnDecl->getStorageClass() == SC_Static) {
12413     return SemaRef.Diag(FnDecl->getLocation(),
12414                         diag::err_operator_new_delete_declared_static)
12415       << FnDecl->getDeclName();
12416   }
12417 
12418   return false;
12419 }
12420 
12421 static inline bool
12422 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
12423                             CanQualType ExpectedResultType,
12424                             CanQualType ExpectedFirstParamType,
12425                             unsigned DependentParamTypeDiag,
12426                             unsigned InvalidParamTypeDiag) {
12427   QualType ResultType =
12428       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
12429 
12430   // Check that the result type is not dependent.
12431   if (ResultType->isDependentType())
12432     return SemaRef.Diag(FnDecl->getLocation(),
12433                         diag::err_operator_new_delete_dependent_result_type)
12434     << FnDecl->getDeclName() << ExpectedResultType;
12435 
12436   // Check that the result type is what we expect.
12437   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
12438     return SemaRef.Diag(FnDecl->getLocation(),
12439                         diag::err_operator_new_delete_invalid_result_type)
12440     << FnDecl->getDeclName() << ExpectedResultType;
12441 
12442   // A function template must have at least 2 parameters.
12443   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
12444     return SemaRef.Diag(FnDecl->getLocation(),
12445                       diag::err_operator_new_delete_template_too_few_parameters)
12446         << FnDecl->getDeclName();
12447 
12448   // The function decl must have at least 1 parameter.
12449   if (FnDecl->getNumParams() == 0)
12450     return SemaRef.Diag(FnDecl->getLocation(),
12451                         diag::err_operator_new_delete_too_few_parameters)
12452       << FnDecl->getDeclName();
12453 
12454   // Check the first parameter type is not dependent.
12455   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
12456   if (FirstParamType->isDependentType())
12457     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
12458       << FnDecl->getDeclName() << ExpectedFirstParamType;
12459 
12460   // Check that the first parameter type is what we expect.
12461   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
12462       ExpectedFirstParamType)
12463     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
12464     << FnDecl->getDeclName() << ExpectedFirstParamType;
12465 
12466   return false;
12467 }
12468 
12469 static bool
12470 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
12471   // C++ [basic.stc.dynamic.allocation]p1:
12472   //   A program is ill-formed if an allocation function is declared in a
12473   //   namespace scope other than global scope or declared static in global
12474   //   scope.
12475   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12476     return true;
12477 
12478   CanQualType SizeTy =
12479     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
12480 
12481   // C++ [basic.stc.dynamic.allocation]p1:
12482   //  The return type shall be void*. The first parameter shall have type
12483   //  std::size_t.
12484   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
12485                                   SizeTy,
12486                                   diag::err_operator_new_dependent_param_type,
12487                                   diag::err_operator_new_param_type))
12488     return true;
12489 
12490   // C++ [basic.stc.dynamic.allocation]p1:
12491   //  The first parameter shall not have an associated default argument.
12492   if (FnDecl->getParamDecl(0)->hasDefaultArg())
12493     return SemaRef.Diag(FnDecl->getLocation(),
12494                         diag::err_operator_new_default_arg)
12495       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
12496 
12497   return false;
12498 }
12499 
12500 static bool
12501 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
12502   // C++ [basic.stc.dynamic.deallocation]p1:
12503   //   A program is ill-formed if deallocation functions are declared in a
12504   //   namespace scope other than global scope or declared static in global
12505   //   scope.
12506   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12507     return true;
12508 
12509   // C++ [basic.stc.dynamic.deallocation]p2:
12510   //   Each deallocation function shall return void and its first parameter
12511   //   shall be void*.
12512   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
12513                                   SemaRef.Context.VoidPtrTy,
12514                                  diag::err_operator_delete_dependent_param_type,
12515                                  diag::err_operator_delete_param_type))
12516     return true;
12517 
12518   return false;
12519 }
12520 
12521 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
12522 /// of this overloaded operator is well-formed. If so, returns false;
12523 /// otherwise, emits appropriate diagnostics and returns true.
12524 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
12525   assert(FnDecl && FnDecl->isOverloadedOperator() &&
12526          "Expected an overloaded operator declaration");
12527 
12528   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
12529 
12530   // C++ [over.oper]p5:
12531   //   The allocation and deallocation functions, operator new,
12532   //   operator new[], operator delete and operator delete[], are
12533   //   described completely in 3.7.3. The attributes and restrictions
12534   //   found in the rest of this subclause do not apply to them unless
12535   //   explicitly stated in 3.7.3.
12536   if (Op == OO_Delete || Op == OO_Array_Delete)
12537     return CheckOperatorDeleteDeclaration(*this, FnDecl);
12538 
12539   if (Op == OO_New || Op == OO_Array_New)
12540     return CheckOperatorNewDeclaration(*this, FnDecl);
12541 
12542   // C++ [over.oper]p6:
12543   //   An operator function shall either be a non-static member
12544   //   function or be a non-member function and have at least one
12545   //   parameter whose type is a class, a reference to a class, an
12546   //   enumeration, or a reference to an enumeration.
12547   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
12548     if (MethodDecl->isStatic())
12549       return Diag(FnDecl->getLocation(),
12550                   diag::err_operator_overload_static) << FnDecl->getDeclName();
12551   } else {
12552     bool ClassOrEnumParam = false;
12553     for (auto Param : FnDecl->parameters()) {
12554       QualType ParamType = Param->getType().getNonReferenceType();
12555       if (ParamType->isDependentType() || ParamType->isRecordType() ||
12556           ParamType->isEnumeralType()) {
12557         ClassOrEnumParam = true;
12558         break;
12559       }
12560     }
12561 
12562     if (!ClassOrEnumParam)
12563       return Diag(FnDecl->getLocation(),
12564                   diag::err_operator_overload_needs_class_or_enum)
12565         << FnDecl->getDeclName();
12566   }
12567 
12568   // C++ [over.oper]p8:
12569   //   An operator function cannot have default arguments (8.3.6),
12570   //   except where explicitly stated below.
12571   //
12572   // Only the function-call operator allows default arguments
12573   // (C++ [over.call]p1).
12574   if (Op != OO_Call) {
12575     for (auto Param : FnDecl->parameters()) {
12576       if (Param->hasDefaultArg())
12577         return Diag(Param->getLocation(),
12578                     diag::err_operator_overload_default_arg)
12579           << FnDecl->getDeclName() << Param->getDefaultArgRange();
12580     }
12581   }
12582 
12583   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
12584     { false, false, false }
12585 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
12586     , { Unary, Binary, MemberOnly }
12587 #include "clang/Basic/OperatorKinds.def"
12588   };
12589 
12590   bool CanBeUnaryOperator = OperatorUses[Op][0];
12591   bool CanBeBinaryOperator = OperatorUses[Op][1];
12592   bool MustBeMemberOperator = OperatorUses[Op][2];
12593 
12594   // C++ [over.oper]p8:
12595   //   [...] Operator functions cannot have more or fewer parameters
12596   //   than the number required for the corresponding operator, as
12597   //   described in the rest of this subclause.
12598   unsigned NumParams = FnDecl->getNumParams()
12599                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
12600   if (Op != OO_Call &&
12601       ((NumParams == 1 && !CanBeUnaryOperator) ||
12602        (NumParams == 2 && !CanBeBinaryOperator) ||
12603        (NumParams < 1) || (NumParams > 2))) {
12604     // We have the wrong number of parameters.
12605     unsigned ErrorKind;
12606     if (CanBeUnaryOperator && CanBeBinaryOperator) {
12607       ErrorKind = 2;  // 2 -> unary or binary.
12608     } else if (CanBeUnaryOperator) {
12609       ErrorKind = 0;  // 0 -> unary
12610     } else {
12611       assert(CanBeBinaryOperator &&
12612              "All non-call overloaded operators are unary or binary!");
12613       ErrorKind = 1;  // 1 -> binary
12614     }
12615 
12616     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
12617       << FnDecl->getDeclName() << NumParams << ErrorKind;
12618   }
12619 
12620   // Overloaded operators other than operator() cannot be variadic.
12621   if (Op != OO_Call &&
12622       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
12623     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
12624       << FnDecl->getDeclName();
12625   }
12626 
12627   // Some operators must be non-static member functions.
12628   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
12629     return Diag(FnDecl->getLocation(),
12630                 diag::err_operator_overload_must_be_member)
12631       << FnDecl->getDeclName();
12632   }
12633 
12634   // C++ [over.inc]p1:
12635   //   The user-defined function called operator++ implements the
12636   //   prefix and postfix ++ operator. If this function is a member
12637   //   function with no parameters, or a non-member function with one
12638   //   parameter of class or enumeration type, it defines the prefix
12639   //   increment operator ++ for objects of that type. If the function
12640   //   is a member function with one parameter (which shall be of type
12641   //   int) or a non-member function with two parameters (the second
12642   //   of which shall be of type int), it defines the postfix
12643   //   increment operator ++ for objects of that type.
12644   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
12645     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
12646     QualType ParamType = LastParam->getType();
12647 
12648     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
12649         !ParamType->isDependentType())
12650       return Diag(LastParam->getLocation(),
12651                   diag::err_operator_overload_post_incdec_must_be_int)
12652         << LastParam->getType() << (Op == OO_MinusMinus);
12653   }
12654 
12655   return false;
12656 }
12657 
12658 static bool
12659 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
12660                                           FunctionTemplateDecl *TpDecl) {
12661   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
12662 
12663   // Must have one or two template parameters.
12664   if (TemplateParams->size() == 1) {
12665     NonTypeTemplateParmDecl *PmDecl =
12666         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
12667 
12668     // The template parameter must be a char parameter pack.
12669     if (PmDecl && PmDecl->isTemplateParameterPack() &&
12670         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
12671       return false;
12672 
12673   } else if (TemplateParams->size() == 2) {
12674     TemplateTypeParmDecl *PmType =
12675         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
12676     NonTypeTemplateParmDecl *PmArgs =
12677         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
12678 
12679     // The second template parameter must be a parameter pack with the
12680     // first template parameter as its type.
12681     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
12682         PmArgs->isTemplateParameterPack()) {
12683       const TemplateTypeParmType *TArgs =
12684           PmArgs->getType()->getAs<TemplateTypeParmType>();
12685       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
12686           TArgs->getIndex() == PmType->getIndex()) {
12687         if (SemaRef.ActiveTemplateInstantiations.empty())
12688           SemaRef.Diag(TpDecl->getLocation(),
12689                        diag::ext_string_literal_operator_template);
12690         return false;
12691       }
12692     }
12693   }
12694 
12695   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
12696                diag::err_literal_operator_template)
12697       << TpDecl->getTemplateParameters()->getSourceRange();
12698   return true;
12699 }
12700 
12701 /// CheckLiteralOperatorDeclaration - Check whether the declaration
12702 /// of this literal operator function is well-formed. If so, returns
12703 /// false; otherwise, emits appropriate diagnostics and returns true.
12704 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
12705   if (isa<CXXMethodDecl>(FnDecl)) {
12706     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
12707       << FnDecl->getDeclName();
12708     return true;
12709   }
12710 
12711   if (FnDecl->isExternC()) {
12712     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
12713     return true;
12714   }
12715 
12716   // This might be the definition of a literal operator template.
12717   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
12718 
12719   // This might be a specialization of a literal operator template.
12720   if (!TpDecl)
12721     TpDecl = FnDecl->getPrimaryTemplate();
12722 
12723   // template <char...> type operator "" name() and
12724   // template <class T, T...> type operator "" name() are the only valid
12725   // template signatures, and the only valid signatures with no parameters.
12726   if (TpDecl) {
12727     if (FnDecl->param_size() != 0) {
12728       Diag(FnDecl->getLocation(),
12729            diag::err_literal_operator_template_with_params);
12730       return true;
12731     }
12732 
12733     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
12734       return true;
12735 
12736   } else if (FnDecl->param_size() == 1) {
12737     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
12738 
12739     QualType ParamType = Param->getType().getUnqualifiedType();
12740 
12741     // Only unsigned long long int, long double, any character type, and const
12742     // char * are allowed as the only parameters.
12743     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
12744         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
12745         Context.hasSameType(ParamType, Context.CharTy) ||
12746         Context.hasSameType(ParamType, Context.WideCharTy) ||
12747         Context.hasSameType(ParamType, Context.Char16Ty) ||
12748         Context.hasSameType(ParamType, Context.Char32Ty)) {
12749     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
12750       QualType InnerType = Ptr->getPointeeType();
12751 
12752       // Pointer parameter must be a const char *.
12753       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
12754                                 Context.CharTy) &&
12755             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
12756         Diag(Param->getSourceRange().getBegin(),
12757              diag::err_literal_operator_param)
12758             << ParamType << "'const char *'" << Param->getSourceRange();
12759         return true;
12760       }
12761 
12762     } else if (ParamType->isRealFloatingType()) {
12763       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
12764           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
12765       return true;
12766 
12767     } else if (ParamType->isIntegerType()) {
12768       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
12769           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
12770       return true;
12771 
12772     } else {
12773       Diag(Param->getSourceRange().getBegin(),
12774            diag::err_literal_operator_invalid_param)
12775           << ParamType << Param->getSourceRange();
12776       return true;
12777     }
12778 
12779   } else if (FnDecl->param_size() == 2) {
12780     FunctionDecl::param_iterator Param = FnDecl->param_begin();
12781 
12782     // First, verify that the first parameter is correct.
12783 
12784     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
12785 
12786     // Two parameter function must have a pointer to const as a
12787     // first parameter; let's strip those qualifiers.
12788     const PointerType *PT = FirstParamType->getAs<PointerType>();
12789 
12790     if (!PT) {
12791       Diag((*Param)->getSourceRange().getBegin(),
12792            diag::err_literal_operator_param)
12793           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12794       return true;
12795     }
12796 
12797     QualType PointeeType = PT->getPointeeType();
12798     // First parameter must be const
12799     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
12800       Diag((*Param)->getSourceRange().getBegin(),
12801            diag::err_literal_operator_param)
12802           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12803       return true;
12804     }
12805 
12806     QualType InnerType = PointeeType.getUnqualifiedType();
12807     // Only const char *, const wchar_t*, const char16_t*, and const char32_t*
12808     // are allowed as the first parameter to a two-parameter function
12809     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
12810           Context.hasSameType(InnerType, Context.WideCharTy) ||
12811           Context.hasSameType(InnerType, Context.Char16Ty) ||
12812           Context.hasSameType(InnerType, Context.Char32Ty))) {
12813       Diag((*Param)->getSourceRange().getBegin(),
12814            diag::err_literal_operator_param)
12815           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12816       return true;
12817     }
12818 
12819     // Move on to the second and final parameter.
12820     ++Param;
12821 
12822     // The second parameter must be a std::size_t.
12823     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
12824     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
12825       Diag((*Param)->getSourceRange().getBegin(),
12826            diag::err_literal_operator_param)
12827           << SecondParamType << Context.getSizeType()
12828           << (*Param)->getSourceRange();
12829       return true;
12830     }
12831   } else {
12832     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
12833     return true;
12834   }
12835 
12836   // Parameters are good.
12837 
12838   // A parameter-declaration-clause containing a default argument is not
12839   // equivalent to any of the permitted forms.
12840   for (auto Param : FnDecl->parameters()) {
12841     if (Param->hasDefaultArg()) {
12842       Diag(Param->getDefaultArgRange().getBegin(),
12843            diag::err_literal_operator_default_argument)
12844         << Param->getDefaultArgRange();
12845       break;
12846     }
12847   }
12848 
12849   StringRef LiteralName
12850     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
12851   if (LiteralName[0] != '_') {
12852     // C++11 [usrlit.suffix]p1:
12853     //   Literal suffix identifiers that do not start with an underscore
12854     //   are reserved for future standardization.
12855     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
12856       << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
12857   }
12858 
12859   return false;
12860 }
12861 
12862 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
12863 /// linkage specification, including the language and (if present)
12864 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
12865 /// language string literal. LBraceLoc, if valid, provides the location of
12866 /// the '{' brace. Otherwise, this linkage specification does not
12867 /// have any braces.
12868 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
12869                                            Expr *LangStr,
12870                                            SourceLocation LBraceLoc) {
12871   StringLiteral *Lit = cast<StringLiteral>(LangStr);
12872   if (!Lit->isAscii()) {
12873     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
12874       << LangStr->getSourceRange();
12875     return nullptr;
12876   }
12877 
12878   StringRef Lang = Lit->getString();
12879   LinkageSpecDecl::LanguageIDs Language;
12880   if (Lang == "C")
12881     Language = LinkageSpecDecl::lang_c;
12882   else if (Lang == "C++")
12883     Language = LinkageSpecDecl::lang_cxx;
12884   else {
12885     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
12886       << LangStr->getSourceRange();
12887     return nullptr;
12888   }
12889 
12890   // FIXME: Add all the various semantics of linkage specifications
12891 
12892   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
12893                                                LangStr->getExprLoc(), Language,
12894                                                LBraceLoc.isValid());
12895   CurContext->addDecl(D);
12896   PushDeclContext(S, D);
12897   return D;
12898 }
12899 
12900 /// ActOnFinishLinkageSpecification - Complete the definition of
12901 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
12902 /// valid, it's the position of the closing '}' brace in a linkage
12903 /// specification that uses braces.
12904 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
12905                                             Decl *LinkageSpec,
12906                                             SourceLocation RBraceLoc) {
12907   if (RBraceLoc.isValid()) {
12908     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
12909     LSDecl->setRBraceLoc(RBraceLoc);
12910   }
12911   PopDeclContext();
12912   return LinkageSpec;
12913 }
12914 
12915 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
12916                                   AttributeList *AttrList,
12917                                   SourceLocation SemiLoc) {
12918   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
12919   // Attribute declarations appertain to empty declaration so we handle
12920   // them here.
12921   if (AttrList)
12922     ProcessDeclAttributeList(S, ED, AttrList);
12923 
12924   CurContext->addDecl(ED);
12925   return ED;
12926 }
12927 
12928 /// \brief Perform semantic analysis for the variable declaration that
12929 /// occurs within a C++ catch clause, returning the newly-created
12930 /// variable.
12931 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
12932                                          TypeSourceInfo *TInfo,
12933                                          SourceLocation StartLoc,
12934                                          SourceLocation Loc,
12935                                          IdentifierInfo *Name) {
12936   bool Invalid = false;
12937   QualType ExDeclType = TInfo->getType();
12938 
12939   // Arrays and functions decay.
12940   if (ExDeclType->isArrayType())
12941     ExDeclType = Context.getArrayDecayedType(ExDeclType);
12942   else if (ExDeclType->isFunctionType())
12943     ExDeclType = Context.getPointerType(ExDeclType);
12944 
12945   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
12946   // The exception-declaration shall not denote a pointer or reference to an
12947   // incomplete type, other than [cv] void*.
12948   // N2844 forbids rvalue references.
12949   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
12950     Diag(Loc, diag::err_catch_rvalue_ref);
12951     Invalid = true;
12952   }
12953 
12954   if (ExDeclType->isVariablyModifiedType()) {
12955     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
12956     Invalid = true;
12957   }
12958 
12959   QualType BaseType = ExDeclType;
12960   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
12961   unsigned DK = diag::err_catch_incomplete;
12962   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
12963     BaseType = Ptr->getPointeeType();
12964     Mode = 1;
12965     DK = diag::err_catch_incomplete_ptr;
12966   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
12967     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
12968     BaseType = Ref->getPointeeType();
12969     Mode = 2;
12970     DK = diag::err_catch_incomplete_ref;
12971   }
12972   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
12973       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
12974     Invalid = true;
12975 
12976   if (!Invalid && !ExDeclType->isDependentType() &&
12977       RequireNonAbstractType(Loc, ExDeclType,
12978                              diag::err_abstract_type_in_decl,
12979                              AbstractVariableType))
12980     Invalid = true;
12981 
12982   // Only the non-fragile NeXT runtime currently supports C++ catches
12983   // of ObjC types, and no runtime supports catching ObjC types by value.
12984   if (!Invalid && getLangOpts().ObjC1) {
12985     QualType T = ExDeclType;
12986     if (const ReferenceType *RT = T->getAs<ReferenceType>())
12987       T = RT->getPointeeType();
12988 
12989     if (T->isObjCObjectType()) {
12990       Diag(Loc, diag::err_objc_object_catch);
12991       Invalid = true;
12992     } else if (T->isObjCObjectPointerType()) {
12993       // FIXME: should this be a test for macosx-fragile specifically?
12994       if (getLangOpts().ObjCRuntime.isFragile())
12995         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
12996     }
12997   }
12998 
12999   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
13000                                     ExDeclType, TInfo, SC_None);
13001   ExDecl->setExceptionVariable(true);
13002 
13003   // In ARC, infer 'retaining' for variables of retainable type.
13004   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
13005     Invalid = true;
13006 
13007   if (!Invalid && !ExDeclType->isDependentType()) {
13008     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
13009       // Insulate this from anything else we might currently be parsing.
13010       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
13011 
13012       // C++ [except.handle]p16:
13013       //   The object declared in an exception-declaration or, if the
13014       //   exception-declaration does not specify a name, a temporary (12.2) is
13015       //   copy-initialized (8.5) from the exception object. [...]
13016       //   The object is destroyed when the handler exits, after the destruction
13017       //   of any automatic objects initialized within the handler.
13018       //
13019       // We just pretend to initialize the object with itself, then make sure
13020       // it can be destroyed later.
13021       QualType initType = Context.getExceptionObjectType(ExDeclType);
13022 
13023       InitializedEntity entity =
13024         InitializedEntity::InitializeVariable(ExDecl);
13025       InitializationKind initKind =
13026         InitializationKind::CreateCopy(Loc, SourceLocation());
13027 
13028       Expr *opaqueValue =
13029         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
13030       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13031       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
13032       if (result.isInvalid())
13033         Invalid = true;
13034       else {
13035         // If the constructor used was non-trivial, set this as the
13036         // "initializer".
13037         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
13038         if (!construct->getConstructor()->isTrivial()) {
13039           Expr *init = MaybeCreateExprWithCleanups(construct);
13040           ExDecl->setInit(init);
13041         }
13042 
13043         // And make sure it's destructable.
13044         FinalizeVarWithDestructor(ExDecl, recordType);
13045       }
13046     }
13047   }
13048 
13049   if (Invalid)
13050     ExDecl->setInvalidDecl();
13051 
13052   return ExDecl;
13053 }
13054 
13055 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13056 /// handler.
13057 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
13058   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13059   bool Invalid = D.isInvalidType();
13060 
13061   // Check for unexpanded parameter packs.
13062   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13063                                       UPPC_ExceptionType)) {
13064     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13065                                              D.getIdentifierLoc());
13066     Invalid = true;
13067   }
13068 
13069   IdentifierInfo *II = D.getIdentifier();
13070   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
13071                                              LookupOrdinaryName,
13072                                              ForRedeclaration)) {
13073     // The scope should be freshly made just for us. There is just no way
13074     // it contains any previous declaration, except for function parameters in
13075     // a function-try-block's catch statement.
13076     assert(!S->isDeclScope(PrevDecl));
13077     if (isDeclInScope(PrevDecl, CurContext, S)) {
13078       Diag(D.getIdentifierLoc(), diag::err_redefinition)
13079         << D.getIdentifier();
13080       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13081       Invalid = true;
13082     } else if (PrevDecl->isTemplateParameter())
13083       // Maybe we will complain about the shadowed template parameter.
13084       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13085   }
13086 
13087   if (D.getCXXScopeSpec().isSet() && !Invalid) {
13088     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13089       << D.getCXXScopeSpec().getRange();
13090     Invalid = true;
13091   }
13092 
13093   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
13094                                               D.getLocStart(),
13095                                               D.getIdentifierLoc(),
13096                                               D.getIdentifier());
13097   if (Invalid)
13098     ExDecl->setInvalidDecl();
13099 
13100   // Add the exception declaration into this scope.
13101   if (II)
13102     PushOnScopeChains(ExDecl, S);
13103   else
13104     CurContext->addDecl(ExDecl);
13105 
13106   ProcessDeclAttributes(S, ExDecl, D);
13107   return ExDecl;
13108 }
13109 
13110 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13111                                          Expr *AssertExpr,
13112                                          Expr *AssertMessageExpr,
13113                                          SourceLocation RParenLoc) {
13114   StringLiteral *AssertMessage =
13115       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
13116 
13117   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
13118     return nullptr;
13119 
13120   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
13121                                       AssertMessage, RParenLoc, false);
13122 }
13123 
13124 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13125                                          Expr *AssertExpr,
13126                                          StringLiteral *AssertMessage,
13127                                          SourceLocation RParenLoc,
13128                                          bool Failed) {
13129   assert(AssertExpr != nullptr && "Expected non-null condition");
13130   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
13131       !Failed) {
13132     // In a static_assert-declaration, the constant-expression shall be a
13133     // constant expression that can be contextually converted to bool.
13134     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
13135     if (Converted.isInvalid())
13136       Failed = true;
13137 
13138     llvm::APSInt Cond;
13139     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
13140           diag::err_static_assert_expression_is_not_constant,
13141           /*AllowFold=*/false).isInvalid())
13142       Failed = true;
13143 
13144     if (!Failed && !Cond) {
13145       SmallString<256> MsgBuffer;
13146       llvm::raw_svector_ostream Msg(MsgBuffer);
13147       if (AssertMessage)
13148         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
13149       Diag(StaticAssertLoc, diag::err_static_assert_failed)
13150         << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
13151       Failed = true;
13152     }
13153   }
13154 
13155   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
13156                                         AssertExpr, AssertMessage, RParenLoc,
13157                                         Failed);
13158 
13159   CurContext->addDecl(Decl);
13160   return Decl;
13161 }
13162 
13163 /// \brief Perform semantic analysis of the given friend type declaration.
13164 ///
13165 /// \returns A friend declaration that.
13166 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
13167                                       SourceLocation FriendLoc,
13168                                       TypeSourceInfo *TSInfo) {
13169   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
13170 
13171   QualType T = TSInfo->getType();
13172   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
13173 
13174   // C++03 [class.friend]p2:
13175   //   An elaborated-type-specifier shall be used in a friend declaration
13176   //   for a class.*
13177   //
13178   //   * The class-key of the elaborated-type-specifier is required.
13179   if (!ActiveTemplateInstantiations.empty()) {
13180     // Do not complain about the form of friend template types during
13181     // template instantiation; we will already have complained when the
13182     // template was declared.
13183   } else {
13184     if (!T->isElaboratedTypeSpecifier()) {
13185       // If we evaluated the type to a record type, suggest putting
13186       // a tag in front.
13187       if (const RecordType *RT = T->getAs<RecordType>()) {
13188         RecordDecl *RD = RT->getDecl();
13189 
13190         SmallString<16> InsertionText(" ");
13191         InsertionText += RD->getKindName();
13192 
13193         Diag(TypeRange.getBegin(),
13194              getLangOpts().CPlusPlus11 ?
13195                diag::warn_cxx98_compat_unelaborated_friend_type :
13196                diag::ext_unelaborated_friend_type)
13197           << (unsigned) RD->getTagKind()
13198           << T
13199           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
13200                                         InsertionText);
13201       } else {
13202         Diag(FriendLoc,
13203              getLangOpts().CPlusPlus11 ?
13204                diag::warn_cxx98_compat_nonclass_type_friend :
13205                diag::ext_nonclass_type_friend)
13206           << T
13207           << TypeRange;
13208       }
13209     } else if (T->getAs<EnumType>()) {
13210       Diag(FriendLoc,
13211            getLangOpts().CPlusPlus11 ?
13212              diag::warn_cxx98_compat_enum_friend :
13213              diag::ext_enum_friend)
13214         << T
13215         << TypeRange;
13216     }
13217 
13218     // C++11 [class.friend]p3:
13219     //   A friend declaration that does not declare a function shall have one
13220     //   of the following forms:
13221     //     friend elaborated-type-specifier ;
13222     //     friend simple-type-specifier ;
13223     //     friend typename-specifier ;
13224     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
13225       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
13226   }
13227 
13228   //   If the type specifier in a friend declaration designates a (possibly
13229   //   cv-qualified) class type, that class is declared as a friend; otherwise,
13230   //   the friend declaration is ignored.
13231   return FriendDecl::Create(Context, CurContext,
13232                             TSInfo->getTypeLoc().getLocStart(), TSInfo,
13233                             FriendLoc);
13234 }
13235 
13236 /// Handle a friend tag declaration where the scope specifier was
13237 /// templated.
13238 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
13239                                     unsigned TagSpec, SourceLocation TagLoc,
13240                                     CXXScopeSpec &SS,
13241                                     IdentifierInfo *Name,
13242                                     SourceLocation NameLoc,
13243                                     AttributeList *Attr,
13244                                     MultiTemplateParamsArg TempParamLists) {
13245   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13246 
13247   bool isExplicitSpecialization = false;
13248   bool Invalid = false;
13249 
13250   if (TemplateParameterList *TemplateParams =
13251           MatchTemplateParametersToScopeSpecifier(
13252               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
13253               isExplicitSpecialization, Invalid)) {
13254     if (TemplateParams->size() > 0) {
13255       // This is a declaration of a class template.
13256       if (Invalid)
13257         return nullptr;
13258 
13259       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
13260                                 NameLoc, Attr, TemplateParams, AS_public,
13261                                 /*ModulePrivateLoc=*/SourceLocation(),
13262                                 FriendLoc, TempParamLists.size() - 1,
13263                                 TempParamLists.data()).get();
13264     } else {
13265       // The "template<>" header is extraneous.
13266       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13267         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13268       isExplicitSpecialization = true;
13269     }
13270   }
13271 
13272   if (Invalid) return nullptr;
13273 
13274   bool isAllExplicitSpecializations = true;
13275   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
13276     if (TempParamLists[I]->size()) {
13277       isAllExplicitSpecializations = false;
13278       break;
13279     }
13280   }
13281 
13282   // FIXME: don't ignore attributes.
13283 
13284   // If it's explicit specializations all the way down, just forget
13285   // about the template header and build an appropriate non-templated
13286   // friend.  TODO: for source fidelity, remember the headers.
13287   if (isAllExplicitSpecializations) {
13288     if (SS.isEmpty()) {
13289       bool Owned = false;
13290       bool IsDependent = false;
13291       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
13292                       Attr, AS_public,
13293                       /*ModulePrivateLoc=*/SourceLocation(),
13294                       MultiTemplateParamsArg(), Owned, IsDependent,
13295                       /*ScopedEnumKWLoc=*/SourceLocation(),
13296                       /*ScopedEnumUsesClassTag=*/false,
13297                       /*UnderlyingType=*/TypeResult(),
13298                       /*IsTypeSpecifier=*/false);
13299     }
13300 
13301     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
13302     ElaboratedTypeKeyword Keyword
13303       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13304     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
13305                                    *Name, NameLoc);
13306     if (T.isNull())
13307       return nullptr;
13308 
13309     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13310     if (isa<DependentNameType>(T)) {
13311       DependentNameTypeLoc TL =
13312           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
13313       TL.setElaboratedKeywordLoc(TagLoc);
13314       TL.setQualifierLoc(QualifierLoc);
13315       TL.setNameLoc(NameLoc);
13316     } else {
13317       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
13318       TL.setElaboratedKeywordLoc(TagLoc);
13319       TL.setQualifierLoc(QualifierLoc);
13320       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
13321     }
13322 
13323     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
13324                                             TSI, FriendLoc, TempParamLists);
13325     Friend->setAccess(AS_public);
13326     CurContext->addDecl(Friend);
13327     return Friend;
13328   }
13329 
13330   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
13331 
13332 
13333 
13334   // Handle the case of a templated-scope friend class.  e.g.
13335   //   template <class T> class A<T>::B;
13336   // FIXME: we don't support these right now.
13337   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
13338     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
13339   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13340   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
13341   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13342   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
13343   TL.setElaboratedKeywordLoc(TagLoc);
13344   TL.setQualifierLoc(SS.getWithLocInContext(Context));
13345   TL.setNameLoc(NameLoc);
13346 
13347   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
13348                                           TSI, FriendLoc, TempParamLists);
13349   Friend->setAccess(AS_public);
13350   Friend->setUnsupportedFriend(true);
13351   CurContext->addDecl(Friend);
13352   return Friend;
13353 }
13354 
13355 
13356 /// Handle a friend type declaration.  This works in tandem with
13357 /// ActOnTag.
13358 ///
13359 /// Notes on friend class templates:
13360 ///
13361 /// We generally treat friend class declarations as if they were
13362 /// declaring a class.  So, for example, the elaborated type specifier
13363 /// in a friend declaration is required to obey the restrictions of a
13364 /// class-head (i.e. no typedefs in the scope chain), template
13365 /// parameters are required to match up with simple template-ids, &c.
13366 /// However, unlike when declaring a template specialization, it's
13367 /// okay to refer to a template specialization without an empty
13368 /// template parameter declaration, e.g.
13369 ///   friend class A<T>::B<unsigned>;
13370 /// We permit this as a special case; if there are any template
13371 /// parameters present at all, require proper matching, i.e.
13372 ///   template <> template \<class T> friend class A<int>::B;
13373 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
13374                                 MultiTemplateParamsArg TempParams) {
13375   SourceLocation Loc = DS.getLocStart();
13376 
13377   assert(DS.isFriendSpecified());
13378   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13379 
13380   // Try to convert the decl specifier to a type.  This works for
13381   // friend templates because ActOnTag never produces a ClassTemplateDecl
13382   // for a TUK_Friend.
13383   Declarator TheDeclarator(DS, Declarator::MemberContext);
13384   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
13385   QualType T = TSI->getType();
13386   if (TheDeclarator.isInvalidType())
13387     return nullptr;
13388 
13389   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
13390     return nullptr;
13391 
13392   // This is definitely an error in C++98.  It's probably meant to
13393   // be forbidden in C++0x, too, but the specification is just
13394   // poorly written.
13395   //
13396   // The problem is with declarations like the following:
13397   //   template <T> friend A<T>::foo;
13398   // where deciding whether a class C is a friend or not now hinges
13399   // on whether there exists an instantiation of A that causes
13400   // 'foo' to equal C.  There are restrictions on class-heads
13401   // (which we declare (by fiat) elaborated friend declarations to
13402   // be) that makes this tractable.
13403   //
13404   // FIXME: handle "template <> friend class A<T>;", which
13405   // is possibly well-formed?  Who even knows?
13406   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
13407     Diag(Loc, diag::err_tagless_friend_type_template)
13408       << DS.getSourceRange();
13409     return nullptr;
13410   }
13411 
13412   // C++98 [class.friend]p1: A friend of a class is a function
13413   //   or class that is not a member of the class . . .
13414   // This is fixed in DR77, which just barely didn't make the C++03
13415   // deadline.  It's also a very silly restriction that seriously
13416   // affects inner classes and which nobody else seems to implement;
13417   // thus we never diagnose it, not even in -pedantic.
13418   //
13419   // But note that we could warn about it: it's always useless to
13420   // friend one of your own members (it's not, however, worthless to
13421   // friend a member of an arbitrary specialization of your template).
13422 
13423   Decl *D;
13424   if (!TempParams.empty())
13425     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
13426                                    TempParams,
13427                                    TSI,
13428                                    DS.getFriendSpecLoc());
13429   else
13430     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
13431 
13432   if (!D)
13433     return nullptr;
13434 
13435   D->setAccess(AS_public);
13436   CurContext->addDecl(D);
13437 
13438   return D;
13439 }
13440 
13441 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
13442                                         MultiTemplateParamsArg TemplateParams) {
13443   const DeclSpec &DS = D.getDeclSpec();
13444 
13445   assert(DS.isFriendSpecified());
13446   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13447 
13448   SourceLocation Loc = D.getIdentifierLoc();
13449   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13450 
13451   // C++ [class.friend]p1
13452   //   A friend of a class is a function or class....
13453   // Note that this sees through typedefs, which is intended.
13454   // It *doesn't* see through dependent types, which is correct
13455   // according to [temp.arg.type]p3:
13456   //   If a declaration acquires a function type through a
13457   //   type dependent on a template-parameter and this causes
13458   //   a declaration that does not use the syntactic form of a
13459   //   function declarator to have a function type, the program
13460   //   is ill-formed.
13461   if (!TInfo->getType()->isFunctionType()) {
13462     Diag(Loc, diag::err_unexpected_friend);
13463 
13464     // It might be worthwhile to try to recover by creating an
13465     // appropriate declaration.
13466     return nullptr;
13467   }
13468 
13469   // C++ [namespace.memdef]p3
13470   //  - If a friend declaration in a non-local class first declares a
13471   //    class or function, the friend class or function is a member
13472   //    of the innermost enclosing namespace.
13473   //  - The name of the friend is not found by simple name lookup
13474   //    until a matching declaration is provided in that namespace
13475   //    scope (either before or after the class declaration granting
13476   //    friendship).
13477   //  - If a friend function is called, its name may be found by the
13478   //    name lookup that considers functions from namespaces and
13479   //    classes associated with the types of the function arguments.
13480   //  - When looking for a prior declaration of a class or a function
13481   //    declared as a friend, scopes outside the innermost enclosing
13482   //    namespace scope are not considered.
13483 
13484   CXXScopeSpec &SS = D.getCXXScopeSpec();
13485   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
13486   DeclarationName Name = NameInfo.getName();
13487   assert(Name);
13488 
13489   // Check for unexpanded parameter packs.
13490   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
13491       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
13492       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
13493     return nullptr;
13494 
13495   // The context we found the declaration in, or in which we should
13496   // create the declaration.
13497   DeclContext *DC;
13498   Scope *DCScope = S;
13499   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13500                         ForRedeclaration);
13501 
13502   // There are five cases here.
13503   //   - There's no scope specifier and we're in a local class. Only look
13504   //     for functions declared in the immediately-enclosing block scope.
13505   // We recover from invalid scope qualifiers as if they just weren't there.
13506   FunctionDecl *FunctionContainingLocalClass = nullptr;
13507   if ((SS.isInvalid() || !SS.isSet()) &&
13508       (FunctionContainingLocalClass =
13509            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
13510     // C++11 [class.friend]p11:
13511     //   If a friend declaration appears in a local class and the name
13512     //   specified is an unqualified name, a prior declaration is
13513     //   looked up without considering scopes that are outside the
13514     //   innermost enclosing non-class scope. For a friend function
13515     //   declaration, if there is no prior declaration, the program is
13516     //   ill-formed.
13517 
13518     // Find the innermost enclosing non-class scope. This is the block
13519     // scope containing the local class definition (or for a nested class,
13520     // the outer local class).
13521     DCScope = S->getFnParent();
13522 
13523     // Look up the function name in the scope.
13524     Previous.clear(LookupLocalFriendName);
13525     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
13526 
13527     if (!Previous.empty()) {
13528       // All possible previous declarations must have the same context:
13529       // either they were declared at block scope or they are members of
13530       // one of the enclosing local classes.
13531       DC = Previous.getRepresentativeDecl()->getDeclContext();
13532     } else {
13533       // This is ill-formed, but provide the context that we would have
13534       // declared the function in, if we were permitted to, for error recovery.
13535       DC = FunctionContainingLocalClass;
13536     }
13537     adjustContextForLocalExternDecl(DC);
13538 
13539     // C++ [class.friend]p6:
13540     //   A function can be defined in a friend declaration of a class if and
13541     //   only if the class is a non-local class (9.8), the function name is
13542     //   unqualified, and the function has namespace scope.
13543     if (D.isFunctionDefinition()) {
13544       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
13545     }
13546 
13547   //   - There's no scope specifier, in which case we just go to the
13548   //     appropriate scope and look for a function or function template
13549   //     there as appropriate.
13550   } else if (SS.isInvalid() || !SS.isSet()) {
13551     // C++11 [namespace.memdef]p3:
13552     //   If the name in a friend declaration is neither qualified nor
13553     //   a template-id and the declaration is a function or an
13554     //   elaborated-type-specifier, the lookup to determine whether
13555     //   the entity has been previously declared shall not consider
13556     //   any scopes outside the innermost enclosing namespace.
13557     bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
13558 
13559     // Find the appropriate context according to the above.
13560     DC = CurContext;
13561 
13562     // Skip class contexts.  If someone can cite chapter and verse
13563     // for this behavior, that would be nice --- it's what GCC and
13564     // EDG do, and it seems like a reasonable intent, but the spec
13565     // really only says that checks for unqualified existing
13566     // declarations should stop at the nearest enclosing namespace,
13567     // not that they should only consider the nearest enclosing
13568     // namespace.
13569     while (DC->isRecord())
13570       DC = DC->getParent();
13571 
13572     DeclContext *LookupDC = DC;
13573     while (LookupDC->isTransparentContext())
13574       LookupDC = LookupDC->getParent();
13575 
13576     while (true) {
13577       LookupQualifiedName(Previous, LookupDC);
13578 
13579       if (!Previous.empty()) {
13580         DC = LookupDC;
13581         break;
13582       }
13583 
13584       if (isTemplateId) {
13585         if (isa<TranslationUnitDecl>(LookupDC)) break;
13586       } else {
13587         if (LookupDC->isFileContext()) break;
13588       }
13589       LookupDC = LookupDC->getParent();
13590     }
13591 
13592     DCScope = getScopeForDeclContext(S, DC);
13593 
13594   //   - There's a non-dependent scope specifier, in which case we
13595   //     compute it and do a previous lookup there for a function
13596   //     or function template.
13597   } else if (!SS.getScopeRep()->isDependent()) {
13598     DC = computeDeclContext(SS);
13599     if (!DC) return nullptr;
13600 
13601     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
13602 
13603     LookupQualifiedName(Previous, DC);
13604 
13605     // Ignore things found implicitly in the wrong scope.
13606     // TODO: better diagnostics for this case.  Suggesting the right
13607     // qualified scope would be nice...
13608     LookupResult::Filter F = Previous.makeFilter();
13609     while (F.hasNext()) {
13610       NamedDecl *D = F.next();
13611       if (!DC->InEnclosingNamespaceSetOf(
13612               D->getDeclContext()->getRedeclContext()))
13613         F.erase();
13614     }
13615     F.done();
13616 
13617     if (Previous.empty()) {
13618       D.setInvalidType();
13619       Diag(Loc, diag::err_qualified_friend_not_found)
13620           << Name << TInfo->getType();
13621       return nullptr;
13622     }
13623 
13624     // C++ [class.friend]p1: A friend of a class is a function or
13625     //   class that is not a member of the class . . .
13626     if (DC->Equals(CurContext))
13627       Diag(DS.getFriendSpecLoc(),
13628            getLangOpts().CPlusPlus11 ?
13629              diag::warn_cxx98_compat_friend_is_member :
13630              diag::err_friend_is_member);
13631 
13632     if (D.isFunctionDefinition()) {
13633       // C++ [class.friend]p6:
13634       //   A function can be defined in a friend declaration of a class if and
13635       //   only if the class is a non-local class (9.8), the function name is
13636       //   unqualified, and the function has namespace scope.
13637       SemaDiagnosticBuilder DB
13638         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
13639 
13640       DB << SS.getScopeRep();
13641       if (DC->isFileContext())
13642         DB << FixItHint::CreateRemoval(SS.getRange());
13643       SS.clear();
13644     }
13645 
13646   //   - There's a scope specifier that does not match any template
13647   //     parameter lists, in which case we use some arbitrary context,
13648   //     create a method or method template, and wait for instantiation.
13649   //   - There's a scope specifier that does match some template
13650   //     parameter lists, which we don't handle right now.
13651   } else {
13652     if (D.isFunctionDefinition()) {
13653       // C++ [class.friend]p6:
13654       //   A function can be defined in a friend declaration of a class if and
13655       //   only if the class is a non-local class (9.8), the function name is
13656       //   unqualified, and the function has namespace scope.
13657       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
13658         << SS.getScopeRep();
13659     }
13660 
13661     DC = CurContext;
13662     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
13663   }
13664 
13665   if (!DC->isRecord()) {
13666     int DiagArg = -1;
13667     switch (D.getName().getKind()) {
13668     case UnqualifiedId::IK_ConstructorTemplateId:
13669     case UnqualifiedId::IK_ConstructorName:
13670       DiagArg = 0;
13671       break;
13672     case UnqualifiedId::IK_DestructorName:
13673       DiagArg = 1;
13674       break;
13675     case UnqualifiedId::IK_ConversionFunctionId:
13676       DiagArg = 2;
13677       break;
13678     case UnqualifiedId::IK_Identifier:
13679     case UnqualifiedId::IK_ImplicitSelfParam:
13680     case UnqualifiedId::IK_LiteralOperatorId:
13681     case UnqualifiedId::IK_OperatorFunctionId:
13682     case UnqualifiedId::IK_TemplateId:
13683       break;
13684     }
13685     // This implies that it has to be an operator or function.
13686     if (DiagArg >= 0) {
13687       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
13688       return nullptr;
13689     }
13690   }
13691 
13692   // FIXME: This is an egregious hack to cope with cases where the scope stack
13693   // does not contain the declaration context, i.e., in an out-of-line
13694   // definition of a class.
13695   Scope FakeDCScope(S, Scope::DeclScope, Diags);
13696   if (!DCScope) {
13697     FakeDCScope.setEntity(DC);
13698     DCScope = &FakeDCScope;
13699   }
13700 
13701   bool AddToScope = true;
13702   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
13703                                           TemplateParams, AddToScope);
13704   if (!ND) return nullptr;
13705 
13706   assert(ND->getLexicalDeclContext() == CurContext);
13707 
13708   // If we performed typo correction, we might have added a scope specifier
13709   // and changed the decl context.
13710   DC = ND->getDeclContext();
13711 
13712   // Add the function declaration to the appropriate lookup tables,
13713   // adjusting the redeclarations list as necessary.  We don't
13714   // want to do this yet if the friending class is dependent.
13715   //
13716   // Also update the scope-based lookup if the target context's
13717   // lookup context is in lexical scope.
13718   if (!CurContext->isDependentContext()) {
13719     DC = DC->getRedeclContext();
13720     DC->makeDeclVisibleInContext(ND);
13721     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
13722       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
13723   }
13724 
13725   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
13726                                        D.getIdentifierLoc(), ND,
13727                                        DS.getFriendSpecLoc());
13728   FrD->setAccess(AS_public);
13729   CurContext->addDecl(FrD);
13730 
13731   if (ND->isInvalidDecl()) {
13732     FrD->setInvalidDecl();
13733   } else {
13734     if (DC->isRecord()) CheckFriendAccess(ND);
13735 
13736     FunctionDecl *FD;
13737     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
13738       FD = FTD->getTemplatedDecl();
13739     else
13740       FD = cast<FunctionDecl>(ND);
13741 
13742     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
13743     // default argument expression, that declaration shall be a definition
13744     // and shall be the only declaration of the function or function
13745     // template in the translation unit.
13746     if (functionDeclHasDefaultArgument(FD)) {
13747       if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
13748         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
13749         Diag(OldFD->getLocation(), diag::note_previous_declaration);
13750       } else if (!D.isFunctionDefinition())
13751         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
13752     }
13753 
13754     // Mark templated-scope function declarations as unsupported.
13755     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
13756       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
13757         << SS.getScopeRep() << SS.getRange()
13758         << cast<CXXRecordDecl>(CurContext);
13759       FrD->setUnsupportedFriend(true);
13760     }
13761   }
13762 
13763   return ND;
13764 }
13765 
13766 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
13767   AdjustDeclIfTemplate(Dcl);
13768 
13769   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
13770   if (!Fn) {
13771     Diag(DelLoc, diag::err_deleted_non_function);
13772     return;
13773   }
13774 
13775   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
13776     // Don't consider the implicit declaration we generate for explicit
13777     // specializations. FIXME: Do not generate these implicit declarations.
13778     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
13779          Prev->getPreviousDecl()) &&
13780         !Prev->isDefined()) {
13781       Diag(DelLoc, diag::err_deleted_decl_not_first);
13782       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
13783            Prev->isImplicit() ? diag::note_previous_implicit_declaration
13784                               : diag::note_previous_declaration);
13785     }
13786     // If the declaration wasn't the first, we delete the function anyway for
13787     // recovery.
13788     Fn = Fn->getCanonicalDecl();
13789   }
13790 
13791   // dllimport/dllexport cannot be deleted.
13792   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
13793     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
13794     Fn->setInvalidDecl();
13795   }
13796 
13797   if (Fn->isDeleted())
13798     return;
13799 
13800   // See if we're deleting a function which is already known to override a
13801   // non-deleted virtual function.
13802   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
13803     bool IssuedDiagnostic = false;
13804     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
13805                                         E = MD->end_overridden_methods();
13806          I != E; ++I) {
13807       if (!(*MD->begin_overridden_methods())->isDeleted()) {
13808         if (!IssuedDiagnostic) {
13809           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
13810           IssuedDiagnostic = true;
13811         }
13812         Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
13813       }
13814     }
13815   }
13816 
13817   // C++11 [basic.start.main]p3:
13818   //   A program that defines main as deleted [...] is ill-formed.
13819   if (Fn->isMain())
13820     Diag(DelLoc, diag::err_deleted_main);
13821 
13822   Fn->setDeletedAsWritten();
13823 }
13824 
13825 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
13826   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
13827 
13828   if (MD) {
13829     if (MD->getParent()->isDependentType()) {
13830       MD->setDefaulted();
13831       MD->setExplicitlyDefaulted();
13832       return;
13833     }
13834 
13835     CXXSpecialMember Member = getSpecialMember(MD);
13836     if (Member == CXXInvalid) {
13837       if (!MD->isInvalidDecl())
13838         Diag(DefaultLoc, diag::err_default_special_members);
13839       return;
13840     }
13841 
13842     MD->setDefaulted();
13843     MD->setExplicitlyDefaulted();
13844 
13845     // If this definition appears within the record, do the checking when
13846     // the record is complete.
13847     const FunctionDecl *Primary = MD;
13848     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
13849       // Ask the template instantiation pattern that actually had the
13850       // '= default' on it.
13851       Primary = Pattern;
13852 
13853     // If the method was defaulted on its first declaration, we will have
13854     // already performed the checking in CheckCompletedCXXClass. Such a
13855     // declaration doesn't trigger an implicit definition.
13856     if (Primary->getCanonicalDecl()->isDefaulted())
13857       return;
13858 
13859     CheckExplicitlyDefaultedSpecialMember(MD);
13860 
13861     if (!MD->isInvalidDecl())
13862       DefineImplicitSpecialMember(*this, MD, DefaultLoc);
13863   } else {
13864     Diag(DefaultLoc, diag::err_default_special_members);
13865   }
13866 }
13867 
13868 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
13869   for (Stmt *SubStmt : S->children()) {
13870     if (!SubStmt)
13871       continue;
13872     if (isa<ReturnStmt>(SubStmt))
13873       Self.Diag(SubStmt->getLocStart(),
13874            diag::err_return_in_constructor_handler);
13875     if (!isa<Expr>(SubStmt))
13876       SearchForReturnInStmt(Self, SubStmt);
13877   }
13878 }
13879 
13880 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
13881   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
13882     CXXCatchStmt *Handler = TryBlock->getHandler(I);
13883     SearchForReturnInStmt(*this, Handler);
13884   }
13885 }
13886 
13887 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
13888                                              const CXXMethodDecl *Old) {
13889   const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
13890   const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
13891 
13892   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
13893 
13894   // If the calling conventions match, everything is fine
13895   if (NewCC == OldCC)
13896     return false;
13897 
13898   // If the calling conventions mismatch because the new function is static,
13899   // suppress the calling convention mismatch error; the error about static
13900   // function override (err_static_overrides_virtual from
13901   // Sema::CheckFunctionDeclaration) is more clear.
13902   if (New->getStorageClass() == SC_Static)
13903     return false;
13904 
13905   Diag(New->getLocation(),
13906        diag::err_conflicting_overriding_cc_attributes)
13907     << New->getDeclName() << New->getType() << Old->getType();
13908   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
13909   return true;
13910 }
13911 
13912 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
13913                                              const CXXMethodDecl *Old) {
13914   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
13915   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
13916 
13917   if (Context.hasSameType(NewTy, OldTy) ||
13918       NewTy->isDependentType() || OldTy->isDependentType())
13919     return false;
13920 
13921   // Check if the return types are covariant
13922   QualType NewClassTy, OldClassTy;
13923 
13924   /// Both types must be pointers or references to classes.
13925   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
13926     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
13927       NewClassTy = NewPT->getPointeeType();
13928       OldClassTy = OldPT->getPointeeType();
13929     }
13930   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
13931     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
13932       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
13933         NewClassTy = NewRT->getPointeeType();
13934         OldClassTy = OldRT->getPointeeType();
13935       }
13936     }
13937   }
13938 
13939   // The return types aren't either both pointers or references to a class type.
13940   if (NewClassTy.isNull()) {
13941     Diag(New->getLocation(),
13942          diag::err_different_return_type_for_overriding_virtual_function)
13943         << New->getDeclName() << NewTy << OldTy
13944         << New->getReturnTypeSourceRange();
13945     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13946         << Old->getReturnTypeSourceRange();
13947 
13948     return true;
13949   }
13950 
13951   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
13952     // C++14 [class.virtual]p8:
13953     //   If the class type in the covariant return type of D::f differs from
13954     //   that of B::f, the class type in the return type of D::f shall be
13955     //   complete at the point of declaration of D::f or shall be the class
13956     //   type D.
13957     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
13958       if (!RT->isBeingDefined() &&
13959           RequireCompleteType(New->getLocation(), NewClassTy,
13960                               diag::err_covariant_return_incomplete,
13961                               New->getDeclName()))
13962         return true;
13963     }
13964 
13965     // Check if the new class derives from the old class.
13966     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
13967       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
13968           << New->getDeclName() << NewTy << OldTy
13969           << New->getReturnTypeSourceRange();
13970       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13971           << Old->getReturnTypeSourceRange();
13972       return true;
13973     }
13974 
13975     // Check if we the conversion from derived to base is valid.
13976     if (CheckDerivedToBaseConversion(
13977             NewClassTy, OldClassTy,
13978             diag::err_covariant_return_inaccessible_base,
13979             diag::err_covariant_return_ambiguous_derived_to_base_conv,
13980             New->getLocation(), New->getReturnTypeSourceRange(),
13981             New->getDeclName(), nullptr)) {
13982       // FIXME: this note won't trigger for delayed access control
13983       // diagnostics, and it's impossible to get an undelayed error
13984       // here from access control during the original parse because
13985       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
13986       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13987           << Old->getReturnTypeSourceRange();
13988       return true;
13989     }
13990   }
13991 
13992   // The qualifiers of the return types must be the same.
13993   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
13994     Diag(New->getLocation(),
13995          diag::err_covariant_return_type_different_qualifications)
13996         << New->getDeclName() << NewTy << OldTy
13997         << New->getReturnTypeSourceRange();
13998     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13999         << Old->getReturnTypeSourceRange();
14000     return true;
14001   }
14002 
14003 
14004   // The new class type must have the same or less qualifiers as the old type.
14005   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14006     Diag(New->getLocation(),
14007          diag::err_covariant_return_type_class_type_more_qualified)
14008         << New->getDeclName() << NewTy << OldTy
14009         << New->getReturnTypeSourceRange();
14010     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14011         << Old->getReturnTypeSourceRange();
14012     return true;
14013   }
14014 
14015   return false;
14016 }
14017 
14018 /// \brief Mark the given method pure.
14019 ///
14020 /// \param Method the method to be marked pure.
14021 ///
14022 /// \param InitRange the source range that covers the "0" initializer.
14023 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
14024   SourceLocation EndLoc = InitRange.getEnd();
14025   if (EndLoc.isValid())
14026     Method->setRangeEnd(EndLoc);
14027 
14028   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14029     Method->setPure();
14030     return false;
14031   }
14032 
14033   if (!Method->isInvalidDecl())
14034     Diag(Method->getLocation(), diag::err_non_virtual_pure)
14035       << Method->getDeclName() << InitRange;
14036   return true;
14037 }
14038 
14039 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
14040   if (D->getFriendObjectKind())
14041     Diag(D->getLocation(), diag::err_pure_friend);
14042   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14043     CheckPureMethod(M, ZeroLoc);
14044   else
14045     Diag(D->getLocation(), diag::err_illegal_initializer);
14046 }
14047 
14048 /// \brief Determine whether the given declaration is a static data member.
14049 static bool isStaticDataMember(const Decl *D) {
14050   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
14051     return Var->isStaticDataMember();
14052 
14053   return false;
14054 }
14055 
14056 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
14057 /// an initializer for the out-of-line declaration 'Dcl'.  The scope
14058 /// is a fresh scope pushed for just this purpose.
14059 ///
14060 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
14061 /// static data member of class X, names should be looked up in the scope of
14062 /// class X.
14063 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
14064   // If there is no declaration, there was an error parsing it.
14065   if (!D || D->isInvalidDecl())
14066     return;
14067 
14068   // We will always have a nested name specifier here, but this declaration
14069   // might not be out of line if the specifier names the current namespace:
14070   //   extern int n;
14071   //   int ::n = 0;
14072   if (D->isOutOfLine())
14073     EnterDeclaratorContext(S, D->getDeclContext());
14074 
14075   // If we are parsing the initializer for a static data member, push a
14076   // new expression evaluation context that is associated with this static
14077   // data member.
14078   if (isStaticDataMember(D))
14079     PushExpressionEvaluationContext(PotentiallyEvaluated, D);
14080 }
14081 
14082 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
14083 /// initializer for the out-of-line declaration 'D'.
14084 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
14085   // If there is no declaration, there was an error parsing it.
14086   if (!D || D->isInvalidDecl())
14087     return;
14088 
14089   if (isStaticDataMember(D))
14090     PopExpressionEvaluationContext();
14091 
14092   if (D->isOutOfLine())
14093     ExitDeclaratorContext(S);
14094 }
14095 
14096 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
14097 /// C++ if/switch/while/for statement.
14098 /// e.g: "if (int x = f()) {...}"
14099 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
14100   // C++ 6.4p2:
14101   // The declarator shall not specify a function or an array.
14102   // The type-specifier-seq shall not contain typedef and shall not declare a
14103   // new class or enumeration.
14104   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
14105          "Parser allowed 'typedef' as storage class of condition decl.");
14106 
14107   Decl *Dcl = ActOnDeclarator(S, D);
14108   if (!Dcl)
14109     return true;
14110 
14111   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
14112     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
14113       << D.getSourceRange();
14114     return true;
14115   }
14116 
14117   return Dcl;
14118 }
14119 
14120 void Sema::LoadExternalVTableUses() {
14121   if (!ExternalSource)
14122     return;
14123 
14124   SmallVector<ExternalVTableUse, 4> VTables;
14125   ExternalSource->ReadUsedVTables(VTables);
14126   SmallVector<VTableUse, 4> NewUses;
14127   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
14128     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
14129       = VTablesUsed.find(VTables[I].Record);
14130     // Even if a definition wasn't required before, it may be required now.
14131     if (Pos != VTablesUsed.end()) {
14132       if (!Pos->second && VTables[I].DefinitionRequired)
14133         Pos->second = true;
14134       continue;
14135     }
14136 
14137     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
14138     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
14139   }
14140 
14141   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
14142 }
14143 
14144 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
14145                           bool DefinitionRequired) {
14146   // Ignore any vtable uses in unevaluated operands or for classes that do
14147   // not have a vtable.
14148   if (!Class->isDynamicClass() || Class->isDependentContext() ||
14149       CurContext->isDependentContext() || isUnevaluatedContext())
14150     return;
14151 
14152   // Try to insert this class into the map.
14153   LoadExternalVTableUses();
14154   Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
14155   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
14156     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
14157   if (!Pos.second) {
14158     // If we already had an entry, check to see if we are promoting this vtable
14159     // to require a definition. If so, we need to reappend to the VTableUses
14160     // list, since we may have already processed the first entry.
14161     if (DefinitionRequired && !Pos.first->second) {
14162       Pos.first->second = true;
14163     } else {
14164       // Otherwise, we can early exit.
14165       return;
14166     }
14167   } else {
14168     // The Microsoft ABI requires that we perform the destructor body
14169     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
14170     // the deleting destructor is emitted with the vtable, not with the
14171     // destructor definition as in the Itanium ABI.
14172     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14173       CXXDestructorDecl *DD = Class->getDestructor();
14174       if (DD && DD->isVirtual() && !DD->isDeleted()) {
14175         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
14176           // If this is an out-of-line declaration, marking it referenced will
14177           // not do anything. Manually call CheckDestructor to look up operator
14178           // delete().
14179           ContextRAII SavedContext(*this, DD);
14180           CheckDestructor(DD);
14181         } else {
14182           MarkFunctionReferenced(Loc, Class->getDestructor());
14183         }
14184       }
14185     }
14186   }
14187 
14188   // Local classes need to have their virtual members marked
14189   // immediately. For all other classes, we mark their virtual members
14190   // at the end of the translation unit.
14191   if (Class->isLocalClass())
14192     MarkVirtualMembersReferenced(Loc, Class);
14193   else
14194     VTableUses.push_back(std::make_pair(Class, Loc));
14195 }
14196 
14197 bool Sema::DefineUsedVTables() {
14198   LoadExternalVTableUses();
14199   if (VTableUses.empty())
14200     return false;
14201 
14202   // Note: The VTableUses vector could grow as a result of marking
14203   // the members of a class as "used", so we check the size each
14204   // time through the loop and prefer indices (which are stable) to
14205   // iterators (which are not).
14206   bool DefinedAnything = false;
14207   for (unsigned I = 0; I != VTableUses.size(); ++I) {
14208     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
14209     if (!Class)
14210       continue;
14211 
14212     SourceLocation Loc = VTableUses[I].second;
14213 
14214     bool DefineVTable = true;
14215 
14216     // If this class has a key function, but that key function is
14217     // defined in another translation unit, we don't need to emit the
14218     // vtable even though we're using it.
14219     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
14220     if (KeyFunction && !KeyFunction->hasBody()) {
14221       // The key function is in another translation unit.
14222       DefineVTable = false;
14223       TemplateSpecializationKind TSK =
14224           KeyFunction->getTemplateSpecializationKind();
14225       assert(TSK != TSK_ExplicitInstantiationDefinition &&
14226              TSK != TSK_ImplicitInstantiation &&
14227              "Instantiations don't have key functions");
14228       (void)TSK;
14229     } else if (!KeyFunction) {
14230       // If we have a class with no key function that is the subject
14231       // of an explicit instantiation declaration, suppress the
14232       // vtable; it will live with the explicit instantiation
14233       // definition.
14234       bool IsExplicitInstantiationDeclaration
14235         = Class->getTemplateSpecializationKind()
14236                                       == TSK_ExplicitInstantiationDeclaration;
14237       for (auto R : Class->redecls()) {
14238         TemplateSpecializationKind TSK
14239           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
14240         if (TSK == TSK_ExplicitInstantiationDeclaration)
14241           IsExplicitInstantiationDeclaration = true;
14242         else if (TSK == TSK_ExplicitInstantiationDefinition) {
14243           IsExplicitInstantiationDeclaration = false;
14244           break;
14245         }
14246       }
14247 
14248       if (IsExplicitInstantiationDeclaration)
14249         DefineVTable = false;
14250     }
14251 
14252     // The exception specifications for all virtual members may be needed even
14253     // if we are not providing an authoritative form of the vtable in this TU.
14254     // We may choose to emit it available_externally anyway.
14255     if (!DefineVTable) {
14256       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
14257       continue;
14258     }
14259 
14260     // Mark all of the virtual members of this class as referenced, so
14261     // that we can build a vtable. Then, tell the AST consumer that a
14262     // vtable for this class is required.
14263     DefinedAnything = true;
14264     MarkVirtualMembersReferenced(Loc, Class);
14265     CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
14266     if (VTablesUsed[Canonical])
14267       Consumer.HandleVTable(Class);
14268 
14269     // Optionally warn if we're emitting a weak vtable.
14270     if (Class->isExternallyVisible() &&
14271         Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
14272       const FunctionDecl *KeyFunctionDef = nullptr;
14273       if (!KeyFunction ||
14274           (KeyFunction->hasBody(KeyFunctionDef) &&
14275            KeyFunctionDef->isInlined()))
14276         Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
14277              TSK_ExplicitInstantiationDefinition
14278              ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
14279           << Class;
14280     }
14281   }
14282   VTableUses.clear();
14283 
14284   return DefinedAnything;
14285 }
14286 
14287 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
14288                                                  const CXXRecordDecl *RD) {
14289   for (const auto *I : RD->methods())
14290     if (I->isVirtual() && !I->isPure())
14291       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
14292 }
14293 
14294 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
14295                                         const CXXRecordDecl *RD) {
14296   // Mark all functions which will appear in RD's vtable as used.
14297   CXXFinalOverriderMap FinalOverriders;
14298   RD->getFinalOverriders(FinalOverriders);
14299   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
14300                                             E = FinalOverriders.end();
14301        I != E; ++I) {
14302     for (OverridingMethods::const_iterator OI = I->second.begin(),
14303                                            OE = I->second.end();
14304          OI != OE; ++OI) {
14305       assert(OI->second.size() > 0 && "no final overrider");
14306       CXXMethodDecl *Overrider = OI->second.front().Method;
14307 
14308       // C++ [basic.def.odr]p2:
14309       //   [...] A virtual member function is used if it is not pure. [...]
14310       if (!Overrider->isPure())
14311         MarkFunctionReferenced(Loc, Overrider);
14312     }
14313   }
14314 
14315   // Only classes that have virtual bases need a VTT.
14316   if (RD->getNumVBases() == 0)
14317     return;
14318 
14319   for (const auto &I : RD->bases()) {
14320     const CXXRecordDecl *Base =
14321         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
14322     if (Base->getNumVBases() == 0)
14323       continue;
14324     MarkVirtualMembersReferenced(Loc, Base);
14325   }
14326 }
14327 
14328 /// SetIvarInitializers - This routine builds initialization ASTs for the
14329 /// Objective-C implementation whose ivars need be initialized.
14330 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
14331   if (!getLangOpts().CPlusPlus)
14332     return;
14333   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
14334     SmallVector<ObjCIvarDecl*, 8> ivars;
14335     CollectIvarsToConstructOrDestruct(OID, ivars);
14336     if (ivars.empty())
14337       return;
14338     SmallVector<CXXCtorInitializer*, 32> AllToInit;
14339     for (unsigned i = 0; i < ivars.size(); i++) {
14340       FieldDecl *Field = ivars[i];
14341       if (Field->isInvalidDecl())
14342         continue;
14343 
14344       CXXCtorInitializer *Member;
14345       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
14346       InitializationKind InitKind =
14347         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
14348 
14349       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
14350       ExprResult MemberInit =
14351         InitSeq.Perform(*this, InitEntity, InitKind, None);
14352       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
14353       // Note, MemberInit could actually come back empty if no initialization
14354       // is required (e.g., because it would call a trivial default constructor)
14355       if (!MemberInit.get() || MemberInit.isInvalid())
14356         continue;
14357 
14358       Member =
14359         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
14360                                          SourceLocation(),
14361                                          MemberInit.getAs<Expr>(),
14362                                          SourceLocation());
14363       AllToInit.push_back(Member);
14364 
14365       // Be sure that the destructor is accessible and is marked as referenced.
14366       if (const RecordType *RecordTy =
14367               Context.getBaseElementType(Field->getType())
14368                   ->getAs<RecordType>()) {
14369         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
14370         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
14371           MarkFunctionReferenced(Field->getLocation(), Destructor);
14372           CheckDestructorAccess(Field->getLocation(), Destructor,
14373                             PDiag(diag::err_access_dtor_ivar)
14374                               << Context.getBaseElementType(Field->getType()));
14375         }
14376       }
14377     }
14378     ObjCImplementation->setIvarInitializers(Context,
14379                                             AllToInit.data(), AllToInit.size());
14380   }
14381 }
14382 
14383 static
14384 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
14385                            llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
14386                            llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
14387                            llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
14388                            Sema &S) {
14389   if (Ctor->isInvalidDecl())
14390     return;
14391 
14392   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
14393 
14394   // Target may not be determinable yet, for instance if this is a dependent
14395   // call in an uninstantiated template.
14396   if (Target) {
14397     const FunctionDecl *FNTarget = nullptr;
14398     (void)Target->hasBody(FNTarget);
14399     Target = const_cast<CXXConstructorDecl*>(
14400       cast_or_null<CXXConstructorDecl>(FNTarget));
14401   }
14402 
14403   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
14404                      // Avoid dereferencing a null pointer here.
14405                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
14406 
14407   if (!Current.insert(Canonical).second)
14408     return;
14409 
14410   // We know that beyond here, we aren't chaining into a cycle.
14411   if (!Target || !Target->isDelegatingConstructor() ||
14412       Target->isInvalidDecl() || Valid.count(TCanonical)) {
14413     Valid.insert(Current.begin(), Current.end());
14414     Current.clear();
14415   // We've hit a cycle.
14416   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
14417              Current.count(TCanonical)) {
14418     // If we haven't diagnosed this cycle yet, do so now.
14419     if (!Invalid.count(TCanonical)) {
14420       S.Diag((*Ctor->init_begin())->getSourceLocation(),
14421              diag::warn_delegating_ctor_cycle)
14422         << Ctor;
14423 
14424       // Don't add a note for a function delegating directly to itself.
14425       if (TCanonical != Canonical)
14426         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
14427 
14428       CXXConstructorDecl *C = Target;
14429       while (C->getCanonicalDecl() != Canonical) {
14430         const FunctionDecl *FNTarget = nullptr;
14431         (void)C->getTargetConstructor()->hasBody(FNTarget);
14432         assert(FNTarget && "Ctor cycle through bodiless function");
14433 
14434         C = const_cast<CXXConstructorDecl*>(
14435           cast<CXXConstructorDecl>(FNTarget));
14436         S.Diag(C->getLocation(), diag::note_which_delegates_to);
14437       }
14438     }
14439 
14440     Invalid.insert(Current.begin(), Current.end());
14441     Current.clear();
14442   } else {
14443     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
14444   }
14445 }
14446 
14447 
14448 void Sema::CheckDelegatingCtorCycles() {
14449   llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
14450 
14451   for (DelegatingCtorDeclsType::iterator
14452          I = DelegatingCtorDecls.begin(ExternalSource),
14453          E = DelegatingCtorDecls.end();
14454        I != E; ++I)
14455     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
14456 
14457   for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
14458                                                          CE = Invalid.end();
14459        CI != CE; ++CI)
14460     (*CI)->setInvalidDecl();
14461 }
14462 
14463 namespace {
14464   /// \brief AST visitor that finds references to the 'this' expression.
14465   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
14466     Sema &S;
14467 
14468   public:
14469     explicit FindCXXThisExpr(Sema &S) : S(S) { }
14470 
14471     bool VisitCXXThisExpr(CXXThisExpr *E) {
14472       S.Diag(E->getLocation(), diag::err_this_static_member_func)
14473         << E->isImplicit();
14474       return false;
14475     }
14476   };
14477 }
14478 
14479 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
14480   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14481   if (!TSInfo)
14482     return false;
14483 
14484   TypeLoc TL = TSInfo->getTypeLoc();
14485   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
14486   if (!ProtoTL)
14487     return false;
14488 
14489   // C++11 [expr.prim.general]p3:
14490   //   [The expression this] shall not appear before the optional
14491   //   cv-qualifier-seq and it shall not appear within the declaration of a
14492   //   static member function (although its type and value category are defined
14493   //   within a static member function as they are within a non-static member
14494   //   function). [ Note: this is because declaration matching does not occur
14495   //  until the complete declarator is known. - end note ]
14496   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
14497   FindCXXThisExpr Finder(*this);
14498 
14499   // If the return type came after the cv-qualifier-seq, check it now.
14500   if (Proto->hasTrailingReturn() &&
14501       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
14502     return true;
14503 
14504   // Check the exception specification.
14505   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
14506     return true;
14507 
14508   return checkThisInStaticMemberFunctionAttributes(Method);
14509 }
14510 
14511 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
14512   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14513   if (!TSInfo)
14514     return false;
14515 
14516   TypeLoc TL = TSInfo->getTypeLoc();
14517   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
14518   if (!ProtoTL)
14519     return false;
14520 
14521   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
14522   FindCXXThisExpr Finder(*this);
14523 
14524   switch (Proto->getExceptionSpecType()) {
14525   case EST_Unparsed:
14526   case EST_Uninstantiated:
14527   case EST_Unevaluated:
14528   case EST_BasicNoexcept:
14529   case EST_DynamicNone:
14530   case EST_MSAny:
14531   case EST_None:
14532     break;
14533 
14534   case EST_ComputedNoexcept:
14535     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
14536       return true;
14537 
14538   case EST_Dynamic:
14539     for (const auto &E : Proto->exceptions()) {
14540       if (!Finder.TraverseType(E))
14541         return true;
14542     }
14543     break;
14544   }
14545 
14546   return false;
14547 }
14548 
14549 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
14550   FindCXXThisExpr Finder(*this);
14551 
14552   // Check attributes.
14553   for (const auto *A : Method->attrs()) {
14554     // FIXME: This should be emitted by tblgen.
14555     Expr *Arg = nullptr;
14556     ArrayRef<Expr *> Args;
14557     if (const auto *G = dyn_cast<GuardedByAttr>(A))
14558       Arg = G->getArg();
14559     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
14560       Arg = G->getArg();
14561     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
14562       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
14563     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
14564       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
14565     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
14566       Arg = ETLF->getSuccessValue();
14567       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
14568     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
14569       Arg = STLF->getSuccessValue();
14570       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
14571     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
14572       Arg = LR->getArg();
14573     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
14574       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
14575     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
14576       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
14577     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
14578       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
14579     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
14580       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
14581     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
14582       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
14583 
14584     if (Arg && !Finder.TraverseStmt(Arg))
14585       return true;
14586 
14587     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
14588       if (!Finder.TraverseStmt(Args[I]))
14589         return true;
14590     }
14591   }
14592 
14593   return false;
14594 }
14595 
14596 void Sema::checkExceptionSpecification(
14597     bool IsTopLevel, ExceptionSpecificationType EST,
14598     ArrayRef<ParsedType> DynamicExceptions,
14599     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
14600     SmallVectorImpl<QualType> &Exceptions,
14601     FunctionProtoType::ExceptionSpecInfo &ESI) {
14602   Exceptions.clear();
14603   ESI.Type = EST;
14604   if (EST == EST_Dynamic) {
14605     Exceptions.reserve(DynamicExceptions.size());
14606     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
14607       // FIXME: Preserve type source info.
14608       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
14609 
14610       if (IsTopLevel) {
14611         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
14612         collectUnexpandedParameterPacks(ET, Unexpanded);
14613         if (!Unexpanded.empty()) {
14614           DiagnoseUnexpandedParameterPacks(
14615               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
14616               Unexpanded);
14617           continue;
14618         }
14619       }
14620 
14621       // Check that the type is valid for an exception spec, and
14622       // drop it if not.
14623       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
14624         Exceptions.push_back(ET);
14625     }
14626     ESI.Exceptions = Exceptions;
14627     return;
14628   }
14629 
14630   if (EST == EST_ComputedNoexcept) {
14631     // If an error occurred, there's no expression here.
14632     if (NoexceptExpr) {
14633       assert((NoexceptExpr->isTypeDependent() ||
14634               NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
14635               Context.BoolTy) &&
14636              "Parser should have made sure that the expression is boolean");
14637       if (IsTopLevel && NoexceptExpr &&
14638           DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
14639         ESI.Type = EST_BasicNoexcept;
14640         return;
14641       }
14642 
14643       if (!NoexceptExpr->isValueDependent())
14644         NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
14645                          diag::err_noexcept_needs_constant_expression,
14646                          /*AllowFold*/ false).get();
14647       ESI.NoexceptExpr = NoexceptExpr;
14648     }
14649     return;
14650   }
14651 }
14652 
14653 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
14654              ExceptionSpecificationType EST,
14655              SourceRange SpecificationRange,
14656              ArrayRef<ParsedType> DynamicExceptions,
14657              ArrayRef<SourceRange> DynamicExceptionRanges,
14658              Expr *NoexceptExpr) {
14659   if (!MethodD)
14660     return;
14661 
14662   // Dig out the method we're referring to.
14663   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
14664     MethodD = FunTmpl->getTemplatedDecl();
14665 
14666   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
14667   if (!Method)
14668     return;
14669 
14670   // Check the exception specification.
14671   llvm::SmallVector<QualType, 4> Exceptions;
14672   FunctionProtoType::ExceptionSpecInfo ESI;
14673   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
14674                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
14675                               ESI);
14676 
14677   // Update the exception specification on the function type.
14678   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
14679 
14680   if (Method->isStatic())
14681     checkThisInStaticMemberFunctionExceptionSpec(Method);
14682 
14683   if (Method->isVirtual()) {
14684     // Check overrides, which we previously had to delay.
14685     for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
14686                                      OEnd = Method->end_overridden_methods();
14687          O != OEnd; ++O)
14688       CheckOverridingFunctionExceptionSpec(Method, *O);
14689   }
14690 }
14691 
14692 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
14693 ///
14694 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
14695                                        SourceLocation DeclStart,
14696                                        Declarator &D, Expr *BitWidth,
14697                                        InClassInitStyle InitStyle,
14698                                        AccessSpecifier AS,
14699                                        AttributeList *MSPropertyAttr) {
14700   IdentifierInfo *II = D.getIdentifier();
14701   if (!II) {
14702     Diag(DeclStart, diag::err_anonymous_property);
14703     return nullptr;
14704   }
14705   SourceLocation Loc = D.getIdentifierLoc();
14706 
14707   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14708   QualType T = TInfo->getType();
14709   if (getLangOpts().CPlusPlus) {
14710     CheckExtraCXXDefaultArguments(D);
14711 
14712     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14713                                         UPPC_DataMemberType)) {
14714       D.setInvalidType();
14715       T = Context.IntTy;
14716       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
14717     }
14718   }
14719 
14720   DiagnoseFunctionSpecifiers(D.getDeclSpec());
14721 
14722   if (D.getDeclSpec().isInlineSpecified())
14723     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14724         << getLangOpts().CPlusPlus1z;
14725   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
14726     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
14727          diag::err_invalid_thread)
14728       << DeclSpec::getSpecifierName(TSCS);
14729 
14730   // Check to see if this name was declared as a member previously
14731   NamedDecl *PrevDecl = nullptr;
14732   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
14733   LookupName(Previous, S);
14734   switch (Previous.getResultKind()) {
14735   case LookupResult::Found:
14736   case LookupResult::FoundUnresolvedValue:
14737     PrevDecl = Previous.getAsSingle<NamedDecl>();
14738     break;
14739 
14740   case LookupResult::FoundOverloaded:
14741     PrevDecl = Previous.getRepresentativeDecl();
14742     break;
14743 
14744   case LookupResult::NotFound:
14745   case LookupResult::NotFoundInCurrentInstantiation:
14746   case LookupResult::Ambiguous:
14747     break;
14748   }
14749 
14750   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14751     // Maybe we will complain about the shadowed template parameter.
14752     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14753     // Just pretend that we didn't see the previous declaration.
14754     PrevDecl = nullptr;
14755   }
14756 
14757   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
14758     PrevDecl = nullptr;
14759 
14760   SourceLocation TSSL = D.getLocStart();
14761   const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
14762   MSPropertyDecl *NewPD = MSPropertyDecl::Create(
14763       Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
14764   ProcessDeclAttributes(TUScope, NewPD, D);
14765   NewPD->setAccess(AS);
14766 
14767   if (NewPD->isInvalidDecl())
14768     Record->setInvalidDecl();
14769 
14770   if (D.getDeclSpec().isModulePrivateSpecified())
14771     NewPD->setModulePrivate();
14772 
14773   if (NewPD->isInvalidDecl() && PrevDecl) {
14774     // Don't introduce NewFD into scope; there's already something
14775     // with the same name in the same scope.
14776   } else if (II) {
14777     PushOnScopeChains(NewPD, S);
14778   } else
14779     Record->addDecl(NewPD);
14780 
14781   return NewPD;
14782 }
14783