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
1069 checkTupleLikeDecomposition(Sema &S, ArrayRef<BindingDecl *> Bindings,
1070                             ValueDecl *Src, InitializedEntity &ParentEntity,
1071                             QualType DecompType, 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 =
1156         InitializedEntity::InitializeBinding(ParentEntity, B, RefType);
1157     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1158     InitializationSequence Seq(S, Entity, Kind, Init);
1159     E = Seq.Perform(S, Entity, Kind, Init);
1160     if (E.isInvalid())
1161       return true;
1162 
1163     B->setBinding(T, E.get());
1164     I++;
1165   }
1166 
1167   return false;
1168 }
1169 
1170 /// Find the base class to decompose in a built-in decomposition of a class type.
1171 /// This base class search is, unfortunately, not quite like any other that we
1172 /// perform anywhere else in C++.
1173 static const CXXRecordDecl *findDecomposableBaseClass(Sema &S,
1174                                                       SourceLocation Loc,
1175                                                       const CXXRecordDecl *RD,
1176                                                       CXXCastPath &BasePath) {
1177   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1178                           CXXBasePath &Path) {
1179     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1180   };
1181 
1182   const CXXRecordDecl *ClassWithFields = nullptr;
1183   if (RD->hasDirectFields())
1184     // [dcl.decomp]p4:
1185     //   Otherwise, all of E's non-static data members shall be public direct
1186     //   members of E ...
1187     ClassWithFields = RD;
1188   else {
1189     //   ... or of ...
1190     CXXBasePaths Paths;
1191     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1192     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1193       // If no classes have fields, just decompose RD itself. (This will work
1194       // if and only if zero bindings were provided.)
1195       return RD;
1196     }
1197 
1198     CXXBasePath *BestPath = nullptr;
1199     for (auto &P : Paths) {
1200       if (!BestPath)
1201         BestPath = &P;
1202       else if (!S.Context.hasSameType(P.back().Base->getType(),
1203                                       BestPath->back().Base->getType())) {
1204         //   ... the same ...
1205         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1206           << false << RD << BestPath->back().Base->getType()
1207           << P.back().Base->getType();
1208         return nullptr;
1209       } else if (P.Access < BestPath->Access) {
1210         BestPath = &P;
1211       }
1212     }
1213 
1214     //   ... unambiguous ...
1215     QualType BaseType = BestPath->back().Base->getType();
1216     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1217       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1218         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1219       return nullptr;
1220     }
1221 
1222     //   ... public base class of E.
1223     if (BestPath->Access != AS_public) {
1224       S.Diag(Loc, diag::err_decomp_decl_non_public_base)
1225         << RD << BaseType;
1226       for (auto &BS : *BestPath) {
1227         if (BS.Base->getAccessSpecifier() != AS_public) {
1228           S.Diag(BS.Base->getLocStart(), diag::note_access_constrained_by_path)
1229             << (BS.Base->getAccessSpecifier() == AS_protected)
1230             << (BS.Base->getAccessSpecifierAsWritten() == AS_none);
1231           break;
1232         }
1233       }
1234       return nullptr;
1235     }
1236 
1237     ClassWithFields = BaseType->getAsCXXRecordDecl();
1238     S.BuildBasePathArray(Paths, BasePath);
1239   }
1240 
1241   // The above search did not check whether the selected class itself has base
1242   // classes with fields, so check that now.
1243   CXXBasePaths Paths;
1244   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1245     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1246       << (ClassWithFields == RD) << RD << ClassWithFields
1247       << Paths.front().back().Base->getType();
1248     return nullptr;
1249   }
1250 
1251   return ClassWithFields;
1252 }
1253 
1254 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1255                                      ValueDecl *Src, QualType DecompType,
1256                                      const CXXRecordDecl *RD) {
1257   CXXCastPath BasePath;
1258   RD = findDecomposableBaseClass(S, Src->getLocation(), RD, BasePath);
1259   if (!RD)
1260     return true;
1261   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1262                                                  DecompType.getQualifiers());
1263 
1264   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1265     unsigned NumFields = std::distance(RD->field_begin(), RD->field_end());
1266     assert(Bindings.size() != NumFields);
1267     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1268         << DecompType << (unsigned)Bindings.size() << NumFields
1269         << (NumFields < Bindings.size());
1270     return true;
1271   };
1272 
1273   //   all of E's non-static data members shall be public [...] members,
1274   //   E shall not have an anonymous union member, ...
1275   unsigned I = 0;
1276   for (auto *FD : RD->fields()) {
1277     if (FD->isUnnamedBitfield())
1278       continue;
1279 
1280     if (FD->isAnonymousStructOrUnion()) {
1281       S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1282         << DecompType << FD->getType()->isUnionType();
1283       S.Diag(FD->getLocation(), diag::note_declared_at);
1284       return true;
1285     }
1286 
1287     // We have a real field to bind.
1288     if (I >= Bindings.size())
1289       return DiagnoseBadNumberOfBindings();
1290     auto *B = Bindings[I++];
1291 
1292     SourceLocation Loc = B->getLocation();
1293     if (FD->getAccess() != AS_public) {
1294       S.Diag(Loc, diag::err_decomp_decl_non_public_member) << FD << DecompType;
1295 
1296       // Determine whether the access specifier was explicit.
1297       bool Implicit = true;
1298       for (const auto *D : RD->decls()) {
1299         if (declaresSameEntity(D, FD))
1300           break;
1301         if (isa<AccessSpecDecl>(D)) {
1302           Implicit = false;
1303           break;
1304         }
1305       }
1306 
1307       S.Diag(FD->getLocation(), diag::note_access_natural)
1308         << (FD->getAccess() == AS_protected) << Implicit;
1309       return true;
1310     }
1311 
1312     // Initialize the binding to Src.FD.
1313     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1314     if (E.isInvalid())
1315       return true;
1316     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1317                             VK_LValue, &BasePath);
1318     if (E.isInvalid())
1319       return true;
1320     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1321                                   CXXScopeSpec(), FD,
1322                                   DeclAccessPair::make(FD, FD->getAccess()),
1323                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1324     if (E.isInvalid())
1325       return true;
1326 
1327     // If the type of the member is T, the referenced type is cv T, where cv is
1328     // the cv-qualification of the decomposition expression.
1329     //
1330     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1331     // 'const' to the type of the field.
1332     Qualifiers Q = DecompType.getQualifiers();
1333     if (FD->isMutable())
1334       Q.removeConst();
1335     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1336   }
1337 
1338   if (I != Bindings.size())
1339     return DiagnoseBadNumberOfBindings();
1340 
1341   return false;
1342 }
1343 
1344 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD,
1345                                                  InitializedEntity &Entity) {
1346   QualType DecompType = DD->getType();
1347 
1348   // If the type of the decomposition is dependent, then so is the type of
1349   // each binding.
1350   if (DecompType->isDependentType()) {
1351     for (auto *B : DD->bindings())
1352       B->setType(Context.DependentTy);
1353     return;
1354   }
1355 
1356   DecompType = DecompType.getNonReferenceType();
1357   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1358 
1359   // C++1z [dcl.decomp]/2:
1360   //   If E is an array type [...]
1361   // As an extension, we also support decomposition of built-in complex and
1362   // vector types.
1363   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1364     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1365       DD->setInvalidDecl();
1366     return;
1367   }
1368   if (auto *VT = DecompType->getAs<VectorType>()) {
1369     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1370       DD->setInvalidDecl();
1371     return;
1372   }
1373   if (auto *CT = DecompType->getAs<ComplexType>()) {
1374     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1375       DD->setInvalidDecl();
1376     return;
1377   }
1378 
1379   // C++1z [dcl.decomp]/3:
1380   //   if the expression std::tuple_size<E>::value is a well-formed integral
1381   //   constant expression, [...]
1382   llvm::APSInt TupleSize(32);
1383   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1384   case IsTupleLike::Error:
1385     DD->setInvalidDecl();
1386     return;
1387 
1388   case IsTupleLike::TupleLike:
1389     if (checkTupleLikeDecomposition(*this, Bindings, DD, Entity, DecompType,
1390                                     TupleSize))
1391       DD->setInvalidDecl();
1392     return;
1393 
1394   case IsTupleLike::NotTupleLike:
1395     break;
1396   }
1397 
1398   // C++1z [dcl.dcl]/8:
1399   //   [E shall be of array or non-union class type]
1400   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1401   if (!RD || RD->isUnion()) {
1402     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1403         << DD << !RD << DecompType;
1404     DD->setInvalidDecl();
1405     return;
1406   }
1407 
1408   // C++1z [dcl.decomp]/4:
1409   //   all of E's non-static data members shall be [...] direct members of
1410   //   E or of the same unambiguous public base class of E, ...
1411   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1412     DD->setInvalidDecl();
1413 }
1414 
1415 /// \brief Merge the exception specifications of two variable declarations.
1416 ///
1417 /// This is called when there's a redeclaration of a VarDecl. The function
1418 /// checks if the redeclaration might have an exception specification and
1419 /// validates compatibility and merges the specs if necessary.
1420 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1421   // Shortcut if exceptions are disabled.
1422   if (!getLangOpts().CXXExceptions)
1423     return;
1424 
1425   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1426          "Should only be called if types are otherwise the same.");
1427 
1428   QualType NewType = New->getType();
1429   QualType OldType = Old->getType();
1430 
1431   // We're only interested in pointers and references to functions, as well
1432   // as pointers to member functions.
1433   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1434     NewType = R->getPointeeType();
1435     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1436   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1437     NewType = P->getPointeeType();
1438     OldType = OldType->getAs<PointerType>()->getPointeeType();
1439   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1440     NewType = M->getPointeeType();
1441     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1442   }
1443 
1444   if (!NewType->isFunctionProtoType())
1445     return;
1446 
1447   // There's lots of special cases for functions. For function pointers, system
1448   // libraries are hopefully not as broken so that we don't need these
1449   // workarounds.
1450   if (CheckEquivalentExceptionSpec(
1451         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1452         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1453     New->setInvalidDecl();
1454   }
1455 }
1456 
1457 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1458 /// function declaration are well-formed according to C++
1459 /// [dcl.fct.default].
1460 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1461   unsigned NumParams = FD->getNumParams();
1462   unsigned p;
1463 
1464   // Find first parameter with a default argument
1465   for (p = 0; p < NumParams; ++p) {
1466     ParmVarDecl *Param = FD->getParamDecl(p);
1467     if (Param->hasDefaultArg())
1468       break;
1469   }
1470 
1471   // C++11 [dcl.fct.default]p4:
1472   //   In a given function declaration, each parameter subsequent to a parameter
1473   //   with a default argument shall have a default argument supplied in this or
1474   //   a previous declaration or shall be a function parameter pack. A default
1475   //   argument shall not be redefined by a later declaration (not even to the
1476   //   same value).
1477   unsigned LastMissingDefaultArg = 0;
1478   for (; p < NumParams; ++p) {
1479     ParmVarDecl *Param = FD->getParamDecl(p);
1480     if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
1481       if (Param->isInvalidDecl())
1482         /* We already complained about this parameter. */;
1483       else if (Param->getIdentifier())
1484         Diag(Param->getLocation(),
1485              diag::err_param_default_argument_missing_name)
1486           << Param->getIdentifier();
1487       else
1488         Diag(Param->getLocation(),
1489              diag::err_param_default_argument_missing);
1490 
1491       LastMissingDefaultArg = p;
1492     }
1493   }
1494 
1495   if (LastMissingDefaultArg > 0) {
1496     // Some default arguments were missing. Clear out all of the
1497     // default arguments up to (and including) the last missing
1498     // default argument, so that we leave the function parameters
1499     // in a semantically valid state.
1500     for (p = 0; p <= LastMissingDefaultArg; ++p) {
1501       ParmVarDecl *Param = FD->getParamDecl(p);
1502       if (Param->hasDefaultArg()) {
1503         Param->setDefaultArg(nullptr);
1504       }
1505     }
1506   }
1507 }
1508 
1509 // CheckConstexprParameterTypes - Check whether a function's parameter types
1510 // are all literal types. If so, return true. If not, produce a suitable
1511 // diagnostic and return false.
1512 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1513                                          const FunctionDecl *FD) {
1514   unsigned ArgIndex = 0;
1515   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
1516   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1517                                               e = FT->param_type_end();
1518        i != e; ++i, ++ArgIndex) {
1519     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1520     SourceLocation ParamLoc = PD->getLocation();
1521     if (!(*i)->isDependentType() &&
1522         SemaRef.RequireLiteralType(ParamLoc, *i,
1523                                    diag::err_constexpr_non_literal_param,
1524                                    ArgIndex+1, PD->getSourceRange(),
1525                                    isa<CXXConstructorDecl>(FD)))
1526       return false;
1527   }
1528   return true;
1529 }
1530 
1531 /// \brief Get diagnostic %select index for tag kind for
1532 /// record diagnostic message.
1533 /// WARNING: Indexes apply to particular diagnostics only!
1534 ///
1535 /// \returns diagnostic %select index.
1536 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1537   switch (Tag) {
1538   case TTK_Struct: return 0;
1539   case TTK_Interface: return 1;
1540   case TTK_Class:  return 2;
1541   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1542   }
1543 }
1544 
1545 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
1546 // the requirements of a constexpr function definition or a constexpr
1547 // constructor definition. If so, return true. If not, produce appropriate
1548 // diagnostics and return false.
1549 //
1550 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1551 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
1552   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1553   if (MD && MD->isInstance()) {
1554     // C++11 [dcl.constexpr]p4:
1555     //  The definition of a constexpr constructor shall satisfy the following
1556     //  constraints:
1557     //  - the class shall not have any virtual base classes;
1558     const CXXRecordDecl *RD = MD->getParent();
1559     if (RD->getNumVBases()) {
1560       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1561         << isa<CXXConstructorDecl>(NewFD)
1562         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1563       for (const auto &I : RD->vbases())
1564         Diag(I.getLocStart(),
1565              diag::note_constexpr_virtual_base_here) << I.getSourceRange();
1566       return false;
1567     }
1568   }
1569 
1570   if (!isa<CXXConstructorDecl>(NewFD)) {
1571     // C++11 [dcl.constexpr]p3:
1572     //  The definition of a constexpr function shall satisfy the following
1573     //  constraints:
1574     // - it shall not be virtual;
1575     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1576     if (Method && Method->isVirtual()) {
1577       Method = Method->getCanonicalDecl();
1578       Diag(Method->getLocation(), diag::err_constexpr_virtual);
1579 
1580       // If it's not obvious why this function is virtual, find an overridden
1581       // function which uses the 'virtual' keyword.
1582       const CXXMethodDecl *WrittenVirtual = Method;
1583       while (!WrittenVirtual->isVirtualAsWritten())
1584         WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1585       if (WrittenVirtual != Method)
1586         Diag(WrittenVirtual->getLocation(),
1587              diag::note_overridden_virtual_function);
1588       return false;
1589     }
1590 
1591     // - its return type shall be a literal type;
1592     QualType RT = NewFD->getReturnType();
1593     if (!RT->isDependentType() &&
1594         RequireLiteralType(NewFD->getLocation(), RT,
1595                            diag::err_constexpr_non_literal_return))
1596       return false;
1597   }
1598 
1599   // - each of its parameter types shall be a literal type;
1600   if (!CheckConstexprParameterTypes(*this, NewFD))
1601     return false;
1602 
1603   return true;
1604 }
1605 
1606 /// Check the given declaration statement is legal within a constexpr function
1607 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1608 ///
1609 /// \return true if the body is OK (maybe only as an extension), false if we
1610 ///         have diagnosed a problem.
1611 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1612                                    DeclStmt *DS, SourceLocation &Cxx1yLoc) {
1613   // C++11 [dcl.constexpr]p3 and p4:
1614   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1615   //  contain only
1616   for (const auto *DclIt : DS->decls()) {
1617     switch (DclIt->getKind()) {
1618     case Decl::StaticAssert:
1619     case Decl::Using:
1620     case Decl::UsingShadow:
1621     case Decl::UsingDirective:
1622     case Decl::UnresolvedUsingTypename:
1623     case Decl::UnresolvedUsingValue:
1624       //   - static_assert-declarations
1625       //   - using-declarations,
1626       //   - using-directives,
1627       continue;
1628 
1629     case Decl::Typedef:
1630     case Decl::TypeAlias: {
1631       //   - typedef declarations and alias-declarations that do not define
1632       //     classes or enumerations,
1633       const auto *TN = cast<TypedefNameDecl>(DclIt);
1634       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1635         // Don't allow variably-modified types in constexpr functions.
1636         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1637         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1638           << TL.getSourceRange() << TL.getType()
1639           << isa<CXXConstructorDecl>(Dcl);
1640         return false;
1641       }
1642       continue;
1643     }
1644 
1645     case Decl::Enum:
1646     case Decl::CXXRecord:
1647       // C++1y allows types to be defined, not just declared.
1648       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
1649         SemaRef.Diag(DS->getLocStart(),
1650                      SemaRef.getLangOpts().CPlusPlus14
1651                        ? diag::warn_cxx11_compat_constexpr_type_definition
1652                        : diag::ext_constexpr_type_definition)
1653           << isa<CXXConstructorDecl>(Dcl);
1654       continue;
1655 
1656     case Decl::EnumConstant:
1657     case Decl::IndirectField:
1658     case Decl::ParmVar:
1659       // These can only appear with other declarations which are banned in
1660       // C++11 and permitted in C++1y, so ignore them.
1661       continue;
1662 
1663     case Decl::Var:
1664     case Decl::Decomposition: {
1665       // C++1y [dcl.constexpr]p3 allows anything except:
1666       //   a definition of a variable of non-literal type or of static or
1667       //   thread storage duration or for which no initialization is performed.
1668       const auto *VD = cast<VarDecl>(DclIt);
1669       if (VD->isThisDeclarationADefinition()) {
1670         if (VD->isStaticLocal()) {
1671           SemaRef.Diag(VD->getLocation(),
1672                        diag::err_constexpr_local_var_static)
1673             << isa<CXXConstructorDecl>(Dcl)
1674             << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1675           return false;
1676         }
1677         if (!VD->getType()->isDependentType() &&
1678             SemaRef.RequireLiteralType(
1679               VD->getLocation(), VD->getType(),
1680               diag::err_constexpr_local_var_non_literal_type,
1681               isa<CXXConstructorDecl>(Dcl)))
1682           return false;
1683         if (!VD->getType()->isDependentType() &&
1684             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1685           SemaRef.Diag(VD->getLocation(),
1686                        diag::err_constexpr_local_var_no_init)
1687             << isa<CXXConstructorDecl>(Dcl);
1688           return false;
1689         }
1690       }
1691       SemaRef.Diag(VD->getLocation(),
1692                    SemaRef.getLangOpts().CPlusPlus14
1693                     ? diag::warn_cxx11_compat_constexpr_local_var
1694                     : diag::ext_constexpr_local_var)
1695         << isa<CXXConstructorDecl>(Dcl);
1696       continue;
1697     }
1698 
1699     case Decl::NamespaceAlias:
1700     case Decl::Function:
1701       // These are disallowed in C++11 and permitted in C++1y. Allow them
1702       // everywhere as an extension.
1703       if (!Cxx1yLoc.isValid())
1704         Cxx1yLoc = DS->getLocStart();
1705       continue;
1706 
1707     default:
1708       SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1709         << isa<CXXConstructorDecl>(Dcl);
1710       return false;
1711     }
1712   }
1713 
1714   return true;
1715 }
1716 
1717 /// Check that the given field is initialized within a constexpr constructor.
1718 ///
1719 /// \param Dcl The constexpr constructor being checked.
1720 /// \param Field The field being checked. This may be a member of an anonymous
1721 ///        struct or union nested within the class being checked.
1722 /// \param Inits All declarations, including anonymous struct/union members and
1723 ///        indirect members, for which any initialization was provided.
1724 /// \param Diagnosed Set to true if an error is produced.
1725 static void CheckConstexprCtorInitializer(Sema &SemaRef,
1726                                           const FunctionDecl *Dcl,
1727                                           FieldDecl *Field,
1728                                           llvm::SmallSet<Decl*, 16> &Inits,
1729                                           bool &Diagnosed) {
1730   if (Field->isInvalidDecl())
1731     return;
1732 
1733   if (Field->isUnnamedBitfield())
1734     return;
1735 
1736   // Anonymous unions with no variant members and empty anonymous structs do not
1737   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1738   // indirect fields don't need initializing.
1739   if (Field->isAnonymousStructOrUnion() &&
1740       (Field->getType()->isUnionType()
1741            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1742            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1743     return;
1744 
1745   if (!Inits.count(Field)) {
1746     if (!Diagnosed) {
1747       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1748       Diagnosed = true;
1749     }
1750     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1751   } else if (Field->isAnonymousStructOrUnion()) {
1752     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1753     for (auto *I : RD->fields())
1754       // If an anonymous union contains an anonymous struct of which any member
1755       // is initialized, all members must be initialized.
1756       if (!RD->isUnion() || Inits.count(I))
1757         CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
1758   }
1759 }
1760 
1761 /// Check the provided statement is allowed in a constexpr function
1762 /// definition.
1763 static bool
1764 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1765                            SmallVectorImpl<SourceLocation> &ReturnStmts,
1766                            SourceLocation &Cxx1yLoc) {
1767   // - its function-body shall be [...] a compound-statement that contains only
1768   switch (S->getStmtClass()) {
1769   case Stmt::NullStmtClass:
1770     //   - null statements,
1771     return true;
1772 
1773   case Stmt::DeclStmtClass:
1774     //   - static_assert-declarations
1775     //   - using-declarations,
1776     //   - using-directives,
1777     //   - typedef declarations and alias-declarations that do not define
1778     //     classes or enumerations,
1779     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1780       return false;
1781     return true;
1782 
1783   case Stmt::ReturnStmtClass:
1784     //   - and exactly one return statement;
1785     if (isa<CXXConstructorDecl>(Dcl)) {
1786       // C++1y allows return statements in constexpr constructors.
1787       if (!Cxx1yLoc.isValid())
1788         Cxx1yLoc = S->getLocStart();
1789       return true;
1790     }
1791 
1792     ReturnStmts.push_back(S->getLocStart());
1793     return true;
1794 
1795   case Stmt::CompoundStmtClass: {
1796     // C++1y allows compound-statements.
1797     if (!Cxx1yLoc.isValid())
1798       Cxx1yLoc = S->getLocStart();
1799 
1800     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1801     for (auto *BodyIt : CompStmt->body()) {
1802       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1803                                       Cxx1yLoc))
1804         return false;
1805     }
1806     return true;
1807   }
1808 
1809   case Stmt::AttributedStmtClass:
1810     if (!Cxx1yLoc.isValid())
1811       Cxx1yLoc = S->getLocStart();
1812     return true;
1813 
1814   case Stmt::IfStmtClass: {
1815     // C++1y allows if-statements.
1816     if (!Cxx1yLoc.isValid())
1817       Cxx1yLoc = S->getLocStart();
1818 
1819     IfStmt *If = cast<IfStmt>(S);
1820     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1821                                     Cxx1yLoc))
1822       return false;
1823     if (If->getElse() &&
1824         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1825                                     Cxx1yLoc))
1826       return false;
1827     return true;
1828   }
1829 
1830   case Stmt::WhileStmtClass:
1831   case Stmt::DoStmtClass:
1832   case Stmt::ForStmtClass:
1833   case Stmt::CXXForRangeStmtClass:
1834   case Stmt::ContinueStmtClass:
1835     // C++1y allows all of these. We don't allow them as extensions in C++11,
1836     // because they don't make sense without variable mutation.
1837     if (!SemaRef.getLangOpts().CPlusPlus14)
1838       break;
1839     if (!Cxx1yLoc.isValid())
1840       Cxx1yLoc = S->getLocStart();
1841     for (Stmt *SubStmt : S->children())
1842       if (SubStmt &&
1843           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1844                                       Cxx1yLoc))
1845         return false;
1846     return true;
1847 
1848   case Stmt::SwitchStmtClass:
1849   case Stmt::CaseStmtClass:
1850   case Stmt::DefaultStmtClass:
1851   case Stmt::BreakStmtClass:
1852     // C++1y allows switch-statements, and since they don't need variable
1853     // mutation, we can reasonably allow them in C++11 as an extension.
1854     if (!Cxx1yLoc.isValid())
1855       Cxx1yLoc = S->getLocStart();
1856     for (Stmt *SubStmt : S->children())
1857       if (SubStmt &&
1858           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1859                                       Cxx1yLoc))
1860         return false;
1861     return true;
1862 
1863   default:
1864     if (!isa<Expr>(S))
1865       break;
1866 
1867     // C++1y allows expression-statements.
1868     if (!Cxx1yLoc.isValid())
1869       Cxx1yLoc = S->getLocStart();
1870     return true;
1871   }
1872 
1873   SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1874     << isa<CXXConstructorDecl>(Dcl);
1875   return false;
1876 }
1877 
1878 /// Check the body for the given constexpr function declaration only contains
1879 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1880 ///
1881 /// \return true if the body is OK, false if we have diagnosed a problem.
1882 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1883   if (isa<CXXTryStmt>(Body)) {
1884     // C++11 [dcl.constexpr]p3:
1885     //  The definition of a constexpr function shall satisfy the following
1886     //  constraints: [...]
1887     // - its function-body shall be = delete, = default, or a
1888     //   compound-statement
1889     //
1890     // C++11 [dcl.constexpr]p4:
1891     //  In the definition of a constexpr constructor, [...]
1892     // - its function-body shall not be a function-try-block;
1893     Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1894       << isa<CXXConstructorDecl>(Dcl);
1895     return false;
1896   }
1897 
1898   SmallVector<SourceLocation, 4> ReturnStmts;
1899 
1900   // - its function-body shall be [...] a compound-statement that contains only
1901   //   [... list of cases ...]
1902   CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1903   SourceLocation Cxx1yLoc;
1904   for (auto *BodyIt : CompBody->body()) {
1905     if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
1906       return false;
1907   }
1908 
1909   if (Cxx1yLoc.isValid())
1910     Diag(Cxx1yLoc,
1911          getLangOpts().CPlusPlus14
1912            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1913            : diag::ext_constexpr_body_invalid_stmt)
1914       << isa<CXXConstructorDecl>(Dcl);
1915 
1916   if (const CXXConstructorDecl *Constructor
1917         = dyn_cast<CXXConstructorDecl>(Dcl)) {
1918     const CXXRecordDecl *RD = Constructor->getParent();
1919     // DR1359:
1920     // - every non-variant non-static data member and base class sub-object
1921     //   shall be initialized;
1922     // DR1460:
1923     // - if the class is a union having variant members, exactly one of them
1924     //   shall be initialized;
1925     if (RD->isUnion()) {
1926       if (Constructor->getNumCtorInitializers() == 0 &&
1927           RD->hasVariantMembers()) {
1928         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1929         return false;
1930       }
1931     } else if (!Constructor->isDependentContext() &&
1932                !Constructor->isDelegatingConstructor()) {
1933       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1934 
1935       // Skip detailed checking if we have enough initializers, and we would
1936       // allow at most one initializer per member.
1937       bool AnyAnonStructUnionMembers = false;
1938       unsigned Fields = 0;
1939       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1940            E = RD->field_end(); I != E; ++I, ++Fields) {
1941         if (I->isAnonymousStructOrUnion()) {
1942           AnyAnonStructUnionMembers = true;
1943           break;
1944         }
1945       }
1946       // DR1460:
1947       // - if the class is a union-like class, but is not a union, for each of
1948       //   its anonymous union members having variant members, exactly one of
1949       //   them shall be initialized;
1950       if (AnyAnonStructUnionMembers ||
1951           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1952         // Check initialization of non-static data members. Base classes are
1953         // always initialized so do not need to be checked. Dependent bases
1954         // might not have initializers in the member initializer list.
1955         llvm::SmallSet<Decl*, 16> Inits;
1956         for (const auto *I: Constructor->inits()) {
1957           if (FieldDecl *FD = I->getMember())
1958             Inits.insert(FD);
1959           else if (IndirectFieldDecl *ID = I->getIndirectMember())
1960             Inits.insert(ID->chain_begin(), ID->chain_end());
1961         }
1962 
1963         bool Diagnosed = false;
1964         for (auto *I : RD->fields())
1965           CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
1966         if (Diagnosed)
1967           return false;
1968       }
1969     }
1970   } else {
1971     if (ReturnStmts.empty()) {
1972       // C++1y doesn't require constexpr functions to contain a 'return'
1973       // statement. We still do, unless the return type might be void, because
1974       // otherwise if there's no return statement, the function cannot
1975       // be used in a core constant expression.
1976       bool OK = getLangOpts().CPlusPlus14 &&
1977                 (Dcl->getReturnType()->isVoidType() ||
1978                  Dcl->getReturnType()->isDependentType());
1979       Diag(Dcl->getLocation(),
1980            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1981               : diag::err_constexpr_body_no_return);
1982       if (!OK)
1983         return false;
1984     } else if (ReturnStmts.size() > 1) {
1985       Diag(ReturnStmts.back(),
1986            getLangOpts().CPlusPlus14
1987              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1988              : diag::ext_constexpr_body_multiple_return);
1989       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1990         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
1991     }
1992   }
1993 
1994   // C++11 [dcl.constexpr]p5:
1995   //   if no function argument values exist such that the function invocation
1996   //   substitution would produce a constant expression, the program is
1997   //   ill-formed; no diagnostic required.
1998   // C++11 [dcl.constexpr]p3:
1999   //   - every constructor call and implicit conversion used in initializing the
2000   //     return value shall be one of those allowed in a constant expression.
2001   // C++11 [dcl.constexpr]p4:
2002   //   - every constructor involved in initializing non-static data members and
2003   //     base class sub-objects shall be a constexpr constructor.
2004   SmallVector<PartialDiagnosticAt, 8> Diags;
2005   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
2006     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
2007       << isa<CXXConstructorDecl>(Dcl);
2008     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2009       Diag(Diags[I].first, Diags[I].second);
2010     // Don't return false here: we allow this for compatibility in
2011     // system headers.
2012   }
2013 
2014   return true;
2015 }
2016 
2017 /// isCurrentClassName - Determine whether the identifier II is the
2018 /// name of the class type currently being defined. In the case of
2019 /// nested classes, this will only return true if II is the name of
2020 /// the innermost class.
2021 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
2022                               const CXXScopeSpec *SS) {
2023   assert(getLangOpts().CPlusPlus && "No class names in C!");
2024 
2025   CXXRecordDecl *CurDecl;
2026   if (SS && SS->isSet() && !SS->isInvalid()) {
2027     DeclContext *DC = computeDeclContext(*SS, true);
2028     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2029   } else
2030     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2031 
2032   if (CurDecl && CurDecl->getIdentifier())
2033     return &II == CurDecl->getIdentifier();
2034   return false;
2035 }
2036 
2037 /// \brief Determine whether the identifier II is a typo for the name of
2038 /// the class type currently being defined. If so, update it to the identifier
2039 /// that should have been used.
2040 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2041   assert(getLangOpts().CPlusPlus && "No class names in C!");
2042 
2043   if (!getLangOpts().SpellChecking)
2044     return false;
2045 
2046   CXXRecordDecl *CurDecl;
2047   if (SS && SS->isSet() && !SS->isInvalid()) {
2048     DeclContext *DC = computeDeclContext(*SS, true);
2049     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2050   } else
2051     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2052 
2053   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2054       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2055           < II->getLength()) {
2056     II = CurDecl->getIdentifier();
2057     return true;
2058   }
2059 
2060   return false;
2061 }
2062 
2063 /// \brief Determine whether the given class is a base class of the given
2064 /// class, including looking at dependent bases.
2065 static bool findCircularInheritance(const CXXRecordDecl *Class,
2066                                     const CXXRecordDecl *Current) {
2067   SmallVector<const CXXRecordDecl*, 8> Queue;
2068 
2069   Class = Class->getCanonicalDecl();
2070   while (true) {
2071     for (const auto &I : Current->bases()) {
2072       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2073       if (!Base)
2074         continue;
2075 
2076       Base = Base->getDefinition();
2077       if (!Base)
2078         continue;
2079 
2080       if (Base->getCanonicalDecl() == Class)
2081         return true;
2082 
2083       Queue.push_back(Base);
2084     }
2085 
2086     if (Queue.empty())
2087       return false;
2088 
2089     Current = Queue.pop_back_val();
2090   }
2091 
2092   return false;
2093 }
2094 
2095 /// \brief Check the validity of a C++ base class specifier.
2096 ///
2097 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2098 /// and returns NULL otherwise.
2099 CXXBaseSpecifier *
2100 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2101                          SourceRange SpecifierRange,
2102                          bool Virtual, AccessSpecifier Access,
2103                          TypeSourceInfo *TInfo,
2104                          SourceLocation EllipsisLoc) {
2105   QualType BaseType = TInfo->getType();
2106 
2107   // C++ [class.union]p1:
2108   //   A union shall not have base classes.
2109   if (Class->isUnion()) {
2110     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2111       << SpecifierRange;
2112     return nullptr;
2113   }
2114 
2115   if (EllipsisLoc.isValid() &&
2116       !TInfo->getType()->containsUnexpandedParameterPack()) {
2117     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2118       << TInfo->getTypeLoc().getSourceRange();
2119     EllipsisLoc = SourceLocation();
2120   }
2121 
2122   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2123 
2124   if (BaseType->isDependentType()) {
2125     // Make sure that we don't have circular inheritance among our dependent
2126     // bases. For non-dependent bases, the check for completeness below handles
2127     // this.
2128     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2129       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2130           ((BaseDecl = BaseDecl->getDefinition()) &&
2131            findCircularInheritance(Class, BaseDecl))) {
2132         Diag(BaseLoc, diag::err_circular_inheritance)
2133           << BaseType << Context.getTypeDeclType(Class);
2134 
2135         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2136           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2137             << BaseType;
2138 
2139         return nullptr;
2140       }
2141     }
2142 
2143     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2144                                           Class->getTagKind() == TTK_Class,
2145                                           Access, TInfo, EllipsisLoc);
2146   }
2147 
2148   // Base specifiers must be record types.
2149   if (!BaseType->isRecordType()) {
2150     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2151     return nullptr;
2152   }
2153 
2154   // C++ [class.union]p1:
2155   //   A union shall not be used as a base class.
2156   if (BaseType->isUnionType()) {
2157     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2158     return nullptr;
2159   }
2160 
2161   // For the MS ABI, propagate DLL attributes to base class templates.
2162   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2163     if (Attr *ClassAttr = getDLLAttr(Class)) {
2164       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2165               BaseType->getAsCXXRecordDecl())) {
2166         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2167                                             BaseLoc);
2168       }
2169     }
2170   }
2171 
2172   // C++ [class.derived]p2:
2173   //   The class-name in a base-specifier shall not be an incompletely
2174   //   defined class.
2175   if (RequireCompleteType(BaseLoc, BaseType,
2176                           diag::err_incomplete_base_class, SpecifierRange)) {
2177     Class->setInvalidDecl();
2178     return nullptr;
2179   }
2180 
2181   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2182   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
2183   assert(BaseDecl && "Record type has no declaration");
2184   BaseDecl = BaseDecl->getDefinition();
2185   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2186   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2187   assert(CXXBaseDecl && "Base type is not a C++ type");
2188 
2189   // A class which contains a flexible array member is not suitable for use as a
2190   // base class:
2191   //   - If the layout determines that a base comes before another base,
2192   //     the flexible array member would index into the subsequent base.
2193   //   - If the layout determines that base comes before the derived class,
2194   //     the flexible array member would index into the derived class.
2195   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2196     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2197       << CXXBaseDecl->getDeclName();
2198     return nullptr;
2199   }
2200 
2201   // C++ [class]p3:
2202   //   If a class is marked final and it appears as a base-type-specifier in
2203   //   base-clause, the program is ill-formed.
2204   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2205     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2206       << CXXBaseDecl->getDeclName()
2207       << FA->isSpelledAsSealed();
2208     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2209         << CXXBaseDecl->getDeclName() << FA->getRange();
2210     return nullptr;
2211   }
2212 
2213   if (BaseDecl->isInvalidDecl())
2214     Class->setInvalidDecl();
2215 
2216   // Create the base specifier.
2217   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2218                                         Class->getTagKind() == TTK_Class,
2219                                         Access, TInfo, EllipsisLoc);
2220 }
2221 
2222 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2223 /// one entry in the base class list of a class specifier, for
2224 /// example:
2225 ///    class foo : public bar, virtual private baz {
2226 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2227 BaseResult
2228 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2229                          ParsedAttributes &Attributes,
2230                          bool Virtual, AccessSpecifier Access,
2231                          ParsedType basetype, SourceLocation BaseLoc,
2232                          SourceLocation EllipsisLoc) {
2233   if (!classdecl)
2234     return true;
2235 
2236   AdjustDeclIfTemplate(classdecl);
2237   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2238   if (!Class)
2239     return true;
2240 
2241   // We haven't yet attached the base specifiers.
2242   Class->setIsParsingBaseSpecifiers();
2243 
2244   // We do not support any C++11 attributes on base-specifiers yet.
2245   // Diagnose any attributes we see.
2246   if (!Attributes.empty()) {
2247     for (AttributeList *Attr = Attributes.getList(); Attr;
2248          Attr = Attr->getNext()) {
2249       if (Attr->isInvalid() ||
2250           Attr->getKind() == AttributeList::IgnoredAttribute)
2251         continue;
2252       Diag(Attr->getLoc(),
2253            Attr->getKind() == AttributeList::UnknownAttribute
2254              ? diag::warn_unknown_attribute_ignored
2255              : diag::err_base_specifier_attribute)
2256         << Attr->getName();
2257     }
2258   }
2259 
2260   TypeSourceInfo *TInfo = nullptr;
2261   GetTypeFromParser(basetype, &TInfo);
2262 
2263   if (EllipsisLoc.isInvalid() &&
2264       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2265                                       UPPC_BaseType))
2266     return true;
2267 
2268   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2269                                                       Virtual, Access, TInfo,
2270                                                       EllipsisLoc))
2271     return BaseSpec;
2272   else
2273     Class->setInvalidDecl();
2274 
2275   return true;
2276 }
2277 
2278 /// Use small set to collect indirect bases.  As this is only used
2279 /// locally, there's no need to abstract the small size parameter.
2280 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2281 
2282 /// \brief Recursively add the bases of Type.  Don't add Type itself.
2283 static void
2284 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2285                   const QualType &Type)
2286 {
2287   // Even though the incoming type is a base, it might not be
2288   // a class -- it could be a template parm, for instance.
2289   if (auto Rec = Type->getAs<RecordType>()) {
2290     auto Decl = Rec->getAsCXXRecordDecl();
2291 
2292     // Iterate over its bases.
2293     for (const auto &BaseSpec : Decl->bases()) {
2294       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2295         .getUnqualifiedType();
2296       if (Set.insert(Base).second)
2297         // If we've not already seen it, recurse.
2298         NoteIndirectBases(Context, Set, Base);
2299     }
2300   }
2301 }
2302 
2303 /// \brief Performs the actual work of attaching the given base class
2304 /// specifiers to a C++ class.
2305 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2306                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2307  if (Bases.empty())
2308     return false;
2309 
2310   // Used to keep track of which base types we have already seen, so
2311   // that we can properly diagnose redundant direct base types. Note
2312   // that the key is always the unqualified canonical type of the base
2313   // class.
2314   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2315 
2316   // Used to track indirect bases so we can see if a direct base is
2317   // ambiguous.
2318   IndirectBaseSet IndirectBaseTypes;
2319 
2320   // Copy non-redundant base specifiers into permanent storage.
2321   unsigned NumGoodBases = 0;
2322   bool Invalid = false;
2323   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2324     QualType NewBaseType
2325       = Context.getCanonicalType(Bases[idx]->getType());
2326     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2327 
2328     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2329     if (KnownBase) {
2330       // C++ [class.mi]p3:
2331       //   A class shall not be specified as a direct base class of a
2332       //   derived class more than once.
2333       Diag(Bases[idx]->getLocStart(),
2334            diag::err_duplicate_base_class)
2335         << KnownBase->getType()
2336         << Bases[idx]->getSourceRange();
2337 
2338       // Delete the duplicate base class specifier; we're going to
2339       // overwrite its pointer later.
2340       Context.Deallocate(Bases[idx]);
2341 
2342       Invalid = true;
2343     } else {
2344       // Okay, add this new base class.
2345       KnownBase = Bases[idx];
2346       Bases[NumGoodBases++] = Bases[idx];
2347 
2348       // Note this base's direct & indirect bases, if there could be ambiguity.
2349       if (Bases.size() > 1)
2350         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2351 
2352       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2353         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2354         if (Class->isInterface() &&
2355               (!RD->isInterface() ||
2356                KnownBase->getAccessSpecifier() != AS_public)) {
2357           // The Microsoft extension __interface does not permit bases that
2358           // are not themselves public interfaces.
2359           Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
2360             << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
2361             << RD->getSourceRange();
2362           Invalid = true;
2363         }
2364         if (RD->hasAttr<WeakAttr>())
2365           Class->addAttr(WeakAttr::CreateImplicit(Context));
2366       }
2367     }
2368   }
2369 
2370   // Attach the remaining base class specifiers to the derived class.
2371   Class->setBases(Bases.data(), NumGoodBases);
2372 
2373   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2374     // Check whether this direct base is inaccessible due to ambiguity.
2375     QualType BaseType = Bases[idx]->getType();
2376     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2377       .getUnqualifiedType();
2378 
2379     if (IndirectBaseTypes.count(CanonicalBase)) {
2380       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2381                          /*DetectVirtual=*/true);
2382       bool found
2383         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2384       assert(found);
2385       (void)found;
2386 
2387       if (Paths.isAmbiguous(CanonicalBase))
2388         Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
2389           << BaseType << getAmbiguousPathsDisplayString(Paths)
2390           << Bases[idx]->getSourceRange();
2391       else
2392         assert(Bases[idx]->isVirtual());
2393     }
2394 
2395     // Delete the base class specifier, since its data has been copied
2396     // into the CXXRecordDecl.
2397     Context.Deallocate(Bases[idx]);
2398   }
2399 
2400   return Invalid;
2401 }
2402 
2403 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2404 /// class, after checking whether there are any duplicate base
2405 /// classes.
2406 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2407                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2408   if (!ClassDecl || Bases.empty())
2409     return;
2410 
2411   AdjustDeclIfTemplate(ClassDecl);
2412   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2413 }
2414 
2415 /// \brief Determine whether the type \p Derived is a C++ class that is
2416 /// derived from the type \p Base.
2417 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2418   if (!getLangOpts().CPlusPlus)
2419     return false;
2420 
2421   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2422   if (!DerivedRD)
2423     return false;
2424 
2425   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2426   if (!BaseRD)
2427     return false;
2428 
2429   // If either the base or the derived type is invalid, don't try to
2430   // check whether one is derived from the other.
2431   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2432     return false;
2433 
2434   // FIXME: In a modules build, do we need the entire path to be visible for us
2435   // to be able to use the inheritance relationship?
2436   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2437     return false;
2438 
2439   return DerivedRD->isDerivedFrom(BaseRD);
2440 }
2441 
2442 /// \brief Determine whether the type \p Derived is a C++ class that is
2443 /// derived from the type \p Base.
2444 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2445                          CXXBasePaths &Paths) {
2446   if (!getLangOpts().CPlusPlus)
2447     return false;
2448 
2449   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2450   if (!DerivedRD)
2451     return false;
2452 
2453   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2454   if (!BaseRD)
2455     return false;
2456 
2457   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2458     return false;
2459 
2460   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2461 }
2462 
2463 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2464                               CXXCastPath &BasePathArray) {
2465   assert(BasePathArray.empty() && "Base path array must be empty!");
2466   assert(Paths.isRecordingPaths() && "Must record paths!");
2467 
2468   const CXXBasePath &Path = Paths.front();
2469 
2470   // We first go backward and check if we have a virtual base.
2471   // FIXME: It would be better if CXXBasePath had the base specifier for
2472   // the nearest virtual base.
2473   unsigned Start = 0;
2474   for (unsigned I = Path.size(); I != 0; --I) {
2475     if (Path[I - 1].Base->isVirtual()) {
2476       Start = I - 1;
2477       break;
2478     }
2479   }
2480 
2481   // Now add all bases.
2482   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2483     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2484 }
2485 
2486 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2487 /// conversion (where Derived and Base are class types) is
2488 /// well-formed, meaning that the conversion is unambiguous (and
2489 /// that all of the base classes are accessible). Returns true
2490 /// and emits a diagnostic if the code is ill-formed, returns false
2491 /// otherwise. Loc is the location where this routine should point to
2492 /// if there is an error, and Range is the source range to highlight
2493 /// if there is an error.
2494 ///
2495 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2496 /// diagnostic for the respective type of error will be suppressed, but the
2497 /// check for ill-formed code will still be performed.
2498 bool
2499 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2500                                    unsigned InaccessibleBaseID,
2501                                    unsigned AmbigiousBaseConvID,
2502                                    SourceLocation Loc, SourceRange Range,
2503                                    DeclarationName Name,
2504                                    CXXCastPath *BasePath,
2505                                    bool IgnoreAccess) {
2506   // First, determine whether the path from Derived to Base is
2507   // ambiguous. This is slightly more expensive than checking whether
2508   // the Derived to Base conversion exists, because here we need to
2509   // explore multiple paths to determine if there is an ambiguity.
2510   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2511                      /*DetectVirtual=*/false);
2512   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2513   assert(DerivationOkay &&
2514          "Can only be used with a derived-to-base conversion");
2515   (void)DerivationOkay;
2516 
2517   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
2518     if (!IgnoreAccess) {
2519       // Check that the base class can be accessed.
2520       switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
2521                                    InaccessibleBaseID)) {
2522         case AR_inaccessible:
2523           return true;
2524         case AR_accessible:
2525         case AR_dependent:
2526         case AR_delayed:
2527           break;
2528       }
2529     }
2530 
2531     // Build a base path if necessary.
2532     if (BasePath)
2533       BuildBasePathArray(Paths, *BasePath);
2534     return false;
2535   }
2536 
2537   if (AmbigiousBaseConvID) {
2538     // We know that the derived-to-base conversion is ambiguous, and
2539     // we're going to produce a diagnostic. Perform the derived-to-base
2540     // search just one more time to compute all of the possible paths so
2541     // that we can print them out. This is more expensive than any of
2542     // the previous derived-to-base checks we've done, but at this point
2543     // performance isn't as much of an issue.
2544     Paths.clear();
2545     Paths.setRecordingPaths(true);
2546     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2547     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2548     (void)StillOkay;
2549 
2550     // Build up a textual representation of the ambiguous paths, e.g.,
2551     // D -> B -> A, that will be used to illustrate the ambiguous
2552     // conversions in the diagnostic. We only print one of the paths
2553     // to each base class subobject.
2554     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2555 
2556     Diag(Loc, AmbigiousBaseConvID)
2557     << Derived << Base << PathDisplayStr << Range << Name;
2558   }
2559   return true;
2560 }
2561 
2562 bool
2563 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2564                                    SourceLocation Loc, SourceRange Range,
2565                                    CXXCastPath *BasePath,
2566                                    bool IgnoreAccess) {
2567   return CheckDerivedToBaseConversion(
2568       Derived, Base, diag::err_upcast_to_inaccessible_base,
2569       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2570       BasePath, IgnoreAccess);
2571 }
2572 
2573 
2574 /// @brief Builds a string representing ambiguous paths from a
2575 /// specific derived class to different subobjects of the same base
2576 /// class.
2577 ///
2578 /// This function builds a string that can be used in error messages
2579 /// to show the different paths that one can take through the
2580 /// inheritance hierarchy to go from the derived class to different
2581 /// subobjects of a base class. The result looks something like this:
2582 /// @code
2583 /// struct D -> struct B -> struct A
2584 /// struct D -> struct C -> struct A
2585 /// @endcode
2586 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2587   std::string PathDisplayStr;
2588   std::set<unsigned> DisplayedPaths;
2589   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2590        Path != Paths.end(); ++Path) {
2591     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2592       // We haven't displayed a path to this particular base
2593       // class subobject yet.
2594       PathDisplayStr += "\n    ";
2595       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2596       for (CXXBasePath::const_iterator Element = Path->begin();
2597            Element != Path->end(); ++Element)
2598         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2599     }
2600   }
2601 
2602   return PathDisplayStr;
2603 }
2604 
2605 //===----------------------------------------------------------------------===//
2606 // C++ class member Handling
2607 //===----------------------------------------------------------------------===//
2608 
2609 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2610 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
2611                                 SourceLocation ASLoc,
2612                                 SourceLocation ColonLoc,
2613                                 AttributeList *Attrs) {
2614   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2615   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2616                                                   ASLoc, ColonLoc);
2617   CurContext->addHiddenDecl(ASDecl);
2618   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2619 }
2620 
2621 /// CheckOverrideControl - Check C++11 override control semantics.
2622 void Sema::CheckOverrideControl(NamedDecl *D) {
2623   if (D->isInvalidDecl())
2624     return;
2625 
2626   // We only care about "override" and "final" declarations.
2627   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2628     return;
2629 
2630   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2631 
2632   // We can't check dependent instance methods.
2633   if (MD && MD->isInstance() &&
2634       (MD->getParent()->hasAnyDependentBases() ||
2635        MD->getType()->isDependentType()))
2636     return;
2637 
2638   if (MD && !MD->isVirtual()) {
2639     // If we have a non-virtual method, check if if hides a virtual method.
2640     // (In that case, it's most likely the method has the wrong type.)
2641     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2642     FindHiddenVirtualMethods(MD, OverloadedMethods);
2643 
2644     if (!OverloadedMethods.empty()) {
2645       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2646         Diag(OA->getLocation(),
2647              diag::override_keyword_hides_virtual_member_function)
2648           << "override" << (OverloadedMethods.size() > 1);
2649       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2650         Diag(FA->getLocation(),
2651              diag::override_keyword_hides_virtual_member_function)
2652           << (FA->isSpelledAsSealed() ? "sealed" : "final")
2653           << (OverloadedMethods.size() > 1);
2654       }
2655       NoteHiddenVirtualMethods(MD, OverloadedMethods);
2656       MD->setInvalidDecl();
2657       return;
2658     }
2659     // Fall through into the general case diagnostic.
2660     // FIXME: We might want to attempt typo correction here.
2661   }
2662 
2663   if (!MD || !MD->isVirtual()) {
2664     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2665       Diag(OA->getLocation(),
2666            diag::override_keyword_only_allowed_on_virtual_member_functions)
2667         << "override" << FixItHint::CreateRemoval(OA->getLocation());
2668       D->dropAttr<OverrideAttr>();
2669     }
2670     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2671       Diag(FA->getLocation(),
2672            diag::override_keyword_only_allowed_on_virtual_member_functions)
2673         << (FA->isSpelledAsSealed() ? "sealed" : "final")
2674         << FixItHint::CreateRemoval(FA->getLocation());
2675       D->dropAttr<FinalAttr>();
2676     }
2677     return;
2678   }
2679 
2680   // C++11 [class.virtual]p5:
2681   //   If a function is marked with the virt-specifier override and
2682   //   does not override a member function of a base class, the program is
2683   //   ill-formed.
2684   bool HasOverriddenMethods =
2685     MD->begin_overridden_methods() != MD->end_overridden_methods();
2686   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2687     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2688       << MD->getDeclName();
2689 }
2690 
2691 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2692   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2693     return;
2694   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2695   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
2696       isa<CXXDestructorDecl>(MD))
2697     return;
2698 
2699   SourceLocation Loc = MD->getLocation();
2700   SourceLocation SpellingLoc = Loc;
2701   if (getSourceManager().isMacroArgExpansion(Loc))
2702     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
2703   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2704   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
2705       return;
2706 
2707   if (MD->size_overridden_methods() > 0) {
2708     Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
2709       << MD->getDeclName();
2710     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2711     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2712   }
2713 }
2714 
2715 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
2716 /// function overrides a virtual member function marked 'final', according to
2717 /// C++11 [class.virtual]p4.
2718 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2719                                                   const CXXMethodDecl *Old) {
2720   FinalAttr *FA = Old->getAttr<FinalAttr>();
2721   if (!FA)
2722     return false;
2723 
2724   Diag(New->getLocation(), diag::err_final_function_overridden)
2725     << New->getDeclName()
2726     << FA->isSpelledAsSealed();
2727   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2728   return true;
2729 }
2730 
2731 static bool InitializationHasSideEffects(const FieldDecl &FD) {
2732   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2733   // FIXME: Destruction of ObjC lifetime types has side-effects.
2734   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2735     return !RD->isCompleteDefinition() ||
2736            !RD->hasTrivialDefaultConstructor() ||
2737            !RD->hasTrivialDestructor();
2738   return false;
2739 }
2740 
2741 static AttributeList *getMSPropertyAttr(AttributeList *list) {
2742   for (AttributeList *it = list; it != nullptr; it = it->getNext())
2743     if (it->isDeclspecPropertyAttribute())
2744       return it;
2745   return nullptr;
2746 }
2747 
2748 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2749 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2750 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
2751 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2752 /// present (but parsing it has been deferred).
2753 NamedDecl *
2754 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2755                                MultiTemplateParamsArg TemplateParameterLists,
2756                                Expr *BW, const VirtSpecifiers &VS,
2757                                InClassInitStyle InitStyle) {
2758   const DeclSpec &DS = D.getDeclSpec();
2759   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2760   DeclarationName Name = NameInfo.getName();
2761   SourceLocation Loc = NameInfo.getLoc();
2762 
2763   // For anonymous bitfields, the location should point to the type.
2764   if (Loc.isInvalid())
2765     Loc = D.getLocStart();
2766 
2767   Expr *BitWidth = static_cast<Expr*>(BW);
2768 
2769   assert(isa<CXXRecordDecl>(CurContext));
2770   assert(!DS.isFriendSpecified());
2771 
2772   bool isFunc = D.isDeclarationOfFunction();
2773 
2774   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2775     // The Microsoft extension __interface only permits public member functions
2776     // and prohibits constructors, destructors, operators, non-public member
2777     // functions, static methods and data members.
2778     unsigned InvalidDecl;
2779     bool ShowDeclName = true;
2780     if (!isFunc)
2781       InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
2782     else if (AS != AS_public)
2783       InvalidDecl = 2;
2784     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2785       InvalidDecl = 3;
2786     else switch (Name.getNameKind()) {
2787       case DeclarationName::CXXConstructorName:
2788         InvalidDecl = 4;
2789         ShowDeclName = false;
2790         break;
2791 
2792       case DeclarationName::CXXDestructorName:
2793         InvalidDecl = 5;
2794         ShowDeclName = false;
2795         break;
2796 
2797       case DeclarationName::CXXOperatorName:
2798       case DeclarationName::CXXConversionFunctionName:
2799         InvalidDecl = 6;
2800         break;
2801 
2802       default:
2803         InvalidDecl = 0;
2804         break;
2805     }
2806 
2807     if (InvalidDecl) {
2808       if (ShowDeclName)
2809         Diag(Loc, diag::err_invalid_member_in_interface)
2810           << (InvalidDecl-1) << Name;
2811       else
2812         Diag(Loc, diag::err_invalid_member_in_interface)
2813           << (InvalidDecl-1) << "";
2814       return nullptr;
2815     }
2816   }
2817 
2818   // C++ 9.2p6: A member shall not be declared to have automatic storage
2819   // duration (auto, register) or with the extern storage-class-specifier.
2820   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2821   // data members and cannot be applied to names declared const or static,
2822   // and cannot be applied to reference members.
2823   switch (DS.getStorageClassSpec()) {
2824   case DeclSpec::SCS_unspecified:
2825   case DeclSpec::SCS_typedef:
2826   case DeclSpec::SCS_static:
2827     break;
2828   case DeclSpec::SCS_mutable:
2829     if (isFunc) {
2830       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2831 
2832       // FIXME: It would be nicer if the keyword was ignored only for this
2833       // declarator. Otherwise we could get follow-up errors.
2834       D.getMutableDeclSpec().ClearStorageClassSpecs();
2835     }
2836     break;
2837   default:
2838     Diag(DS.getStorageClassSpecLoc(),
2839          diag::err_storageclass_invalid_for_member);
2840     D.getMutableDeclSpec().ClearStorageClassSpecs();
2841     break;
2842   }
2843 
2844   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2845                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
2846                       !isFunc);
2847 
2848   if (DS.isConstexprSpecified() && isInstField) {
2849     SemaDiagnosticBuilder B =
2850         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2851     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2852     if (InitStyle == ICIS_NoInit) {
2853       B << 0 << 0;
2854       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2855         B << FixItHint::CreateRemoval(ConstexprLoc);
2856       else {
2857         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2858         D.getMutableDeclSpec().ClearConstexprSpec();
2859         const char *PrevSpec;
2860         unsigned DiagID;
2861         bool Failed = D.getMutableDeclSpec().SetTypeQual(
2862             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2863         (void)Failed;
2864         assert(!Failed && "Making a constexpr member const shouldn't fail");
2865       }
2866     } else {
2867       B << 1;
2868       const char *PrevSpec;
2869       unsigned DiagID;
2870       if (D.getMutableDeclSpec().SetStorageClassSpec(
2871           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2872           Context.getPrintingPolicy())) {
2873         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
2874                "This is the only DeclSpec that should fail to be applied");
2875         B << 1;
2876       } else {
2877         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2878         isInstField = false;
2879       }
2880     }
2881   }
2882 
2883   NamedDecl *Member;
2884   if (isInstField) {
2885     CXXScopeSpec &SS = D.getCXXScopeSpec();
2886 
2887     // Data members must have identifiers for names.
2888     if (!Name.isIdentifier()) {
2889       Diag(Loc, diag::err_bad_variable_name)
2890         << Name;
2891       return nullptr;
2892     }
2893 
2894     IdentifierInfo *II = Name.getAsIdentifierInfo();
2895 
2896     // Member field could not be with "template" keyword.
2897     // So TemplateParameterLists should be empty in this case.
2898     if (TemplateParameterLists.size()) {
2899       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
2900       if (TemplateParams->size()) {
2901         // There is no such thing as a member field template.
2902         Diag(D.getIdentifierLoc(), diag::err_template_member)
2903             << II
2904             << SourceRange(TemplateParams->getTemplateLoc(),
2905                 TemplateParams->getRAngleLoc());
2906       } else {
2907         // There is an extraneous 'template<>' for this member.
2908         Diag(TemplateParams->getTemplateLoc(),
2909             diag::err_template_member_noparams)
2910             << II
2911             << SourceRange(TemplateParams->getTemplateLoc(),
2912                 TemplateParams->getRAngleLoc());
2913       }
2914       return nullptr;
2915     }
2916 
2917     if (SS.isSet() && !SS.isInvalid()) {
2918       // The user provided a superfluous scope specifier inside a class
2919       // definition:
2920       //
2921       // class X {
2922       //   int X::member;
2923       // };
2924       if (DeclContext *DC = computeDeclContext(SS, false))
2925         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
2926       else
2927         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2928           << Name << SS.getRange();
2929 
2930       SS.clear();
2931     }
2932 
2933     AttributeList *MSPropertyAttr =
2934       getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
2935     if (MSPropertyAttr) {
2936       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2937                                 BitWidth, InitStyle, AS, MSPropertyAttr);
2938       if (!Member)
2939         return nullptr;
2940       isInstField = false;
2941     } else {
2942       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2943                                 BitWidth, InitStyle, AS);
2944       if (!Member)
2945         return nullptr;
2946     }
2947   } else {
2948     Member = HandleDeclarator(S, D, TemplateParameterLists);
2949     if (!Member)
2950       return nullptr;
2951 
2952     // Non-instance-fields can't have a bitfield.
2953     if (BitWidth) {
2954       if (Member->isInvalidDecl()) {
2955         // don't emit another diagnostic.
2956       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
2957         // C++ 9.6p3: A bit-field shall not be a static member.
2958         // "static member 'A' cannot be a bit-field"
2959         Diag(Loc, diag::err_static_not_bitfield)
2960           << Name << BitWidth->getSourceRange();
2961       } else if (isa<TypedefDecl>(Member)) {
2962         // "typedef member 'x' cannot be a bit-field"
2963         Diag(Loc, diag::err_typedef_not_bitfield)
2964           << Name << BitWidth->getSourceRange();
2965       } else {
2966         // A function typedef ("typedef int f(); f a;").
2967         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2968         Diag(Loc, diag::err_not_integral_type_bitfield)
2969           << Name << cast<ValueDecl>(Member)->getType()
2970           << BitWidth->getSourceRange();
2971       }
2972 
2973       BitWidth = nullptr;
2974       Member->setInvalidDecl();
2975     }
2976 
2977     Member->setAccess(AS);
2978 
2979     // If we have declared a member function template or static data member
2980     // template, set the access of the templated declaration as well.
2981     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2982       FunTmpl->getTemplatedDecl()->setAccess(AS);
2983     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2984       VarTmpl->getTemplatedDecl()->setAccess(AS);
2985   }
2986 
2987   if (VS.isOverrideSpecified())
2988     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
2989   if (VS.isFinalSpecified())
2990     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2991                                             VS.isFinalSpelledSealed()));
2992 
2993   if (VS.getLastLocation().isValid()) {
2994     // Update the end location of a method that has a virt-specifiers.
2995     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2996       MD->setRangeEnd(VS.getLastLocation());
2997   }
2998 
2999   CheckOverrideControl(Member);
3000 
3001   assert((Name || isInstField) && "No identifier for non-field ?");
3002 
3003   if (isInstField) {
3004     FieldDecl *FD = cast<FieldDecl>(Member);
3005     FieldCollector->Add(FD);
3006 
3007     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3008       // Remember all explicit private FieldDecls that have a name, no side
3009       // effects and are not part of a dependent type declaration.
3010       if (!FD->isImplicit() && FD->getDeclName() &&
3011           FD->getAccess() == AS_private &&
3012           !FD->hasAttr<UnusedAttr>() &&
3013           !FD->getParent()->isDependentContext() &&
3014           !InitializationHasSideEffects(*FD))
3015         UnusedPrivateFields.insert(FD);
3016     }
3017   }
3018 
3019   return Member;
3020 }
3021 
3022 namespace {
3023   class UninitializedFieldVisitor
3024       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3025     Sema &S;
3026     // List of Decls to generate a warning on.  Also remove Decls that become
3027     // initialized.
3028     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3029     // List of base classes of the record.  Classes are removed after their
3030     // initializers.
3031     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3032     // Vector of decls to be removed from the Decl set prior to visiting the
3033     // nodes.  These Decls may have been initialized in the prior initializer.
3034     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3035     // If non-null, add a note to the warning pointing back to the constructor.
3036     const CXXConstructorDecl *Constructor;
3037     // Variables to hold state when processing an initializer list.  When
3038     // InitList is true, special case initialization of FieldDecls matching
3039     // InitListFieldDecl.
3040     bool InitList;
3041     FieldDecl *InitListFieldDecl;
3042     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3043 
3044   public:
3045     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3046     UninitializedFieldVisitor(Sema &S,
3047                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3048                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3049       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3050         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3051 
3052     // Returns true if the use of ME is not an uninitialized use.
3053     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3054                                          bool CheckReferenceOnly) {
3055       llvm::SmallVector<FieldDecl*, 4> Fields;
3056       bool ReferenceField = false;
3057       while (ME) {
3058         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3059         if (!FD)
3060           return false;
3061         Fields.push_back(FD);
3062         if (FD->getType()->isReferenceType())
3063           ReferenceField = true;
3064         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3065       }
3066 
3067       // Binding a reference to an unintialized field is not an
3068       // uninitialized use.
3069       if (CheckReferenceOnly && !ReferenceField)
3070         return true;
3071 
3072       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3073       // Discard the first field since it is the field decl that is being
3074       // initialized.
3075       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3076         UsedFieldIndex.push_back((*I)->getFieldIndex());
3077       }
3078 
3079       for (auto UsedIter = UsedFieldIndex.begin(),
3080                 UsedEnd = UsedFieldIndex.end(),
3081                 OrigIter = InitFieldIndex.begin(),
3082                 OrigEnd = InitFieldIndex.end();
3083            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3084         if (*UsedIter < *OrigIter)
3085           return true;
3086         if (*UsedIter > *OrigIter)
3087           break;
3088       }
3089 
3090       return false;
3091     }
3092 
3093     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3094                           bool AddressOf) {
3095       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3096         return;
3097 
3098       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3099       // or union.
3100       MemberExpr *FieldME = ME;
3101 
3102       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3103 
3104       Expr *Base = ME;
3105       while (MemberExpr *SubME =
3106                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3107 
3108         if (isa<VarDecl>(SubME->getMemberDecl()))
3109           return;
3110 
3111         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3112           if (!FD->isAnonymousStructOrUnion())
3113             FieldME = SubME;
3114 
3115         if (!FieldME->getType().isPODType(S.Context))
3116           AllPODFields = false;
3117 
3118         Base = SubME->getBase();
3119       }
3120 
3121       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3122         return;
3123 
3124       if (AddressOf && AllPODFields)
3125         return;
3126 
3127       ValueDecl* FoundVD = FieldME->getMemberDecl();
3128 
3129       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3130         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3131           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3132         }
3133 
3134         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3135           QualType T = BaseCast->getType();
3136           if (T->isPointerType() &&
3137               BaseClasses.count(T->getPointeeType())) {
3138             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3139                 << T->getPointeeType() << FoundVD;
3140           }
3141         }
3142       }
3143 
3144       if (!Decls.count(FoundVD))
3145         return;
3146 
3147       const bool IsReference = FoundVD->getType()->isReferenceType();
3148 
3149       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3150         // Special checking for initializer lists.
3151         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3152           return;
3153         }
3154       } else {
3155         // Prevent double warnings on use of unbounded references.
3156         if (CheckReferenceOnly && !IsReference)
3157           return;
3158       }
3159 
3160       unsigned diag = IsReference
3161           ? diag::warn_reference_field_is_uninit
3162           : diag::warn_field_is_uninit;
3163       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3164       if (Constructor)
3165         S.Diag(Constructor->getLocation(),
3166                diag::note_uninit_in_this_constructor)
3167           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3168 
3169     }
3170 
3171     void HandleValue(Expr *E, bool AddressOf) {
3172       E = E->IgnoreParens();
3173 
3174       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3175         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3176                          AddressOf /*AddressOf*/);
3177         return;
3178       }
3179 
3180       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3181         Visit(CO->getCond());
3182         HandleValue(CO->getTrueExpr(), AddressOf);
3183         HandleValue(CO->getFalseExpr(), AddressOf);
3184         return;
3185       }
3186 
3187       if (BinaryConditionalOperator *BCO =
3188               dyn_cast<BinaryConditionalOperator>(E)) {
3189         Visit(BCO->getCond());
3190         HandleValue(BCO->getFalseExpr(), AddressOf);
3191         return;
3192       }
3193 
3194       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3195         HandleValue(OVE->getSourceExpr(), AddressOf);
3196         return;
3197       }
3198 
3199       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3200         switch (BO->getOpcode()) {
3201         default:
3202           break;
3203         case(BO_PtrMemD):
3204         case(BO_PtrMemI):
3205           HandleValue(BO->getLHS(), AddressOf);
3206           Visit(BO->getRHS());
3207           return;
3208         case(BO_Comma):
3209           Visit(BO->getLHS());
3210           HandleValue(BO->getRHS(), AddressOf);
3211           return;
3212         }
3213       }
3214 
3215       Visit(E);
3216     }
3217 
3218     void CheckInitListExpr(InitListExpr *ILE) {
3219       InitFieldIndex.push_back(0);
3220       for (auto Child : ILE->children()) {
3221         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3222           CheckInitListExpr(SubList);
3223         } else {
3224           Visit(Child);
3225         }
3226         ++InitFieldIndex.back();
3227       }
3228       InitFieldIndex.pop_back();
3229     }
3230 
3231     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3232                           FieldDecl *Field, const Type *BaseClass) {
3233       // Remove Decls that may have been initialized in the previous
3234       // initializer.
3235       for (ValueDecl* VD : DeclsToRemove)
3236         Decls.erase(VD);
3237       DeclsToRemove.clear();
3238 
3239       Constructor = FieldConstructor;
3240       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3241 
3242       if (ILE && Field) {
3243         InitList = true;
3244         InitListFieldDecl = Field;
3245         InitFieldIndex.clear();
3246         CheckInitListExpr(ILE);
3247       } else {
3248         InitList = false;
3249         Visit(E);
3250       }
3251 
3252       if (Field)
3253         Decls.erase(Field);
3254       if (BaseClass)
3255         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3256     }
3257 
3258     void VisitMemberExpr(MemberExpr *ME) {
3259       // All uses of unbounded reference fields will warn.
3260       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3261     }
3262 
3263     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3264       if (E->getCastKind() == CK_LValueToRValue) {
3265         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3266         return;
3267       }
3268 
3269       Inherited::VisitImplicitCastExpr(E);
3270     }
3271 
3272     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3273       if (E->getConstructor()->isCopyConstructor()) {
3274         Expr *ArgExpr = E->getArg(0);
3275         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3276           if (ILE->getNumInits() == 1)
3277             ArgExpr = ILE->getInit(0);
3278         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3279           if (ICE->getCastKind() == CK_NoOp)
3280             ArgExpr = ICE->getSubExpr();
3281         HandleValue(ArgExpr, false /*AddressOf*/);
3282         return;
3283       }
3284       Inherited::VisitCXXConstructExpr(E);
3285     }
3286 
3287     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3288       Expr *Callee = E->getCallee();
3289       if (isa<MemberExpr>(Callee)) {
3290         HandleValue(Callee, false /*AddressOf*/);
3291         for (auto Arg : E->arguments())
3292           Visit(Arg);
3293         return;
3294       }
3295 
3296       Inherited::VisitCXXMemberCallExpr(E);
3297     }
3298 
3299     void VisitCallExpr(CallExpr *E) {
3300       // Treat std::move as a use.
3301       if (E->getNumArgs() == 1) {
3302         if (FunctionDecl *FD = E->getDirectCallee()) {
3303           if (FD->isInStdNamespace() && FD->getIdentifier() &&
3304               FD->getIdentifier()->isStr("move")) {
3305             HandleValue(E->getArg(0), false /*AddressOf*/);
3306             return;
3307           }
3308         }
3309       }
3310 
3311       Inherited::VisitCallExpr(E);
3312     }
3313 
3314     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3315       Expr *Callee = E->getCallee();
3316 
3317       if (isa<UnresolvedLookupExpr>(Callee))
3318         return Inherited::VisitCXXOperatorCallExpr(E);
3319 
3320       Visit(Callee);
3321       for (auto Arg : E->arguments())
3322         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3323     }
3324 
3325     void VisitBinaryOperator(BinaryOperator *E) {
3326       // If a field assignment is detected, remove the field from the
3327       // uninitiailized field set.
3328       if (E->getOpcode() == BO_Assign)
3329         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3330           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3331             if (!FD->getType()->isReferenceType())
3332               DeclsToRemove.push_back(FD);
3333 
3334       if (E->isCompoundAssignmentOp()) {
3335         HandleValue(E->getLHS(), false /*AddressOf*/);
3336         Visit(E->getRHS());
3337         return;
3338       }
3339 
3340       Inherited::VisitBinaryOperator(E);
3341     }
3342 
3343     void VisitUnaryOperator(UnaryOperator *E) {
3344       if (E->isIncrementDecrementOp()) {
3345         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3346         return;
3347       }
3348       if (E->getOpcode() == UO_AddrOf) {
3349         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3350           HandleValue(ME->getBase(), true /*AddressOf*/);
3351           return;
3352         }
3353       }
3354 
3355       Inherited::VisitUnaryOperator(E);
3356     }
3357   };
3358 
3359   // Diagnose value-uses of fields to initialize themselves, e.g.
3360   //   foo(foo)
3361   // where foo is not also a parameter to the constructor.
3362   // Also diagnose across field uninitialized use such as
3363   //   x(y), y(x)
3364   // TODO: implement -Wuninitialized and fold this into that framework.
3365   static void DiagnoseUninitializedFields(
3366       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3367 
3368     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3369                                            Constructor->getLocation())) {
3370       return;
3371     }
3372 
3373     if (Constructor->isInvalidDecl())
3374       return;
3375 
3376     const CXXRecordDecl *RD = Constructor->getParent();
3377 
3378     if (RD->getDescribedClassTemplate())
3379       return;
3380 
3381     // Holds fields that are uninitialized.
3382     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3383 
3384     // At the beginning, all fields are uninitialized.
3385     for (auto *I : RD->decls()) {
3386       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3387         UninitializedFields.insert(FD);
3388       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3389         UninitializedFields.insert(IFD->getAnonField());
3390       }
3391     }
3392 
3393     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3394     for (auto I : RD->bases())
3395       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3396 
3397     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3398       return;
3399 
3400     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3401                                                    UninitializedFields,
3402                                                    UninitializedBaseClasses);
3403 
3404     for (const auto *FieldInit : Constructor->inits()) {
3405       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3406         break;
3407 
3408       Expr *InitExpr = FieldInit->getInit();
3409       if (!InitExpr)
3410         continue;
3411 
3412       if (CXXDefaultInitExpr *Default =
3413               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3414         InitExpr = Default->getExpr();
3415         if (!InitExpr)
3416           continue;
3417         // In class initializers will point to the constructor.
3418         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3419                                               FieldInit->getAnyMember(),
3420                                               FieldInit->getBaseClass());
3421       } else {
3422         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3423                                               FieldInit->getAnyMember(),
3424                                               FieldInit->getBaseClass());
3425       }
3426     }
3427   }
3428 } // namespace
3429 
3430 /// \brief Enter a new C++ default initializer scope. After calling this, the
3431 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3432 /// parsing or instantiating the initializer failed.
3433 void Sema::ActOnStartCXXInClassMemberInitializer() {
3434   // Create a synthetic function scope to represent the call to the constructor
3435   // that notionally surrounds a use of this initializer.
3436   PushFunctionScope();
3437 }
3438 
3439 /// \brief This is invoked after parsing an in-class initializer for a
3440 /// non-static C++ class member, and after instantiating an in-class initializer
3441 /// in a class template. Such actions are deferred until the class is complete.
3442 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3443                                                   SourceLocation InitLoc,
3444                                                   Expr *InitExpr) {
3445   // Pop the notional constructor scope we created earlier.
3446   PopFunctionScopeInfo(nullptr, D);
3447 
3448   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3449   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3450          "must set init style when field is created");
3451 
3452   if (!InitExpr) {
3453     D->setInvalidDecl();
3454     if (FD)
3455       FD->removeInClassInitializer();
3456     return;
3457   }
3458 
3459   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3460     FD->setInvalidDecl();
3461     FD->removeInClassInitializer();
3462     return;
3463   }
3464 
3465   ExprResult Init = InitExpr;
3466   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3467     InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
3468     InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
3469         ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
3470         : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
3471     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3472     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3473     if (Init.isInvalid()) {
3474       FD->setInvalidDecl();
3475       return;
3476     }
3477   }
3478 
3479   // C++11 [class.base.init]p7:
3480   //   The initialization of each base and member constitutes a
3481   //   full-expression.
3482   Init = ActOnFinishFullExpr(Init.get(), InitLoc);
3483   if (Init.isInvalid()) {
3484     FD->setInvalidDecl();
3485     return;
3486   }
3487 
3488   InitExpr = Init.get();
3489 
3490   FD->setInClassInitializer(InitExpr);
3491 }
3492 
3493 /// \brief Find the direct and/or virtual base specifiers that
3494 /// correspond to the given base type, for use in base initialization
3495 /// within a constructor.
3496 static bool FindBaseInitializer(Sema &SemaRef,
3497                                 CXXRecordDecl *ClassDecl,
3498                                 QualType BaseType,
3499                                 const CXXBaseSpecifier *&DirectBaseSpec,
3500                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
3501   // First, check for a direct base class.
3502   DirectBaseSpec = nullptr;
3503   for (const auto &Base : ClassDecl->bases()) {
3504     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3505       // We found a direct base of this type. That's what we're
3506       // initializing.
3507       DirectBaseSpec = &Base;
3508       break;
3509     }
3510   }
3511 
3512   // Check for a virtual base class.
3513   // FIXME: We might be able to short-circuit this if we know in advance that
3514   // there are no virtual bases.
3515   VirtualBaseSpec = nullptr;
3516   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3517     // We haven't found a base yet; search the class hierarchy for a
3518     // virtual base class.
3519     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3520                        /*DetectVirtual=*/false);
3521     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3522                               SemaRef.Context.getTypeDeclType(ClassDecl),
3523                               BaseType, Paths)) {
3524       for (CXXBasePaths::paths_iterator Path = Paths.begin();
3525            Path != Paths.end(); ++Path) {
3526         if (Path->back().Base->isVirtual()) {
3527           VirtualBaseSpec = Path->back().Base;
3528           break;
3529         }
3530       }
3531     }
3532   }
3533 
3534   return DirectBaseSpec || VirtualBaseSpec;
3535 }
3536 
3537 /// \brief Handle a C++ member initializer using braced-init-list syntax.
3538 MemInitResult
3539 Sema::ActOnMemInitializer(Decl *ConstructorD,
3540                           Scope *S,
3541                           CXXScopeSpec &SS,
3542                           IdentifierInfo *MemberOrBase,
3543                           ParsedType TemplateTypeTy,
3544                           const DeclSpec &DS,
3545                           SourceLocation IdLoc,
3546                           Expr *InitList,
3547                           SourceLocation EllipsisLoc) {
3548   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3549                              DS, IdLoc, InitList,
3550                              EllipsisLoc);
3551 }
3552 
3553 /// \brief Handle a C++ member initializer using parentheses syntax.
3554 MemInitResult
3555 Sema::ActOnMemInitializer(Decl *ConstructorD,
3556                           Scope *S,
3557                           CXXScopeSpec &SS,
3558                           IdentifierInfo *MemberOrBase,
3559                           ParsedType TemplateTypeTy,
3560                           const DeclSpec &DS,
3561                           SourceLocation IdLoc,
3562                           SourceLocation LParenLoc,
3563                           ArrayRef<Expr *> Args,
3564                           SourceLocation RParenLoc,
3565                           SourceLocation EllipsisLoc) {
3566   Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
3567                                            Args, RParenLoc);
3568   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3569                              DS, IdLoc, List, EllipsisLoc);
3570 }
3571 
3572 namespace {
3573 
3574 // Callback to only accept typo corrections that can be a valid C++ member
3575 // intializer: either a non-static field member or a base class.
3576 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
3577 public:
3578   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3579       : ClassDecl(ClassDecl) {}
3580 
3581   bool ValidateCandidate(const TypoCorrection &candidate) override {
3582     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3583       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3584         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
3585       return isa<TypeDecl>(ND);
3586     }
3587     return false;
3588   }
3589 
3590 private:
3591   CXXRecordDecl *ClassDecl;
3592 };
3593 
3594 }
3595 
3596 /// \brief Handle a C++ member initializer.
3597 MemInitResult
3598 Sema::BuildMemInitializer(Decl *ConstructorD,
3599                           Scope *S,
3600                           CXXScopeSpec &SS,
3601                           IdentifierInfo *MemberOrBase,
3602                           ParsedType TemplateTypeTy,
3603                           const DeclSpec &DS,
3604                           SourceLocation IdLoc,
3605                           Expr *Init,
3606                           SourceLocation EllipsisLoc) {
3607   ExprResult Res = CorrectDelayedTyposInExpr(Init);
3608   if (!Res.isUsable())
3609     return true;
3610   Init = Res.get();
3611 
3612   if (!ConstructorD)
3613     return true;
3614 
3615   AdjustDeclIfTemplate(ConstructorD);
3616 
3617   CXXConstructorDecl *Constructor
3618     = dyn_cast<CXXConstructorDecl>(ConstructorD);
3619   if (!Constructor) {
3620     // The user wrote a constructor initializer on a function that is
3621     // not a C++ constructor. Ignore the error for now, because we may
3622     // have more member initializers coming; we'll diagnose it just
3623     // once in ActOnMemInitializers.
3624     return true;
3625   }
3626 
3627   CXXRecordDecl *ClassDecl = Constructor->getParent();
3628 
3629   // C++ [class.base.init]p2:
3630   //   Names in a mem-initializer-id are looked up in the scope of the
3631   //   constructor's class and, if not found in that scope, are looked
3632   //   up in the scope containing the constructor's definition.
3633   //   [Note: if the constructor's class contains a member with the
3634   //   same name as a direct or virtual base class of the class, a
3635   //   mem-initializer-id naming the member or base class and composed
3636   //   of a single identifier refers to the class member. A
3637   //   mem-initializer-id for the hidden base class may be specified
3638   //   using a qualified name. ]
3639   if (!SS.getScopeRep() && !TemplateTypeTy) {
3640     // Look for a member, first.
3641     DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
3642     if (!Result.empty()) {
3643       ValueDecl *Member;
3644       if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3645           (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
3646         if (EllipsisLoc.isValid())
3647           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
3648             << MemberOrBase
3649             << SourceRange(IdLoc, Init->getSourceRange().getEnd());
3650 
3651         return BuildMemberInitializer(Member, Init, IdLoc);
3652       }
3653     }
3654   }
3655   // It didn't name a member, so see if it names a class.
3656   QualType BaseType;
3657   TypeSourceInfo *TInfo = nullptr;
3658 
3659   if (TemplateTypeTy) {
3660     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
3661   } else if (DS.getTypeSpecType() == TST_decltype) {
3662     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
3663   } else {
3664     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3665     LookupParsedName(R, S, &SS);
3666 
3667     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3668     if (!TyD) {
3669       if (R.isAmbiguous()) return true;
3670 
3671       // We don't want access-control diagnostics here.
3672       R.suppressDiagnostics();
3673 
3674       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3675         bool NotUnknownSpecialization = false;
3676         DeclContext *DC = computeDeclContext(SS, false);
3677         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3678           NotUnknownSpecialization = !Record->hasAnyDependentBases();
3679 
3680         if (!NotUnknownSpecialization) {
3681           // When the scope specifier can refer to a member of an unknown
3682           // specialization, we take it as a type name.
3683           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3684                                        SS.getWithLocInContext(Context),
3685                                        *MemberOrBase, IdLoc);
3686           if (BaseType.isNull())
3687             return true;
3688 
3689           R.clear();
3690           R.setLookupName(MemberOrBase);
3691         }
3692       }
3693 
3694       // If no results were found, try to correct typos.
3695       TypoCorrection Corr;
3696       if (R.empty() && BaseType.isNull() &&
3697           (Corr = CorrectTypo(
3698                R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3699                llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
3700                CTK_ErrorRecovery, ClassDecl))) {
3701         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
3702           // We have found a non-static data member with a similar
3703           // name to what was typed; complain and initialize that
3704           // member.
3705           diagnoseTypo(Corr,
3706                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
3707                          << MemberOrBase << true);
3708           return BuildMemberInitializer(Member, Init, IdLoc);
3709         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
3710           const CXXBaseSpecifier *DirectBaseSpec;
3711           const CXXBaseSpecifier *VirtualBaseSpec;
3712           if (FindBaseInitializer(*this, ClassDecl,
3713                                   Context.getTypeDeclType(Type),
3714                                   DirectBaseSpec, VirtualBaseSpec)) {
3715             // We have found a direct or virtual base class with a
3716             // similar name to what was typed; complain and initialize
3717             // that base class.
3718             diagnoseTypo(Corr,
3719                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
3720                            << MemberOrBase << false,
3721                          PDiag() /*Suppress note, we provide our own.*/);
3722 
3723             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3724                                                               : VirtualBaseSpec;
3725             Diag(BaseSpec->getLocStart(),
3726                  diag::note_base_class_specified_here)
3727               << BaseSpec->getType()
3728               << BaseSpec->getSourceRange();
3729 
3730             TyD = Type;
3731           }
3732         }
3733       }
3734 
3735       if (!TyD && BaseType.isNull()) {
3736         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
3737           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
3738         return true;
3739       }
3740     }
3741 
3742     if (BaseType.isNull()) {
3743       BaseType = Context.getTypeDeclType(TyD);
3744       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
3745       if (SS.isSet()) {
3746         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3747                                              BaseType);
3748         TInfo = Context.CreateTypeSourceInfo(BaseType);
3749         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3750         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3751         TL.setElaboratedKeywordLoc(SourceLocation());
3752         TL.setQualifierLoc(SS.getWithLocInContext(Context));
3753       }
3754     }
3755   }
3756 
3757   if (!TInfo)
3758     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
3759 
3760   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
3761 }
3762 
3763 /// Checks a member initializer expression for cases where reference (or
3764 /// pointer) members are bound to by-value parameters (or their addresses).
3765 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3766                                                Expr *Init,
3767                                                SourceLocation IdLoc) {
3768   QualType MemberTy = Member->getType();
3769 
3770   // We only handle pointers and references currently.
3771   // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3772   if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3773     return;
3774 
3775   const bool IsPointer = MemberTy->isPointerType();
3776   if (IsPointer) {
3777     if (const UnaryOperator *Op
3778           = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3779       // The only case we're worried about with pointers requires taking the
3780       // address.
3781       if (Op->getOpcode() != UO_AddrOf)
3782         return;
3783 
3784       Init = Op->getSubExpr();
3785     } else {
3786       // We only handle address-of expression initializers for pointers.
3787       return;
3788     }
3789   }
3790 
3791   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
3792     // We only warn when referring to a non-reference parameter declaration.
3793     const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3794     if (!Parameter || Parameter->getType()->isReferenceType())
3795       return;
3796 
3797     S.Diag(Init->getExprLoc(),
3798            IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3799                      : diag::warn_bind_ref_member_to_parameter)
3800       << Member << Parameter << Init->getSourceRange();
3801   } else {
3802     // Other initializers are fine.
3803     return;
3804   }
3805 
3806   S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3807     << (unsigned)IsPointer;
3808 }
3809 
3810 MemInitResult
3811 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3812                              SourceLocation IdLoc) {
3813   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3814   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3815   assert((DirectMember || IndirectMember) &&
3816          "Member must be a FieldDecl or IndirectFieldDecl");
3817 
3818   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3819     return true;
3820 
3821   if (Member->isInvalidDecl())
3822     return true;
3823 
3824   MultiExprArg Args;
3825   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3826     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3827   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3828     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
3829   } else {
3830     // Template instantiation doesn't reconstruct ParenListExprs for us.
3831     Args = Init;
3832   }
3833 
3834   SourceRange InitRange = Init->getSourceRange();
3835 
3836   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
3837     // Can't check initialization for a member of dependent type or when
3838     // any of the arguments are type-dependent expressions.
3839     DiscardCleanupsInEvaluationContext();
3840   } else {
3841     bool InitList = false;
3842     if (isa<InitListExpr>(Init)) {
3843       InitList = true;
3844       Args = Init;
3845     }
3846 
3847     // Initialize the member.
3848     InitializedEntity MemberEntity =
3849       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3850                    : InitializedEntity::InitializeMember(IndirectMember,
3851                                                          nullptr);
3852     InitializationKind Kind =
3853       InitList ? InitializationKind::CreateDirectList(IdLoc)
3854                : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3855                                                   InitRange.getEnd());
3856 
3857     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
3858     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3859                                             nullptr);
3860     if (MemberInit.isInvalid())
3861       return true;
3862 
3863     CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3864 
3865     // C++11 [class.base.init]p7:
3866     //   The initialization of each base and member constitutes a
3867     //   full-expression.
3868     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
3869     if (MemberInit.isInvalid())
3870       return true;
3871 
3872     Init = MemberInit.get();
3873   }
3874 
3875   if (DirectMember) {
3876     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3877                                             InitRange.getBegin(), Init,
3878                                             InitRange.getEnd());
3879   } else {
3880     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3881                                             InitRange.getBegin(), Init,
3882                                             InitRange.getEnd());
3883   }
3884 }
3885 
3886 MemInitResult
3887 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
3888                                  CXXRecordDecl *ClassDecl) {
3889   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
3890   if (!LangOpts.CPlusPlus11)
3891     return Diag(NameLoc, diag::err_delegating_ctor)
3892       << TInfo->getTypeLoc().getLocalSourceRange();
3893   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
3894 
3895   bool InitList = true;
3896   MultiExprArg Args = Init;
3897   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3898     InitList = false;
3899     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3900   }
3901 
3902   SourceRange InitRange = Init->getSourceRange();
3903   // Initialize the object.
3904   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3905                                      QualType(ClassDecl->getTypeForDecl(), 0));
3906   InitializationKind Kind =
3907     InitList ? InitializationKind::CreateDirectList(NameLoc)
3908              : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3909                                                 InitRange.getEnd());
3910   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
3911   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
3912                                               Args, nullptr);
3913   if (DelegationInit.isInvalid())
3914     return true;
3915 
3916   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3917          "Delegating constructor with no target?");
3918 
3919   // C++11 [class.base.init]p7:
3920   //   The initialization of each base and member constitutes a
3921   //   full-expression.
3922   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
3923                                        InitRange.getBegin());
3924   if (DelegationInit.isInvalid())
3925     return true;
3926 
3927   // If we are in a dependent context, template instantiation will
3928   // perform this type-checking again. Just save the arguments that we
3929   // received in a ParenListExpr.
3930   // FIXME: This isn't quite ideal, since our ASTs don't capture all
3931   // of the information that we have about the base
3932   // initializer. However, deconstructing the ASTs is a dicey process,
3933   // and this approach is far more likely to get the corner cases right.
3934   if (CurContext->isDependentContext())
3935     DelegationInit = Init;
3936 
3937   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
3938                                           DelegationInit.getAs<Expr>(),
3939                                           InitRange.getEnd());
3940 }
3941 
3942 MemInitResult
3943 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
3944                            Expr *Init, CXXRecordDecl *ClassDecl,
3945                            SourceLocation EllipsisLoc) {
3946   SourceLocation BaseLoc
3947     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
3948 
3949   if (!BaseType->isDependentType() && !BaseType->isRecordType())
3950     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
3951              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3952 
3953   // C++ [class.base.init]p2:
3954   //   [...] Unless the mem-initializer-id names a nonstatic data
3955   //   member of the constructor's class or a direct or virtual base
3956   //   of that class, the mem-initializer is ill-formed. A
3957   //   mem-initializer-list can initialize a base class using any
3958   //   name that denotes that base class type.
3959   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
3960 
3961   SourceRange InitRange = Init->getSourceRange();
3962   if (EllipsisLoc.isValid()) {
3963     // This is a pack expansion.
3964     if (!BaseType->containsUnexpandedParameterPack())  {
3965       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
3966         << SourceRange(BaseLoc, InitRange.getEnd());
3967 
3968       EllipsisLoc = SourceLocation();
3969     }
3970   } else {
3971     // Check for any unexpanded parameter packs.
3972     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
3973       return true;
3974 
3975     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3976       return true;
3977   }
3978 
3979   // Check for direct and virtual base classes.
3980   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
3981   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
3982   if (!Dependent) {
3983     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
3984                                        BaseType))
3985       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
3986 
3987     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
3988                         VirtualBaseSpec);
3989 
3990     // C++ [base.class.init]p2:
3991     // Unless the mem-initializer-id names a nonstatic data member of the
3992     // constructor's class or a direct or virtual base of that class, the
3993     // mem-initializer is ill-formed.
3994     if (!DirectBaseSpec && !VirtualBaseSpec) {
3995       // If the class has any dependent bases, then it's possible that
3996       // one of those types will resolve to the same type as
3997       // BaseType. Therefore, just treat this as a dependent base
3998       // class initialization.  FIXME: Should we try to check the
3999       // initialization anyway? It seems odd.
4000       if (ClassDecl->hasAnyDependentBases())
4001         Dependent = true;
4002       else
4003         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4004           << BaseType << Context.getTypeDeclType(ClassDecl)
4005           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4006     }
4007   }
4008 
4009   if (Dependent) {
4010     DiscardCleanupsInEvaluationContext();
4011 
4012     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4013                                             /*IsVirtual=*/false,
4014                                             InitRange.getBegin(), Init,
4015                                             InitRange.getEnd(), EllipsisLoc);
4016   }
4017 
4018   // C++ [base.class.init]p2:
4019   //   If a mem-initializer-id is ambiguous because it designates both
4020   //   a direct non-virtual base class and an inherited virtual base
4021   //   class, the mem-initializer is ill-formed.
4022   if (DirectBaseSpec && VirtualBaseSpec)
4023     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4024       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4025 
4026   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4027   if (!BaseSpec)
4028     BaseSpec = VirtualBaseSpec;
4029 
4030   // Initialize the base.
4031   bool InitList = true;
4032   MultiExprArg Args = Init;
4033   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4034     InitList = false;
4035     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4036   }
4037 
4038   InitializedEntity BaseEntity =
4039     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4040   InitializationKind Kind =
4041     InitList ? InitializationKind::CreateDirectList(BaseLoc)
4042              : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4043                                                 InitRange.getEnd());
4044   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4045   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4046   if (BaseInit.isInvalid())
4047     return true;
4048 
4049   // C++11 [class.base.init]p7:
4050   //   The initialization of each base and member constitutes a
4051   //   full-expression.
4052   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
4053   if (BaseInit.isInvalid())
4054     return true;
4055 
4056   // If we are in a dependent context, template instantiation will
4057   // perform this type-checking again. Just save the arguments that we
4058   // received in a ParenListExpr.
4059   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4060   // of the information that we have about the base
4061   // initializer. However, deconstructing the ASTs is a dicey process,
4062   // and this approach is far more likely to get the corner cases right.
4063   if (CurContext->isDependentContext())
4064     BaseInit = Init;
4065 
4066   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4067                                           BaseSpec->isVirtual(),
4068                                           InitRange.getBegin(),
4069                                           BaseInit.getAs<Expr>(),
4070                                           InitRange.getEnd(), EllipsisLoc);
4071 }
4072 
4073 // Create a static_cast\<T&&>(expr).
4074 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4075   if (T.isNull()) T = E->getType();
4076   QualType TargetType = SemaRef.BuildReferenceType(
4077       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4078   SourceLocation ExprLoc = E->getLocStart();
4079   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4080       TargetType, ExprLoc);
4081 
4082   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4083                                    SourceRange(ExprLoc, ExprLoc),
4084                                    E->getSourceRange()).get();
4085 }
4086 
4087 /// ImplicitInitializerKind - How an implicit base or member initializer should
4088 /// initialize its base or member.
4089 enum ImplicitInitializerKind {
4090   IIK_Default,
4091   IIK_Copy,
4092   IIK_Move,
4093   IIK_Inherit
4094 };
4095 
4096 static bool
4097 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4098                              ImplicitInitializerKind ImplicitInitKind,
4099                              CXXBaseSpecifier *BaseSpec,
4100                              bool IsInheritedVirtualBase,
4101                              CXXCtorInitializer *&CXXBaseInit) {
4102   InitializedEntity InitEntity
4103     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4104                                         IsInheritedVirtualBase);
4105 
4106   ExprResult BaseInit;
4107 
4108   switch (ImplicitInitKind) {
4109   case IIK_Inherit:
4110   case IIK_Default: {
4111     InitializationKind InitKind
4112       = InitializationKind::CreateDefault(Constructor->getLocation());
4113     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4114     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4115     break;
4116   }
4117 
4118   case IIK_Move:
4119   case IIK_Copy: {
4120     bool Moving = ImplicitInitKind == IIK_Move;
4121     ParmVarDecl *Param = Constructor->getParamDecl(0);
4122     QualType ParamType = Param->getType().getNonReferenceType();
4123 
4124     Expr *CopyCtorArg =
4125       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4126                           SourceLocation(), Param, false,
4127                           Constructor->getLocation(), ParamType,
4128                           VK_LValue, nullptr);
4129 
4130     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4131 
4132     // Cast to the base class to avoid ambiguities.
4133     QualType ArgTy =
4134       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4135                                        ParamType.getQualifiers());
4136 
4137     if (Moving) {
4138       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4139     }
4140 
4141     CXXCastPath BasePath;
4142     BasePath.push_back(BaseSpec);
4143     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4144                                             CK_UncheckedDerivedToBase,
4145                                             Moving ? VK_XValue : VK_LValue,
4146                                             &BasePath).get();
4147 
4148     InitializationKind InitKind
4149       = InitializationKind::CreateDirect(Constructor->getLocation(),
4150                                          SourceLocation(), SourceLocation());
4151     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4152     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4153     break;
4154   }
4155   }
4156 
4157   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4158   if (BaseInit.isInvalid())
4159     return true;
4160 
4161   CXXBaseInit =
4162     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4163                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4164                                                         SourceLocation()),
4165                                              BaseSpec->isVirtual(),
4166                                              SourceLocation(),
4167                                              BaseInit.getAs<Expr>(),
4168                                              SourceLocation(),
4169                                              SourceLocation());
4170 
4171   return false;
4172 }
4173 
4174 static bool RefersToRValueRef(Expr *MemRef) {
4175   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4176   return Referenced->getType()->isRValueReferenceType();
4177 }
4178 
4179 static bool
4180 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4181                                ImplicitInitializerKind ImplicitInitKind,
4182                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4183                                CXXCtorInitializer *&CXXMemberInit) {
4184   if (Field->isInvalidDecl())
4185     return true;
4186 
4187   SourceLocation Loc = Constructor->getLocation();
4188 
4189   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4190     bool Moving = ImplicitInitKind == IIK_Move;
4191     ParmVarDecl *Param = Constructor->getParamDecl(0);
4192     QualType ParamType = Param->getType().getNonReferenceType();
4193 
4194     // Suppress copying zero-width bitfields.
4195     if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
4196       return false;
4197 
4198     Expr *MemberExprBase =
4199       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4200                           SourceLocation(), Param, false,
4201                           Loc, ParamType, VK_LValue, nullptr);
4202 
4203     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4204 
4205     if (Moving) {
4206       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4207     }
4208 
4209     // Build a reference to this field within the parameter.
4210     CXXScopeSpec SS;
4211     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4212                               Sema::LookupMemberName);
4213     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4214                                   : cast<ValueDecl>(Field), AS_public);
4215     MemberLookup.resolveKind();
4216     ExprResult CtorArg
4217       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4218                                          ParamType, Loc,
4219                                          /*IsArrow=*/false,
4220                                          SS,
4221                                          /*TemplateKWLoc=*/SourceLocation(),
4222                                          /*FirstQualifierInScope=*/nullptr,
4223                                          MemberLookup,
4224                                          /*TemplateArgs=*/nullptr,
4225                                          /*S*/nullptr);
4226     if (CtorArg.isInvalid())
4227       return true;
4228 
4229     // C++11 [class.copy]p15:
4230     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4231     //     with static_cast<T&&>(x.m);
4232     if (RefersToRValueRef(CtorArg.get())) {
4233       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4234     }
4235 
4236     // When the field we are copying is an array, create index variables for
4237     // each dimension of the array. We use these index variables to subscript
4238     // the source array, and other clients (e.g., CodeGen) will perform the
4239     // necessary iteration with these index variables.
4240     SmallVector<VarDecl *, 4> IndexVariables;
4241     QualType BaseType = Field->getType();
4242     QualType SizeType = SemaRef.Context.getSizeType();
4243     bool InitializingArray = false;
4244     while (const ConstantArrayType *Array
4245                           = SemaRef.Context.getAsConstantArrayType(BaseType)) {
4246       InitializingArray = true;
4247       // Create the iteration variable for this array index.
4248       IdentifierInfo *IterationVarName = nullptr;
4249       {
4250         SmallString<8> Str;
4251         llvm::raw_svector_ostream OS(Str);
4252         OS << "__i" << IndexVariables.size();
4253         IterationVarName = &SemaRef.Context.Idents.get(OS.str());
4254       }
4255       VarDecl *IterationVar
4256         = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
4257                           IterationVarName, SizeType,
4258                         SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
4259                           SC_None);
4260       IndexVariables.push_back(IterationVar);
4261 
4262       // Create a reference to the iteration variable.
4263       ExprResult IterationVarRef
4264         = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
4265       assert(!IterationVarRef.isInvalid() &&
4266              "Reference to invented variable cannot fail!");
4267       IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
4268       assert(!IterationVarRef.isInvalid() &&
4269              "Conversion of invented variable cannot fail!");
4270 
4271       // Subscript the array with this iteration variable.
4272       CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
4273                                                         IterationVarRef.get(),
4274                                                         Loc);
4275       if (CtorArg.isInvalid())
4276         return true;
4277 
4278       BaseType = Array->getElementType();
4279     }
4280 
4281     // The array subscript expression is an lvalue, which is wrong for moving.
4282     if (Moving && InitializingArray)
4283       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4284 
4285     // Construct the entity that we will be initializing. For an array, this
4286     // will be first element in the array, which may require several levels
4287     // of array-subscript entities.
4288     SmallVector<InitializedEntity, 4> Entities;
4289     Entities.reserve(1 + IndexVariables.size());
4290     if (Indirect)
4291       Entities.push_back(InitializedEntity::InitializeMember(Indirect));
4292     else
4293       Entities.push_back(InitializedEntity::InitializeMember(Field));
4294     for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
4295       Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
4296                                                               0,
4297                                                               Entities.back()));
4298 
4299     // Direct-initialize to use the copy constructor.
4300     InitializationKind InitKind =
4301       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4302 
4303     Expr *CtorArgE = CtorArg.getAs<Expr>();
4304     InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
4305                                    CtorArgE);
4306 
4307     ExprResult MemberInit
4308       = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
4309                         MultiExprArg(&CtorArgE, 1));
4310     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4311     if (MemberInit.isInvalid())
4312       return true;
4313 
4314     if (Indirect) {
4315       assert(IndexVariables.size() == 0 &&
4316              "Indirect field improperly initialized");
4317       CXXMemberInit
4318         = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
4319                                                    Loc, Loc,
4320                                                    MemberInit.getAs<Expr>(),
4321                                                    Loc);
4322     } else
4323       CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
4324                                                  Loc, MemberInit.getAs<Expr>(),
4325                                                  Loc,
4326                                                  IndexVariables.data(),
4327                                                  IndexVariables.size());
4328     return false;
4329   }
4330 
4331   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4332          "Unhandled implicit init kind!");
4333 
4334   QualType FieldBaseElementType =
4335     SemaRef.Context.getBaseElementType(Field->getType());
4336 
4337   if (FieldBaseElementType->isRecordType()) {
4338     InitializedEntity InitEntity
4339       = Indirect? InitializedEntity::InitializeMember(Indirect)
4340                 : InitializedEntity::InitializeMember(Field);
4341     InitializationKind InitKind =
4342       InitializationKind::CreateDefault(Loc);
4343 
4344     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4345     ExprResult MemberInit =
4346       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4347 
4348     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4349     if (MemberInit.isInvalid())
4350       return true;
4351 
4352     if (Indirect)
4353       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4354                                                                Indirect, Loc,
4355                                                                Loc,
4356                                                                MemberInit.get(),
4357                                                                Loc);
4358     else
4359       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4360                                                                Field, Loc, Loc,
4361                                                                MemberInit.get(),
4362                                                                Loc);
4363     return false;
4364   }
4365 
4366   if (!Field->getParent()->isUnion()) {
4367     if (FieldBaseElementType->isReferenceType()) {
4368       SemaRef.Diag(Constructor->getLocation(),
4369                    diag::err_uninitialized_member_in_ctor)
4370       << (int)Constructor->isImplicit()
4371       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4372       << 0 << Field->getDeclName();
4373       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4374       return true;
4375     }
4376 
4377     if (FieldBaseElementType.isConstQualified()) {
4378       SemaRef.Diag(Constructor->getLocation(),
4379                    diag::err_uninitialized_member_in_ctor)
4380       << (int)Constructor->isImplicit()
4381       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4382       << 1 << Field->getDeclName();
4383       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4384       return true;
4385     }
4386   }
4387 
4388   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
4389       FieldBaseElementType->isObjCRetainableType() &&
4390       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
4391       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
4392     // ARC:
4393     //   Default-initialize Objective-C pointers to NULL.
4394     CXXMemberInit
4395       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4396                                                  Loc, Loc,
4397                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4398                                                  Loc);
4399     return false;
4400   }
4401 
4402   // Nothing to initialize.
4403   CXXMemberInit = nullptr;
4404   return false;
4405 }
4406 
4407 namespace {
4408 struct BaseAndFieldInfo {
4409   Sema &S;
4410   CXXConstructorDecl *Ctor;
4411   bool AnyErrorsInInits;
4412   ImplicitInitializerKind IIK;
4413   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4414   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4415   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4416 
4417   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4418     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4419     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4420     if (Ctor->getInheritedConstructor())
4421       IIK = IIK_Inherit;
4422     else if (Generated && Ctor->isCopyConstructor())
4423       IIK = IIK_Copy;
4424     else if (Generated && Ctor->isMoveConstructor())
4425       IIK = IIK_Move;
4426     else
4427       IIK = IIK_Default;
4428   }
4429 
4430   bool isImplicitCopyOrMove() const {
4431     switch (IIK) {
4432     case IIK_Copy:
4433     case IIK_Move:
4434       return true;
4435 
4436     case IIK_Default:
4437     case IIK_Inherit:
4438       return false;
4439     }
4440 
4441     llvm_unreachable("Invalid ImplicitInitializerKind!");
4442   }
4443 
4444   bool addFieldInitializer(CXXCtorInitializer *Init) {
4445     AllToInit.push_back(Init);
4446 
4447     // Check whether this initializer makes the field "used".
4448     if (Init->getInit()->HasSideEffects(S.Context))
4449       S.UnusedPrivateFields.remove(Init->getAnyMember());
4450 
4451     return false;
4452   }
4453 
4454   bool isInactiveUnionMember(FieldDecl *Field) {
4455     RecordDecl *Record = Field->getParent();
4456     if (!Record->isUnion())
4457       return false;
4458 
4459     if (FieldDecl *Active =
4460             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4461       return Active != Field->getCanonicalDecl();
4462 
4463     // In an implicit copy or move constructor, ignore any in-class initializer.
4464     if (isImplicitCopyOrMove())
4465       return true;
4466 
4467     // If there's no explicit initialization, the field is active only if it
4468     // has an in-class initializer...
4469     if (Field->hasInClassInitializer())
4470       return false;
4471     // ... or it's an anonymous struct or union whose class has an in-class
4472     // initializer.
4473     if (!Field->isAnonymousStructOrUnion())
4474       return true;
4475     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4476     return !FieldRD->hasInClassInitializer();
4477   }
4478 
4479   /// \brief Determine whether the given field is, or is within, a union member
4480   /// that is inactive (because there was an initializer given for a different
4481   /// member of the union, or because the union was not initialized at all).
4482   bool isWithinInactiveUnionMember(FieldDecl *Field,
4483                                    IndirectFieldDecl *Indirect) {
4484     if (!Indirect)
4485       return isInactiveUnionMember(Field);
4486 
4487     for (auto *C : Indirect->chain()) {
4488       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4489       if (Field && isInactiveUnionMember(Field))
4490         return true;
4491     }
4492     return false;
4493   }
4494 };
4495 }
4496 
4497 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
4498 /// array type.
4499 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4500   if (T->isIncompleteArrayType())
4501     return true;
4502 
4503   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4504     if (!ArrayT->getSize())
4505       return true;
4506 
4507     T = ArrayT->getElementType();
4508   }
4509 
4510   return false;
4511 }
4512 
4513 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4514                                     FieldDecl *Field,
4515                                     IndirectFieldDecl *Indirect = nullptr) {
4516   if (Field->isInvalidDecl())
4517     return false;
4518 
4519   // Overwhelmingly common case: we have a direct initializer for this field.
4520   if (CXXCtorInitializer *Init =
4521           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4522     return Info.addFieldInitializer(Init);
4523 
4524   // C++11 [class.base.init]p8:
4525   //   if the entity is a non-static data member that has a
4526   //   brace-or-equal-initializer and either
4527   //   -- the constructor's class is a union and no other variant member of that
4528   //      union is designated by a mem-initializer-id or
4529   //   -- the constructor's class is not a union, and, if the entity is a member
4530   //      of an anonymous union, no other member of that union is designated by
4531   //      a mem-initializer-id,
4532   //   the entity is initialized as specified in [dcl.init].
4533   //
4534   // We also apply the same rules to handle anonymous structs within anonymous
4535   // unions.
4536   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4537     return false;
4538 
4539   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4540     ExprResult DIE =
4541         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4542     if (DIE.isInvalid())
4543       return true;
4544     CXXCtorInitializer *Init;
4545     if (Indirect)
4546       Init = new (SemaRef.Context)
4547           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4548                              SourceLocation(), DIE.get(), SourceLocation());
4549     else
4550       Init = new (SemaRef.Context)
4551           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4552                              SourceLocation(), DIE.get(), SourceLocation());
4553     return Info.addFieldInitializer(Init);
4554   }
4555 
4556   // Don't initialize incomplete or zero-length arrays.
4557   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4558     return false;
4559 
4560   // Don't try to build an implicit initializer if there were semantic
4561   // errors in any of the initializers (and therefore we might be
4562   // missing some that the user actually wrote).
4563   if (Info.AnyErrorsInInits)
4564     return false;
4565 
4566   CXXCtorInitializer *Init = nullptr;
4567   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4568                                      Indirect, Init))
4569     return true;
4570 
4571   if (!Init)
4572     return false;
4573 
4574   return Info.addFieldInitializer(Init);
4575 }
4576 
4577 bool
4578 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4579                                CXXCtorInitializer *Initializer) {
4580   assert(Initializer->isDelegatingInitializer());
4581   Constructor->setNumCtorInitializers(1);
4582   CXXCtorInitializer **initializer =
4583     new (Context) CXXCtorInitializer*[1];
4584   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4585   Constructor->setCtorInitializers(initializer);
4586 
4587   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4588     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4589     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4590   }
4591 
4592   DelegatingCtorDecls.push_back(Constructor);
4593 
4594   DiagnoseUninitializedFields(*this, Constructor);
4595 
4596   return false;
4597 }
4598 
4599 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4600                                ArrayRef<CXXCtorInitializer *> Initializers) {
4601   if (Constructor->isDependentContext()) {
4602     // Just store the initializers as written, they will be checked during
4603     // instantiation.
4604     if (!Initializers.empty()) {
4605       Constructor->setNumCtorInitializers(Initializers.size());
4606       CXXCtorInitializer **baseOrMemberInitializers =
4607         new (Context) CXXCtorInitializer*[Initializers.size()];
4608       memcpy(baseOrMemberInitializers, Initializers.data(),
4609              Initializers.size() * sizeof(CXXCtorInitializer*));
4610       Constructor->setCtorInitializers(baseOrMemberInitializers);
4611     }
4612 
4613     // Let template instantiation know whether we had errors.
4614     if (AnyErrors)
4615       Constructor->setInvalidDecl();
4616 
4617     return false;
4618   }
4619 
4620   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4621 
4622   // We need to build the initializer AST according to order of construction
4623   // and not what user specified in the Initializers list.
4624   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4625   if (!ClassDecl)
4626     return true;
4627 
4628   bool HadError = false;
4629 
4630   for (unsigned i = 0; i < Initializers.size(); i++) {
4631     CXXCtorInitializer *Member = Initializers[i];
4632 
4633     if (Member->isBaseInitializer())
4634       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4635     else {
4636       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4637 
4638       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4639         for (auto *C : F->chain()) {
4640           FieldDecl *FD = dyn_cast<FieldDecl>(C);
4641           if (FD && FD->getParent()->isUnion())
4642             Info.ActiveUnionMember.insert(std::make_pair(
4643                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4644         }
4645       } else if (FieldDecl *FD = Member->getMember()) {
4646         if (FD->getParent()->isUnion())
4647           Info.ActiveUnionMember.insert(std::make_pair(
4648               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4649       }
4650     }
4651   }
4652 
4653   // Keep track of the direct virtual bases.
4654   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4655   for (auto &I : ClassDecl->bases()) {
4656     if (I.isVirtual())
4657       DirectVBases.insert(&I);
4658   }
4659 
4660   // Push virtual bases before others.
4661   for (auto &VBase : ClassDecl->vbases()) {
4662     if (CXXCtorInitializer *Value
4663         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
4664       // [class.base.init]p7, per DR257:
4665       //   A mem-initializer where the mem-initializer-id names a virtual base
4666       //   class is ignored during execution of a constructor of any class that
4667       //   is not the most derived class.
4668       if (ClassDecl->isAbstract()) {
4669         // FIXME: Provide a fixit to remove the base specifier. This requires
4670         // tracking the location of the associated comma for a base specifier.
4671         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
4672           << VBase.getType() << ClassDecl;
4673         DiagnoseAbstractType(ClassDecl);
4674       }
4675 
4676       Info.AllToInit.push_back(Value);
4677     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4678       // [class.base.init]p8, per DR257:
4679       //   If a given [...] base class is not named by a mem-initializer-id
4680       //   [...] and the entity is not a virtual base class of an abstract
4681       //   class, then [...] the entity is default-initialized.
4682       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
4683       CXXCtorInitializer *CXXBaseInit;
4684       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4685                                        &VBase, IsInheritedVirtualBase,
4686                                        CXXBaseInit)) {
4687         HadError = true;
4688         continue;
4689       }
4690 
4691       Info.AllToInit.push_back(CXXBaseInit);
4692     }
4693   }
4694 
4695   // Non-virtual bases.
4696   for (auto &Base : ClassDecl->bases()) {
4697     // Virtuals are in the virtual base list and already constructed.
4698     if (Base.isVirtual())
4699       continue;
4700 
4701     if (CXXCtorInitializer *Value
4702           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
4703       Info.AllToInit.push_back(Value);
4704     } else if (!AnyErrors) {
4705       CXXCtorInitializer *CXXBaseInit;
4706       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4707                                        &Base, /*IsInheritedVirtualBase=*/false,
4708                                        CXXBaseInit)) {
4709         HadError = true;
4710         continue;
4711       }
4712 
4713       Info.AllToInit.push_back(CXXBaseInit);
4714     }
4715   }
4716 
4717   // Fields.
4718   for (auto *Mem : ClassDecl->decls()) {
4719     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
4720       // C++ [class.bit]p2:
4721       //   A declaration for a bit-field that omits the identifier declares an
4722       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
4723       //   initialized.
4724       if (F->isUnnamedBitfield())
4725         continue;
4726 
4727       // If we're not generating the implicit copy/move constructor, then we'll
4728       // handle anonymous struct/union fields based on their individual
4729       // indirect fields.
4730       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4731         continue;
4732 
4733       if (CollectFieldInitializer(*this, Info, F))
4734         HadError = true;
4735       continue;
4736     }
4737 
4738     // Beyond this point, we only consider default initialization.
4739     if (Info.isImplicitCopyOrMove())
4740       continue;
4741 
4742     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4743       if (F->getType()->isIncompleteArrayType()) {
4744         assert(ClassDecl->hasFlexibleArrayMember() &&
4745                "Incomplete array type is not valid");
4746         continue;
4747       }
4748 
4749       // Initialize each field of an anonymous struct individually.
4750       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4751         HadError = true;
4752 
4753       continue;
4754     }
4755   }
4756 
4757   unsigned NumInitializers = Info.AllToInit.size();
4758   if (NumInitializers > 0) {
4759     Constructor->setNumCtorInitializers(NumInitializers);
4760     CXXCtorInitializer **baseOrMemberInitializers =
4761       new (Context) CXXCtorInitializer*[NumInitializers];
4762     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4763            NumInitializers * sizeof(CXXCtorInitializer*));
4764     Constructor->setCtorInitializers(baseOrMemberInitializers);
4765 
4766     // Constructors implicitly reference the base and member
4767     // destructors.
4768     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4769                                            Constructor->getParent());
4770   }
4771 
4772   return HadError;
4773 }
4774 
4775 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4776   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4777     const RecordDecl *RD = RT->getDecl();
4778     if (RD->isAnonymousStructOrUnion()) {
4779       for (auto *Field : RD->fields())
4780         PopulateKeysForFields(Field, IdealInits);
4781       return;
4782     }
4783   }
4784   IdealInits.push_back(Field->getCanonicalDecl());
4785 }
4786 
4787 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4788   return Context.getCanonicalType(BaseType).getTypePtr();
4789 }
4790 
4791 static const void *GetKeyForMember(ASTContext &Context,
4792                                    CXXCtorInitializer *Member) {
4793   if (!Member->isAnyMemberInitializer())
4794     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4795 
4796   return Member->getAnyMember()->getCanonicalDecl();
4797 }
4798 
4799 static void DiagnoseBaseOrMemInitializerOrder(
4800     Sema &SemaRef, const CXXConstructorDecl *Constructor,
4801     ArrayRef<CXXCtorInitializer *> Inits) {
4802   if (Constructor->getDeclContext()->isDependentContext())
4803     return;
4804 
4805   // Don't check initializers order unless the warning is enabled at the
4806   // location of at least one initializer.
4807   bool ShouldCheckOrder = false;
4808   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4809     CXXCtorInitializer *Init = Inits[InitIndex];
4810     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4811                                  Init->getSourceLocation())) {
4812       ShouldCheckOrder = true;
4813       break;
4814     }
4815   }
4816   if (!ShouldCheckOrder)
4817     return;
4818 
4819   // Build the list of bases and members in the order that they'll
4820   // actually be initialized.  The explicit initializers should be in
4821   // this same order but may be missing things.
4822   SmallVector<const void*, 32> IdealInitKeys;
4823 
4824   const CXXRecordDecl *ClassDecl = Constructor->getParent();
4825 
4826   // 1. Virtual bases.
4827   for (const auto &VBase : ClassDecl->vbases())
4828     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4829 
4830   // 2. Non-virtual bases.
4831   for (const auto &Base : ClassDecl->bases()) {
4832     if (Base.isVirtual())
4833       continue;
4834     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4835   }
4836 
4837   // 3. Direct fields.
4838   for (auto *Field : ClassDecl->fields()) {
4839     if (Field->isUnnamedBitfield())
4840       continue;
4841 
4842     PopulateKeysForFields(Field, IdealInitKeys);
4843   }
4844 
4845   unsigned NumIdealInits = IdealInitKeys.size();
4846   unsigned IdealIndex = 0;
4847 
4848   CXXCtorInitializer *PrevInit = nullptr;
4849   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4850     CXXCtorInitializer *Init = Inits[InitIndex];
4851     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4852 
4853     // Scan forward to try to find this initializer in the idealized
4854     // initializers list.
4855     for (; IdealIndex != NumIdealInits; ++IdealIndex)
4856       if (InitKey == IdealInitKeys[IdealIndex])
4857         break;
4858 
4859     // If we didn't find this initializer, it must be because we
4860     // scanned past it on a previous iteration.  That can only
4861     // happen if we're out of order;  emit a warning.
4862     if (IdealIndex == NumIdealInits && PrevInit) {
4863       Sema::SemaDiagnosticBuilder D =
4864         SemaRef.Diag(PrevInit->getSourceLocation(),
4865                      diag::warn_initializer_out_of_order);
4866 
4867       if (PrevInit->isAnyMemberInitializer())
4868         D << 0 << PrevInit->getAnyMember()->getDeclName();
4869       else
4870         D << 1 << PrevInit->getTypeSourceInfo()->getType();
4871 
4872       if (Init->isAnyMemberInitializer())
4873         D << 0 << Init->getAnyMember()->getDeclName();
4874       else
4875         D << 1 << Init->getTypeSourceInfo()->getType();
4876 
4877       // Move back to the initializer's location in the ideal list.
4878       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4879         if (InitKey == IdealInitKeys[IdealIndex])
4880           break;
4881 
4882       assert(IdealIndex < NumIdealInits &&
4883              "initializer not found in initializer list");
4884     }
4885 
4886     PrevInit = Init;
4887   }
4888 }
4889 
4890 namespace {
4891 bool CheckRedundantInit(Sema &S,
4892                         CXXCtorInitializer *Init,
4893                         CXXCtorInitializer *&PrevInit) {
4894   if (!PrevInit) {
4895     PrevInit = Init;
4896     return false;
4897   }
4898 
4899   if (FieldDecl *Field = Init->getAnyMember())
4900     S.Diag(Init->getSourceLocation(),
4901            diag::err_multiple_mem_initialization)
4902       << Field->getDeclName()
4903       << Init->getSourceRange();
4904   else {
4905     const Type *BaseClass = Init->getBaseClass();
4906     assert(BaseClass && "neither field nor base");
4907     S.Diag(Init->getSourceLocation(),
4908            diag::err_multiple_base_initialization)
4909       << QualType(BaseClass, 0)
4910       << Init->getSourceRange();
4911   }
4912   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4913     << 0 << PrevInit->getSourceRange();
4914 
4915   return true;
4916 }
4917 
4918 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
4919 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4920 
4921 bool CheckRedundantUnionInit(Sema &S,
4922                              CXXCtorInitializer *Init,
4923                              RedundantUnionMap &Unions) {
4924   FieldDecl *Field = Init->getAnyMember();
4925   RecordDecl *Parent = Field->getParent();
4926   NamedDecl *Child = Field;
4927 
4928   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
4929     if (Parent->isUnion()) {
4930       UnionEntry &En = Unions[Parent];
4931       if (En.first && En.first != Child) {
4932         S.Diag(Init->getSourceLocation(),
4933                diag::err_multiple_mem_union_initialization)
4934           << Field->getDeclName()
4935           << Init->getSourceRange();
4936         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4937           << 0 << En.second->getSourceRange();
4938         return true;
4939       }
4940       if (!En.first) {
4941         En.first = Child;
4942         En.second = Init;
4943       }
4944       if (!Parent->isAnonymousStructOrUnion())
4945         return false;
4946     }
4947 
4948     Child = Parent;
4949     Parent = cast<RecordDecl>(Parent->getDeclContext());
4950   }
4951 
4952   return false;
4953 }
4954 }
4955 
4956 /// ActOnMemInitializers - Handle the member initializers for a constructor.
4957 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
4958                                 SourceLocation ColonLoc,
4959                                 ArrayRef<CXXCtorInitializer*> MemInits,
4960                                 bool AnyErrors) {
4961   if (!ConstructorDecl)
4962     return;
4963 
4964   AdjustDeclIfTemplate(ConstructorDecl);
4965 
4966   CXXConstructorDecl *Constructor
4967     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
4968 
4969   if (!Constructor) {
4970     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4971     return;
4972   }
4973 
4974   // Mapping for the duplicate initializers check.
4975   // For member initializers, this is keyed with a FieldDecl*.
4976   // For base initializers, this is keyed with a Type*.
4977   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
4978 
4979   // Mapping for the inconsistent anonymous-union initializers check.
4980   RedundantUnionMap MemberUnions;
4981 
4982   bool HadError = false;
4983   for (unsigned i = 0; i < MemInits.size(); i++) {
4984     CXXCtorInitializer *Init = MemInits[i];
4985 
4986     // Set the source order index.
4987     Init->setSourceOrder(i);
4988 
4989     if (Init->isAnyMemberInitializer()) {
4990       const void *Key = GetKeyForMember(Context, Init);
4991       if (CheckRedundantInit(*this, Init, Members[Key]) ||
4992           CheckRedundantUnionInit(*this, Init, MemberUnions))
4993         HadError = true;
4994     } else if (Init->isBaseInitializer()) {
4995       const void *Key = GetKeyForMember(Context, Init);
4996       if (CheckRedundantInit(*this, Init, Members[Key]))
4997         HadError = true;
4998     } else {
4999       assert(Init->isDelegatingInitializer());
5000       // This must be the only initializer
5001       if (MemInits.size() != 1) {
5002         Diag(Init->getSourceLocation(),
5003              diag::err_delegating_initializer_alone)
5004           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5005         // We will treat this as being the only initializer.
5006       }
5007       SetDelegatingInitializer(Constructor, MemInits[i]);
5008       // Return immediately as the initializer is set.
5009       return;
5010     }
5011   }
5012 
5013   if (HadError)
5014     return;
5015 
5016   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5017 
5018   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5019 
5020   DiagnoseUninitializedFields(*this, Constructor);
5021 }
5022 
5023 void
5024 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5025                                              CXXRecordDecl *ClassDecl) {
5026   // Ignore dependent contexts. Also ignore unions, since their members never
5027   // have destructors implicitly called.
5028   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5029     return;
5030 
5031   // FIXME: all the access-control diagnostics are positioned on the
5032   // field/base declaration.  That's probably good; that said, the
5033   // user might reasonably want to know why the destructor is being
5034   // emitted, and we currently don't say.
5035 
5036   // Non-static data members.
5037   for (auto *Field : ClassDecl->fields()) {
5038     if (Field->isInvalidDecl())
5039       continue;
5040 
5041     // Don't destroy incomplete or zero-length arrays.
5042     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5043       continue;
5044 
5045     QualType FieldType = Context.getBaseElementType(Field->getType());
5046 
5047     const RecordType* RT = FieldType->getAs<RecordType>();
5048     if (!RT)
5049       continue;
5050 
5051     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5052     if (FieldClassDecl->isInvalidDecl())
5053       continue;
5054     if (FieldClassDecl->hasIrrelevantDestructor())
5055       continue;
5056     // The destructor for an implicit anonymous union member is never invoked.
5057     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5058       continue;
5059 
5060     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5061     assert(Dtor && "No dtor found for FieldClassDecl!");
5062     CheckDestructorAccess(Field->getLocation(), Dtor,
5063                           PDiag(diag::err_access_dtor_field)
5064                             << Field->getDeclName()
5065                             << FieldType);
5066 
5067     MarkFunctionReferenced(Location, Dtor);
5068     DiagnoseUseOfDecl(Dtor, Location);
5069   }
5070 
5071   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5072 
5073   // Bases.
5074   for (const auto &Base : ClassDecl->bases()) {
5075     // Bases are always records in a well-formed non-dependent class.
5076     const RecordType *RT = Base.getType()->getAs<RecordType>();
5077 
5078     // Remember direct virtual bases.
5079     if (Base.isVirtual())
5080       DirectVirtualBases.insert(RT);
5081 
5082     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5083     // If our base class is invalid, we probably can't get its dtor anyway.
5084     if (BaseClassDecl->isInvalidDecl())
5085       continue;
5086     if (BaseClassDecl->hasIrrelevantDestructor())
5087       continue;
5088 
5089     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5090     assert(Dtor && "No dtor found for BaseClassDecl!");
5091 
5092     // FIXME: caret should be on the start of the class name
5093     CheckDestructorAccess(Base.getLocStart(), Dtor,
5094                           PDiag(diag::err_access_dtor_base)
5095                             << Base.getType()
5096                             << Base.getSourceRange(),
5097                           Context.getTypeDeclType(ClassDecl));
5098 
5099     MarkFunctionReferenced(Location, Dtor);
5100     DiagnoseUseOfDecl(Dtor, Location);
5101   }
5102 
5103   // Virtual bases.
5104   for (const auto &VBase : ClassDecl->vbases()) {
5105     // Bases are always records in a well-formed non-dependent class.
5106     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5107 
5108     // Ignore direct virtual bases.
5109     if (DirectVirtualBases.count(RT))
5110       continue;
5111 
5112     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5113     // If our base class is invalid, we probably can't get its dtor anyway.
5114     if (BaseClassDecl->isInvalidDecl())
5115       continue;
5116     if (BaseClassDecl->hasIrrelevantDestructor())
5117       continue;
5118 
5119     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5120     assert(Dtor && "No dtor found for BaseClassDecl!");
5121     if (CheckDestructorAccess(
5122             ClassDecl->getLocation(), Dtor,
5123             PDiag(diag::err_access_dtor_vbase)
5124                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5125             Context.getTypeDeclType(ClassDecl)) ==
5126         AR_accessible) {
5127       CheckDerivedToBaseConversion(
5128           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5129           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5130           SourceRange(), DeclarationName(), nullptr);
5131     }
5132 
5133     MarkFunctionReferenced(Location, Dtor);
5134     DiagnoseUseOfDecl(Dtor, Location);
5135   }
5136 }
5137 
5138 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5139   if (!CDtorDecl)
5140     return;
5141 
5142   if (CXXConstructorDecl *Constructor
5143       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5144     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5145     DiagnoseUninitializedFields(*this, Constructor);
5146   }
5147 }
5148 
5149 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5150   if (!getLangOpts().CPlusPlus)
5151     return false;
5152 
5153   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5154   if (!RD)
5155     return false;
5156 
5157   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5158   // class template specialization here, but doing so breaks a lot of code.
5159 
5160   // We can't answer whether something is abstract until it has a
5161   // definition. If it's currently being defined, we'll walk back
5162   // over all the declarations when we have a full definition.
5163   const CXXRecordDecl *Def = RD->getDefinition();
5164   if (!Def || Def->isBeingDefined())
5165     return false;
5166 
5167   return RD->isAbstract();
5168 }
5169 
5170 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5171                                   TypeDiagnoser &Diagnoser) {
5172   if (!isAbstractType(Loc, T))
5173     return false;
5174 
5175   T = Context.getBaseElementType(T);
5176   Diagnoser.diagnose(*this, Loc, T);
5177   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5178   return true;
5179 }
5180 
5181 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5182   // Check if we've already emitted the list of pure virtual functions
5183   // for this class.
5184   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5185     return;
5186 
5187   // If the diagnostic is suppressed, don't emit the notes. We're only
5188   // going to emit them once, so try to attach them to a diagnostic we're
5189   // actually going to show.
5190   if (Diags.isLastDiagnosticIgnored())
5191     return;
5192 
5193   CXXFinalOverriderMap FinalOverriders;
5194   RD->getFinalOverriders(FinalOverriders);
5195 
5196   // Keep a set of seen pure methods so we won't diagnose the same method
5197   // more than once.
5198   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5199 
5200   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5201                                    MEnd = FinalOverriders.end();
5202        M != MEnd;
5203        ++M) {
5204     for (OverridingMethods::iterator SO = M->second.begin(),
5205                                   SOEnd = M->second.end();
5206          SO != SOEnd; ++SO) {
5207       // C++ [class.abstract]p4:
5208       //   A class is abstract if it contains or inherits at least one
5209       //   pure virtual function for which the final overrider is pure
5210       //   virtual.
5211 
5212       //
5213       if (SO->second.size() != 1)
5214         continue;
5215 
5216       if (!SO->second.front().Method->isPure())
5217         continue;
5218 
5219       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5220         continue;
5221 
5222       Diag(SO->second.front().Method->getLocation(),
5223            diag::note_pure_virtual_function)
5224         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5225     }
5226   }
5227 
5228   if (!PureVirtualClassDiagSet)
5229     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5230   PureVirtualClassDiagSet->insert(RD);
5231 }
5232 
5233 namespace {
5234 struct AbstractUsageInfo {
5235   Sema &S;
5236   CXXRecordDecl *Record;
5237   CanQualType AbstractType;
5238   bool Invalid;
5239 
5240   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5241     : S(S), Record(Record),
5242       AbstractType(S.Context.getCanonicalType(
5243                    S.Context.getTypeDeclType(Record))),
5244       Invalid(false) {}
5245 
5246   void DiagnoseAbstractType() {
5247     if (Invalid) return;
5248     S.DiagnoseAbstractType(Record);
5249     Invalid = true;
5250   }
5251 
5252   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5253 };
5254 
5255 struct CheckAbstractUsage {
5256   AbstractUsageInfo &Info;
5257   const NamedDecl *Ctx;
5258 
5259   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5260     : Info(Info), Ctx(Ctx) {}
5261 
5262   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5263     switch (TL.getTypeLocClass()) {
5264 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5265 #define TYPELOC(CLASS, PARENT) \
5266     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5267 #include "clang/AST/TypeLocNodes.def"
5268     }
5269   }
5270 
5271   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5272     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5273     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5274       if (!TL.getParam(I))
5275         continue;
5276 
5277       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5278       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5279     }
5280   }
5281 
5282   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5283     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5284   }
5285 
5286   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5287     // Visit the type parameters from a permissive context.
5288     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5289       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5290       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5291         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5292           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5293       // TODO: other template argument types?
5294     }
5295   }
5296 
5297   // Visit pointee types from a permissive context.
5298 #define CheckPolymorphic(Type) \
5299   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5300     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5301   }
5302   CheckPolymorphic(PointerTypeLoc)
5303   CheckPolymorphic(ReferenceTypeLoc)
5304   CheckPolymorphic(MemberPointerTypeLoc)
5305   CheckPolymorphic(BlockPointerTypeLoc)
5306   CheckPolymorphic(AtomicTypeLoc)
5307 
5308   /// Handle all the types we haven't given a more specific
5309   /// implementation for above.
5310   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5311     // Every other kind of type that we haven't called out already
5312     // that has an inner type is either (1) sugar or (2) contains that
5313     // inner type in some way as a subobject.
5314     if (TypeLoc Next = TL.getNextTypeLoc())
5315       return Visit(Next, Sel);
5316 
5317     // If there's no inner type and we're in a permissive context,
5318     // don't diagnose.
5319     if (Sel == Sema::AbstractNone) return;
5320 
5321     // Check whether the type matches the abstract type.
5322     QualType T = TL.getType();
5323     if (T->isArrayType()) {
5324       Sel = Sema::AbstractArrayType;
5325       T = Info.S.Context.getBaseElementType(T);
5326     }
5327     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5328     if (CT != Info.AbstractType) return;
5329 
5330     // It matched; do some magic.
5331     if (Sel == Sema::AbstractArrayType) {
5332       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5333         << T << TL.getSourceRange();
5334     } else {
5335       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5336         << Sel << T << TL.getSourceRange();
5337     }
5338     Info.DiagnoseAbstractType();
5339   }
5340 };
5341 
5342 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5343                                   Sema::AbstractDiagSelID Sel) {
5344   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5345 }
5346 
5347 }
5348 
5349 /// Check for invalid uses of an abstract type in a method declaration.
5350 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5351                                     CXXMethodDecl *MD) {
5352   // No need to do the check on definitions, which require that
5353   // the return/param types be complete.
5354   if (MD->doesThisDeclarationHaveABody())
5355     return;
5356 
5357   // For safety's sake, just ignore it if we don't have type source
5358   // information.  This should never happen for non-implicit methods,
5359   // but...
5360   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5361     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5362 }
5363 
5364 /// Check for invalid uses of an abstract type within a class definition.
5365 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5366                                     CXXRecordDecl *RD) {
5367   for (auto *D : RD->decls()) {
5368     if (D->isImplicit()) continue;
5369 
5370     // Methods and method templates.
5371     if (isa<CXXMethodDecl>(D)) {
5372       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5373     } else if (isa<FunctionTemplateDecl>(D)) {
5374       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5375       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5376 
5377     // Fields and static variables.
5378     } else if (isa<FieldDecl>(D)) {
5379       FieldDecl *FD = cast<FieldDecl>(D);
5380       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5381         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5382     } else if (isa<VarDecl>(D)) {
5383       VarDecl *VD = cast<VarDecl>(D);
5384       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5385         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5386 
5387     // Nested classes and class templates.
5388     } else if (isa<CXXRecordDecl>(D)) {
5389       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5390     } else if (isa<ClassTemplateDecl>(D)) {
5391       CheckAbstractClassUsage(Info,
5392                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5393     }
5394   }
5395 }
5396 
5397 static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) {
5398   Attr *ClassAttr = getDLLAttr(Class);
5399   if (!ClassAttr)
5400     return;
5401 
5402   assert(ClassAttr->getKind() == attr::DLLExport);
5403 
5404   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5405 
5406   if (TSK == TSK_ExplicitInstantiationDeclaration)
5407     // Don't go any further if this is just an explicit instantiation
5408     // declaration.
5409     return;
5410 
5411   for (Decl *Member : Class->decls()) {
5412     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5413     if (!MD)
5414       continue;
5415 
5416     if (Member->getAttr<DLLExportAttr>()) {
5417       if (MD->isUserProvided()) {
5418         // Instantiate non-default class member functions ...
5419 
5420         // .. except for certain kinds of template specializations.
5421         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5422           continue;
5423 
5424         S.MarkFunctionReferenced(Class->getLocation(), MD);
5425 
5426         // The function will be passed to the consumer when its definition is
5427         // encountered.
5428       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5429                  MD->isCopyAssignmentOperator() ||
5430                  MD->isMoveAssignmentOperator()) {
5431         // Synthesize and instantiate non-trivial implicit methods, explicitly
5432         // defaulted methods, and the copy and move assignment operators. The
5433         // latter are exported even if they are trivial, because the address of
5434         // an operator can be taken and should compare equal accross libraries.
5435         DiagnosticErrorTrap Trap(S.Diags);
5436         S.MarkFunctionReferenced(Class->getLocation(), MD);
5437         if (Trap.hasErrorOccurred()) {
5438           S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5439               << Class->getName() << !S.getLangOpts().CPlusPlus11;
5440           break;
5441         }
5442 
5443         // There is no later point when we will see the definition of this
5444         // function, so pass it to the consumer now.
5445         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5446       }
5447     }
5448   }
5449 }
5450 
5451 /// \brief Check class-level dllimport/dllexport attribute.
5452 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
5453   Attr *ClassAttr = getDLLAttr(Class);
5454 
5455   // MSVC inherits DLL attributes to partial class template specializations.
5456   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5457     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5458       if (Attr *TemplateAttr =
5459               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5460         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5461         A->setInherited(true);
5462         ClassAttr = A;
5463       }
5464     }
5465   }
5466 
5467   if (!ClassAttr)
5468     return;
5469 
5470   if (!Class->isExternallyVisible()) {
5471     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5472         << Class << ClassAttr;
5473     return;
5474   }
5475 
5476   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5477       !ClassAttr->isInherited()) {
5478     // Diagnose dll attributes on members of class with dll attribute.
5479     for (Decl *Member : Class->decls()) {
5480       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5481         continue;
5482       InheritableAttr *MemberAttr = getDLLAttr(Member);
5483       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5484         continue;
5485 
5486       Diag(MemberAttr->getLocation(),
5487              diag::err_attribute_dll_member_of_dll_class)
5488           << MemberAttr << ClassAttr;
5489       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5490       Member->setInvalidDecl();
5491     }
5492   }
5493 
5494   if (Class->getDescribedClassTemplate())
5495     // Don't inherit dll attribute until the template is instantiated.
5496     return;
5497 
5498   // The class is either imported or exported.
5499   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5500 
5501   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5502 
5503   // Ignore explicit dllexport on explicit class template instantiation declarations.
5504   if (ClassExported && !ClassAttr->isInherited() &&
5505       TSK == TSK_ExplicitInstantiationDeclaration) {
5506     Class->dropAttr<DLLExportAttr>();
5507     return;
5508   }
5509 
5510   // Force declaration of implicit members so they can inherit the attribute.
5511   ForceDeclarationOfImplicitMembers(Class);
5512 
5513   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5514   // seem to be true in practice?
5515 
5516   for (Decl *Member : Class->decls()) {
5517     VarDecl *VD = dyn_cast<VarDecl>(Member);
5518     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5519 
5520     // Only methods and static fields inherit the attributes.
5521     if (!VD && !MD)
5522       continue;
5523 
5524     if (MD) {
5525       // Don't process deleted methods.
5526       if (MD->isDeleted())
5527         continue;
5528 
5529       if (MD->isInlined()) {
5530         // MinGW does not import or export inline methods.
5531         if (!Context.getTargetInfo().getCXXABI().isMicrosoft())
5532           continue;
5533 
5534         // MSVC versions before 2015 don't export the move assignment operators
5535         // and move constructor, so don't attempt to import/export them if
5536         // we have a definition.
5537         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5538         if ((MD->isMoveAssignmentOperator() ||
5539              (Ctor && Ctor->isMoveConstructor())) &&
5540             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5541           continue;
5542 
5543         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5544         // operator is exported anyway.
5545         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5546             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5547           continue;
5548       }
5549     }
5550 
5551     if (!cast<NamedDecl>(Member)->isExternallyVisible())
5552       continue;
5553 
5554     if (!getDLLAttr(Member)) {
5555       auto *NewAttr =
5556           cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5557       NewAttr->setInherited(true);
5558       Member->addAttr(NewAttr);
5559     }
5560   }
5561 
5562   if (ClassExported)
5563     DelayedDllExportClasses.push_back(Class);
5564 }
5565 
5566 /// \brief Perform propagation of DLL attributes from a derived class to a
5567 /// templated base class for MS compatibility.
5568 void Sema::propagateDLLAttrToBaseClassTemplate(
5569     CXXRecordDecl *Class, Attr *ClassAttr,
5570     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5571   if (getDLLAttr(
5572           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5573     // If the base class template has a DLL attribute, don't try to change it.
5574     return;
5575   }
5576 
5577   auto TSK = BaseTemplateSpec->getSpecializationKind();
5578   if (!getDLLAttr(BaseTemplateSpec) &&
5579       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5580        TSK == TSK_ImplicitInstantiation)) {
5581     // The template hasn't been instantiated yet (or it has, but only as an
5582     // explicit instantiation declaration or implicit instantiation, which means
5583     // we haven't codegenned any members yet), so propagate the attribute.
5584     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5585     NewAttr->setInherited(true);
5586     BaseTemplateSpec->addAttr(NewAttr);
5587 
5588     // If the template is already instantiated, checkDLLAttributeRedeclaration()
5589     // needs to be run again to work see the new attribute. Otherwise this will
5590     // get run whenever the template is instantiated.
5591     if (TSK != TSK_Undeclared)
5592       checkClassLevelDLLAttribute(BaseTemplateSpec);
5593 
5594     return;
5595   }
5596 
5597   if (getDLLAttr(BaseTemplateSpec)) {
5598     // The template has already been specialized or instantiated with an
5599     // attribute, explicitly or through propagation. We should not try to change
5600     // it.
5601     return;
5602   }
5603 
5604   // The template was previously instantiated or explicitly specialized without
5605   // a dll attribute, It's too late for us to add an attribute, so warn that
5606   // this is unsupported.
5607   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5608       << BaseTemplateSpec->isExplicitSpecialization();
5609   Diag(ClassAttr->getLocation(), diag::note_attribute);
5610   if (BaseTemplateSpec->isExplicitSpecialization()) {
5611     Diag(BaseTemplateSpec->getLocation(),
5612            diag::note_template_class_explicit_specialization_was_here)
5613         << BaseTemplateSpec;
5614   } else {
5615     Diag(BaseTemplateSpec->getPointOfInstantiation(),
5616            diag::note_template_class_instantiation_was_here)
5617         << BaseTemplateSpec;
5618   }
5619 }
5620 
5621 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5622                                         SourceLocation DefaultLoc) {
5623   switch (S.getSpecialMember(MD)) {
5624   case Sema::CXXDefaultConstructor:
5625     S.DefineImplicitDefaultConstructor(DefaultLoc,
5626                                        cast<CXXConstructorDecl>(MD));
5627     break;
5628   case Sema::CXXCopyConstructor:
5629     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5630     break;
5631   case Sema::CXXCopyAssignment:
5632     S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5633     break;
5634   case Sema::CXXDestructor:
5635     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5636     break;
5637   case Sema::CXXMoveConstructor:
5638     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5639     break;
5640   case Sema::CXXMoveAssignment:
5641     S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5642     break;
5643   case Sema::CXXInvalid:
5644     llvm_unreachable("Invalid special member.");
5645   }
5646 }
5647 
5648 /// \brief Perform semantic checks on a class definition that has been
5649 /// completing, introducing implicitly-declared members, checking for
5650 /// abstract types, etc.
5651 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
5652   if (!Record)
5653     return;
5654 
5655   if (Record->isAbstract() && !Record->isInvalidDecl()) {
5656     AbstractUsageInfo Info(*this, Record);
5657     CheckAbstractClassUsage(Info, Record);
5658   }
5659 
5660   // If this is not an aggregate type and has no user-declared constructor,
5661   // complain about any non-static data members of reference or const scalar
5662   // type, since they will never get initializers.
5663   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
5664       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
5665       !Record->isLambda()) {
5666     bool Complained = false;
5667     for (const auto *F : Record->fields()) {
5668       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
5669         continue;
5670 
5671       if (F->getType()->isReferenceType() ||
5672           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
5673         if (!Complained) {
5674           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
5675             << Record->getTagKind() << Record;
5676           Complained = true;
5677         }
5678 
5679         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
5680           << F->getType()->isReferenceType()
5681           << F->getDeclName();
5682       }
5683     }
5684   }
5685 
5686   if (Record->getIdentifier()) {
5687     // C++ [class.mem]p13:
5688     //   If T is the name of a class, then each of the following shall have a
5689     //   name different from T:
5690     //     - every member of every anonymous union that is a member of class T.
5691     //
5692     // C++ [class.mem]p14:
5693     //   In addition, if class T has a user-declared constructor (12.1), every
5694     //   non-static data member of class T shall have a name different from T.
5695     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
5696     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
5697          ++I) {
5698       NamedDecl *D = *I;
5699       if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
5700           isa<IndirectFieldDecl>(D)) {
5701         Diag(D->getLocation(), diag::err_member_name_of_class)
5702           << D->getDeclName();
5703         break;
5704       }
5705     }
5706   }
5707 
5708   // Warn if the class has virtual methods but non-virtual public destructor.
5709   if (Record->isPolymorphic() && !Record->isDependentType()) {
5710     CXXDestructorDecl *dtor = Record->getDestructor();
5711     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
5712         !Record->hasAttr<FinalAttr>())
5713       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
5714            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
5715   }
5716 
5717   if (Record->isAbstract()) {
5718     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
5719       Diag(Record->getLocation(), diag::warn_abstract_final_class)
5720         << FA->isSpelledAsSealed();
5721       DiagnoseAbstractType(Record);
5722     }
5723   }
5724 
5725   bool HasMethodWithOverrideControl = false,
5726        HasOverridingMethodWithoutOverrideControl = false;
5727   if (!Record->isDependentType()) {
5728     for (auto *M : Record->methods()) {
5729       // See if a method overloads virtual methods in a base
5730       // class without overriding any.
5731       if (!M->isStatic())
5732         DiagnoseHiddenVirtualMethods(M);
5733       if (M->hasAttr<OverrideAttr>())
5734         HasMethodWithOverrideControl = true;
5735       else if (M->size_overridden_methods() > 0)
5736         HasOverridingMethodWithoutOverrideControl = true;
5737       // Check whether the explicitly-defaulted special members are valid.
5738       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
5739         CheckExplicitlyDefaultedSpecialMember(M);
5740 
5741       // For an explicitly defaulted or deleted special member, we defer
5742       // determining triviality until the class is complete. That time is now!
5743       CXXSpecialMember CSM = getSpecialMember(M);
5744       if (!M->isImplicit() && !M->isUserProvided()) {
5745         if (CSM != CXXInvalid) {
5746           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
5747 
5748           // Inform the class that we've finished declaring this member.
5749           Record->finishedDefaultedOrDeletedMember(M);
5750         }
5751       }
5752 
5753       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
5754           M->hasAttr<DLLExportAttr>()) {
5755         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5756             M->isTrivial() &&
5757             (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
5758              CSM == CXXDestructor))
5759           M->dropAttr<DLLExportAttr>();
5760 
5761         if (M->hasAttr<DLLExportAttr>()) {
5762           DefineImplicitSpecialMember(*this, M, M->getLocation());
5763           ActOnFinishInlineFunctionDef(M);
5764         }
5765       }
5766     }
5767   }
5768 
5769   if (HasMethodWithOverrideControl &&
5770       HasOverridingMethodWithoutOverrideControl) {
5771     // At least one method has the 'override' control declared.
5772     // Diagnose all other overridden methods which do not have 'override' specified on them.
5773     for (auto *M : Record->methods())
5774       DiagnoseAbsenceOfOverrideControl(M);
5775   }
5776 
5777   // ms_struct is a request to use the same ABI rules as MSVC.  Check
5778   // whether this class uses any C++ features that are implemented
5779   // completely differently in MSVC, and if so, emit a diagnostic.
5780   // That diagnostic defaults to an error, but we allow projects to
5781   // map it down to a warning (or ignore it).  It's a fairly common
5782   // practice among users of the ms_struct pragma to mass-annotate
5783   // headers, sweeping up a bunch of types that the project doesn't
5784   // really rely on MSVC-compatible layout for.  We must therefore
5785   // support "ms_struct except for C++ stuff" as a secondary ABI.
5786   if (Record->isMsStruct(Context) &&
5787       (Record->isPolymorphic() || Record->getNumBases())) {
5788     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
5789   }
5790 
5791   checkClassLevelDLLAttribute(Record);
5792 }
5793 
5794 /// Look up the special member function that would be called by a special
5795 /// member function for a subobject of class type.
5796 ///
5797 /// \param Class The class type of the subobject.
5798 /// \param CSM The kind of special member function.
5799 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
5800 /// \param ConstRHS True if this is a copy operation with a const object
5801 ///        on its RHS, that is, if the argument to the outer special member
5802 ///        function is 'const' and this is not a field marked 'mutable'.
5803 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
5804     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
5805     unsigned FieldQuals, bool ConstRHS) {
5806   unsigned LHSQuals = 0;
5807   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
5808     LHSQuals = FieldQuals;
5809 
5810   unsigned RHSQuals = FieldQuals;
5811   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
5812     RHSQuals = 0;
5813   else if (ConstRHS)
5814     RHSQuals |= Qualifiers::Const;
5815 
5816   return S.LookupSpecialMember(Class, CSM,
5817                                RHSQuals & Qualifiers::Const,
5818                                RHSQuals & Qualifiers::Volatile,
5819                                false,
5820                                LHSQuals & Qualifiers::Const,
5821                                LHSQuals & Qualifiers::Volatile);
5822 }
5823 
5824 class Sema::InheritedConstructorInfo {
5825   Sema &S;
5826   SourceLocation UseLoc;
5827 
5828   /// A mapping from the base classes through which the constructor was
5829   /// inherited to the using shadow declaration in that base class (or a null
5830   /// pointer if the constructor was declared in that base class).
5831   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
5832       InheritedFromBases;
5833 
5834 public:
5835   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
5836                            ConstructorUsingShadowDecl *Shadow)
5837       : S(S), UseLoc(UseLoc) {
5838     bool DiagnosedMultipleConstructedBases = false;
5839     CXXRecordDecl *ConstructedBase = nullptr;
5840     UsingDecl *ConstructedBaseUsing = nullptr;
5841 
5842     // Find the set of such base class subobjects and check that there's a
5843     // unique constructed subobject.
5844     for (auto *D : Shadow->redecls()) {
5845       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
5846       auto *DNominatedBase = DShadow->getNominatedBaseClass();
5847       auto *DConstructedBase = DShadow->getConstructedBaseClass();
5848 
5849       InheritedFromBases.insert(
5850           std::make_pair(DNominatedBase->getCanonicalDecl(),
5851                          DShadow->getNominatedBaseClassShadowDecl()));
5852       if (DShadow->constructsVirtualBase())
5853         InheritedFromBases.insert(
5854             std::make_pair(DConstructedBase->getCanonicalDecl(),
5855                            DShadow->getConstructedBaseClassShadowDecl()));
5856       else
5857         assert(DNominatedBase == DConstructedBase);
5858 
5859       // [class.inhctor.init]p2:
5860       //   If the constructor was inherited from multiple base class subobjects
5861       //   of type B, the program is ill-formed.
5862       if (!ConstructedBase) {
5863         ConstructedBase = DConstructedBase;
5864         ConstructedBaseUsing = D->getUsingDecl();
5865       } else if (ConstructedBase != DConstructedBase &&
5866                  !Shadow->isInvalidDecl()) {
5867         if (!DiagnosedMultipleConstructedBases) {
5868           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
5869               << Shadow->getTargetDecl();
5870           S.Diag(ConstructedBaseUsing->getLocation(),
5871                diag::note_ambiguous_inherited_constructor_using)
5872               << ConstructedBase;
5873           DiagnosedMultipleConstructedBases = true;
5874         }
5875         S.Diag(D->getUsingDecl()->getLocation(),
5876                diag::note_ambiguous_inherited_constructor_using)
5877             << DConstructedBase;
5878       }
5879     }
5880 
5881     if (DiagnosedMultipleConstructedBases)
5882       Shadow->setInvalidDecl();
5883   }
5884 
5885   /// Find the constructor to use for inherited construction of a base class,
5886   /// and whether that base class constructor inherits the constructor from a
5887   /// virtual base class (in which case it won't actually invoke it).
5888   std::pair<CXXConstructorDecl *, bool>
5889   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
5890     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
5891     if (It == InheritedFromBases.end())
5892       return std::make_pair(nullptr, false);
5893 
5894     // This is an intermediary class.
5895     if (It->second)
5896       return std::make_pair(
5897           S.findInheritingConstructor(UseLoc, Ctor, It->second),
5898           It->second->constructsVirtualBase());
5899 
5900     // This is the base class from which the constructor was inherited.
5901     return std::make_pair(Ctor, false);
5902   }
5903 };
5904 
5905 /// Is the special member function which would be selected to perform the
5906 /// specified operation on the specified class type a constexpr constructor?
5907 static bool
5908 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5909                          Sema::CXXSpecialMember CSM, unsigned Quals,
5910                          bool ConstRHS,
5911                          CXXConstructorDecl *InheritedCtor = nullptr,
5912                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
5913   // If we're inheriting a constructor, see if we need to call it for this base
5914   // class.
5915   if (InheritedCtor) {
5916     assert(CSM == Sema::CXXDefaultConstructor);
5917     auto BaseCtor =
5918         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
5919     if (BaseCtor)
5920       return BaseCtor->isConstexpr();
5921   }
5922 
5923   if (CSM == Sema::CXXDefaultConstructor)
5924     return ClassDecl->hasConstexprDefaultConstructor();
5925 
5926   Sema::SpecialMemberOverloadResult *SMOR =
5927       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
5928   if (!SMOR || !SMOR->getMethod())
5929     // A constructor we wouldn't select can't be "involved in initializing"
5930     // anything.
5931     return true;
5932   return SMOR->getMethod()->isConstexpr();
5933 }
5934 
5935 /// Determine whether the specified special member function would be constexpr
5936 /// if it were implicitly defined.
5937 static bool defaultedSpecialMemberIsConstexpr(
5938     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
5939     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
5940     Sema::InheritedConstructorInfo *Inherited = nullptr) {
5941   if (!S.getLangOpts().CPlusPlus11)
5942     return false;
5943 
5944   // C++11 [dcl.constexpr]p4:
5945   // In the definition of a constexpr constructor [...]
5946   bool Ctor = true;
5947   switch (CSM) {
5948   case Sema::CXXDefaultConstructor:
5949     if (Inherited)
5950       break;
5951     // Since default constructor lookup is essentially trivial (and cannot
5952     // involve, for instance, template instantiation), we compute whether a
5953     // defaulted default constructor is constexpr directly within CXXRecordDecl.
5954     //
5955     // This is important for performance; we need to know whether the default
5956     // constructor is constexpr to determine whether the type is a literal type.
5957     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
5958 
5959   case Sema::CXXCopyConstructor:
5960   case Sema::CXXMoveConstructor:
5961     // For copy or move constructors, we need to perform overload resolution.
5962     break;
5963 
5964   case Sema::CXXCopyAssignment:
5965   case Sema::CXXMoveAssignment:
5966     if (!S.getLangOpts().CPlusPlus14)
5967       return false;
5968     // In C++1y, we need to perform overload resolution.
5969     Ctor = false;
5970     break;
5971 
5972   case Sema::CXXDestructor:
5973   case Sema::CXXInvalid:
5974     return false;
5975   }
5976 
5977   //   -- if the class is a non-empty union, or for each non-empty anonymous
5978   //      union member of a non-union class, exactly one non-static data member
5979   //      shall be initialized; [DR1359]
5980   //
5981   // If we squint, this is guaranteed, since exactly one non-static data member
5982   // will be initialized (if the constructor isn't deleted), we just don't know
5983   // which one.
5984   if (Ctor && ClassDecl->isUnion())
5985     return CSM == Sema::CXXDefaultConstructor
5986                ? ClassDecl->hasInClassInitializer() ||
5987                      !ClassDecl->hasVariantMembers()
5988                : true;
5989 
5990   //   -- the class shall not have any virtual base classes;
5991   if (Ctor && ClassDecl->getNumVBases())
5992     return false;
5993 
5994   // C++1y [class.copy]p26:
5995   //   -- [the class] is a literal type, and
5996   if (!Ctor && !ClassDecl->isLiteral())
5997     return false;
5998 
5999   //   -- every constructor involved in initializing [...] base class
6000   //      sub-objects shall be a constexpr constructor;
6001   //   -- the assignment operator selected to copy/move each direct base
6002   //      class is a constexpr function, and
6003   for (const auto &B : ClassDecl->bases()) {
6004     const RecordType *BaseType = B.getType()->getAs<RecordType>();
6005     if (!BaseType) continue;
6006 
6007     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6008     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6009                                   InheritedCtor, Inherited))
6010       return false;
6011   }
6012 
6013   //   -- every constructor involved in initializing non-static data members
6014   //      [...] shall be a constexpr constructor;
6015   //   -- every non-static data member and base class sub-object shall be
6016   //      initialized
6017   //   -- for each non-static data member of X that is of class type (or array
6018   //      thereof), the assignment operator selected to copy/move that member is
6019   //      a constexpr function
6020   for (const auto *F : ClassDecl->fields()) {
6021     if (F->isInvalidDecl())
6022       continue;
6023     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6024       continue;
6025     QualType BaseType = S.Context.getBaseElementType(F->getType());
6026     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
6027       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6028       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6029                                     BaseType.getCVRQualifiers(),
6030                                     ConstArg && !F->isMutable()))
6031         return false;
6032     } else if (CSM == Sema::CXXDefaultConstructor) {
6033       return false;
6034     }
6035   }
6036 
6037   // All OK, it's constexpr!
6038   return true;
6039 }
6040 
6041 static Sema::ImplicitExceptionSpecification
6042 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6043   switch (S.getSpecialMember(MD)) {
6044   case Sema::CXXDefaultConstructor:
6045     return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
6046   case Sema::CXXCopyConstructor:
6047     return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
6048   case Sema::CXXCopyAssignment:
6049     return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
6050   case Sema::CXXMoveConstructor:
6051     return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
6052   case Sema::CXXMoveAssignment:
6053     return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
6054   case Sema::CXXDestructor:
6055     return S.ComputeDefaultedDtorExceptionSpec(MD);
6056   case Sema::CXXInvalid:
6057     break;
6058   }
6059   assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
6060          "only special members have implicit exception specs");
6061   return S.ComputeInheritingCtorExceptionSpec(Loc,
6062                                               cast<CXXConstructorDecl>(MD));
6063 }
6064 
6065 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6066                                                             CXXMethodDecl *MD) {
6067   FunctionProtoType::ExtProtoInfo EPI;
6068 
6069   // Build an exception specification pointing back at this member.
6070   EPI.ExceptionSpec.Type = EST_Unevaluated;
6071   EPI.ExceptionSpec.SourceDecl = MD;
6072 
6073   // Set the calling convention to the default for C++ instance methods.
6074   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6075       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6076                                             /*IsCXXMethod=*/true));
6077   return EPI;
6078 }
6079 
6080 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6081   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6082   if (FPT->getExceptionSpecType() != EST_Unevaluated)
6083     return;
6084 
6085   // Evaluate the exception specification.
6086   auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
6087 
6088   // Update the type of the special member to use it.
6089   UpdateExceptionSpec(MD, ESI);
6090 
6091   // A user-provided destructor can be defined outside the class. When that
6092   // happens, be sure to update the exception specification on both
6093   // declarations.
6094   const FunctionProtoType *CanonicalFPT =
6095     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6096   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
6097     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
6098 }
6099 
6100 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6101   CXXRecordDecl *RD = MD->getParent();
6102   CXXSpecialMember CSM = getSpecialMember(MD);
6103 
6104   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6105          "not an explicitly-defaulted special member");
6106 
6107   // Whether this was the first-declared instance of the constructor.
6108   // This affects whether we implicitly add an exception spec and constexpr.
6109   bool First = MD == MD->getCanonicalDecl();
6110 
6111   bool HadError = false;
6112 
6113   // C++11 [dcl.fct.def.default]p1:
6114   //   A function that is explicitly defaulted shall
6115   //     -- be a special member function (checked elsewhere),
6116   //     -- have the same type (except for ref-qualifiers, and except that a
6117   //        copy operation can take a non-const reference) as an implicit
6118   //        declaration, and
6119   //     -- not have default arguments.
6120   unsigned ExpectedParams = 1;
6121   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6122     ExpectedParams = 0;
6123   if (MD->getNumParams() != ExpectedParams) {
6124     // This also checks for default arguments: a copy or move constructor with a
6125     // default argument is classified as a default constructor, and assignment
6126     // operations and destructors can't have default arguments.
6127     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6128       << CSM << MD->getSourceRange();
6129     HadError = true;
6130   } else if (MD->isVariadic()) {
6131     Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6132       << CSM << MD->getSourceRange();
6133     HadError = true;
6134   }
6135 
6136   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
6137 
6138   bool CanHaveConstParam = false;
6139   if (CSM == CXXCopyConstructor)
6140     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
6141   else if (CSM == CXXCopyAssignment)
6142     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
6143 
6144   QualType ReturnType = Context.VoidTy;
6145   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6146     // Check for return type matching.
6147     ReturnType = Type->getReturnType();
6148     QualType ExpectedReturnType =
6149         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
6150     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6151       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6152         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6153       HadError = true;
6154     }
6155 
6156     // A defaulted special member cannot have cv-qualifiers.
6157     if (Type->getTypeQuals()) {
6158       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
6159         << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
6160       HadError = true;
6161     }
6162   }
6163 
6164   // Check for parameter type matching.
6165   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
6166   bool HasConstParam = false;
6167   if (ExpectedParams && ArgType->isReferenceType()) {
6168     // Argument must be reference to possibly-const T.
6169     QualType ReferentType = ArgType->getPointeeType();
6170     HasConstParam = ReferentType.isConstQualified();
6171 
6172     if (ReferentType.isVolatileQualified()) {
6173       Diag(MD->getLocation(),
6174            diag::err_defaulted_special_member_volatile_param) << CSM;
6175       HadError = true;
6176     }
6177 
6178     if (HasConstParam && !CanHaveConstParam) {
6179       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6180         Diag(MD->getLocation(),
6181              diag::err_defaulted_special_member_copy_const_param)
6182           << (CSM == CXXCopyAssignment);
6183         // FIXME: Explain why this special member can't be const.
6184       } else {
6185         Diag(MD->getLocation(),
6186              diag::err_defaulted_special_member_move_const_param)
6187           << (CSM == CXXMoveAssignment);
6188       }
6189       HadError = true;
6190     }
6191   } else if (ExpectedParams) {
6192     // A copy assignment operator can take its argument by value, but a
6193     // defaulted one cannot.
6194     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
6195     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
6196     HadError = true;
6197   }
6198 
6199   // C++11 [dcl.fct.def.default]p2:
6200   //   An explicitly-defaulted function may be declared constexpr only if it
6201   //   would have been implicitly declared as constexpr,
6202   // Do not apply this rule to members of class templates, since core issue 1358
6203   // makes such functions always instantiate to constexpr functions. For
6204   // functions which cannot be constexpr (for non-constructors in C++11 and for
6205   // destructors in C++1y), this is checked elsewhere.
6206   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6207                                                      HasConstParam);
6208   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
6209                                  : isa<CXXConstructorDecl>(MD)) &&
6210       MD->isConstexpr() && !Constexpr &&
6211       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6212     Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
6213     // FIXME: Explain why the special member can't be constexpr.
6214     HadError = true;
6215   }
6216 
6217   //   and may have an explicit exception-specification only if it is compatible
6218   //   with the exception-specification on the implicit declaration.
6219   if (Type->hasExceptionSpec()) {
6220     // Delay the check if this is the first declaration of the special member,
6221     // since we may not have parsed some necessary in-class initializers yet.
6222     if (First) {
6223       // If the exception specification needs to be instantiated, do so now,
6224       // before we clobber it with an EST_Unevaluated specification below.
6225       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
6226         InstantiateExceptionSpec(MD->getLocStart(), MD);
6227         Type = MD->getType()->getAs<FunctionProtoType>();
6228       }
6229       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
6230     } else
6231       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
6232   }
6233 
6234   //   If a function is explicitly defaulted on its first declaration,
6235   if (First) {
6236     //  -- it is implicitly considered to be constexpr if the implicit
6237     //     definition would be,
6238     MD->setConstexpr(Constexpr);
6239 
6240     //  -- it is implicitly considered to have the same exception-specification
6241     //     as if it had been implicitly declared,
6242     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
6243     EPI.ExceptionSpec.Type = EST_Unevaluated;
6244     EPI.ExceptionSpec.SourceDecl = MD;
6245     MD->setType(Context.getFunctionType(ReturnType,
6246                                         llvm::makeArrayRef(&ArgType,
6247                                                            ExpectedParams),
6248                                         EPI));
6249   }
6250 
6251   if (ShouldDeleteSpecialMember(MD, CSM)) {
6252     if (First) {
6253       SetDeclDeleted(MD, MD->getLocation());
6254     } else {
6255       // C++11 [dcl.fct.def.default]p4:
6256       //   [For a] user-provided explicitly-defaulted function [...] if such a
6257       //   function is implicitly defined as deleted, the program is ill-formed.
6258       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
6259       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6260       HadError = true;
6261     }
6262   }
6263 
6264   if (HadError)
6265     MD->setInvalidDecl();
6266 }
6267 
6268 /// Check whether the exception specification provided for an
6269 /// explicitly-defaulted special member matches the exception specification
6270 /// that would have been generated for an implicit special member, per
6271 /// C++11 [dcl.fct.def.default]p2.
6272 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
6273     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
6274   // If the exception specification was explicitly specified but hadn't been
6275   // parsed when the method was defaulted, grab it now.
6276   if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
6277     SpecifiedType =
6278         MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
6279 
6280   // Compute the implicit exception specification.
6281   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6282                                                        /*IsCXXMethod=*/true);
6283   FunctionProtoType::ExtProtoInfo EPI(CC);
6284   EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
6285                           .getExceptionSpec();
6286   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
6287     Context.getFunctionType(Context.VoidTy, None, EPI));
6288 
6289   // Ensure that it matches.
6290   CheckEquivalentExceptionSpec(
6291     PDiag(diag::err_incorrect_defaulted_exception_spec)
6292       << getSpecialMember(MD), PDiag(),
6293     ImplicitType, SourceLocation(),
6294     SpecifiedType, MD->getLocation());
6295 }
6296 
6297 void Sema::CheckDelayedMemberExceptionSpecs() {
6298   decltype(DelayedExceptionSpecChecks) Checks;
6299   decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
6300 
6301   std::swap(Checks, DelayedExceptionSpecChecks);
6302   std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
6303 
6304   // Perform any deferred checking of exception specifications for virtual
6305   // destructors.
6306   for (auto &Check : Checks)
6307     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
6308 
6309   // Check that any explicitly-defaulted methods have exception specifications
6310   // compatible with their implicit exception specifications.
6311   for (auto &Spec : Specs)
6312     CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
6313 }
6314 
6315 namespace {
6316 struct SpecialMemberDeletionInfo {
6317   Sema &S;
6318   CXXMethodDecl *MD;
6319   Sema::CXXSpecialMember CSM;
6320   Sema::InheritedConstructorInfo *ICI;
6321   bool Diagnose;
6322 
6323   // Properties of the special member, computed for convenience.
6324   bool IsConstructor, IsAssignment, IsMove, ConstArg;
6325   SourceLocation Loc;
6326 
6327   bool AllFieldsAreConst;
6328 
6329   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
6330                             Sema::CXXSpecialMember CSM,
6331                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
6332       : S(S), MD(MD), CSM(CSM), ICI(ICI), Diagnose(Diagnose),
6333         IsConstructor(false), IsAssignment(false), IsMove(false),
6334         ConstArg(false), Loc(MD->getLocation()), AllFieldsAreConst(true) {
6335     switch (CSM) {
6336       case Sema::CXXDefaultConstructor:
6337       case Sema::CXXCopyConstructor:
6338         IsConstructor = true;
6339         break;
6340       case Sema::CXXMoveConstructor:
6341         IsConstructor = true;
6342         IsMove = true;
6343         break;
6344       case Sema::CXXCopyAssignment:
6345         IsAssignment = true;
6346         break;
6347       case Sema::CXXMoveAssignment:
6348         IsAssignment = true;
6349         IsMove = true;
6350         break;
6351       case Sema::CXXDestructor:
6352         break;
6353       case Sema::CXXInvalid:
6354         llvm_unreachable("invalid special member kind");
6355     }
6356 
6357     if (MD->getNumParams()) {
6358       if (const ReferenceType *RT =
6359               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6360         ConstArg = RT->getPointeeType().isConstQualified();
6361     }
6362   }
6363 
6364   bool inUnion() const { return MD->getParent()->isUnion(); }
6365 
6366   Sema::CXXSpecialMember getEffectiveCSM() {
6367     return ICI ? Sema::CXXInvalid : CSM;
6368   }
6369 
6370   /// Look up the corresponding special member in the given class.
6371   Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
6372                                               unsigned Quals, bool IsMutable) {
6373     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6374                                        ConstArg && !IsMutable);
6375   }
6376 
6377   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6378 
6379   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
6380   bool shouldDeleteForField(FieldDecl *FD);
6381   bool shouldDeleteForAllConstMembers();
6382 
6383   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6384                                      unsigned Quals);
6385   bool shouldDeleteForSubobjectCall(Subobject Subobj,
6386                                     Sema::SpecialMemberOverloadResult *SMOR,
6387                                     bool IsDtorCallInCtor);
6388 
6389   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
6390 };
6391 }
6392 
6393 /// Is the given special member inaccessible when used on the given
6394 /// sub-object.
6395 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6396                                              CXXMethodDecl *target) {
6397   /// If we're operating on a base class, the object type is the
6398   /// type of this special member.
6399   QualType objectTy;
6400   AccessSpecifier access = target->getAccess();
6401   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6402     objectTy = S.Context.getTypeDeclType(MD->getParent());
6403     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6404 
6405   // If we're operating on a field, the object type is the type of the field.
6406   } else {
6407     objectTy = S.Context.getTypeDeclType(target->getParent());
6408   }
6409 
6410   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6411 }
6412 
6413 /// Check whether we should delete a special member due to the implicit
6414 /// definition containing a call to a special member of a subobject.
6415 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
6416     Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
6417     bool IsDtorCallInCtor) {
6418   CXXMethodDecl *Decl = SMOR->getMethod();
6419   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6420 
6421   int DiagKind = -1;
6422 
6423   if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
6424     DiagKind = !Decl ? 0 : 1;
6425   else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6426     DiagKind = 2;
6427   else if (!isAccessible(Subobj, Decl))
6428     DiagKind = 3;
6429   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6430            !Decl->isTrivial()) {
6431     // A member of a union must have a trivial corresponding special member.
6432     // As a weird special case, a destructor call from a union's constructor
6433     // must be accessible and non-deleted, but need not be trivial. Such a
6434     // destructor is never actually called, but is semantically checked as
6435     // if it were.
6436     DiagKind = 4;
6437   }
6438 
6439   if (DiagKind == -1)
6440     return false;
6441 
6442   if (Diagnose) {
6443     if (Field) {
6444       S.Diag(Field->getLocation(),
6445              diag::note_deleted_special_member_class_subobject)
6446         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
6447         << Field << DiagKind << IsDtorCallInCtor;
6448     } else {
6449       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6450       S.Diag(Base->getLocStart(),
6451              diag::note_deleted_special_member_class_subobject)
6452         << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6453         << Base->getType() << DiagKind << IsDtorCallInCtor;
6454     }
6455 
6456     if (DiagKind == 1)
6457       S.NoteDeletedFunction(Decl);
6458     // FIXME: Explain inaccessibility if DiagKind == 3.
6459   }
6460 
6461   return true;
6462 }
6463 
6464 /// Check whether we should delete a special member function due to having a
6465 /// direct or virtual base class or non-static data member of class type M.
6466 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
6467     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
6468   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6469   bool IsMutable = Field && Field->isMutable();
6470 
6471   // C++11 [class.ctor]p5:
6472   // -- any direct or virtual base class, or non-static data member with no
6473   //    brace-or-equal-initializer, has class type M (or array thereof) and
6474   //    either M has no default constructor or overload resolution as applied
6475   //    to M's default constructor results in an ambiguity or in a function
6476   //    that is deleted or inaccessible
6477   // C++11 [class.copy]p11, C++11 [class.copy]p23:
6478   // -- a direct or virtual base class B that cannot be copied/moved because
6479   //    overload resolution, as applied to B's corresponding special member,
6480   //    results in an ambiguity or a function that is deleted or inaccessible
6481   //    from the defaulted special member
6482   // C++11 [class.dtor]p5:
6483   // -- any direct or virtual base class [...] has a type with a destructor
6484   //    that is deleted or inaccessible
6485   if (!(CSM == Sema::CXXDefaultConstructor &&
6486         Field && Field->hasInClassInitializer()) &&
6487       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
6488                                    false))
6489     return true;
6490 
6491   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
6492   // -- any direct or virtual base class or non-static data member has a
6493   //    type with a destructor that is deleted or inaccessible
6494   if (IsConstructor) {
6495     Sema::SpecialMemberOverloadResult *SMOR =
6496         S.LookupSpecialMember(Class, Sema::CXXDestructor,
6497                               false, false, false, false, false);
6498     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
6499       return true;
6500   }
6501 
6502   return false;
6503 }
6504 
6505 /// Check whether we should delete a special member function due to the class
6506 /// having a particular direct or virtual base class.
6507 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
6508   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
6509   // If program is correct, BaseClass cannot be null, but if it is, the error
6510   // must be reported elsewhere.
6511   if (!BaseClass)
6512     return false;
6513   // If we have an inheriting constructor, check whether we're calling an
6514   // inherited constructor instead of a default constructor.
6515   if (ICI) {
6516     assert(CSM == Sema::CXXDefaultConstructor);
6517     auto *BaseCtor =
6518         ICI->findConstructorForBase(BaseClass, cast<CXXConstructorDecl>(MD)
6519                                                    ->getInheritedConstructor()
6520                                                    .getConstructor())
6521             .first;
6522     if (BaseCtor) {
6523       if (BaseCtor->isDeleted() && Diagnose) {
6524         S.Diag(Base->getLocStart(),
6525                diag::note_deleted_special_member_class_subobject)
6526           << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6527           << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false;
6528         S.NoteDeletedFunction(BaseCtor);
6529       }
6530       return BaseCtor->isDeleted();
6531     }
6532   }
6533   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
6534 }
6535 
6536 /// Check whether we should delete a special member function due to the class
6537 /// having a particular non-static data member.
6538 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
6539   QualType FieldType = S.Context.getBaseElementType(FD->getType());
6540   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
6541 
6542   if (CSM == Sema::CXXDefaultConstructor) {
6543     // For a default constructor, all references must be initialized in-class
6544     // and, if a union, it must have a non-const member.
6545     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
6546       if (Diagnose)
6547         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
6548           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
6549       return true;
6550     }
6551     // C++11 [class.ctor]p5: any non-variant non-static data member of
6552     // const-qualified type (or array thereof) with no
6553     // brace-or-equal-initializer does not have a user-provided default
6554     // constructor.
6555     if (!inUnion() && FieldType.isConstQualified() &&
6556         !FD->hasInClassInitializer() &&
6557         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
6558       if (Diagnose)
6559         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
6560           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
6561       return true;
6562     }
6563 
6564     if (inUnion() && !FieldType.isConstQualified())
6565       AllFieldsAreConst = false;
6566   } else if (CSM == Sema::CXXCopyConstructor) {
6567     // For a copy constructor, data members must not be of rvalue reference
6568     // type.
6569     if (FieldType->isRValueReferenceType()) {
6570       if (Diagnose)
6571         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
6572           << MD->getParent() << FD << FieldType;
6573       return true;
6574     }
6575   } else if (IsAssignment) {
6576     // For an assignment operator, data members must not be of reference type.
6577     if (FieldType->isReferenceType()) {
6578       if (Diagnose)
6579         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
6580           << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
6581       return true;
6582     }
6583     if (!FieldRecord && FieldType.isConstQualified()) {
6584       // C++11 [class.copy]p23:
6585       // -- a non-static data member of const non-class type (or array thereof)
6586       if (Diagnose)
6587         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
6588           << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
6589       return true;
6590     }
6591   }
6592 
6593   if (FieldRecord) {
6594     // Some additional restrictions exist on the variant members.
6595     if (!inUnion() && FieldRecord->isUnion() &&
6596         FieldRecord->isAnonymousStructOrUnion()) {
6597       bool AllVariantFieldsAreConst = true;
6598 
6599       // FIXME: Handle anonymous unions declared within anonymous unions.
6600       for (auto *UI : FieldRecord->fields()) {
6601         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
6602 
6603         if (!UnionFieldType.isConstQualified())
6604           AllVariantFieldsAreConst = false;
6605 
6606         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
6607         if (UnionFieldRecord &&
6608             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
6609                                           UnionFieldType.getCVRQualifiers()))
6610           return true;
6611       }
6612 
6613       // At least one member in each anonymous union must be non-const
6614       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
6615           !FieldRecord->field_empty()) {
6616         if (Diagnose)
6617           S.Diag(FieldRecord->getLocation(),
6618                  diag::note_deleted_default_ctor_all_const)
6619             << !!ICI << MD->getParent() << /*anonymous union*/1;
6620         return true;
6621       }
6622 
6623       // Don't check the implicit member of the anonymous union type.
6624       // This is technically non-conformant, but sanity demands it.
6625       return false;
6626     }
6627 
6628     if (shouldDeleteForClassSubobject(FieldRecord, FD,
6629                                       FieldType.getCVRQualifiers()))
6630       return true;
6631   }
6632 
6633   return false;
6634 }
6635 
6636 /// C++11 [class.ctor] p5:
6637 ///   A defaulted default constructor for a class X is defined as deleted if
6638 /// X is a union and all of its variant members are of const-qualified type.
6639 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
6640   // This is a silly definition, because it gives an empty union a deleted
6641   // default constructor. Don't do that.
6642   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
6643       !MD->getParent()->field_empty()) {
6644     if (Diagnose)
6645       S.Diag(MD->getParent()->getLocation(),
6646              diag::note_deleted_default_ctor_all_const)
6647         << !!ICI << MD->getParent() << /*not anonymous union*/0;
6648     return true;
6649   }
6650   return false;
6651 }
6652 
6653 /// Determine whether a defaulted special member function should be defined as
6654 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
6655 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
6656 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
6657                                      InheritedConstructorInfo *ICI,
6658                                      bool Diagnose) {
6659   if (MD->isInvalidDecl())
6660     return false;
6661   CXXRecordDecl *RD = MD->getParent();
6662   assert(!RD->isDependentType() && "do deletion after instantiation");
6663   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
6664     return false;
6665 
6666   // C++11 [expr.lambda.prim]p19:
6667   //   The closure type associated with a lambda-expression has a
6668   //   deleted (8.4.3) default constructor and a deleted copy
6669   //   assignment operator.
6670   if (RD->isLambda() &&
6671       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
6672     if (Diagnose)
6673       Diag(RD->getLocation(), diag::note_lambda_decl);
6674     return true;
6675   }
6676 
6677   // For an anonymous struct or union, the copy and assignment special members
6678   // will never be used, so skip the check. For an anonymous union declared at
6679   // namespace scope, the constructor and destructor are used.
6680   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
6681       RD->isAnonymousStructOrUnion())
6682     return false;
6683 
6684   // C++11 [class.copy]p7, p18:
6685   //   If the class definition declares a move constructor or move assignment
6686   //   operator, an implicitly declared copy constructor or copy assignment
6687   //   operator is defined as deleted.
6688   if (MD->isImplicit() &&
6689       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
6690     CXXMethodDecl *UserDeclaredMove = nullptr;
6691 
6692     // In Microsoft mode, a user-declared move only causes the deletion of the
6693     // corresponding copy operation, not both copy operations.
6694     if (RD->hasUserDeclaredMoveConstructor() &&
6695         (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
6696       if (!Diagnose) return true;
6697 
6698       // Find any user-declared move constructor.
6699       for (auto *I : RD->ctors()) {
6700         if (I->isMoveConstructor()) {
6701           UserDeclaredMove = I;
6702           break;
6703         }
6704       }
6705       assert(UserDeclaredMove);
6706     } else if (RD->hasUserDeclaredMoveAssignment() &&
6707                (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
6708       if (!Diagnose) return true;
6709 
6710       // Find any user-declared move assignment operator.
6711       for (auto *I : RD->methods()) {
6712         if (I->isMoveAssignmentOperator()) {
6713           UserDeclaredMove = I;
6714           break;
6715         }
6716       }
6717       assert(UserDeclaredMove);
6718     }
6719 
6720     if (UserDeclaredMove) {
6721       Diag(UserDeclaredMove->getLocation(),
6722            diag::note_deleted_copy_user_declared_move)
6723         << (CSM == CXXCopyAssignment) << RD
6724         << UserDeclaredMove->isMoveAssignmentOperator();
6725       return true;
6726     }
6727   }
6728 
6729   // Do access control from the special member function
6730   ContextRAII MethodContext(*this, MD);
6731 
6732   // C++11 [class.dtor]p5:
6733   // -- for a virtual destructor, lookup of the non-array deallocation function
6734   //    results in an ambiguity or in a function that is deleted or inaccessible
6735   if (CSM == CXXDestructor && MD->isVirtual()) {
6736     FunctionDecl *OperatorDelete = nullptr;
6737     DeclarationName Name =
6738       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6739     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
6740                                  OperatorDelete, false)) {
6741       if (Diagnose)
6742         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
6743       return true;
6744     }
6745   }
6746 
6747   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
6748 
6749   for (auto &BI : RD->bases())
6750     if (!BI.isVirtual() &&
6751         SMI.shouldDeleteForBase(&BI))
6752       return true;
6753 
6754   // Per DR1611, do not consider virtual bases of constructors of abstract
6755   // classes, since we are not going to construct them.
6756   if (!RD->isAbstract() || !SMI.IsConstructor) {
6757     for (auto &BI : RD->vbases())
6758       if (SMI.shouldDeleteForBase(&BI))
6759         return true;
6760   }
6761 
6762   for (auto *FI : RD->fields())
6763     if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
6764         SMI.shouldDeleteForField(FI))
6765       return true;
6766 
6767   if (SMI.shouldDeleteForAllConstMembers())
6768     return true;
6769 
6770   if (getLangOpts().CUDA) {
6771     // We should delete the special member in CUDA mode if target inference
6772     // failed.
6773     return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
6774                                                    Diagnose);
6775   }
6776 
6777   return false;
6778 }
6779 
6780 /// Perform lookup for a special member of the specified kind, and determine
6781 /// whether it is trivial. If the triviality can be determined without the
6782 /// lookup, skip it. This is intended for use when determining whether a
6783 /// special member of a containing object is trivial, and thus does not ever
6784 /// perform overload resolution for default constructors.
6785 ///
6786 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
6787 /// member that was most likely to be intended to be trivial, if any.
6788 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
6789                                      Sema::CXXSpecialMember CSM, unsigned Quals,
6790                                      bool ConstRHS, CXXMethodDecl **Selected) {
6791   if (Selected)
6792     *Selected = nullptr;
6793 
6794   switch (CSM) {
6795   case Sema::CXXInvalid:
6796     llvm_unreachable("not a special member");
6797 
6798   case Sema::CXXDefaultConstructor:
6799     // C++11 [class.ctor]p5:
6800     //   A default constructor is trivial if:
6801     //    - all the [direct subobjects] have trivial default constructors
6802     //
6803     // Note, no overload resolution is performed in this case.
6804     if (RD->hasTrivialDefaultConstructor())
6805       return true;
6806 
6807     if (Selected) {
6808       // If there's a default constructor which could have been trivial, dig it
6809       // out. Otherwise, if there's any user-provided default constructor, point
6810       // to that as an example of why there's not a trivial one.
6811       CXXConstructorDecl *DefCtor = nullptr;
6812       if (RD->needsImplicitDefaultConstructor())
6813         S.DeclareImplicitDefaultConstructor(RD);
6814       for (auto *CI : RD->ctors()) {
6815         if (!CI->isDefaultConstructor())
6816           continue;
6817         DefCtor = CI;
6818         if (!DefCtor->isUserProvided())
6819           break;
6820       }
6821 
6822       *Selected = DefCtor;
6823     }
6824 
6825     return false;
6826 
6827   case Sema::CXXDestructor:
6828     // C++11 [class.dtor]p5:
6829     //   A destructor is trivial if:
6830     //    - all the direct [subobjects] have trivial destructors
6831     if (RD->hasTrivialDestructor())
6832       return true;
6833 
6834     if (Selected) {
6835       if (RD->needsImplicitDestructor())
6836         S.DeclareImplicitDestructor(RD);
6837       *Selected = RD->getDestructor();
6838     }
6839 
6840     return false;
6841 
6842   case Sema::CXXCopyConstructor:
6843     // C++11 [class.copy]p12:
6844     //   A copy constructor is trivial if:
6845     //    - the constructor selected to copy each direct [subobject] is trivial
6846     if (RD->hasTrivialCopyConstructor()) {
6847       if (Quals == Qualifiers::Const)
6848         // We must either select the trivial copy constructor or reach an
6849         // ambiguity; no need to actually perform overload resolution.
6850         return true;
6851     } else if (!Selected) {
6852       return false;
6853     }
6854     // In C++98, we are not supposed to perform overload resolution here, but we
6855     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
6856     // cases like B as having a non-trivial copy constructor:
6857     //   struct A { template<typename T> A(T&); };
6858     //   struct B { mutable A a; };
6859     goto NeedOverloadResolution;
6860 
6861   case Sema::CXXCopyAssignment:
6862     // C++11 [class.copy]p25:
6863     //   A copy assignment operator is trivial if:
6864     //    - the assignment operator selected to copy each direct [subobject] is
6865     //      trivial
6866     if (RD->hasTrivialCopyAssignment()) {
6867       if (Quals == Qualifiers::Const)
6868         return true;
6869     } else if (!Selected) {
6870       return false;
6871     }
6872     // In C++98, we are not supposed to perform overload resolution here, but we
6873     // treat that as a language defect.
6874     goto NeedOverloadResolution;
6875 
6876   case Sema::CXXMoveConstructor:
6877   case Sema::CXXMoveAssignment:
6878   NeedOverloadResolution:
6879     Sema::SpecialMemberOverloadResult *SMOR =
6880         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
6881 
6882     // The standard doesn't describe how to behave if the lookup is ambiguous.
6883     // We treat it as not making the member non-trivial, just like the standard
6884     // mandates for the default constructor. This should rarely matter, because
6885     // the member will also be deleted.
6886     if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6887       return true;
6888 
6889     if (!SMOR->getMethod()) {
6890       assert(SMOR->getKind() ==
6891              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
6892       return false;
6893     }
6894 
6895     // We deliberately don't check if we found a deleted special member. We're
6896     // not supposed to!
6897     if (Selected)
6898       *Selected = SMOR->getMethod();
6899     return SMOR->getMethod()->isTrivial();
6900   }
6901 
6902   llvm_unreachable("unknown special method kind");
6903 }
6904 
6905 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
6906   for (auto *CI : RD->ctors())
6907     if (!CI->isImplicit())
6908       return CI;
6909 
6910   // Look for constructor templates.
6911   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
6912   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
6913     if (CXXConstructorDecl *CD =
6914           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
6915       return CD;
6916   }
6917 
6918   return nullptr;
6919 }
6920 
6921 /// The kind of subobject we are checking for triviality. The values of this
6922 /// enumeration are used in diagnostics.
6923 enum TrivialSubobjectKind {
6924   /// The subobject is a base class.
6925   TSK_BaseClass,
6926   /// The subobject is a non-static data member.
6927   TSK_Field,
6928   /// The object is actually the complete object.
6929   TSK_CompleteObject
6930 };
6931 
6932 /// Check whether the special member selected for a given type would be trivial.
6933 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
6934                                       QualType SubType, bool ConstRHS,
6935                                       Sema::CXXSpecialMember CSM,
6936                                       TrivialSubobjectKind Kind,
6937                                       bool Diagnose) {
6938   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
6939   if (!SubRD)
6940     return true;
6941 
6942   CXXMethodDecl *Selected;
6943   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
6944                                ConstRHS, Diagnose ? &Selected : nullptr))
6945     return true;
6946 
6947   if (Diagnose) {
6948     if (ConstRHS)
6949       SubType.addConst();
6950 
6951     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
6952       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
6953         << Kind << SubType.getUnqualifiedType();
6954       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
6955         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
6956     } else if (!Selected)
6957       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
6958         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
6959     else if (Selected->isUserProvided()) {
6960       if (Kind == TSK_CompleteObject)
6961         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
6962           << Kind << SubType.getUnqualifiedType() << CSM;
6963       else {
6964         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
6965           << Kind << SubType.getUnqualifiedType() << CSM;
6966         S.Diag(Selected->getLocation(), diag::note_declared_at);
6967       }
6968     } else {
6969       if (Kind != TSK_CompleteObject)
6970         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
6971           << Kind << SubType.getUnqualifiedType() << CSM;
6972 
6973       // Explain why the defaulted or deleted special member isn't trivial.
6974       S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
6975     }
6976   }
6977 
6978   return false;
6979 }
6980 
6981 /// Check whether the members of a class type allow a special member to be
6982 /// trivial.
6983 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
6984                                      Sema::CXXSpecialMember CSM,
6985                                      bool ConstArg, bool Diagnose) {
6986   for (const auto *FI : RD->fields()) {
6987     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
6988       continue;
6989 
6990     QualType FieldType = S.Context.getBaseElementType(FI->getType());
6991 
6992     // Pretend anonymous struct or union members are members of this class.
6993     if (FI->isAnonymousStructOrUnion()) {
6994       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
6995                                     CSM, ConstArg, Diagnose))
6996         return false;
6997       continue;
6998     }
6999 
7000     // C++11 [class.ctor]p5:
7001     //   A default constructor is trivial if [...]
7002     //    -- no non-static data member of its class has a
7003     //       brace-or-equal-initializer
7004     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7005       if (Diagnose)
7006         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
7007       return false;
7008     }
7009 
7010     // Objective C ARC 4.3.5:
7011     //   [...] nontrivally ownership-qualified types are [...] not trivially
7012     //   default constructible, copy constructible, move constructible, copy
7013     //   assignable, move assignable, or destructible [...]
7014     if (S.getLangOpts().ObjCAutoRefCount &&
7015         FieldType.hasNonTrivialObjCLifetime()) {
7016       if (Diagnose)
7017         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7018           << RD << FieldType.getObjCLifetime();
7019       return false;
7020     }
7021 
7022     bool ConstRHS = ConstArg && !FI->isMutable();
7023     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7024                                    CSM, TSK_Field, Diagnose))
7025       return false;
7026   }
7027 
7028   return true;
7029 }
7030 
7031 /// Diagnose why the specified class does not have a trivial special member of
7032 /// the given kind.
7033 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7034   QualType Ty = Context.getRecordType(RD);
7035 
7036   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7037   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
7038                             TSK_CompleteObject, /*Diagnose*/true);
7039 }
7040 
7041 /// Determine whether a defaulted or deleted special member function is trivial,
7042 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7043 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7044 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7045                                   bool Diagnose) {
7046   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7047 
7048   CXXRecordDecl *RD = MD->getParent();
7049 
7050   bool ConstArg = false;
7051 
7052   // C++11 [class.copy]p12, p25: [DR1593]
7053   //   A [special member] is trivial if [...] its parameter-type-list is
7054   //   equivalent to the parameter-type-list of an implicit declaration [...]
7055   switch (CSM) {
7056   case CXXDefaultConstructor:
7057   case CXXDestructor:
7058     // Trivial default constructors and destructors cannot have parameters.
7059     break;
7060 
7061   case CXXCopyConstructor:
7062   case CXXCopyAssignment: {
7063     // Trivial copy operations always have const, non-volatile parameter types.
7064     ConstArg = true;
7065     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7066     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7067     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7068       if (Diagnose)
7069         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7070           << Param0->getSourceRange() << Param0->getType()
7071           << Context.getLValueReferenceType(
7072                Context.getRecordType(RD).withConst());
7073       return false;
7074     }
7075     break;
7076   }
7077 
7078   case CXXMoveConstructor:
7079   case CXXMoveAssignment: {
7080     // Trivial move operations always have non-cv-qualified parameters.
7081     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7082     const RValueReferenceType *RT =
7083       Param0->getType()->getAs<RValueReferenceType>();
7084     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7085       if (Diagnose)
7086         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7087           << Param0->getSourceRange() << Param0->getType()
7088           << Context.getRValueReferenceType(Context.getRecordType(RD));
7089       return false;
7090     }
7091     break;
7092   }
7093 
7094   case CXXInvalid:
7095     llvm_unreachable("not a special member");
7096   }
7097 
7098   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7099     if (Diagnose)
7100       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7101            diag::note_nontrivial_default_arg)
7102         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7103     return false;
7104   }
7105   if (MD->isVariadic()) {
7106     if (Diagnose)
7107       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7108     return false;
7109   }
7110 
7111   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7112   //   A copy/move [constructor or assignment operator] is trivial if
7113   //    -- the [member] selected to copy/move each direct base class subobject
7114   //       is trivial
7115   //
7116   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7117   //   A [default constructor or destructor] is trivial if
7118   //    -- all the direct base classes have trivial [default constructors or
7119   //       destructors]
7120   for (const auto &BI : RD->bases())
7121     if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
7122                                    ConstArg, CSM, TSK_BaseClass, Diagnose))
7123       return false;
7124 
7125   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7126   //   A copy/move [constructor or assignment operator] for a class X is
7127   //   trivial if
7128   //    -- for each non-static data member of X that is of class type (or array
7129   //       thereof), the constructor selected to copy/move that member is
7130   //       trivial
7131   //
7132   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7133   //   A [default constructor or destructor] is trivial if
7134   //    -- for all of the non-static data members of its class that are of class
7135   //       type (or array thereof), each such class has a trivial [default
7136   //       constructor or destructor]
7137   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
7138     return false;
7139 
7140   // C++11 [class.dtor]p5:
7141   //   A destructor is trivial if [...]
7142   //    -- the destructor is not virtual
7143   if (CSM == CXXDestructor && MD->isVirtual()) {
7144     if (Diagnose)
7145       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7146     return false;
7147   }
7148 
7149   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7150   //   A [special member] for class X is trivial if [...]
7151   //    -- class X has no virtual functions and no virtual base classes
7152   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7153     if (!Diagnose)
7154       return false;
7155 
7156     if (RD->getNumVBases()) {
7157       // Check for virtual bases. We already know that the corresponding
7158       // member in all bases is trivial, so vbases must all be direct.
7159       CXXBaseSpecifier &BS = *RD->vbases_begin();
7160       assert(BS.isVirtual());
7161       Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
7162       return false;
7163     }
7164 
7165     // Must have a virtual method.
7166     for (const auto *MI : RD->methods()) {
7167       if (MI->isVirtual()) {
7168         SourceLocation MLoc = MI->getLocStart();
7169         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7170         return false;
7171       }
7172     }
7173 
7174     llvm_unreachable("dynamic class with no vbases and no virtual functions");
7175   }
7176 
7177   // Looks like it's trivial!
7178   return true;
7179 }
7180 
7181 namespace {
7182 struct FindHiddenVirtualMethod {
7183   Sema *S;
7184   CXXMethodDecl *Method;
7185   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7186   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7187 
7188 private:
7189   /// Check whether any most overriden method from MD in Methods
7190   static bool CheckMostOverridenMethods(
7191       const CXXMethodDecl *MD,
7192       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7193     if (MD->size_overridden_methods() == 0)
7194       return Methods.count(MD->getCanonicalDecl());
7195     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7196                                         E = MD->end_overridden_methods();
7197          I != E; ++I)
7198       if (CheckMostOverridenMethods(*I, Methods))
7199         return true;
7200     return false;
7201   }
7202 
7203 public:
7204   /// Member lookup function that determines whether a given C++
7205   /// method overloads virtual methods in a base class without overriding any,
7206   /// to be used with CXXRecordDecl::lookupInBases().
7207   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7208     RecordDecl *BaseRecord =
7209         Specifier->getType()->getAs<RecordType>()->getDecl();
7210 
7211     DeclarationName Name = Method->getDeclName();
7212     assert(Name.getNameKind() == DeclarationName::Identifier);
7213 
7214     bool foundSameNameMethod = false;
7215     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7216     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7217          Path.Decls = Path.Decls.slice(1)) {
7218       NamedDecl *D = Path.Decls.front();
7219       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7220         MD = MD->getCanonicalDecl();
7221         foundSameNameMethod = true;
7222         // Interested only in hidden virtual methods.
7223         if (!MD->isVirtual())
7224           continue;
7225         // If the method we are checking overrides a method from its base
7226         // don't warn about the other overloaded methods. Clang deviates from
7227         // GCC by only diagnosing overloads of inherited virtual functions that
7228         // do not override any other virtual functions in the base. GCC's
7229         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7230         // function from a base class. These cases may be better served by a
7231         // warning (not specific to virtual functions) on call sites when the
7232         // call would select a different function from the base class, were it
7233         // visible.
7234         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7235         if (!S->IsOverload(Method, MD, false))
7236           return true;
7237         // Collect the overload only if its hidden.
7238         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7239           overloadedMethods.push_back(MD);
7240       }
7241     }
7242 
7243     if (foundSameNameMethod)
7244       OverloadedMethods.append(overloadedMethods.begin(),
7245                                overloadedMethods.end());
7246     return foundSameNameMethod;
7247   }
7248 };
7249 } // end anonymous namespace
7250 
7251 /// \brief Add the most overriden methods from MD to Methods
7252 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
7253                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
7254   if (MD->size_overridden_methods() == 0)
7255     Methods.insert(MD->getCanonicalDecl());
7256   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7257                                       E = MD->end_overridden_methods();
7258        I != E; ++I)
7259     AddMostOverridenMethods(*I, Methods);
7260 }
7261 
7262 /// \brief Check if a method overloads virtual methods in a base class without
7263 /// overriding any.
7264 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7265                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7266   if (!MD->getDeclName().isIdentifier())
7267     return;
7268 
7269   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7270                      /*bool RecordPaths=*/false,
7271                      /*bool DetectVirtual=*/false);
7272   FindHiddenVirtualMethod FHVM;
7273   FHVM.Method = MD;
7274   FHVM.S = this;
7275 
7276   // Keep the base methods that were overriden or introduced in the subclass
7277   // by 'using' in a set. A base method not in this set is hidden.
7278   CXXRecordDecl *DC = MD->getParent();
7279   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7280   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7281     NamedDecl *ND = *I;
7282     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
7283       ND = shad->getTargetDecl();
7284     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7285       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
7286   }
7287 
7288   if (DC->lookupInBases(FHVM, Paths))
7289     OverloadedMethods = FHVM.OverloadedMethods;
7290 }
7291 
7292 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7293                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7294   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7295     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7296     PartialDiagnostic PD = PDiag(
7297          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7298     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7299     Diag(overloadedMD->getLocation(), PD);
7300   }
7301 }
7302 
7303 /// \brief Diagnose methods which overload virtual methods in a base class
7304 /// without overriding any.
7305 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7306   if (MD->isInvalidDecl())
7307     return;
7308 
7309   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
7310     return;
7311 
7312   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7313   FindHiddenVirtualMethods(MD, OverloadedMethods);
7314   if (!OverloadedMethods.empty()) {
7315     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7316       << MD << (OverloadedMethods.size() > 1);
7317 
7318     NoteHiddenVirtualMethods(MD, OverloadedMethods);
7319   }
7320 }
7321 
7322 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
7323                                              Decl *TagDecl,
7324                                              SourceLocation LBrac,
7325                                              SourceLocation RBrac,
7326                                              AttributeList *AttrList) {
7327   if (!TagDecl)
7328     return;
7329 
7330   AdjustDeclIfTemplate(TagDecl);
7331 
7332   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
7333     if (l->getKind() != AttributeList::AT_Visibility)
7334       continue;
7335     l->setInvalid();
7336     Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
7337       l->getName();
7338   }
7339 
7340   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
7341               // strict aliasing violation!
7342               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
7343               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
7344 
7345   CheckCompletedCXXClass(
7346                         dyn_cast_or_null<CXXRecordDecl>(TagDecl));
7347 }
7348 
7349 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7350 /// special functions, such as the default constructor, copy
7351 /// constructor, or destructor, to the given C++ class (C++
7352 /// [special]p1).  This routine can only be executed just before the
7353 /// definition of the class is complete.
7354 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
7355   if (ClassDecl->needsImplicitDefaultConstructor()) {
7356     ++ASTContext::NumImplicitDefaultConstructors;
7357 
7358     if (ClassDecl->hasInheritedConstructor())
7359       DeclareImplicitDefaultConstructor(ClassDecl);
7360   }
7361 
7362   if (ClassDecl->needsImplicitCopyConstructor()) {
7363     ++ASTContext::NumImplicitCopyConstructors;
7364 
7365     // If the properties or semantics of the copy constructor couldn't be
7366     // determined while the class was being declared, force a declaration
7367     // of it now.
7368     if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7369         ClassDecl->hasInheritedConstructor())
7370       DeclareImplicitCopyConstructor(ClassDecl);
7371   }
7372 
7373   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
7374     ++ASTContext::NumImplicitMoveConstructors;
7375 
7376     if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7377         ClassDecl->hasInheritedConstructor())
7378       DeclareImplicitMoveConstructor(ClassDecl);
7379   }
7380 
7381   if (ClassDecl->needsImplicitCopyAssignment()) {
7382     ++ASTContext::NumImplicitCopyAssignmentOperators;
7383 
7384     // If we have a dynamic class, then the copy assignment operator may be
7385     // virtual, so we have to declare it immediately. This ensures that, e.g.,
7386     // it shows up in the right place in the vtable and that we diagnose
7387     // problems with the implicit exception specification.
7388     if (ClassDecl->isDynamicClass() ||
7389         ClassDecl->needsOverloadResolutionForCopyAssignment() ||
7390         ClassDecl->hasInheritedAssignment())
7391       DeclareImplicitCopyAssignment(ClassDecl);
7392   }
7393 
7394   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
7395     ++ASTContext::NumImplicitMoveAssignmentOperators;
7396 
7397     // Likewise for the move assignment operator.
7398     if (ClassDecl->isDynamicClass() ||
7399         ClassDecl->needsOverloadResolutionForMoveAssignment() ||
7400         ClassDecl->hasInheritedAssignment())
7401       DeclareImplicitMoveAssignment(ClassDecl);
7402   }
7403 
7404   if (ClassDecl->needsImplicitDestructor()) {
7405     ++ASTContext::NumImplicitDestructors;
7406 
7407     // If we have a dynamic class, then the destructor may be virtual, so we
7408     // have to declare the destructor immediately. This ensures that, e.g., it
7409     // shows up in the right place in the vtable and that we diagnose problems
7410     // with the implicit exception specification.
7411     if (ClassDecl->isDynamicClass() ||
7412         ClassDecl->needsOverloadResolutionForDestructor())
7413       DeclareImplicitDestructor(ClassDecl);
7414   }
7415 }
7416 
7417 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
7418   if (!D)
7419     return 0;
7420 
7421   // The order of template parameters is not important here. All names
7422   // get added to the same scope.
7423   SmallVector<TemplateParameterList *, 4> ParameterLists;
7424 
7425   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
7426     D = TD->getTemplatedDecl();
7427 
7428   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
7429     ParameterLists.push_back(PSD->getTemplateParameters());
7430 
7431   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
7432     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
7433       ParameterLists.push_back(DD->getTemplateParameterList(i));
7434 
7435     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7436       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
7437         ParameterLists.push_back(FTD->getTemplateParameters());
7438     }
7439   }
7440 
7441   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
7442     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
7443       ParameterLists.push_back(TD->getTemplateParameterList(i));
7444 
7445     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
7446       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
7447         ParameterLists.push_back(CTD->getTemplateParameters());
7448     }
7449   }
7450 
7451   unsigned Count = 0;
7452   for (TemplateParameterList *Params : ParameterLists) {
7453     if (Params->size() > 0)
7454       // Ignore explicit specializations; they don't contribute to the template
7455       // depth.
7456       ++Count;
7457     for (NamedDecl *Param : *Params) {
7458       if (Param->getDeclName()) {
7459         S->AddDecl(Param);
7460         IdResolver.AddDecl(Param);
7461       }
7462     }
7463   }
7464 
7465   return Count;
7466 }
7467 
7468 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7469   if (!RecordD) return;
7470   AdjustDeclIfTemplate(RecordD);
7471   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
7472   PushDeclContext(S, Record);
7473 }
7474 
7475 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7476   if (!RecordD) return;
7477   PopDeclContext();
7478 }
7479 
7480 /// This is used to implement the constant expression evaluation part of the
7481 /// attribute enable_if extension. There is nothing in standard C++ which would
7482 /// require reentering parameters.
7483 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
7484   if (!Param)
7485     return;
7486 
7487   S->AddDecl(Param);
7488   if (Param->getDeclName())
7489     IdResolver.AddDecl(Param);
7490 }
7491 
7492 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
7493 /// parsing a top-level (non-nested) C++ class, and we are now
7494 /// parsing those parts of the given Method declaration that could
7495 /// not be parsed earlier (C++ [class.mem]p2), such as default
7496 /// arguments. This action should enter the scope of the given
7497 /// Method declaration as if we had just parsed the qualified method
7498 /// name. However, it should not bring the parameters into scope;
7499 /// that will be performed by ActOnDelayedCXXMethodParameter.
7500 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
7501 }
7502 
7503 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
7504 /// C++ method declaration. We're (re-)introducing the given
7505 /// function parameter into scope for use in parsing later parts of
7506 /// the method declaration. For example, we could see an
7507 /// ActOnParamDefaultArgument event for this parameter.
7508 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
7509   if (!ParamD)
7510     return;
7511 
7512   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
7513 
7514   // If this parameter has an unparsed default argument, clear it out
7515   // to make way for the parsed default argument.
7516   if (Param->hasUnparsedDefaultArg())
7517     Param->setDefaultArg(nullptr);
7518 
7519   S->AddDecl(Param);
7520   if (Param->getDeclName())
7521     IdResolver.AddDecl(Param);
7522 }
7523 
7524 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
7525 /// processing the delayed method declaration for Method. The method
7526 /// declaration is now considered finished. There may be a separate
7527 /// ActOnStartOfFunctionDef action later (not necessarily
7528 /// immediately!) for this method, if it was also defined inside the
7529 /// class body.
7530 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
7531   if (!MethodD)
7532     return;
7533 
7534   AdjustDeclIfTemplate(MethodD);
7535 
7536   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
7537 
7538   // Now that we have our default arguments, check the constructor
7539   // again. It could produce additional diagnostics or affect whether
7540   // the class has implicitly-declared destructors, among other
7541   // things.
7542   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
7543     CheckConstructor(Constructor);
7544 
7545   // Check the default arguments, which we may have added.
7546   if (!Method->isInvalidDecl())
7547     CheckCXXDefaultArguments(Method);
7548 }
7549 
7550 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
7551 /// the well-formedness of the constructor declarator @p D with type @p
7552 /// R. If there are any errors in the declarator, this routine will
7553 /// emit diagnostics and set the invalid bit to true.  In any case, the type
7554 /// will be updated to reflect a well-formed type for the constructor and
7555 /// returned.
7556 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
7557                                           StorageClass &SC) {
7558   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7559 
7560   // C++ [class.ctor]p3:
7561   //   A constructor shall not be virtual (10.3) or static (9.4). A
7562   //   constructor can be invoked for a const, volatile or const
7563   //   volatile object. A constructor shall not be declared const,
7564   //   volatile, or const volatile (9.3.2).
7565   if (isVirtual) {
7566     if (!D.isInvalidType())
7567       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7568         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
7569         << SourceRange(D.getIdentifierLoc());
7570     D.setInvalidType();
7571   }
7572   if (SC == SC_Static) {
7573     if (!D.isInvalidType())
7574       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7575         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7576         << SourceRange(D.getIdentifierLoc());
7577     D.setInvalidType();
7578     SC = SC_None;
7579   }
7580 
7581   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7582     diagnoseIgnoredQualifiers(
7583         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
7584         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
7585         D.getDeclSpec().getRestrictSpecLoc(),
7586         D.getDeclSpec().getAtomicSpecLoc());
7587     D.setInvalidType();
7588   }
7589 
7590   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7591   if (FTI.TypeQuals != 0) {
7592     if (FTI.TypeQuals & Qualifiers::Const)
7593       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7594         << "const" << SourceRange(D.getIdentifierLoc());
7595     if (FTI.TypeQuals & Qualifiers::Volatile)
7596       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7597         << "volatile" << SourceRange(D.getIdentifierLoc());
7598     if (FTI.TypeQuals & Qualifiers::Restrict)
7599       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7600         << "restrict" << SourceRange(D.getIdentifierLoc());
7601     D.setInvalidType();
7602   }
7603 
7604   // C++0x [class.ctor]p4:
7605   //   A constructor shall not be declared with a ref-qualifier.
7606   if (FTI.hasRefQualifier()) {
7607     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
7608       << FTI.RefQualifierIsLValueRef
7609       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7610     D.setInvalidType();
7611   }
7612 
7613   // Rebuild the function type "R" without any type qualifiers (in
7614   // case any of the errors above fired) and with "void" as the
7615   // return type, since constructors don't have return types.
7616   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
7617   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
7618     return R;
7619 
7620   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
7621   EPI.TypeQuals = 0;
7622   EPI.RefQualifier = RQ_None;
7623 
7624   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
7625 }
7626 
7627 /// CheckConstructor - Checks a fully-formed constructor for
7628 /// well-formedness, issuing any diagnostics required. Returns true if
7629 /// the constructor declarator is invalid.
7630 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
7631   CXXRecordDecl *ClassDecl
7632     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
7633   if (!ClassDecl)
7634     return Constructor->setInvalidDecl();
7635 
7636   // C++ [class.copy]p3:
7637   //   A declaration of a constructor for a class X is ill-formed if
7638   //   its first parameter is of type (optionally cv-qualified) X and
7639   //   either there are no other parameters or else all other
7640   //   parameters have default arguments.
7641   if (!Constructor->isInvalidDecl() &&
7642       ((Constructor->getNumParams() == 1) ||
7643        (Constructor->getNumParams() > 1 &&
7644         Constructor->getParamDecl(1)->hasDefaultArg())) &&
7645       Constructor->getTemplateSpecializationKind()
7646                                               != TSK_ImplicitInstantiation) {
7647     QualType ParamType = Constructor->getParamDecl(0)->getType();
7648     QualType ClassTy = Context.getTagDeclType(ClassDecl);
7649     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
7650       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
7651       const char *ConstRef
7652         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
7653                                                         : " const &";
7654       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
7655         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
7656 
7657       // FIXME: Rather that making the constructor invalid, we should endeavor
7658       // to fix the type.
7659       Constructor->setInvalidDecl();
7660     }
7661   }
7662 }
7663 
7664 /// CheckDestructor - Checks a fully-formed destructor definition for
7665 /// well-formedness, issuing any diagnostics required.  Returns true
7666 /// on error.
7667 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
7668   CXXRecordDecl *RD = Destructor->getParent();
7669 
7670   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
7671     SourceLocation Loc;
7672 
7673     if (!Destructor->isImplicit())
7674       Loc = Destructor->getLocation();
7675     else
7676       Loc = RD->getLocation();
7677 
7678     // If we have a virtual destructor, look up the deallocation function
7679     FunctionDecl *OperatorDelete = nullptr;
7680     DeclarationName Name =
7681     Context.DeclarationNames.getCXXOperatorName(OO_Delete);
7682     if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
7683       return true;
7684     // If there's no class-specific operator delete, look up the global
7685     // non-array delete.
7686     if (!OperatorDelete)
7687       OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
7688 
7689     MarkFunctionReferenced(Loc, OperatorDelete);
7690 
7691     Destructor->setOperatorDelete(OperatorDelete);
7692   }
7693 
7694   return false;
7695 }
7696 
7697 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
7698 /// the well-formednes of the destructor declarator @p D with type @p
7699 /// R. If there are any errors in the declarator, this routine will
7700 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
7701 /// will be updated to reflect a well-formed type for the destructor and
7702 /// returned.
7703 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
7704                                          StorageClass& SC) {
7705   // C++ [class.dtor]p1:
7706   //   [...] A typedef-name that names a class is a class-name
7707   //   (7.1.3); however, a typedef-name that names a class shall not
7708   //   be used as the identifier in the declarator for a destructor
7709   //   declaration.
7710   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
7711   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
7712     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
7713       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
7714   else if (const TemplateSpecializationType *TST =
7715              DeclaratorType->getAs<TemplateSpecializationType>())
7716     if (TST->isTypeAlias())
7717       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
7718         << DeclaratorType << 1;
7719 
7720   // C++ [class.dtor]p2:
7721   //   A destructor is used to destroy objects of its class type. A
7722   //   destructor takes no parameters, and no return type can be
7723   //   specified for it (not even void). The address of a destructor
7724   //   shall not be taken. A destructor shall not be static. A
7725   //   destructor can be invoked for a const, volatile or const
7726   //   volatile object. A destructor shall not be declared const,
7727   //   volatile or const volatile (9.3.2).
7728   if (SC == SC_Static) {
7729     if (!D.isInvalidType())
7730       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
7731         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7732         << SourceRange(D.getIdentifierLoc())
7733         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7734 
7735     SC = SC_None;
7736   }
7737   if (!D.isInvalidType()) {
7738     // Destructors don't have return types, but the parser will
7739     // happily parse something like:
7740     //
7741     //   class X {
7742     //     float ~X();
7743     //   };
7744     //
7745     // The return type will be eliminated later.
7746     if (D.getDeclSpec().hasTypeSpecifier())
7747       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
7748         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7749         << SourceRange(D.getIdentifierLoc());
7750     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7751       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
7752                                 SourceLocation(),
7753                                 D.getDeclSpec().getConstSpecLoc(),
7754                                 D.getDeclSpec().getVolatileSpecLoc(),
7755                                 D.getDeclSpec().getRestrictSpecLoc(),
7756                                 D.getDeclSpec().getAtomicSpecLoc());
7757       D.setInvalidType();
7758     }
7759   }
7760 
7761   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7762   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
7763     if (FTI.TypeQuals & Qualifiers::Const)
7764       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7765         << "const" << SourceRange(D.getIdentifierLoc());
7766     if (FTI.TypeQuals & Qualifiers::Volatile)
7767       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7768         << "volatile" << SourceRange(D.getIdentifierLoc());
7769     if (FTI.TypeQuals & Qualifiers::Restrict)
7770       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7771         << "restrict" << SourceRange(D.getIdentifierLoc());
7772     D.setInvalidType();
7773   }
7774 
7775   // C++0x [class.dtor]p2:
7776   //   A destructor shall not be declared with a ref-qualifier.
7777   if (FTI.hasRefQualifier()) {
7778     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
7779       << FTI.RefQualifierIsLValueRef
7780       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7781     D.setInvalidType();
7782   }
7783 
7784   // Make sure we don't have any parameters.
7785   if (FTIHasNonVoidParameters(FTI)) {
7786     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
7787 
7788     // Delete the parameters.
7789     FTI.freeParams();
7790     D.setInvalidType();
7791   }
7792 
7793   // Make sure the destructor isn't variadic.
7794   if (FTI.isVariadic) {
7795     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
7796     D.setInvalidType();
7797   }
7798 
7799   // Rebuild the function type "R" without any type qualifiers or
7800   // parameters (in case any of the errors above fired) and with
7801   // "void" as the return type, since destructors don't have return
7802   // types.
7803   if (!D.isInvalidType())
7804     return R;
7805 
7806   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
7807   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
7808   EPI.Variadic = false;
7809   EPI.TypeQuals = 0;
7810   EPI.RefQualifier = RQ_None;
7811   return Context.getFunctionType(Context.VoidTy, None, EPI);
7812 }
7813 
7814 static void extendLeft(SourceRange &R, SourceRange Before) {
7815   if (Before.isInvalid())
7816     return;
7817   R.setBegin(Before.getBegin());
7818   if (R.getEnd().isInvalid())
7819     R.setEnd(Before.getEnd());
7820 }
7821 
7822 static void extendRight(SourceRange &R, SourceRange After) {
7823   if (After.isInvalid())
7824     return;
7825   if (R.getBegin().isInvalid())
7826     R.setBegin(After.getBegin());
7827   R.setEnd(After.getEnd());
7828 }
7829 
7830 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
7831 /// well-formednes of the conversion function declarator @p D with
7832 /// type @p R. If there are any errors in the declarator, this routine
7833 /// will emit diagnostics and return true. Otherwise, it will return
7834 /// false. Either way, the type @p R will be updated to reflect a
7835 /// well-formed type for the conversion operator.
7836 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
7837                                      StorageClass& SC) {
7838   // C++ [class.conv.fct]p1:
7839   //   Neither parameter types nor return type can be specified. The
7840   //   type of a conversion function (8.3.5) is "function taking no
7841   //   parameter returning conversion-type-id."
7842   if (SC == SC_Static) {
7843     if (!D.isInvalidType())
7844       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
7845         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7846         << D.getName().getSourceRange();
7847     D.setInvalidType();
7848     SC = SC_None;
7849   }
7850 
7851   TypeSourceInfo *ConvTSI = nullptr;
7852   QualType ConvType =
7853       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
7854 
7855   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
7856     // Conversion functions don't have return types, but the parser will
7857     // happily parse something like:
7858     //
7859     //   class X {
7860     //     float operator bool();
7861     //   };
7862     //
7863     // The return type will be changed later anyway.
7864     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
7865       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7866       << SourceRange(D.getIdentifierLoc());
7867     D.setInvalidType();
7868   }
7869 
7870   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
7871 
7872   // Make sure we don't have any parameters.
7873   if (Proto->getNumParams() > 0) {
7874     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
7875 
7876     // Delete the parameters.
7877     D.getFunctionTypeInfo().freeParams();
7878     D.setInvalidType();
7879   } else if (Proto->isVariadic()) {
7880     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
7881     D.setInvalidType();
7882   }
7883 
7884   // Diagnose "&operator bool()" and other such nonsense.  This
7885   // is actually a gcc extension which we don't support.
7886   if (Proto->getReturnType() != ConvType) {
7887     bool NeedsTypedef = false;
7888     SourceRange Before, After;
7889 
7890     // Walk the chunks and extract information on them for our diagnostic.
7891     bool PastFunctionChunk = false;
7892     for (auto &Chunk : D.type_objects()) {
7893       switch (Chunk.Kind) {
7894       case DeclaratorChunk::Function:
7895         if (!PastFunctionChunk) {
7896           if (Chunk.Fun.HasTrailingReturnType) {
7897             TypeSourceInfo *TRT = nullptr;
7898             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
7899             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
7900           }
7901           PastFunctionChunk = true;
7902           break;
7903         }
7904         // Fall through.
7905       case DeclaratorChunk::Array:
7906         NeedsTypedef = true;
7907         extendRight(After, Chunk.getSourceRange());
7908         break;
7909 
7910       case DeclaratorChunk::Pointer:
7911       case DeclaratorChunk::BlockPointer:
7912       case DeclaratorChunk::Reference:
7913       case DeclaratorChunk::MemberPointer:
7914       case DeclaratorChunk::Pipe:
7915         extendLeft(Before, Chunk.getSourceRange());
7916         break;
7917 
7918       case DeclaratorChunk::Paren:
7919         extendLeft(Before, Chunk.Loc);
7920         extendRight(After, Chunk.EndLoc);
7921         break;
7922       }
7923     }
7924 
7925     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
7926                          After.isValid()  ? After.getBegin() :
7927                                             D.getIdentifierLoc();
7928     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
7929     DB << Before << After;
7930 
7931     if (!NeedsTypedef) {
7932       DB << /*don't need a typedef*/0;
7933 
7934       // If we can provide a correct fix-it hint, do so.
7935       if (After.isInvalid() && ConvTSI) {
7936         SourceLocation InsertLoc =
7937             getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
7938         DB << FixItHint::CreateInsertion(InsertLoc, " ")
7939            << FixItHint::CreateInsertionFromRange(
7940                   InsertLoc, CharSourceRange::getTokenRange(Before))
7941            << FixItHint::CreateRemoval(Before);
7942       }
7943     } else if (!Proto->getReturnType()->isDependentType()) {
7944       DB << /*typedef*/1 << Proto->getReturnType();
7945     } else if (getLangOpts().CPlusPlus11) {
7946       DB << /*alias template*/2 << Proto->getReturnType();
7947     } else {
7948       DB << /*might not be fixable*/3;
7949     }
7950 
7951     // Recover by incorporating the other type chunks into the result type.
7952     // Note, this does *not* change the name of the function. This is compatible
7953     // with the GCC extension:
7954     //   struct S { &operator int(); } s;
7955     //   int &r = s.operator int(); // ok in GCC
7956     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
7957     ConvType = Proto->getReturnType();
7958   }
7959 
7960   // C++ [class.conv.fct]p4:
7961   //   The conversion-type-id shall not represent a function type nor
7962   //   an array type.
7963   if (ConvType->isArrayType()) {
7964     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
7965     ConvType = Context.getPointerType(ConvType);
7966     D.setInvalidType();
7967   } else if (ConvType->isFunctionType()) {
7968     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
7969     ConvType = Context.getPointerType(ConvType);
7970     D.setInvalidType();
7971   }
7972 
7973   // Rebuild the function type "R" without any parameters (in case any
7974   // of the errors above fired) and with the conversion type as the
7975   // return type.
7976   if (D.isInvalidType())
7977     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
7978 
7979   // C++0x explicit conversion operators.
7980   if (D.getDeclSpec().isExplicitSpecified())
7981     Diag(D.getDeclSpec().getExplicitSpecLoc(),
7982          getLangOpts().CPlusPlus11 ?
7983            diag::warn_cxx98_compat_explicit_conversion_functions :
7984            diag::ext_explicit_conversion_functions)
7985       << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
7986 }
7987 
7988 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
7989 /// the declaration of the given C++ conversion function. This routine
7990 /// is responsible for recording the conversion function in the C++
7991 /// class, if possible.
7992 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
7993   assert(Conversion && "Expected to receive a conversion function declaration");
7994 
7995   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
7996 
7997   // Make sure we aren't redeclaring the conversion function.
7998   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
7999 
8000   // C++ [class.conv.fct]p1:
8001   //   [...] A conversion function is never used to convert a
8002   //   (possibly cv-qualified) object to the (possibly cv-qualified)
8003   //   same object type (or a reference to it), to a (possibly
8004   //   cv-qualified) base class of that type (or a reference to it),
8005   //   or to (possibly cv-qualified) void.
8006   // FIXME: Suppress this warning if the conversion function ends up being a
8007   // virtual function that overrides a virtual function in a base class.
8008   QualType ClassType
8009     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8010   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
8011     ConvType = ConvTypeRef->getPointeeType();
8012   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8013       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
8014     /* Suppress diagnostics for instantiations. */;
8015   else if (ConvType->isRecordType()) {
8016     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8017     if (ConvType == ClassType)
8018       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
8019         << ClassType;
8020     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
8021       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
8022         <<  ClassType << ConvType;
8023   } else if (ConvType->isVoidType()) {
8024     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
8025       << ClassType << ConvType;
8026   }
8027 
8028   if (FunctionTemplateDecl *ConversionTemplate
8029                                 = Conversion->getDescribedFunctionTemplate())
8030     return ConversionTemplate;
8031 
8032   return Conversion;
8033 }
8034 
8035 //===----------------------------------------------------------------------===//
8036 // Namespace Handling
8037 //===----------------------------------------------------------------------===//
8038 
8039 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
8040 /// reopened.
8041 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8042                                             SourceLocation Loc,
8043                                             IdentifierInfo *II, bool *IsInline,
8044                                             NamespaceDecl *PrevNS) {
8045   assert(*IsInline != PrevNS->isInline());
8046 
8047   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8048   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8049   // inline namespaces, with the intention of bringing names into namespace std.
8050   //
8051   // We support this just well enough to get that case working; this is not
8052   // sufficient to support reopening namespaces as inline in general.
8053   if (*IsInline && II && II->getName().startswith("__atomic") &&
8054       S.getSourceManager().isInSystemHeader(Loc)) {
8055     // Mark all prior declarations of the namespace as inline.
8056     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8057          NS = NS->getPreviousDecl())
8058       NS->setInline(*IsInline);
8059     // Patch up the lookup table for the containing namespace. This isn't really
8060     // correct, but it's good enough for this particular case.
8061     for (auto *I : PrevNS->decls())
8062       if (auto *ND = dyn_cast<NamedDecl>(I))
8063         PrevNS->getParent()->makeDeclVisibleInContext(ND);
8064     return;
8065   }
8066 
8067   if (PrevNS->isInline())
8068     // The user probably just forgot the 'inline', so suggest that it
8069     // be added back.
8070     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8071       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8072   else
8073     S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
8074 
8075   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8076   *IsInline = PrevNS->isInline();
8077 }
8078 
8079 /// ActOnStartNamespaceDef - This is called at the start of a namespace
8080 /// definition.
8081 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
8082                                    SourceLocation InlineLoc,
8083                                    SourceLocation NamespaceLoc,
8084                                    SourceLocation IdentLoc,
8085                                    IdentifierInfo *II,
8086                                    SourceLocation LBrace,
8087                                    AttributeList *AttrList,
8088                                    UsingDirectiveDecl *&UD) {
8089   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8090   // For anonymous namespace, take the location of the left brace.
8091   SourceLocation Loc = II ? IdentLoc : LBrace;
8092   bool IsInline = InlineLoc.isValid();
8093   bool IsInvalid = false;
8094   bool IsStd = false;
8095   bool AddToKnown = false;
8096   Scope *DeclRegionScope = NamespcScope->getParent();
8097 
8098   NamespaceDecl *PrevNS = nullptr;
8099   if (II) {
8100     // C++ [namespace.def]p2:
8101     //   The identifier in an original-namespace-definition shall not
8102     //   have been previously defined in the declarative region in
8103     //   which the original-namespace-definition appears. The
8104     //   identifier in an original-namespace-definition is the name of
8105     //   the namespace. Subsequently in that declarative region, it is
8106     //   treated as an original-namespace-name.
8107     //
8108     // Since namespace names are unique in their scope, and we don't
8109     // look through using directives, just look for any ordinary names
8110     // as if by qualified name lookup.
8111     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, ForRedeclaration);
8112     LookupQualifiedName(R, CurContext->getRedeclContext());
8113     NamedDecl *PrevDecl =
8114         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
8115     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
8116 
8117     if (PrevNS) {
8118       // This is an extended namespace definition.
8119       if (IsInline != PrevNS->isInline())
8120         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8121                                         &IsInline, PrevNS);
8122     } else if (PrevDecl) {
8123       // This is an invalid name redefinition.
8124       Diag(Loc, diag::err_redefinition_different_kind)
8125         << II;
8126       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8127       IsInvalid = true;
8128       // Continue on to push Namespc as current DeclContext and return it.
8129     } else if (II->isStr("std") &&
8130                CurContext->getRedeclContext()->isTranslationUnit()) {
8131       // This is the first "real" definition of the namespace "std", so update
8132       // our cache of the "std" namespace to point at this definition.
8133       PrevNS = getStdNamespace();
8134       IsStd = true;
8135       AddToKnown = !IsInline;
8136     } else {
8137       // We've seen this namespace for the first time.
8138       AddToKnown = !IsInline;
8139     }
8140   } else {
8141     // Anonymous namespaces.
8142 
8143     // Determine whether the parent already has an anonymous namespace.
8144     DeclContext *Parent = CurContext->getRedeclContext();
8145     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8146       PrevNS = TU->getAnonymousNamespace();
8147     } else {
8148       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
8149       PrevNS = ND->getAnonymousNamespace();
8150     }
8151 
8152     if (PrevNS && IsInline != PrevNS->isInline())
8153       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8154                                       &IsInline, PrevNS);
8155   }
8156 
8157   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8158                                                  StartLoc, Loc, II, PrevNS);
8159   if (IsInvalid)
8160     Namespc->setInvalidDecl();
8161 
8162   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
8163 
8164   // FIXME: Should we be merging attributes?
8165   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
8166     PushNamespaceVisibilityAttr(Attr, Loc);
8167 
8168   if (IsStd)
8169     StdNamespace = Namespc;
8170   if (AddToKnown)
8171     KnownNamespaces[Namespc] = false;
8172 
8173   if (II) {
8174     PushOnScopeChains(Namespc, DeclRegionScope);
8175   } else {
8176     // Link the anonymous namespace into its parent.
8177     DeclContext *Parent = CurContext->getRedeclContext();
8178     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8179       TU->setAnonymousNamespace(Namespc);
8180     } else {
8181       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
8182     }
8183 
8184     CurContext->addDecl(Namespc);
8185 
8186     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
8187     //   behaves as if it were replaced by
8188     //     namespace unique { /* empty body */ }
8189     //     using namespace unique;
8190     //     namespace unique { namespace-body }
8191     //   where all occurrences of 'unique' in a translation unit are
8192     //   replaced by the same identifier and this identifier differs
8193     //   from all other identifiers in the entire program.
8194 
8195     // We just create the namespace with an empty name and then add an
8196     // implicit using declaration, just like the standard suggests.
8197     //
8198     // CodeGen enforces the "universally unique" aspect by giving all
8199     // declarations semantically contained within an anonymous
8200     // namespace internal linkage.
8201 
8202     if (!PrevNS) {
8203       UD = UsingDirectiveDecl::Create(Context, Parent,
8204                                       /* 'using' */ LBrace,
8205                                       /* 'namespace' */ SourceLocation(),
8206                                       /* qualifier */ NestedNameSpecifierLoc(),
8207                                       /* identifier */ SourceLocation(),
8208                                       Namespc,
8209                                       /* Ancestor */ Parent);
8210       UD->setImplicit();
8211       Parent->addDecl(UD);
8212     }
8213   }
8214 
8215   ActOnDocumentableDecl(Namespc);
8216 
8217   // Although we could have an invalid decl (i.e. the namespace name is a
8218   // redefinition), push it as current DeclContext and try to continue parsing.
8219   // FIXME: We should be able to push Namespc here, so that the each DeclContext
8220   // for the namespace has the declarations that showed up in that particular
8221   // namespace definition.
8222   PushDeclContext(NamespcScope, Namespc);
8223   return Namespc;
8224 }
8225 
8226 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
8227 /// is a namespace alias, returns the namespace it points to.
8228 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
8229   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
8230     return AD->getNamespace();
8231   return dyn_cast_or_null<NamespaceDecl>(D);
8232 }
8233 
8234 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
8235 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
8236 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
8237   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
8238   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
8239   Namespc->setRBraceLoc(RBrace);
8240   PopDeclContext();
8241   if (Namespc->hasAttr<VisibilityAttr>())
8242     PopPragmaVisibility(true, RBrace);
8243 }
8244 
8245 CXXRecordDecl *Sema::getStdBadAlloc() const {
8246   return cast_or_null<CXXRecordDecl>(
8247                                   StdBadAlloc.get(Context.getExternalSource()));
8248 }
8249 
8250 NamespaceDecl *Sema::getStdNamespace() const {
8251   return cast_or_null<NamespaceDecl>(
8252                                  StdNamespace.get(Context.getExternalSource()));
8253 }
8254 
8255 /// \brief Retrieve the special "std" namespace, which may require us to
8256 /// implicitly define the namespace.
8257 NamespaceDecl *Sema::getOrCreateStdNamespace() {
8258   if (!StdNamespace) {
8259     // The "std" namespace has not yet been defined, so build one implicitly.
8260     StdNamespace = NamespaceDecl::Create(Context,
8261                                          Context.getTranslationUnitDecl(),
8262                                          /*Inline=*/false,
8263                                          SourceLocation(), SourceLocation(),
8264                                          &PP.getIdentifierTable().get("std"),
8265                                          /*PrevDecl=*/nullptr);
8266     getStdNamespace()->setImplicit(true);
8267   }
8268 
8269   return getStdNamespace();
8270 }
8271 
8272 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
8273   assert(getLangOpts().CPlusPlus &&
8274          "Looking for std::initializer_list outside of C++.");
8275 
8276   // We're looking for implicit instantiations of
8277   // template <typename E> class std::initializer_list.
8278 
8279   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
8280     return false;
8281 
8282   ClassTemplateDecl *Template = nullptr;
8283   const TemplateArgument *Arguments = nullptr;
8284 
8285   if (const RecordType *RT = Ty->getAs<RecordType>()) {
8286 
8287     ClassTemplateSpecializationDecl *Specialization =
8288         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
8289     if (!Specialization)
8290       return false;
8291 
8292     Template = Specialization->getSpecializedTemplate();
8293     Arguments = Specialization->getTemplateArgs().data();
8294   } else if (const TemplateSpecializationType *TST =
8295                  Ty->getAs<TemplateSpecializationType>()) {
8296     Template = dyn_cast_or_null<ClassTemplateDecl>(
8297         TST->getTemplateName().getAsTemplateDecl());
8298     Arguments = TST->getArgs();
8299   }
8300   if (!Template)
8301     return false;
8302 
8303   if (!StdInitializerList) {
8304     // Haven't recognized std::initializer_list yet, maybe this is it.
8305     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
8306     if (TemplateClass->getIdentifier() !=
8307             &PP.getIdentifierTable().get("initializer_list") ||
8308         !getStdNamespace()->InEnclosingNamespaceSetOf(
8309             TemplateClass->getDeclContext()))
8310       return false;
8311     // This is a template called std::initializer_list, but is it the right
8312     // template?
8313     TemplateParameterList *Params = Template->getTemplateParameters();
8314     if (Params->getMinRequiredArguments() != 1)
8315       return false;
8316     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
8317       return false;
8318 
8319     // It's the right template.
8320     StdInitializerList = Template;
8321   }
8322 
8323   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
8324     return false;
8325 
8326   // This is an instance of std::initializer_list. Find the argument type.
8327   if (Element)
8328     *Element = Arguments[0].getAsType();
8329   return true;
8330 }
8331 
8332 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
8333   NamespaceDecl *Std = S.getStdNamespace();
8334   if (!Std) {
8335     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
8336     return nullptr;
8337   }
8338 
8339   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
8340                       Loc, Sema::LookupOrdinaryName);
8341   if (!S.LookupQualifiedName(Result, Std)) {
8342     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
8343     return nullptr;
8344   }
8345   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
8346   if (!Template) {
8347     Result.suppressDiagnostics();
8348     // We found something weird. Complain about the first thing we found.
8349     NamedDecl *Found = *Result.begin();
8350     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
8351     return nullptr;
8352   }
8353 
8354   // We found some template called std::initializer_list. Now verify that it's
8355   // correct.
8356   TemplateParameterList *Params = Template->getTemplateParameters();
8357   if (Params->getMinRequiredArguments() != 1 ||
8358       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
8359     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
8360     return nullptr;
8361   }
8362 
8363   return Template;
8364 }
8365 
8366 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
8367   if (!StdInitializerList) {
8368     StdInitializerList = LookupStdInitializerList(*this, Loc);
8369     if (!StdInitializerList)
8370       return QualType();
8371   }
8372 
8373   TemplateArgumentListInfo Args(Loc, Loc);
8374   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
8375                                        Context.getTrivialTypeSourceInfo(Element,
8376                                                                         Loc)));
8377   return Context.getCanonicalType(
8378       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
8379 }
8380 
8381 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
8382   // C++ [dcl.init.list]p2:
8383   //   A constructor is an initializer-list constructor if its first parameter
8384   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
8385   //   std::initializer_list<E> for some type E, and either there are no other
8386   //   parameters or else all other parameters have default arguments.
8387   if (Ctor->getNumParams() < 1 ||
8388       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
8389     return false;
8390 
8391   QualType ArgType = Ctor->getParamDecl(0)->getType();
8392   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
8393     ArgType = RT->getPointeeType().getUnqualifiedType();
8394 
8395   return isStdInitializerList(ArgType, nullptr);
8396 }
8397 
8398 /// \brief Determine whether a using statement is in a context where it will be
8399 /// apply in all contexts.
8400 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
8401   switch (CurContext->getDeclKind()) {
8402     case Decl::TranslationUnit:
8403       return true;
8404     case Decl::LinkageSpec:
8405       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
8406     default:
8407       return false;
8408   }
8409 }
8410 
8411 namespace {
8412 
8413 // Callback to only accept typo corrections that are namespaces.
8414 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
8415 public:
8416   bool ValidateCandidate(const TypoCorrection &candidate) override {
8417     if (NamedDecl *ND = candidate.getCorrectionDecl())
8418       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
8419     return false;
8420   }
8421 };
8422 
8423 }
8424 
8425 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
8426                                        CXXScopeSpec &SS,
8427                                        SourceLocation IdentLoc,
8428                                        IdentifierInfo *Ident) {
8429   R.clear();
8430   if (TypoCorrection Corrected =
8431           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
8432                         llvm::make_unique<NamespaceValidatorCCC>(),
8433                         Sema::CTK_ErrorRecovery)) {
8434     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
8435       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
8436       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
8437                               Ident->getName().equals(CorrectedStr);
8438       S.diagnoseTypo(Corrected,
8439                      S.PDiag(diag::err_using_directive_member_suggest)
8440                        << Ident << DC << DroppedSpecifier << SS.getRange(),
8441                      S.PDiag(diag::note_namespace_defined_here));
8442     } else {
8443       S.diagnoseTypo(Corrected,
8444                      S.PDiag(diag::err_using_directive_suggest) << Ident,
8445                      S.PDiag(diag::note_namespace_defined_here));
8446     }
8447     R.addDecl(Corrected.getFoundDecl());
8448     return true;
8449   }
8450   return false;
8451 }
8452 
8453 Decl *Sema::ActOnUsingDirective(Scope *S,
8454                                           SourceLocation UsingLoc,
8455                                           SourceLocation NamespcLoc,
8456                                           CXXScopeSpec &SS,
8457                                           SourceLocation IdentLoc,
8458                                           IdentifierInfo *NamespcName,
8459                                           AttributeList *AttrList) {
8460   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
8461   assert(NamespcName && "Invalid NamespcName.");
8462   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
8463 
8464   // This can only happen along a recovery path.
8465   while (S->isTemplateParamScope())
8466     S = S->getParent();
8467   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
8468 
8469   UsingDirectiveDecl *UDir = nullptr;
8470   NestedNameSpecifier *Qualifier = nullptr;
8471   if (SS.isSet())
8472     Qualifier = SS.getScopeRep();
8473 
8474   // Lookup namespace name.
8475   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
8476   LookupParsedName(R, S, &SS);
8477   if (R.isAmbiguous())
8478     return nullptr;
8479 
8480   if (R.empty()) {
8481     R.clear();
8482     // Allow "using namespace std;" or "using namespace ::std;" even if
8483     // "std" hasn't been defined yet, for GCC compatibility.
8484     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
8485         NamespcName->isStr("std")) {
8486       Diag(IdentLoc, diag::ext_using_undefined_std);
8487       R.addDecl(getOrCreateStdNamespace());
8488       R.resolveKind();
8489     }
8490     // Otherwise, attempt typo correction.
8491     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
8492   }
8493 
8494   if (!R.empty()) {
8495     NamedDecl *Named = R.getRepresentativeDecl();
8496     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
8497     assert(NS && "expected namespace decl");
8498 
8499     // The use of a nested name specifier may trigger deprecation warnings.
8500     DiagnoseUseOfDecl(Named, IdentLoc);
8501 
8502     // C++ [namespace.udir]p1:
8503     //   A using-directive specifies that the names in the nominated
8504     //   namespace can be used in the scope in which the
8505     //   using-directive appears after the using-directive. During
8506     //   unqualified name lookup (3.4.1), the names appear as if they
8507     //   were declared in the nearest enclosing namespace which
8508     //   contains both the using-directive and the nominated
8509     //   namespace. [Note: in this context, "contains" means "contains
8510     //   directly or indirectly". ]
8511 
8512     // Find enclosing context containing both using-directive and
8513     // nominated namespace.
8514     DeclContext *CommonAncestor = cast<DeclContext>(NS);
8515     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
8516       CommonAncestor = CommonAncestor->getParent();
8517 
8518     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
8519                                       SS.getWithLocInContext(Context),
8520                                       IdentLoc, Named, CommonAncestor);
8521 
8522     if (IsUsingDirectiveInToplevelContext(CurContext) &&
8523         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
8524       Diag(IdentLoc, diag::warn_using_directive_in_header);
8525     }
8526 
8527     PushUsingDirective(S, UDir);
8528   } else {
8529     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
8530   }
8531 
8532   if (UDir)
8533     ProcessDeclAttributeList(S, UDir, AttrList);
8534 
8535   return UDir;
8536 }
8537 
8538 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
8539   // If the scope has an associated entity and the using directive is at
8540   // namespace or translation unit scope, add the UsingDirectiveDecl into
8541   // its lookup structure so qualified name lookup can find it.
8542   DeclContext *Ctx = S->getEntity();
8543   if (Ctx && !Ctx->isFunctionOrMethod())
8544     Ctx->addDecl(UDir);
8545   else
8546     // Otherwise, it is at block scope. The using-directives will affect lookup
8547     // only to the end of the scope.
8548     S->PushUsingDirective(UDir);
8549 }
8550 
8551 
8552 Decl *Sema::ActOnUsingDeclaration(Scope *S,
8553                                   AccessSpecifier AS,
8554                                   bool HasUsingKeyword,
8555                                   SourceLocation UsingLoc,
8556                                   CXXScopeSpec &SS,
8557                                   UnqualifiedId &Name,
8558                                   AttributeList *AttrList,
8559                                   bool HasTypenameKeyword,
8560                                   SourceLocation TypenameLoc) {
8561   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
8562 
8563   switch (Name.getKind()) {
8564   case UnqualifiedId::IK_ImplicitSelfParam:
8565   case UnqualifiedId::IK_Identifier:
8566   case UnqualifiedId::IK_OperatorFunctionId:
8567   case UnqualifiedId::IK_LiteralOperatorId:
8568   case UnqualifiedId::IK_ConversionFunctionId:
8569     break;
8570 
8571   case UnqualifiedId::IK_ConstructorName:
8572   case UnqualifiedId::IK_ConstructorTemplateId:
8573     // C++11 inheriting constructors.
8574     Diag(Name.getLocStart(),
8575          getLangOpts().CPlusPlus11 ?
8576            diag::warn_cxx98_compat_using_decl_constructor :
8577            diag::err_using_decl_constructor)
8578       << SS.getRange();
8579 
8580     if (getLangOpts().CPlusPlus11) break;
8581 
8582     return nullptr;
8583 
8584   case UnqualifiedId::IK_DestructorName:
8585     Diag(Name.getLocStart(), diag::err_using_decl_destructor)
8586       << SS.getRange();
8587     return nullptr;
8588 
8589   case UnqualifiedId::IK_TemplateId:
8590     Diag(Name.getLocStart(), diag::err_using_decl_template_id)
8591       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
8592     return nullptr;
8593   }
8594 
8595   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
8596   DeclarationName TargetName = TargetNameInfo.getName();
8597   if (!TargetName)
8598     return nullptr;
8599 
8600   // Warn about access declarations.
8601   if (!HasUsingKeyword) {
8602     Diag(Name.getLocStart(),
8603          getLangOpts().CPlusPlus11 ? diag::err_access_decl
8604                                    : diag::warn_access_decl_deprecated)
8605       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
8606   }
8607 
8608   if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
8609       DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
8610     return nullptr;
8611 
8612   NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
8613                                         TargetNameInfo, AttrList,
8614                                         /* IsInstantiation */ false,
8615                                         HasTypenameKeyword, TypenameLoc);
8616   if (UD)
8617     PushOnScopeChains(UD, S, /*AddToContext*/ false);
8618 
8619   return UD;
8620 }
8621 
8622 /// \brief Determine whether a using declaration considers the given
8623 /// declarations as "equivalent", e.g., if they are redeclarations of
8624 /// the same entity or are both typedefs of the same type.
8625 static bool
8626 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
8627   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
8628     return true;
8629 
8630   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
8631     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
8632       return Context.hasSameType(TD1->getUnderlyingType(),
8633                                  TD2->getUnderlyingType());
8634 
8635   return false;
8636 }
8637 
8638 
8639 /// Determines whether to create a using shadow decl for a particular
8640 /// decl, given the set of decls existing prior to this using lookup.
8641 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
8642                                 const LookupResult &Previous,
8643                                 UsingShadowDecl *&PrevShadow) {
8644   // Diagnose finding a decl which is not from a base class of the
8645   // current class.  We do this now because there are cases where this
8646   // function will silently decide not to build a shadow decl, which
8647   // will pre-empt further diagnostics.
8648   //
8649   // We don't need to do this in C++11 because we do the check once on
8650   // the qualifier.
8651   //
8652   // FIXME: diagnose the following if we care enough:
8653   //   struct A { int foo; };
8654   //   struct B : A { using A::foo; };
8655   //   template <class T> struct C : A {};
8656   //   template <class T> struct D : C<T> { using B::foo; } // <---
8657   // This is invalid (during instantiation) in C++03 because B::foo
8658   // resolves to the using decl in B, which is not a base class of D<T>.
8659   // We can't diagnose it immediately because C<T> is an unknown
8660   // specialization.  The UsingShadowDecl in D<T> then points directly
8661   // to A::foo, which will look well-formed when we instantiate.
8662   // The right solution is to not collapse the shadow-decl chain.
8663   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
8664     DeclContext *OrigDC = Orig->getDeclContext();
8665 
8666     // Handle enums and anonymous structs.
8667     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
8668     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
8669     while (OrigRec->isAnonymousStructOrUnion())
8670       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
8671 
8672     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
8673       if (OrigDC == CurContext) {
8674         Diag(Using->getLocation(),
8675              diag::err_using_decl_nested_name_specifier_is_current_class)
8676           << Using->getQualifierLoc().getSourceRange();
8677         Diag(Orig->getLocation(), diag::note_using_decl_target);
8678         return true;
8679       }
8680 
8681       Diag(Using->getQualifierLoc().getBeginLoc(),
8682            diag::err_using_decl_nested_name_specifier_is_not_base_class)
8683         << Using->getQualifier()
8684         << cast<CXXRecordDecl>(CurContext)
8685         << Using->getQualifierLoc().getSourceRange();
8686       Diag(Orig->getLocation(), diag::note_using_decl_target);
8687       return true;
8688     }
8689   }
8690 
8691   if (Previous.empty()) return false;
8692 
8693   NamedDecl *Target = Orig;
8694   if (isa<UsingShadowDecl>(Target))
8695     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
8696 
8697   // If the target happens to be one of the previous declarations, we
8698   // don't have a conflict.
8699   //
8700   // FIXME: but we might be increasing its access, in which case we
8701   // should redeclare it.
8702   NamedDecl *NonTag = nullptr, *Tag = nullptr;
8703   bool FoundEquivalentDecl = false;
8704   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8705          I != E; ++I) {
8706     NamedDecl *D = (*I)->getUnderlyingDecl();
8707     // We can have UsingDecls in our Previous results because we use the same
8708     // LookupResult for checking whether the UsingDecl itself is a valid
8709     // redeclaration.
8710     if (isa<UsingDecl>(D))
8711       continue;
8712 
8713     if (IsEquivalentForUsingDecl(Context, D, Target)) {
8714       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
8715         PrevShadow = Shadow;
8716       FoundEquivalentDecl = true;
8717     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
8718       // We don't conflict with an existing using shadow decl of an equivalent
8719       // declaration, but we're not a redeclaration of it.
8720       FoundEquivalentDecl = true;
8721     }
8722 
8723     if (isVisible(D))
8724       (isa<TagDecl>(D) ? Tag : NonTag) = D;
8725   }
8726 
8727   if (FoundEquivalentDecl)
8728     return false;
8729 
8730   if (FunctionDecl *FD = Target->getAsFunction()) {
8731     NamedDecl *OldDecl = nullptr;
8732     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
8733                           /*IsForUsingDecl*/ true)) {
8734     case Ovl_Overload:
8735       return false;
8736 
8737     case Ovl_NonFunction:
8738       Diag(Using->getLocation(), diag::err_using_decl_conflict);
8739       break;
8740 
8741     // We found a decl with the exact signature.
8742     case Ovl_Match:
8743       // If we're in a record, we want to hide the target, so we
8744       // return true (without a diagnostic) to tell the caller not to
8745       // build a shadow decl.
8746       if (CurContext->isRecord())
8747         return true;
8748 
8749       // If we're not in a record, this is an error.
8750       Diag(Using->getLocation(), diag::err_using_decl_conflict);
8751       break;
8752     }
8753 
8754     Diag(Target->getLocation(), diag::note_using_decl_target);
8755     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
8756     return true;
8757   }
8758 
8759   // Target is not a function.
8760 
8761   if (isa<TagDecl>(Target)) {
8762     // No conflict between a tag and a non-tag.
8763     if (!Tag) return false;
8764 
8765     Diag(Using->getLocation(), diag::err_using_decl_conflict);
8766     Diag(Target->getLocation(), diag::note_using_decl_target);
8767     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
8768     return true;
8769   }
8770 
8771   // No conflict between a tag and a non-tag.
8772   if (!NonTag) return false;
8773 
8774   Diag(Using->getLocation(), diag::err_using_decl_conflict);
8775   Diag(Target->getLocation(), diag::note_using_decl_target);
8776   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
8777   return true;
8778 }
8779 
8780 /// Determine whether a direct base class is a virtual base class.
8781 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
8782   if (!Derived->getNumVBases())
8783     return false;
8784   for (auto &B : Derived->bases())
8785     if (B.getType()->getAsCXXRecordDecl() == Base)
8786       return B.isVirtual();
8787   llvm_unreachable("not a direct base class");
8788 }
8789 
8790 /// Builds a shadow declaration corresponding to a 'using' declaration.
8791 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
8792                                             UsingDecl *UD,
8793                                             NamedDecl *Orig,
8794                                             UsingShadowDecl *PrevDecl) {
8795   // If we resolved to another shadow declaration, just coalesce them.
8796   NamedDecl *Target = Orig;
8797   if (isa<UsingShadowDecl>(Target)) {
8798     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
8799     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
8800   }
8801 
8802   NamedDecl *NonTemplateTarget = Target;
8803   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
8804     NonTemplateTarget = TargetTD->getTemplatedDecl();
8805 
8806   UsingShadowDecl *Shadow;
8807   if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
8808     bool IsVirtualBase =
8809         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
8810                             UD->getQualifier()->getAsRecordDecl());
8811     Shadow = ConstructorUsingShadowDecl::Create(
8812         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
8813   } else {
8814     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
8815                                      Target);
8816   }
8817   UD->addShadowDecl(Shadow);
8818 
8819   Shadow->setAccess(UD->getAccess());
8820   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
8821     Shadow->setInvalidDecl();
8822 
8823   Shadow->setPreviousDecl(PrevDecl);
8824 
8825   if (S)
8826     PushOnScopeChains(Shadow, S);
8827   else
8828     CurContext->addDecl(Shadow);
8829 
8830 
8831   return Shadow;
8832 }
8833 
8834 /// Hides a using shadow declaration.  This is required by the current
8835 /// using-decl implementation when a resolvable using declaration in a
8836 /// class is followed by a declaration which would hide or override
8837 /// one or more of the using decl's targets; for example:
8838 ///
8839 ///   struct Base { void foo(int); };
8840 ///   struct Derived : Base {
8841 ///     using Base::foo;
8842 ///     void foo(int);
8843 ///   };
8844 ///
8845 /// The governing language is C++03 [namespace.udecl]p12:
8846 ///
8847 ///   When a using-declaration brings names from a base class into a
8848 ///   derived class scope, member functions in the derived class
8849 ///   override and/or hide member functions with the same name and
8850 ///   parameter types in a base class (rather than conflicting).
8851 ///
8852 /// There are two ways to implement this:
8853 ///   (1) optimistically create shadow decls when they're not hidden
8854 ///       by existing declarations, or
8855 ///   (2) don't create any shadow decls (or at least don't make them
8856 ///       visible) until we've fully parsed/instantiated the class.
8857 /// The problem with (1) is that we might have to retroactively remove
8858 /// a shadow decl, which requires several O(n) operations because the
8859 /// decl structures are (very reasonably) not designed for removal.
8860 /// (2) avoids this but is very fiddly and phase-dependent.
8861 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
8862   if (Shadow->getDeclName().getNameKind() ==
8863         DeclarationName::CXXConversionFunctionName)
8864     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
8865 
8866   // Remove it from the DeclContext...
8867   Shadow->getDeclContext()->removeDecl(Shadow);
8868 
8869   // ...and the scope, if applicable...
8870   if (S) {
8871     S->RemoveDecl(Shadow);
8872     IdResolver.RemoveDecl(Shadow);
8873   }
8874 
8875   // ...and the using decl.
8876   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
8877 
8878   // TODO: complain somehow if Shadow was used.  It shouldn't
8879   // be possible for this to happen, because...?
8880 }
8881 
8882 /// Find the base specifier for a base class with the given type.
8883 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
8884                                                 QualType DesiredBase,
8885                                                 bool &AnyDependentBases) {
8886   // Check whether the named type is a direct base class.
8887   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
8888   for (auto &Base : Derived->bases()) {
8889     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
8890     if (CanonicalDesiredBase == BaseType)
8891       return &Base;
8892     if (BaseType->isDependentType())
8893       AnyDependentBases = true;
8894   }
8895   return nullptr;
8896 }
8897 
8898 namespace {
8899 class UsingValidatorCCC : public CorrectionCandidateCallback {
8900 public:
8901   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
8902                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
8903       : HasTypenameKeyword(HasTypenameKeyword),
8904         IsInstantiation(IsInstantiation), OldNNS(NNS),
8905         RequireMemberOf(RequireMemberOf) {}
8906 
8907   bool ValidateCandidate(const TypoCorrection &Candidate) override {
8908     NamedDecl *ND = Candidate.getCorrectionDecl();
8909 
8910     // Keywords are not valid here.
8911     if (!ND || isa<NamespaceDecl>(ND))
8912       return false;
8913 
8914     // Completely unqualified names are invalid for a 'using' declaration.
8915     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
8916       return false;
8917 
8918     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
8919     // reject.
8920 
8921     if (RequireMemberOf) {
8922       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
8923       if (FoundRecord && FoundRecord->isInjectedClassName()) {
8924         // No-one ever wants a using-declaration to name an injected-class-name
8925         // of a base class, unless they're declaring an inheriting constructor.
8926         ASTContext &Ctx = ND->getASTContext();
8927         if (!Ctx.getLangOpts().CPlusPlus11)
8928           return false;
8929         QualType FoundType = Ctx.getRecordType(FoundRecord);
8930 
8931         // Check that the injected-class-name is named as a member of its own
8932         // type; we don't want to suggest 'using Derived::Base;', since that
8933         // means something else.
8934         NestedNameSpecifier *Specifier =
8935             Candidate.WillReplaceSpecifier()
8936                 ? Candidate.getCorrectionSpecifier()
8937                 : OldNNS;
8938         if (!Specifier->getAsType() ||
8939             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
8940           return false;
8941 
8942         // Check that this inheriting constructor declaration actually names a
8943         // direct base class of the current class.
8944         bool AnyDependentBases = false;
8945         if (!findDirectBaseWithType(RequireMemberOf,
8946                                     Ctx.getRecordType(FoundRecord),
8947                                     AnyDependentBases) &&
8948             !AnyDependentBases)
8949           return false;
8950       } else {
8951         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
8952         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
8953           return false;
8954 
8955         // FIXME: Check that the base class member is accessible?
8956       }
8957     } else {
8958       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
8959       if (FoundRecord && FoundRecord->isInjectedClassName())
8960         return false;
8961     }
8962 
8963     if (isa<TypeDecl>(ND))
8964       return HasTypenameKeyword || !IsInstantiation;
8965 
8966     return !HasTypenameKeyword;
8967   }
8968 
8969 private:
8970   bool HasTypenameKeyword;
8971   bool IsInstantiation;
8972   NestedNameSpecifier *OldNNS;
8973   CXXRecordDecl *RequireMemberOf;
8974 };
8975 } // end anonymous namespace
8976 
8977 /// Builds a using declaration.
8978 ///
8979 /// \param IsInstantiation - Whether this call arises from an
8980 ///   instantiation of an unresolved using declaration.  We treat
8981 ///   the lookup differently for these declarations.
8982 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
8983                                        SourceLocation UsingLoc,
8984                                        CXXScopeSpec &SS,
8985                                        DeclarationNameInfo NameInfo,
8986                                        AttributeList *AttrList,
8987                                        bool IsInstantiation,
8988                                        bool HasTypenameKeyword,
8989                                        SourceLocation TypenameLoc) {
8990   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
8991   SourceLocation IdentLoc = NameInfo.getLoc();
8992   assert(IdentLoc.isValid() && "Invalid TargetName location.");
8993 
8994   // FIXME: We ignore attributes for now.
8995 
8996   if (SS.isEmpty()) {
8997     Diag(IdentLoc, diag::err_using_requires_qualname);
8998     return nullptr;
8999   }
9000 
9001   // For an inheriting constructor declaration, the name of the using
9002   // declaration is the name of a constructor in this class, not in the
9003   // base class.
9004   DeclarationNameInfo UsingName = NameInfo;
9005   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9006     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9007       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9008           Context.getCanonicalType(Context.getRecordType(RD))));
9009 
9010   // Do the redeclaration lookup in the current scope.
9011   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
9012                         ForRedeclaration);
9013   Previous.setHideTags(false);
9014   if (S) {
9015     LookupName(Previous, S);
9016 
9017     // It is really dumb that we have to do this.
9018     LookupResult::Filter F = Previous.makeFilter();
9019     while (F.hasNext()) {
9020       NamedDecl *D = F.next();
9021       if (!isDeclInScope(D, CurContext, S))
9022         F.erase();
9023       // If we found a local extern declaration that's not ordinarily visible,
9024       // and this declaration is being added to a non-block scope, ignore it.
9025       // We're only checking for scope conflicts here, not also for violations
9026       // of the linkage rules.
9027       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
9028                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
9029         F.erase();
9030     }
9031     F.done();
9032   } else {
9033     assert(IsInstantiation && "no scope in non-instantiation");
9034     assert(CurContext->isRecord() && "scope not record in instantiation");
9035     LookupQualifiedName(Previous, CurContext);
9036   }
9037 
9038   // Check for invalid redeclarations.
9039   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
9040                                   SS, IdentLoc, Previous))
9041     return nullptr;
9042 
9043   // Check for bad qualifiers.
9044   if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
9045     return nullptr;
9046 
9047   DeclContext *LookupContext = computeDeclContext(SS);
9048   NamedDecl *D;
9049   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9050   if (!LookupContext) {
9051     if (HasTypenameKeyword) {
9052       // FIXME: not all declaration name kinds are legal here
9053       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
9054                                               UsingLoc, TypenameLoc,
9055                                               QualifierLoc,
9056                                               IdentLoc, NameInfo.getName());
9057     } else {
9058       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
9059                                            QualifierLoc, NameInfo);
9060     }
9061     D->setAccess(AS);
9062     CurContext->addDecl(D);
9063     return D;
9064   }
9065 
9066   auto Build = [&](bool Invalid) {
9067     UsingDecl *UD =
9068         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
9069                           UsingName, HasTypenameKeyword);
9070     UD->setAccess(AS);
9071     CurContext->addDecl(UD);
9072     UD->setInvalidDecl(Invalid);
9073     return UD;
9074   };
9075   auto BuildInvalid = [&]{ return Build(true); };
9076   auto BuildValid = [&]{ return Build(false); };
9077 
9078   if (RequireCompleteDeclContext(SS, LookupContext))
9079     return BuildInvalid();
9080 
9081   // Look up the target name.
9082   LookupResult R(*this, NameInfo, LookupOrdinaryName);
9083 
9084   // Unlike most lookups, we don't always want to hide tag
9085   // declarations: tag names are visible through the using declaration
9086   // even if hidden by ordinary names, *except* in a dependent context
9087   // where it's important for the sanity of two-phase lookup.
9088   if (!IsInstantiation)
9089     R.setHideTags(false);
9090 
9091   // For the purposes of this lookup, we have a base object type
9092   // equal to that of the current context.
9093   if (CurContext->isRecord()) {
9094     R.setBaseObjectType(
9095                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
9096   }
9097 
9098   LookupQualifiedName(R, LookupContext);
9099 
9100   // Try to correct typos if possible. If constructor name lookup finds no
9101   // results, that means the named class has no explicit constructors, and we
9102   // suppressed declaring implicit ones (probably because it's dependent or
9103   // invalid).
9104   if (R.empty() &&
9105       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
9106     if (TypoCorrection Corrected = CorrectTypo(
9107             R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
9108             llvm::make_unique<UsingValidatorCCC>(
9109                 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
9110                 dyn_cast<CXXRecordDecl>(CurContext)),
9111             CTK_ErrorRecovery)) {
9112       // We reject any correction for which ND would be NULL.
9113       NamedDecl *ND = Corrected.getCorrectionDecl();
9114 
9115       // We reject candidates where DroppedSpecifier == true, hence the
9116       // literal '0' below.
9117       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
9118                                 << NameInfo.getName() << LookupContext << 0
9119                                 << SS.getRange());
9120 
9121       // If we corrected to an inheriting constructor, handle it as one.
9122       auto *RD = dyn_cast<CXXRecordDecl>(ND);
9123       if (RD && RD->isInjectedClassName()) {
9124         // The parent of the injected class name is the class itself.
9125         RD = cast<CXXRecordDecl>(RD->getParent());
9126 
9127         // Fix up the information we'll use to build the using declaration.
9128         if (Corrected.WillReplaceSpecifier()) {
9129           NestedNameSpecifierLocBuilder Builder;
9130           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
9131                               QualifierLoc.getSourceRange());
9132           QualifierLoc = Builder.getWithLocInContext(Context);
9133         }
9134 
9135         // In this case, the name we introduce is the name of a derived class
9136         // constructor.
9137         auto *CurClass = cast<CXXRecordDecl>(CurContext);
9138         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9139             Context.getCanonicalType(Context.getRecordType(CurClass))));
9140         UsingName.setNamedTypeInfo(nullptr);
9141         for (auto *Ctor : LookupConstructors(RD))
9142           R.addDecl(Ctor);
9143         R.resolveKind();
9144       } else {
9145         // FIXME: Pick up all the declarations if we found an overloaded
9146         // function.
9147         UsingName.setName(ND->getDeclName());
9148         R.addDecl(ND);
9149       }
9150     } else {
9151       Diag(IdentLoc, diag::err_no_member)
9152         << NameInfo.getName() << LookupContext << SS.getRange();
9153       return BuildInvalid();
9154     }
9155   }
9156 
9157   if (R.isAmbiguous())
9158     return BuildInvalid();
9159 
9160   if (HasTypenameKeyword) {
9161     // If we asked for a typename and got a non-type decl, error out.
9162     if (!R.getAsSingle<TypeDecl>()) {
9163       Diag(IdentLoc, diag::err_using_typename_non_type);
9164       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9165         Diag((*I)->getUnderlyingDecl()->getLocation(),
9166              diag::note_using_decl_target);
9167       return BuildInvalid();
9168     }
9169   } else {
9170     // If we asked for a non-typename and we got a type, error out,
9171     // but only if this is an instantiation of an unresolved using
9172     // decl.  Otherwise just silently find the type name.
9173     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
9174       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
9175       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
9176       return BuildInvalid();
9177     }
9178   }
9179 
9180   // C++14 [namespace.udecl]p6:
9181   // A using-declaration shall not name a namespace.
9182   if (R.getAsSingle<NamespaceDecl>()) {
9183     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
9184       << SS.getRange();
9185     return BuildInvalid();
9186   }
9187 
9188   // C++14 [namespace.udecl]p7:
9189   // A using-declaration shall not name a scoped enumerator.
9190   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
9191     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
9192       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
9193         << SS.getRange();
9194       return BuildInvalid();
9195     }
9196   }
9197 
9198   UsingDecl *UD = BuildValid();
9199 
9200   // Some additional rules apply to inheriting constructors.
9201   if (UsingName.getName().getNameKind() ==
9202         DeclarationName::CXXConstructorName) {
9203     // Suppress access diagnostics; the access check is instead performed at the
9204     // point of use for an inheriting constructor.
9205     R.suppressDiagnostics();
9206     if (CheckInheritingConstructorUsingDecl(UD))
9207       return UD;
9208   }
9209 
9210   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
9211     UsingShadowDecl *PrevDecl = nullptr;
9212     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
9213       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
9214   }
9215 
9216   return UD;
9217 }
9218 
9219 /// Additional checks for a using declaration referring to a constructor name.
9220 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
9221   assert(!UD->hasTypename() && "expecting a constructor name");
9222 
9223   const Type *SourceType = UD->getQualifier()->getAsType();
9224   assert(SourceType &&
9225          "Using decl naming constructor doesn't have type in scope spec.");
9226   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
9227 
9228   // Check whether the named type is a direct base class.
9229   bool AnyDependentBases = false;
9230   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
9231                                       AnyDependentBases);
9232   if (!Base && !AnyDependentBases) {
9233     Diag(UD->getUsingLoc(),
9234          diag::err_using_decl_constructor_not_in_direct_base)
9235       << UD->getNameInfo().getSourceRange()
9236       << QualType(SourceType, 0) << TargetClass;
9237     UD->setInvalidDecl();
9238     return true;
9239   }
9240 
9241   if (Base)
9242     Base->setInheritConstructors();
9243 
9244   return false;
9245 }
9246 
9247 /// Checks that the given using declaration is not an invalid
9248 /// redeclaration.  Note that this is checking only for the using decl
9249 /// itself, not for any ill-formedness among the UsingShadowDecls.
9250 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
9251                                        bool HasTypenameKeyword,
9252                                        const CXXScopeSpec &SS,
9253                                        SourceLocation NameLoc,
9254                                        const LookupResult &Prev) {
9255   // C++03 [namespace.udecl]p8:
9256   // C++0x [namespace.udecl]p10:
9257   //   A using-declaration is a declaration and can therefore be used
9258   //   repeatedly where (and only where) multiple declarations are
9259   //   allowed.
9260   //
9261   // That's in non-member contexts.
9262   if (!CurContext->getRedeclContext()->isRecord())
9263     return false;
9264 
9265   NestedNameSpecifier *Qual = SS.getScopeRep();
9266 
9267   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
9268     NamedDecl *D = *I;
9269 
9270     bool DTypename;
9271     NestedNameSpecifier *DQual;
9272     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
9273       DTypename = UD->hasTypename();
9274       DQual = UD->getQualifier();
9275     } else if (UnresolvedUsingValueDecl *UD
9276                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
9277       DTypename = false;
9278       DQual = UD->getQualifier();
9279     } else if (UnresolvedUsingTypenameDecl *UD
9280                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
9281       DTypename = true;
9282       DQual = UD->getQualifier();
9283     } else continue;
9284 
9285     // using decls differ if one says 'typename' and the other doesn't.
9286     // FIXME: non-dependent using decls?
9287     if (HasTypenameKeyword != DTypename) continue;
9288 
9289     // using decls differ if they name different scopes (but note that
9290     // template instantiation can cause this check to trigger when it
9291     // didn't before instantiation).
9292     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
9293         Context.getCanonicalNestedNameSpecifier(DQual))
9294       continue;
9295 
9296     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
9297     Diag(D->getLocation(), diag::note_using_decl) << 1;
9298     return true;
9299   }
9300 
9301   return false;
9302 }
9303 
9304 
9305 /// Checks that the given nested-name qualifier used in a using decl
9306 /// in the current context is appropriately related to the current
9307 /// scope.  If an error is found, diagnoses it and returns true.
9308 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
9309                                    const CXXScopeSpec &SS,
9310                                    const DeclarationNameInfo &NameInfo,
9311                                    SourceLocation NameLoc) {
9312   DeclContext *NamedContext = computeDeclContext(SS);
9313 
9314   if (!CurContext->isRecord()) {
9315     // C++03 [namespace.udecl]p3:
9316     // C++0x [namespace.udecl]p8:
9317     //   A using-declaration for a class member shall be a member-declaration.
9318 
9319     // If we weren't able to compute a valid scope, it must be a
9320     // dependent class scope.
9321     if (!NamedContext || NamedContext->getRedeclContext()->isRecord()) {
9322       auto *RD = NamedContext
9323                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
9324                      : nullptr;
9325       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
9326         RD = nullptr;
9327 
9328       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
9329         << SS.getRange();
9330 
9331       // If we have a complete, non-dependent source type, try to suggest a
9332       // way to get the same effect.
9333       if (!RD)
9334         return true;
9335 
9336       // Find what this using-declaration was referring to.
9337       LookupResult R(*this, NameInfo, LookupOrdinaryName);
9338       R.setHideTags(false);
9339       R.suppressDiagnostics();
9340       LookupQualifiedName(R, RD);
9341 
9342       if (R.getAsSingle<TypeDecl>()) {
9343         if (getLangOpts().CPlusPlus11) {
9344           // Convert 'using X::Y;' to 'using Y = X::Y;'.
9345           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
9346             << 0 // alias declaration
9347             << FixItHint::CreateInsertion(SS.getBeginLoc(),
9348                                           NameInfo.getName().getAsString() +
9349                                               " = ");
9350         } else {
9351           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
9352           SourceLocation InsertLoc =
9353               getLocForEndOfToken(NameInfo.getLocEnd());
9354           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
9355             << 1 // typedef declaration
9356             << FixItHint::CreateReplacement(UsingLoc, "typedef")
9357             << FixItHint::CreateInsertion(
9358                    InsertLoc, " " + NameInfo.getName().getAsString());
9359         }
9360       } else if (R.getAsSingle<VarDecl>()) {
9361         // Don't provide a fixit outside C++11 mode; we don't want to suggest
9362         // repeating the type of the static data member here.
9363         FixItHint FixIt;
9364         if (getLangOpts().CPlusPlus11) {
9365           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
9366           FixIt = FixItHint::CreateReplacement(
9367               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
9368         }
9369 
9370         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
9371           << 2 // reference declaration
9372           << FixIt;
9373       } else if (R.getAsSingle<EnumConstantDecl>()) {
9374         // Don't provide a fixit outside C++11 mode; we don't want to suggest
9375         // repeating the type of the enumeration here, and we can't do so if
9376         // the type is anonymous.
9377         FixItHint FixIt;
9378         if (getLangOpts().CPlusPlus11) {
9379           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
9380           FixIt = FixItHint::CreateReplacement(
9381               UsingLoc, "constexpr auto " + NameInfo.getName().getAsString() + " = ");
9382         }
9383 
9384         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
9385           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
9386           << FixIt;
9387       }
9388       return true;
9389     }
9390 
9391     // Otherwise, everything is known to be fine.
9392     return false;
9393   }
9394 
9395   // The current scope is a record.
9396 
9397   // If the named context is dependent, we can't decide much.
9398   if (!NamedContext) {
9399     // FIXME: in C++0x, we can diagnose if we can prove that the
9400     // nested-name-specifier does not refer to a base class, which is
9401     // still possible in some cases.
9402 
9403     // Otherwise we have to conservatively report that things might be
9404     // okay.
9405     return false;
9406   }
9407 
9408   if (!NamedContext->isRecord()) {
9409     // Ideally this would point at the last name in the specifier,
9410     // but we don't have that level of source info.
9411     Diag(SS.getRange().getBegin(),
9412          diag::err_using_decl_nested_name_specifier_is_not_class)
9413       << SS.getScopeRep() << SS.getRange();
9414     return true;
9415   }
9416 
9417   if (!NamedContext->isDependentContext() &&
9418       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
9419     return true;
9420 
9421   if (getLangOpts().CPlusPlus11) {
9422     // C++11 [namespace.udecl]p3:
9423     //   In a using-declaration used as a member-declaration, the
9424     //   nested-name-specifier shall name a base class of the class
9425     //   being defined.
9426 
9427     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
9428                                  cast<CXXRecordDecl>(NamedContext))) {
9429       if (CurContext == NamedContext) {
9430         Diag(NameLoc,
9431              diag::err_using_decl_nested_name_specifier_is_current_class)
9432           << SS.getRange();
9433         return true;
9434       }
9435 
9436       Diag(SS.getRange().getBegin(),
9437            diag::err_using_decl_nested_name_specifier_is_not_base_class)
9438         << SS.getScopeRep()
9439         << cast<CXXRecordDecl>(CurContext)
9440         << SS.getRange();
9441       return true;
9442     }
9443 
9444     return false;
9445   }
9446 
9447   // C++03 [namespace.udecl]p4:
9448   //   A using-declaration used as a member-declaration shall refer
9449   //   to a member of a base class of the class being defined [etc.].
9450 
9451   // Salient point: SS doesn't have to name a base class as long as
9452   // lookup only finds members from base classes.  Therefore we can
9453   // diagnose here only if we can prove that that can't happen,
9454   // i.e. if the class hierarchies provably don't intersect.
9455 
9456   // TODO: it would be nice if "definitely valid" results were cached
9457   // in the UsingDecl and UsingShadowDecl so that these checks didn't
9458   // need to be repeated.
9459 
9460   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
9461   auto Collect = [&Bases](const CXXRecordDecl *Base) {
9462     Bases.insert(Base);
9463     return true;
9464   };
9465 
9466   // Collect all bases. Return false if we find a dependent base.
9467   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
9468     return false;
9469 
9470   // Returns true if the base is dependent or is one of the accumulated base
9471   // classes.
9472   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
9473     return !Bases.count(Base);
9474   };
9475 
9476   // Return false if the class has a dependent base or if it or one
9477   // of its bases is present in the base set of the current context.
9478   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
9479       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
9480     return false;
9481 
9482   Diag(SS.getRange().getBegin(),
9483        diag::err_using_decl_nested_name_specifier_is_not_base_class)
9484     << SS.getScopeRep()
9485     << cast<CXXRecordDecl>(CurContext)
9486     << SS.getRange();
9487 
9488   return true;
9489 }
9490 
9491 Decl *Sema::ActOnAliasDeclaration(Scope *S,
9492                                   AccessSpecifier AS,
9493                                   MultiTemplateParamsArg TemplateParamLists,
9494                                   SourceLocation UsingLoc,
9495                                   UnqualifiedId &Name,
9496                                   AttributeList *AttrList,
9497                                   TypeResult Type,
9498                                   Decl *DeclFromDeclSpec) {
9499   // Skip up to the relevant declaration scope.
9500   while (S->isTemplateParamScope())
9501     S = S->getParent();
9502   assert((S->getFlags() & Scope::DeclScope) &&
9503          "got alias-declaration outside of declaration scope");
9504 
9505   if (Type.isInvalid())
9506     return nullptr;
9507 
9508   bool Invalid = false;
9509   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
9510   TypeSourceInfo *TInfo = nullptr;
9511   GetTypeFromParser(Type.get(), &TInfo);
9512 
9513   if (DiagnoseClassNameShadow(CurContext, NameInfo))
9514     return nullptr;
9515 
9516   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
9517                                       UPPC_DeclarationType)) {
9518     Invalid = true;
9519     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9520                                              TInfo->getTypeLoc().getBeginLoc());
9521   }
9522 
9523   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
9524   LookupName(Previous, S);
9525 
9526   // Warn about shadowing the name of a template parameter.
9527   if (Previous.isSingleResult() &&
9528       Previous.getFoundDecl()->isTemplateParameter()) {
9529     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
9530     Previous.clear();
9531   }
9532 
9533   assert(Name.Kind == UnqualifiedId::IK_Identifier &&
9534          "name in alias declaration must be an identifier");
9535   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
9536                                                Name.StartLocation,
9537                                                Name.Identifier, TInfo);
9538 
9539   NewTD->setAccess(AS);
9540 
9541   if (Invalid)
9542     NewTD->setInvalidDecl();
9543 
9544   ProcessDeclAttributeList(S, NewTD, AttrList);
9545 
9546   CheckTypedefForVariablyModifiedType(S, NewTD);
9547   Invalid |= NewTD->isInvalidDecl();
9548 
9549   bool Redeclaration = false;
9550 
9551   NamedDecl *NewND;
9552   if (TemplateParamLists.size()) {
9553     TypeAliasTemplateDecl *OldDecl = nullptr;
9554     TemplateParameterList *OldTemplateParams = nullptr;
9555 
9556     if (TemplateParamLists.size() != 1) {
9557       Diag(UsingLoc, diag::err_alias_template_extra_headers)
9558         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
9559          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
9560     }
9561     TemplateParameterList *TemplateParams = TemplateParamLists[0];
9562 
9563     // Check that we can declare a template here.
9564     if (CheckTemplateDeclScope(S, TemplateParams))
9565       return nullptr;
9566 
9567     // Only consider previous declarations in the same scope.
9568     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
9569                          /*ExplicitInstantiationOrSpecialization*/false);
9570     if (!Previous.empty()) {
9571       Redeclaration = true;
9572 
9573       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
9574       if (!OldDecl && !Invalid) {
9575         Diag(UsingLoc, diag::err_redefinition_different_kind)
9576           << Name.Identifier;
9577 
9578         NamedDecl *OldD = Previous.getRepresentativeDecl();
9579         if (OldD->getLocation().isValid())
9580           Diag(OldD->getLocation(), diag::note_previous_definition);
9581 
9582         Invalid = true;
9583       }
9584 
9585       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
9586         if (TemplateParameterListsAreEqual(TemplateParams,
9587                                            OldDecl->getTemplateParameters(),
9588                                            /*Complain=*/true,
9589                                            TPL_TemplateMatch))
9590           OldTemplateParams = OldDecl->getTemplateParameters();
9591         else
9592           Invalid = true;
9593 
9594         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
9595         if (!Invalid &&
9596             !Context.hasSameType(OldTD->getUnderlyingType(),
9597                                  NewTD->getUnderlyingType())) {
9598           // FIXME: The C++0x standard does not clearly say this is ill-formed,
9599           // but we can't reasonably accept it.
9600           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
9601             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
9602           if (OldTD->getLocation().isValid())
9603             Diag(OldTD->getLocation(), diag::note_previous_definition);
9604           Invalid = true;
9605         }
9606       }
9607     }
9608 
9609     // Merge any previous default template arguments into our parameters,
9610     // and check the parameter list.
9611     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
9612                                    TPC_TypeAliasTemplate))
9613       return nullptr;
9614 
9615     TypeAliasTemplateDecl *NewDecl =
9616       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
9617                                     Name.Identifier, TemplateParams,
9618                                     NewTD);
9619     NewTD->setDescribedAliasTemplate(NewDecl);
9620 
9621     NewDecl->setAccess(AS);
9622 
9623     if (Invalid)
9624       NewDecl->setInvalidDecl();
9625     else if (OldDecl)
9626       NewDecl->setPreviousDecl(OldDecl);
9627 
9628     NewND = NewDecl;
9629   } else {
9630     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
9631       setTagNameForLinkagePurposes(TD, NewTD);
9632       handleTagNumbering(TD, S);
9633     }
9634     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
9635     NewND = NewTD;
9636   }
9637 
9638   PushOnScopeChains(NewND, S);
9639   ActOnDocumentableDecl(NewND);
9640   return NewND;
9641 }
9642 
9643 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
9644                                    SourceLocation AliasLoc,
9645                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
9646                                    SourceLocation IdentLoc,
9647                                    IdentifierInfo *Ident) {
9648 
9649   // Lookup the namespace name.
9650   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
9651   LookupParsedName(R, S, &SS);
9652 
9653   if (R.isAmbiguous())
9654     return nullptr;
9655 
9656   if (R.empty()) {
9657     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
9658       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
9659       return nullptr;
9660     }
9661   }
9662   assert(!R.isAmbiguous() && !R.empty());
9663   NamedDecl *ND = R.getRepresentativeDecl();
9664 
9665   // Check if we have a previous declaration with the same name.
9666   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
9667                      ForRedeclaration);
9668   LookupName(PrevR, S);
9669 
9670   // Check we're not shadowing a template parameter.
9671   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
9672     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
9673     PrevR.clear();
9674   }
9675 
9676   // Filter out any other lookup result from an enclosing scope.
9677   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
9678                        /*AllowInlineNamespace*/false);
9679 
9680   // Find the previous declaration and check that we can redeclare it.
9681   NamespaceAliasDecl *Prev = nullptr;
9682   if (PrevR.isSingleResult()) {
9683     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
9684     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
9685       // We already have an alias with the same name that points to the same
9686       // namespace; check that it matches.
9687       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
9688         Prev = AD;
9689       } else if (isVisible(PrevDecl)) {
9690         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
9691           << Alias;
9692         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
9693           << AD->getNamespace();
9694         return nullptr;
9695       }
9696     } else if (isVisible(PrevDecl)) {
9697       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
9698                             ? diag::err_redefinition
9699                             : diag::err_redefinition_different_kind;
9700       Diag(AliasLoc, DiagID) << Alias;
9701       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
9702       return nullptr;
9703     }
9704   }
9705 
9706   // The use of a nested name specifier may trigger deprecation warnings.
9707   DiagnoseUseOfDecl(ND, IdentLoc);
9708 
9709   NamespaceAliasDecl *AliasDecl =
9710     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
9711                                Alias, SS.getWithLocInContext(Context),
9712                                IdentLoc, ND);
9713   if (Prev)
9714     AliasDecl->setPreviousDecl(Prev);
9715 
9716   PushOnScopeChains(AliasDecl, S);
9717   return AliasDecl;
9718 }
9719 
9720 Sema::ImplicitExceptionSpecification
9721 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
9722                                                CXXMethodDecl *MD) {
9723   CXXRecordDecl *ClassDecl = MD->getParent();
9724 
9725   // C++ [except.spec]p14:
9726   //   An implicitly declared special member function (Clause 12) shall have an
9727   //   exception-specification. [...]
9728   ImplicitExceptionSpecification ExceptSpec(*this);
9729   if (ClassDecl->isInvalidDecl())
9730     return ExceptSpec;
9731 
9732   // Direct base-class constructors.
9733   for (const auto &B : ClassDecl->bases()) {
9734     if (B.isVirtual()) // Handled below.
9735       continue;
9736 
9737     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
9738       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
9739       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
9740       // If this is a deleted function, add it anyway. This might be conformant
9741       // with the standard. This might not. I'm not sure. It might not matter.
9742       if (Constructor)
9743         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
9744     }
9745   }
9746 
9747   // Virtual base-class constructors.
9748   for (const auto &B : ClassDecl->vbases()) {
9749     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
9750       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
9751       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
9752       // If this is a deleted function, add it anyway. This might be conformant
9753       // with the standard. This might not. I'm not sure. It might not matter.
9754       if (Constructor)
9755         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
9756     }
9757   }
9758 
9759   // Field constructors.
9760   for (const auto *F : ClassDecl->fields()) {
9761     if (F->hasInClassInitializer()) {
9762       if (Expr *E = F->getInClassInitializer())
9763         ExceptSpec.CalledExpr(E);
9764     } else if (const RecordType *RecordTy
9765               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
9766       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9767       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
9768       // If this is a deleted function, add it anyway. This might be conformant
9769       // with the standard. This might not. I'm not sure. It might not matter.
9770       // In particular, the problem is that this function never gets called. It
9771       // might just be ill-formed because this function attempts to refer to
9772       // a deleted function here.
9773       if (Constructor)
9774         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
9775     }
9776   }
9777 
9778   return ExceptSpec;
9779 }
9780 
9781 Sema::ImplicitExceptionSpecification
9782 Sema::ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
9783                                          CXXConstructorDecl *CD) {
9784   CXXRecordDecl *ClassDecl = CD->getParent();
9785 
9786   // C++ [except.spec]p14:
9787   //   An inheriting constructor [...] shall have an exception-specification. [...]
9788   ImplicitExceptionSpecification ExceptSpec(*this);
9789   if (ClassDecl->isInvalidDecl())
9790     return ExceptSpec;
9791 
9792   auto Inherited = CD->getInheritedConstructor();
9793   InheritedConstructorInfo ICI(*this, Loc, Inherited.getShadowDecl());
9794 
9795   // Direct and virtual base-class constructors.
9796   for (bool VBase : {false, true}) {
9797     for (CXXBaseSpecifier &B :
9798          VBase ? ClassDecl->vbases() : ClassDecl->bases()) {
9799       // Don't visit direct vbases twice.
9800       if (B.isVirtual() != VBase)
9801         continue;
9802 
9803       CXXRecordDecl *BaseClass = B.getType()->getAsCXXRecordDecl();
9804       if (!BaseClass)
9805         continue;
9806 
9807       CXXConstructorDecl *Constructor =
9808           ICI.findConstructorForBase(BaseClass, Inherited.getConstructor())
9809               .first;
9810       if (!Constructor)
9811         Constructor = LookupDefaultConstructor(BaseClass);
9812       if (Constructor)
9813         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
9814     }
9815   }
9816 
9817   // Field constructors.
9818   for (const auto *F : ClassDecl->fields()) {
9819     if (F->hasInClassInitializer()) {
9820       if (Expr *E = F->getInClassInitializer())
9821         ExceptSpec.CalledExpr(E);
9822     } else if (const RecordType *RecordTy
9823               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
9824       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9825       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
9826       if (Constructor)
9827         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
9828     }
9829   }
9830 
9831   return ExceptSpec;
9832 }
9833 
9834 namespace {
9835 /// RAII object to register a special member as being currently declared.
9836 struct DeclaringSpecialMember {
9837   Sema &S;
9838   Sema::SpecialMemberDecl D;
9839   Sema::ContextRAII SavedContext;
9840   bool WasAlreadyBeingDeclared;
9841 
9842   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
9843     : S(S), D(RD, CSM), SavedContext(S, RD) {
9844     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
9845     if (WasAlreadyBeingDeclared)
9846       // This almost never happens, but if it does, ensure that our cache
9847       // doesn't contain a stale result.
9848       S.SpecialMemberCache.clear();
9849 
9850     // FIXME: Register a note to be produced if we encounter an error while
9851     // declaring the special member.
9852   }
9853   ~DeclaringSpecialMember() {
9854     if (!WasAlreadyBeingDeclared)
9855       S.SpecialMembersBeingDeclared.erase(D);
9856   }
9857 
9858   /// \brief Are we already trying to declare this special member?
9859   bool isAlreadyBeingDeclared() const {
9860     return WasAlreadyBeingDeclared;
9861   }
9862 };
9863 }
9864 
9865 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
9866   // Look up any existing declarations, but don't trigger declaration of all
9867   // implicit special members with this name.
9868   DeclarationName Name = FD->getDeclName();
9869   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
9870                  ForRedeclaration);
9871   for (auto *D : FD->getParent()->lookup(Name))
9872     if (auto *Acceptable = R.getAcceptableDecl(D))
9873       R.addDecl(Acceptable);
9874   R.resolveKind();
9875   R.suppressDiagnostics();
9876 
9877   CheckFunctionDeclaration(S, FD, R, /*IsExplicitSpecialization*/false);
9878 }
9879 
9880 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
9881                                                      CXXRecordDecl *ClassDecl) {
9882   // C++ [class.ctor]p5:
9883   //   A default constructor for a class X is a constructor of class X
9884   //   that can be called without an argument. If there is no
9885   //   user-declared constructor for class X, a default constructor is
9886   //   implicitly declared. An implicitly-declared default constructor
9887   //   is an inline public member of its class.
9888   assert(ClassDecl->needsImplicitDefaultConstructor() &&
9889          "Should not build implicit default constructor!");
9890 
9891   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
9892   if (DSM.isAlreadyBeingDeclared())
9893     return nullptr;
9894 
9895   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9896                                                      CXXDefaultConstructor,
9897                                                      false);
9898 
9899   // Create the actual constructor declaration.
9900   CanQualType ClassType
9901     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
9902   SourceLocation ClassLoc = ClassDecl->getLocation();
9903   DeclarationName Name
9904     = Context.DeclarationNames.getCXXConstructorName(ClassType);
9905   DeclarationNameInfo NameInfo(Name, ClassLoc);
9906   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
9907       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
9908       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
9909       /*isImplicitlyDeclared=*/true, Constexpr);
9910   DefaultCon->setAccess(AS_public);
9911   DefaultCon->setDefaulted();
9912 
9913   if (getLangOpts().CUDA) {
9914     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
9915                                             DefaultCon,
9916                                             /* ConstRHS */ false,
9917                                             /* Diagnose */ false);
9918   }
9919 
9920   // Build an exception specification pointing back at this constructor.
9921   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
9922   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9923 
9924   // We don't need to use SpecialMemberIsTrivial here; triviality for default
9925   // constructors is easy to compute.
9926   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
9927 
9928   // Note that we have declared this constructor.
9929   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
9930 
9931   Scope *S = getScopeForContext(ClassDecl);
9932   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
9933 
9934   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
9935     SetDeclDeleted(DefaultCon, ClassLoc);
9936 
9937   if (S)
9938     PushOnScopeChains(DefaultCon, S, false);
9939   ClassDecl->addDecl(DefaultCon);
9940 
9941   return DefaultCon;
9942 }
9943 
9944 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
9945                                             CXXConstructorDecl *Constructor) {
9946   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
9947           !Constructor->doesThisDeclarationHaveABody() &&
9948           !Constructor->isDeleted()) &&
9949     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
9950 
9951   CXXRecordDecl *ClassDecl = Constructor->getParent();
9952   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
9953 
9954   SynthesizedFunctionScope Scope(*this, Constructor);
9955   DiagnosticErrorTrap Trap(Diags);
9956   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
9957       Trap.hasErrorOccurred()) {
9958     Diag(CurrentLocation, diag::note_member_synthesized_at)
9959       << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
9960     Constructor->setInvalidDecl();
9961     return;
9962   }
9963 
9964   // The exception specification is needed because we are defining the
9965   // function.
9966   ResolveExceptionSpec(CurrentLocation,
9967                        Constructor->getType()->castAs<FunctionProtoType>());
9968 
9969   SourceLocation Loc = Constructor->getLocEnd().isValid()
9970                            ? Constructor->getLocEnd()
9971                            : Constructor->getLocation();
9972   Constructor->setBody(new (Context) CompoundStmt(Loc));
9973 
9974   Constructor->markUsed(Context);
9975   MarkVTableUsed(CurrentLocation, ClassDecl);
9976 
9977   if (ASTMutationListener *L = getASTMutationListener()) {
9978     L->CompletedImplicitDefinition(Constructor);
9979   }
9980 
9981   DiagnoseUninitializedFields(*this, Constructor);
9982 }
9983 
9984 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
9985   // Perform any delayed checks on exception specifications.
9986   CheckDelayedMemberExceptionSpecs();
9987 }
9988 
9989 /// Find or create the fake constructor we synthesize to model constructing an
9990 /// object of a derived class via a constructor of a base class.
9991 CXXConstructorDecl *
9992 Sema::findInheritingConstructor(SourceLocation Loc,
9993                                 CXXConstructorDecl *BaseCtor,
9994                                 ConstructorUsingShadowDecl *Shadow) {
9995   CXXRecordDecl *Derived = Shadow->getParent();
9996   SourceLocation UsingLoc = Shadow->getLocation();
9997 
9998   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
9999   // For now we use the name of the base class constructor as a member of the
10000   // derived class to indicate a (fake) inherited constructor name.
10001   DeclarationName Name = BaseCtor->getDeclName();
10002 
10003   // Check to see if we already have a fake constructor for this inherited
10004   // constructor call.
10005   for (NamedDecl *Ctor : Derived->lookup(Name))
10006     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
10007                                ->getInheritedConstructor()
10008                                .getConstructor(),
10009                            BaseCtor))
10010       return cast<CXXConstructorDecl>(Ctor);
10011 
10012   DeclarationNameInfo NameInfo(Name, UsingLoc);
10013   TypeSourceInfo *TInfo =
10014       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
10015   FunctionProtoTypeLoc ProtoLoc =
10016       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
10017 
10018   // Check the inherited constructor is valid and find the list of base classes
10019   // from which it was inherited.
10020   InheritedConstructorInfo ICI(*this, Loc, Shadow);
10021 
10022   bool Constexpr =
10023       BaseCtor->isConstexpr() &&
10024       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
10025                                         false, BaseCtor, &ICI);
10026 
10027   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
10028       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
10029       BaseCtor->isExplicit(), /*Inline=*/true,
10030       /*ImplicitlyDeclared=*/true, Constexpr,
10031       InheritedConstructor(Shadow, BaseCtor));
10032   if (Shadow->isInvalidDecl())
10033     DerivedCtor->setInvalidDecl();
10034 
10035   // Build an unevaluated exception specification for this fake constructor.
10036   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
10037   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10038   EPI.ExceptionSpec.Type = EST_Unevaluated;
10039   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
10040   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
10041                                                FPT->getParamTypes(), EPI));
10042 
10043   // Build the parameter declarations.
10044   SmallVector<ParmVarDecl *, 16> ParamDecls;
10045   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
10046     TypeSourceInfo *TInfo =
10047         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
10048     ParmVarDecl *PD = ParmVarDecl::Create(
10049         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
10050         FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
10051     PD->setScopeInfo(0, I);
10052     PD->setImplicit();
10053     // Ensure attributes are propagated onto parameters (this matters for
10054     // format, pass_object_size, ...).
10055     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
10056     ParamDecls.push_back(PD);
10057     ProtoLoc.setParam(I, PD);
10058   }
10059 
10060   // Set up the new constructor.
10061   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
10062   DerivedCtor->setAccess(BaseCtor->getAccess());
10063   DerivedCtor->setParams(ParamDecls);
10064   Derived->addDecl(DerivedCtor);
10065 
10066   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
10067     SetDeclDeleted(DerivedCtor, UsingLoc);
10068 
10069   return DerivedCtor;
10070 }
10071 
10072 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
10073   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
10074                                Ctor->getInheritedConstructor().getShadowDecl());
10075   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
10076                             /*Diagnose*/true);
10077 }
10078 
10079 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
10080                                        CXXConstructorDecl *Constructor) {
10081   CXXRecordDecl *ClassDecl = Constructor->getParent();
10082   assert(Constructor->getInheritedConstructor() &&
10083          !Constructor->doesThisDeclarationHaveABody() &&
10084          !Constructor->isDeleted());
10085   if (Constructor->isInvalidDecl())
10086     return;
10087 
10088   ConstructorUsingShadowDecl *Shadow =
10089       Constructor->getInheritedConstructor().getShadowDecl();
10090   CXXConstructorDecl *InheritedCtor =
10091       Constructor->getInheritedConstructor().getConstructor();
10092 
10093   // [class.inhctor.init]p1:
10094   //   initialization proceeds as if a defaulted default constructor is used to
10095   //   initialize the D object and each base class subobject from which the
10096   //   constructor was inherited
10097 
10098   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
10099   CXXRecordDecl *RD = Shadow->getParent();
10100   SourceLocation InitLoc = Shadow->getLocation();
10101 
10102   // Initializations are performed "as if by a defaulted default constructor",
10103   // so enter the appropriate scope.
10104   SynthesizedFunctionScope Scope(*this, Constructor);
10105   DiagnosticErrorTrap Trap(Diags);
10106 
10107   // Build explicit initializers for all base classes from which the
10108   // constructor was inherited.
10109   SmallVector<CXXCtorInitializer*, 8> Inits;
10110   for (bool VBase : {false, true}) {
10111     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
10112       if (B.isVirtual() != VBase)
10113         continue;
10114 
10115       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
10116       if (!BaseRD)
10117         continue;
10118 
10119       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
10120       if (!BaseCtor.first)
10121         continue;
10122 
10123       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
10124       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
10125           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
10126 
10127       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
10128       Inits.push_back(new (Context) CXXCtorInitializer(
10129           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
10130           SourceLocation()));
10131     }
10132   }
10133 
10134   // We now proceed as if for a defaulted default constructor, with the relevant
10135   // initializers replaced.
10136 
10137   bool HadError = SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits);
10138   if (HadError || Trap.hasErrorOccurred()) {
10139     Diag(CurrentLocation, diag::note_inhctor_synthesized_at) << RD;
10140     Constructor->setInvalidDecl();
10141     return;
10142   }
10143 
10144   // The exception specification is needed because we are defining the
10145   // function.
10146   ResolveExceptionSpec(CurrentLocation,
10147                        Constructor->getType()->castAs<FunctionProtoType>());
10148 
10149   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
10150 
10151   Constructor->markUsed(Context);
10152   MarkVTableUsed(CurrentLocation, ClassDecl);
10153 
10154   if (ASTMutationListener *L = getASTMutationListener()) {
10155     L->CompletedImplicitDefinition(Constructor);
10156   }
10157 
10158   DiagnoseUninitializedFields(*this, Constructor);
10159 }
10160 
10161 Sema::ImplicitExceptionSpecification
10162 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
10163   CXXRecordDecl *ClassDecl = MD->getParent();
10164 
10165   // C++ [except.spec]p14:
10166   //   An implicitly declared special member function (Clause 12) shall have
10167   //   an exception-specification.
10168   ImplicitExceptionSpecification ExceptSpec(*this);
10169   if (ClassDecl->isInvalidDecl())
10170     return ExceptSpec;
10171 
10172   // Direct base-class destructors.
10173   for (const auto &B : ClassDecl->bases()) {
10174     if (B.isVirtual()) // Handled below.
10175       continue;
10176 
10177     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
10178       ExceptSpec.CalledDecl(B.getLocStart(),
10179                    LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
10180   }
10181 
10182   // Virtual base-class destructors.
10183   for (const auto &B : ClassDecl->vbases()) {
10184     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
10185       ExceptSpec.CalledDecl(B.getLocStart(),
10186                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
10187   }
10188 
10189   // Field destructors.
10190   for (const auto *F : ClassDecl->fields()) {
10191     if (const RecordType *RecordTy
10192         = Context.getBaseElementType(F->getType())->getAs<RecordType>())
10193       ExceptSpec.CalledDecl(F->getLocation(),
10194                   LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
10195   }
10196 
10197   return ExceptSpec;
10198 }
10199 
10200 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
10201   // C++ [class.dtor]p2:
10202   //   If a class has no user-declared destructor, a destructor is
10203   //   declared implicitly. An implicitly-declared destructor is an
10204   //   inline public member of its class.
10205   assert(ClassDecl->needsImplicitDestructor());
10206 
10207   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
10208   if (DSM.isAlreadyBeingDeclared())
10209     return nullptr;
10210 
10211   // Create the actual destructor declaration.
10212   CanQualType ClassType
10213     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10214   SourceLocation ClassLoc = ClassDecl->getLocation();
10215   DeclarationName Name
10216     = Context.DeclarationNames.getCXXDestructorName(ClassType);
10217   DeclarationNameInfo NameInfo(Name, ClassLoc);
10218   CXXDestructorDecl *Destructor
10219       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
10220                                   QualType(), nullptr, /*isInline=*/true,
10221                                   /*isImplicitlyDeclared=*/true);
10222   Destructor->setAccess(AS_public);
10223   Destructor->setDefaulted();
10224 
10225   if (getLangOpts().CUDA) {
10226     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
10227                                             Destructor,
10228                                             /* ConstRHS */ false,
10229                                             /* Diagnose */ false);
10230   }
10231 
10232   // Build an exception specification pointing back at this destructor.
10233   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
10234   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10235 
10236   // We don't need to use SpecialMemberIsTrivial here; triviality for
10237   // destructors is easy to compute.
10238   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
10239 
10240   // Note that we have declared this destructor.
10241   ++ASTContext::NumImplicitDestructorsDeclared;
10242 
10243   Scope *S = getScopeForContext(ClassDecl);
10244   CheckImplicitSpecialMemberDeclaration(S, Destructor);
10245 
10246   if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
10247     SetDeclDeleted(Destructor, ClassLoc);
10248 
10249   // Introduce this destructor into its scope.
10250   if (S)
10251     PushOnScopeChains(Destructor, S, false);
10252   ClassDecl->addDecl(Destructor);
10253 
10254   return Destructor;
10255 }
10256 
10257 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
10258                                     CXXDestructorDecl *Destructor) {
10259   assert((Destructor->isDefaulted() &&
10260           !Destructor->doesThisDeclarationHaveABody() &&
10261           !Destructor->isDeleted()) &&
10262          "DefineImplicitDestructor - call it for implicit default dtor");
10263   CXXRecordDecl *ClassDecl = Destructor->getParent();
10264   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
10265 
10266   if (Destructor->isInvalidDecl())
10267     return;
10268 
10269   SynthesizedFunctionScope Scope(*this, Destructor);
10270 
10271   DiagnosticErrorTrap Trap(Diags);
10272   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
10273                                          Destructor->getParent());
10274 
10275   if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
10276     Diag(CurrentLocation, diag::note_member_synthesized_at)
10277       << CXXDestructor << Context.getTagDeclType(ClassDecl);
10278 
10279     Destructor->setInvalidDecl();
10280     return;
10281   }
10282 
10283   // The exception specification is needed because we are defining the
10284   // function.
10285   ResolveExceptionSpec(CurrentLocation,
10286                        Destructor->getType()->castAs<FunctionProtoType>());
10287 
10288   SourceLocation Loc = Destructor->getLocEnd().isValid()
10289                            ? Destructor->getLocEnd()
10290                            : Destructor->getLocation();
10291   Destructor->setBody(new (Context) CompoundStmt(Loc));
10292   Destructor->markUsed(Context);
10293   MarkVTableUsed(CurrentLocation, ClassDecl);
10294 
10295   if (ASTMutationListener *L = getASTMutationListener()) {
10296     L->CompletedImplicitDefinition(Destructor);
10297   }
10298 }
10299 
10300 /// \brief Perform any semantic analysis which needs to be delayed until all
10301 /// pending class member declarations have been parsed.
10302 void Sema::ActOnFinishCXXMemberDecls() {
10303   // If the context is an invalid C++ class, just suppress these checks.
10304   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
10305     if (Record->isInvalidDecl()) {
10306       DelayedDefaultedMemberExceptionSpecs.clear();
10307       DelayedExceptionSpecChecks.clear();
10308       return;
10309     }
10310   }
10311 }
10312 
10313 static void getDefaultArgExprsForConstructors(Sema &S, CXXRecordDecl *Class) {
10314   // Don't do anything for template patterns.
10315   if (Class->getDescribedClassTemplate())
10316     return;
10317 
10318   CallingConv ExpectedCallingConv = S.Context.getDefaultCallingConvention(
10319       /*IsVariadic=*/false, /*IsCXXMethod=*/true);
10320 
10321   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
10322   for (Decl *Member : Class->decls()) {
10323     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
10324     if (!CD) {
10325       // Recurse on nested classes.
10326       if (auto *NestedRD = dyn_cast<CXXRecordDecl>(Member))
10327         getDefaultArgExprsForConstructors(S, NestedRD);
10328       continue;
10329     } else if (!CD->isDefaultConstructor() || !CD->hasAttr<DLLExportAttr>()) {
10330       continue;
10331     }
10332 
10333     CallingConv ActualCallingConv =
10334         CD->getType()->getAs<FunctionProtoType>()->getCallConv();
10335 
10336     // Skip default constructors with typical calling conventions and no default
10337     // arguments.
10338     unsigned NumParams = CD->getNumParams();
10339     if (ExpectedCallingConv == ActualCallingConv && NumParams == 0)
10340       continue;
10341 
10342     if (LastExportedDefaultCtor) {
10343       S.Diag(LastExportedDefaultCtor->getLocation(),
10344              diag::err_attribute_dll_ambiguous_default_ctor) << Class;
10345       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
10346           << CD->getDeclName();
10347       return;
10348     }
10349     LastExportedDefaultCtor = CD;
10350 
10351     for (unsigned I = 0; I != NumParams; ++I) {
10352       // Skip any default arguments that we've already instantiated.
10353       if (S.Context.getDefaultArgExprForConstructor(CD, I))
10354         continue;
10355 
10356       Expr *DefaultArg = S.BuildCXXDefaultArgExpr(Class->getLocation(), CD,
10357                                                   CD->getParamDecl(I)).get();
10358       S.DiscardCleanupsInEvaluationContext();
10359       S.Context.addDefaultArgExprForConstructor(CD, I, DefaultArg);
10360     }
10361   }
10362 }
10363 
10364 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
10365   auto *RD = dyn_cast<CXXRecordDecl>(D);
10366 
10367   // Default constructors that are annotated with __declspec(dllexport) which
10368   // have default arguments or don't use the standard calling convention are
10369   // wrapped with a thunk called the default constructor closure.
10370   if (RD && Context.getTargetInfo().getCXXABI().isMicrosoft())
10371     getDefaultArgExprsForConstructors(*this, RD);
10372 
10373   referenceDLLExportedClassMethods();
10374 }
10375 
10376 void Sema::referenceDLLExportedClassMethods() {
10377   if (!DelayedDllExportClasses.empty()) {
10378     // Calling ReferenceDllExportedMethods might cause the current function to
10379     // be called again, so use a local copy of DelayedDllExportClasses.
10380     SmallVector<CXXRecordDecl *, 4> WorkList;
10381     std::swap(DelayedDllExportClasses, WorkList);
10382     for (CXXRecordDecl *Class : WorkList)
10383       ReferenceDllExportedMethods(*this, Class);
10384   }
10385 }
10386 
10387 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
10388                                          CXXDestructorDecl *Destructor) {
10389   assert(getLangOpts().CPlusPlus11 &&
10390          "adjusting dtor exception specs was introduced in c++11");
10391 
10392   // C++11 [class.dtor]p3:
10393   //   A declaration of a destructor that does not have an exception-
10394   //   specification is implicitly considered to have the same exception-
10395   //   specification as an implicit declaration.
10396   const FunctionProtoType *DtorType = Destructor->getType()->
10397                                         getAs<FunctionProtoType>();
10398   if (DtorType->hasExceptionSpec())
10399     return;
10400 
10401   // Replace the destructor's type, building off the existing one. Fortunately,
10402   // the only thing of interest in the destructor type is its extended info.
10403   // The return and arguments are fixed.
10404   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
10405   EPI.ExceptionSpec.Type = EST_Unevaluated;
10406   EPI.ExceptionSpec.SourceDecl = Destructor;
10407   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10408 
10409   // FIXME: If the destructor has a body that could throw, and the newly created
10410   // spec doesn't allow exceptions, we should emit a warning, because this
10411   // change in behavior can break conforming C++03 programs at runtime.
10412   // However, we don't have a body or an exception specification yet, so it
10413   // needs to be done somewhere else.
10414 }
10415 
10416 namespace {
10417 /// \brief An abstract base class for all helper classes used in building the
10418 //  copy/move operators. These classes serve as factory functions and help us
10419 //  avoid using the same Expr* in the AST twice.
10420 class ExprBuilder {
10421   ExprBuilder(const ExprBuilder&) = delete;
10422   ExprBuilder &operator=(const ExprBuilder&) = delete;
10423 
10424 protected:
10425   static Expr *assertNotNull(Expr *E) {
10426     assert(E && "Expression construction must not fail.");
10427     return E;
10428   }
10429 
10430 public:
10431   ExprBuilder() {}
10432   virtual ~ExprBuilder() {}
10433 
10434   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
10435 };
10436 
10437 class RefBuilder: public ExprBuilder {
10438   VarDecl *Var;
10439   QualType VarType;
10440 
10441 public:
10442   Expr *build(Sema &S, SourceLocation Loc) const override {
10443     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
10444   }
10445 
10446   RefBuilder(VarDecl *Var, QualType VarType)
10447       : Var(Var), VarType(VarType) {}
10448 };
10449 
10450 class ThisBuilder: public ExprBuilder {
10451 public:
10452   Expr *build(Sema &S, SourceLocation Loc) const override {
10453     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
10454   }
10455 };
10456 
10457 class CastBuilder: public ExprBuilder {
10458   const ExprBuilder &Builder;
10459   QualType Type;
10460   ExprValueKind Kind;
10461   const CXXCastPath &Path;
10462 
10463 public:
10464   Expr *build(Sema &S, SourceLocation Loc) const override {
10465     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
10466                                              CK_UncheckedDerivedToBase, Kind,
10467                                              &Path).get());
10468   }
10469 
10470   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
10471               const CXXCastPath &Path)
10472       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
10473 };
10474 
10475 class DerefBuilder: public ExprBuilder {
10476   const ExprBuilder &Builder;
10477 
10478 public:
10479   Expr *build(Sema &S, SourceLocation Loc) const override {
10480     return assertNotNull(
10481         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
10482   }
10483 
10484   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10485 };
10486 
10487 class MemberBuilder: public ExprBuilder {
10488   const ExprBuilder &Builder;
10489   QualType Type;
10490   CXXScopeSpec SS;
10491   bool IsArrow;
10492   LookupResult &MemberLookup;
10493 
10494 public:
10495   Expr *build(Sema &S, SourceLocation Loc) const override {
10496     return assertNotNull(S.BuildMemberReferenceExpr(
10497         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
10498         nullptr, MemberLookup, nullptr, nullptr).get());
10499   }
10500 
10501   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
10502                 LookupResult &MemberLookup)
10503       : Builder(Builder), Type(Type), IsArrow(IsArrow),
10504         MemberLookup(MemberLookup) {}
10505 };
10506 
10507 class MoveCastBuilder: public ExprBuilder {
10508   const ExprBuilder &Builder;
10509 
10510 public:
10511   Expr *build(Sema &S, SourceLocation Loc) const override {
10512     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
10513   }
10514 
10515   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10516 };
10517 
10518 class LvalueConvBuilder: public ExprBuilder {
10519   const ExprBuilder &Builder;
10520 
10521 public:
10522   Expr *build(Sema &S, SourceLocation Loc) const override {
10523     return assertNotNull(
10524         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
10525   }
10526 
10527   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10528 };
10529 
10530 class SubscriptBuilder: public ExprBuilder {
10531   const ExprBuilder &Base;
10532   const ExprBuilder &Index;
10533 
10534 public:
10535   Expr *build(Sema &S, SourceLocation Loc) const override {
10536     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
10537         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
10538   }
10539 
10540   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
10541       : Base(Base), Index(Index) {}
10542 };
10543 
10544 } // end anonymous namespace
10545 
10546 /// When generating a defaulted copy or move assignment operator, if a field
10547 /// should be copied with __builtin_memcpy rather than via explicit assignments,
10548 /// do so. This optimization only applies for arrays of scalars, and for arrays
10549 /// of class type where the selected copy/move-assignment operator is trivial.
10550 static StmtResult
10551 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
10552                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
10553   // Compute the size of the memory buffer to be copied.
10554   QualType SizeType = S.Context.getSizeType();
10555   llvm::APInt Size(S.Context.getTypeSize(SizeType),
10556                    S.Context.getTypeSizeInChars(T).getQuantity());
10557 
10558   // Take the address of the field references for "from" and "to". We
10559   // directly construct UnaryOperators here because semantic analysis
10560   // does not permit us to take the address of an xvalue.
10561   Expr *From = FromB.build(S, Loc);
10562   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
10563                          S.Context.getPointerType(From->getType()),
10564                          VK_RValue, OK_Ordinary, Loc);
10565   Expr *To = ToB.build(S, Loc);
10566   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
10567                        S.Context.getPointerType(To->getType()),
10568                        VK_RValue, OK_Ordinary, Loc);
10569 
10570   const Type *E = T->getBaseElementTypeUnsafe();
10571   bool NeedsCollectableMemCpy =
10572     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
10573 
10574   // Create a reference to the __builtin_objc_memmove_collectable function
10575   StringRef MemCpyName = NeedsCollectableMemCpy ?
10576     "__builtin_objc_memmove_collectable" :
10577     "__builtin_memcpy";
10578   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
10579                  Sema::LookupOrdinaryName);
10580   S.LookupName(R, S.TUScope, true);
10581 
10582   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
10583   if (!MemCpy)
10584     // Something went horribly wrong earlier, and we will have complained
10585     // about it.
10586     return StmtError();
10587 
10588   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
10589                                             VK_RValue, Loc, nullptr);
10590   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
10591 
10592   Expr *CallArgs[] = {
10593     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
10594   };
10595   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
10596                                     Loc, CallArgs, Loc);
10597 
10598   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
10599   return Call.getAs<Stmt>();
10600 }
10601 
10602 /// \brief Builds a statement that copies/moves the given entity from \p From to
10603 /// \c To.
10604 ///
10605 /// This routine is used to copy/move the members of a class with an
10606 /// implicitly-declared copy/move assignment operator. When the entities being
10607 /// copied are arrays, this routine builds for loops to copy them.
10608 ///
10609 /// \param S The Sema object used for type-checking.
10610 ///
10611 /// \param Loc The location where the implicit copy/move is being generated.
10612 ///
10613 /// \param T The type of the expressions being copied/moved. Both expressions
10614 /// must have this type.
10615 ///
10616 /// \param To The expression we are copying/moving to.
10617 ///
10618 /// \param From The expression we are copying/moving from.
10619 ///
10620 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
10621 /// Otherwise, it's a non-static member subobject.
10622 ///
10623 /// \param Copying Whether we're copying or moving.
10624 ///
10625 /// \param Depth Internal parameter recording the depth of the recursion.
10626 ///
10627 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
10628 /// if a memcpy should be used instead.
10629 static StmtResult
10630 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
10631                                  const ExprBuilder &To, const ExprBuilder &From,
10632                                  bool CopyingBaseSubobject, bool Copying,
10633                                  unsigned Depth = 0) {
10634   // C++11 [class.copy]p28:
10635   //   Each subobject is assigned in the manner appropriate to its type:
10636   //
10637   //     - if the subobject is of class type, as if by a call to operator= with
10638   //       the subobject as the object expression and the corresponding
10639   //       subobject of x as a single function argument (as if by explicit
10640   //       qualification; that is, ignoring any possible virtual overriding
10641   //       functions in more derived classes);
10642   //
10643   // C++03 [class.copy]p13:
10644   //     - if the subobject is of class type, the copy assignment operator for
10645   //       the class is used (as if by explicit qualification; that is,
10646   //       ignoring any possible virtual overriding functions in more derived
10647   //       classes);
10648   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
10649     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
10650 
10651     // Look for operator=.
10652     DeclarationName Name
10653       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10654     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
10655     S.LookupQualifiedName(OpLookup, ClassDecl, false);
10656 
10657     // Prior to C++11, filter out any result that isn't a copy/move-assignment
10658     // operator.
10659     if (!S.getLangOpts().CPlusPlus11) {
10660       LookupResult::Filter F = OpLookup.makeFilter();
10661       while (F.hasNext()) {
10662         NamedDecl *D = F.next();
10663         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
10664           if (Method->isCopyAssignmentOperator() ||
10665               (!Copying && Method->isMoveAssignmentOperator()))
10666             continue;
10667 
10668         F.erase();
10669       }
10670       F.done();
10671     }
10672 
10673     // Suppress the protected check (C++ [class.protected]) for each of the
10674     // assignment operators we found. This strange dance is required when
10675     // we're assigning via a base classes's copy-assignment operator. To
10676     // ensure that we're getting the right base class subobject (without
10677     // ambiguities), we need to cast "this" to that subobject type; to
10678     // ensure that we don't go through the virtual call mechanism, we need
10679     // to qualify the operator= name with the base class (see below). However,
10680     // this means that if the base class has a protected copy assignment
10681     // operator, the protected member access check will fail. So, we
10682     // rewrite "protected" access to "public" access in this case, since we
10683     // know by construction that we're calling from a derived class.
10684     if (CopyingBaseSubobject) {
10685       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
10686            L != LEnd; ++L) {
10687         if (L.getAccess() == AS_protected)
10688           L.setAccess(AS_public);
10689       }
10690     }
10691 
10692     // Create the nested-name-specifier that will be used to qualify the
10693     // reference to operator=; this is required to suppress the virtual
10694     // call mechanism.
10695     CXXScopeSpec SS;
10696     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
10697     SS.MakeTrivial(S.Context,
10698                    NestedNameSpecifier::Create(S.Context, nullptr, false,
10699                                                CanonicalT),
10700                    Loc);
10701 
10702     // Create the reference to operator=.
10703     ExprResult OpEqualRef
10704       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
10705                                    SS, /*TemplateKWLoc=*/SourceLocation(),
10706                                    /*FirstQualifierInScope=*/nullptr,
10707                                    OpLookup,
10708                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
10709                                    /*SuppressQualifierCheck=*/true);
10710     if (OpEqualRef.isInvalid())
10711       return StmtError();
10712 
10713     // Build the call to the assignment operator.
10714 
10715     Expr *FromInst = From.build(S, Loc);
10716     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
10717                                                   OpEqualRef.getAs<Expr>(),
10718                                                   Loc, FromInst, Loc);
10719     if (Call.isInvalid())
10720       return StmtError();
10721 
10722     // If we built a call to a trivial 'operator=' while copying an array,
10723     // bail out. We'll replace the whole shebang with a memcpy.
10724     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
10725     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
10726       return StmtResult((Stmt*)nullptr);
10727 
10728     // Convert to an expression-statement, and clean up any produced
10729     // temporaries.
10730     return S.ActOnExprStmt(Call);
10731   }
10732 
10733   //     - if the subobject is of scalar type, the built-in assignment
10734   //       operator is used.
10735   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
10736   if (!ArrayTy) {
10737     ExprResult Assignment = S.CreateBuiltinBinOp(
10738         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
10739     if (Assignment.isInvalid())
10740       return StmtError();
10741     return S.ActOnExprStmt(Assignment);
10742   }
10743 
10744   //     - if the subobject is an array, each element is assigned, in the
10745   //       manner appropriate to the element type;
10746 
10747   // Construct a loop over the array bounds, e.g.,
10748   //
10749   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
10750   //
10751   // that will copy each of the array elements.
10752   QualType SizeType = S.Context.getSizeType();
10753 
10754   // Create the iteration variable.
10755   IdentifierInfo *IterationVarName = nullptr;
10756   {
10757     SmallString<8> Str;
10758     llvm::raw_svector_ostream OS(Str);
10759     OS << "__i" << Depth;
10760     IterationVarName = &S.Context.Idents.get(OS.str());
10761   }
10762   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10763                                           IterationVarName, SizeType,
10764                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10765                                           SC_None);
10766 
10767   // Initialize the iteration variable to zero.
10768   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
10769   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
10770 
10771   // Creates a reference to the iteration variable.
10772   RefBuilder IterationVarRef(IterationVar, SizeType);
10773   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
10774 
10775   // Create the DeclStmt that holds the iteration variable.
10776   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
10777 
10778   // Subscript the "from" and "to" expressions with the iteration variable.
10779   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
10780   MoveCastBuilder FromIndexMove(FromIndexCopy);
10781   const ExprBuilder *FromIndex;
10782   if (Copying)
10783     FromIndex = &FromIndexCopy;
10784   else
10785     FromIndex = &FromIndexMove;
10786 
10787   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
10788 
10789   // Build the copy/move for an individual element of the array.
10790   StmtResult Copy =
10791     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
10792                                      ToIndex, *FromIndex, CopyingBaseSubobject,
10793                                      Copying, Depth + 1);
10794   // Bail out if copying fails or if we determined that we should use memcpy.
10795   if (Copy.isInvalid() || !Copy.get())
10796     return Copy;
10797 
10798   // Create the comparison against the array bound.
10799   llvm::APInt Upper
10800     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
10801   Expr *Comparison
10802     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
10803                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
10804                                      BO_NE, S.Context.BoolTy,
10805                                      VK_RValue, OK_Ordinary, Loc, false);
10806 
10807   // Create the pre-increment of the iteration variable.
10808   Expr *Increment
10809     = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
10810                                     SizeType, VK_LValue, OK_Ordinary, Loc);
10811 
10812   // Construct the loop that copies all elements of this array.
10813   return S.ActOnForStmt(
10814       Loc, Loc, InitStmt,
10815       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
10816       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
10817 }
10818 
10819 static StmtResult
10820 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
10821                       const ExprBuilder &To, const ExprBuilder &From,
10822                       bool CopyingBaseSubobject, bool Copying) {
10823   // Maybe we should use a memcpy?
10824   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
10825       T.isTriviallyCopyableType(S.Context))
10826     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
10827 
10828   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
10829                                                      CopyingBaseSubobject,
10830                                                      Copying, 0));
10831 
10832   // If we ended up picking a trivial assignment operator for an array of a
10833   // non-trivially-copyable class type, just emit a memcpy.
10834   if (!Result.isInvalid() && !Result.get())
10835     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
10836 
10837   return Result;
10838 }
10839 
10840 Sema::ImplicitExceptionSpecification
10841 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
10842   CXXRecordDecl *ClassDecl = MD->getParent();
10843 
10844   ImplicitExceptionSpecification ExceptSpec(*this);
10845   if (ClassDecl->isInvalidDecl())
10846     return ExceptSpec;
10847 
10848   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
10849   assert(T->getNumParams() == 1 && "not a copy assignment op");
10850   unsigned ArgQuals =
10851       T->getParamType(0).getNonReferenceType().getCVRQualifiers();
10852 
10853   // C++ [except.spec]p14:
10854   //   An implicitly declared special member function (Clause 12) shall have an
10855   //   exception-specification. [...]
10856 
10857   // It is unspecified whether or not an implicit copy assignment operator
10858   // attempts to deduplicate calls to assignment operators of virtual bases are
10859   // made. As such, this exception specification is effectively unspecified.
10860   // Based on a similar decision made for constness in C++0x, we're erring on
10861   // the side of assuming such calls to be made regardless of whether they
10862   // actually happen.
10863   for (const auto &Base : ClassDecl->bases()) {
10864     if (Base.isVirtual())
10865       continue;
10866 
10867     CXXRecordDecl *BaseClassDecl
10868       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10869     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
10870                                                             ArgQuals, false, 0))
10871       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
10872   }
10873 
10874   for (const auto &Base : ClassDecl->vbases()) {
10875     CXXRecordDecl *BaseClassDecl
10876       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10877     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
10878                                                             ArgQuals, false, 0))
10879       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
10880   }
10881 
10882   for (const auto *Field : ClassDecl->fields()) {
10883     QualType FieldType = Context.getBaseElementType(Field->getType());
10884     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10885       if (CXXMethodDecl *CopyAssign =
10886           LookupCopyingAssignment(FieldClassDecl,
10887                                   ArgQuals | FieldType.getCVRQualifiers(),
10888                                   false, 0))
10889         ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
10890     }
10891   }
10892 
10893   return ExceptSpec;
10894 }
10895 
10896 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
10897   // Note: The following rules are largely analoguous to the copy
10898   // constructor rules. Note that virtual bases are not taken into account
10899   // for determining the argument type of the operator. Note also that
10900   // operators taking an object instead of a reference are allowed.
10901   assert(ClassDecl->needsImplicitCopyAssignment());
10902 
10903   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
10904   if (DSM.isAlreadyBeingDeclared())
10905     return nullptr;
10906 
10907   QualType ArgType = Context.getTypeDeclType(ClassDecl);
10908   QualType RetType = Context.getLValueReferenceType(ArgType);
10909   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
10910   if (Const)
10911     ArgType = ArgType.withConst();
10912   ArgType = Context.getLValueReferenceType(ArgType);
10913 
10914   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10915                                                      CXXCopyAssignment,
10916                                                      Const);
10917 
10918   //   An implicitly-declared copy assignment operator is an inline public
10919   //   member of its class.
10920   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10921   SourceLocation ClassLoc = ClassDecl->getLocation();
10922   DeclarationNameInfo NameInfo(Name, ClassLoc);
10923   CXXMethodDecl *CopyAssignment =
10924       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
10925                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10926                             /*isInline=*/true, Constexpr, SourceLocation());
10927   CopyAssignment->setAccess(AS_public);
10928   CopyAssignment->setDefaulted();
10929   CopyAssignment->setImplicit();
10930 
10931   if (getLangOpts().CUDA) {
10932     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
10933                                             CopyAssignment,
10934                                             /* ConstRHS */ Const,
10935                                             /* Diagnose */ false);
10936   }
10937 
10938   // Build an exception specification pointing back at this member.
10939   FunctionProtoType::ExtProtoInfo EPI =
10940       getImplicitMethodEPI(*this, CopyAssignment);
10941   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
10942 
10943   // Add the parameter to the operator.
10944   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
10945                                                ClassLoc, ClassLoc,
10946                                                /*Id=*/nullptr, ArgType,
10947                                                /*TInfo=*/nullptr, SC_None,
10948                                                nullptr);
10949   CopyAssignment->setParams(FromParam);
10950 
10951   CopyAssignment->setTrivial(
10952     ClassDecl->needsOverloadResolutionForCopyAssignment()
10953       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
10954       : ClassDecl->hasTrivialCopyAssignment());
10955 
10956   // Note that we have added this copy-assignment operator.
10957   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
10958 
10959   Scope *S = getScopeForContext(ClassDecl);
10960   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
10961 
10962   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
10963     SetDeclDeleted(CopyAssignment, ClassLoc);
10964 
10965   if (S)
10966     PushOnScopeChains(CopyAssignment, S, false);
10967   ClassDecl->addDecl(CopyAssignment);
10968 
10969   return CopyAssignment;
10970 }
10971 
10972 /// Diagnose an implicit copy operation for a class which is odr-used, but
10973 /// which is deprecated because the class has a user-declared copy constructor,
10974 /// copy assignment operator, or destructor.
10975 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
10976                                             SourceLocation UseLoc) {
10977   assert(CopyOp->isImplicit());
10978 
10979   CXXRecordDecl *RD = CopyOp->getParent();
10980   CXXMethodDecl *UserDeclaredOperation = nullptr;
10981 
10982   // In Microsoft mode, assignment operations don't affect constructors and
10983   // vice versa.
10984   if (RD->hasUserDeclaredDestructor()) {
10985     UserDeclaredOperation = RD->getDestructor();
10986   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
10987              RD->hasUserDeclaredCopyConstructor() &&
10988              !S.getLangOpts().MSVCCompat) {
10989     // Find any user-declared copy constructor.
10990     for (auto *I : RD->ctors()) {
10991       if (I->isCopyConstructor()) {
10992         UserDeclaredOperation = I;
10993         break;
10994       }
10995     }
10996     assert(UserDeclaredOperation);
10997   } else if (isa<CXXConstructorDecl>(CopyOp) &&
10998              RD->hasUserDeclaredCopyAssignment() &&
10999              !S.getLangOpts().MSVCCompat) {
11000     // Find any user-declared move assignment operator.
11001     for (auto *I : RD->methods()) {
11002       if (I->isCopyAssignmentOperator()) {
11003         UserDeclaredOperation = I;
11004         break;
11005       }
11006     }
11007     assert(UserDeclaredOperation);
11008   }
11009 
11010   if (UserDeclaredOperation) {
11011     S.Diag(UserDeclaredOperation->getLocation(),
11012          diag::warn_deprecated_copy_operation)
11013       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
11014       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
11015     S.Diag(UseLoc, diag::note_member_synthesized_at)
11016       << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
11017                                           : Sema::CXXCopyAssignment)
11018       << RD;
11019   }
11020 }
11021 
11022 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
11023                                         CXXMethodDecl *CopyAssignOperator) {
11024   assert((CopyAssignOperator->isDefaulted() &&
11025           CopyAssignOperator->isOverloadedOperator() &&
11026           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
11027           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
11028           !CopyAssignOperator->isDeleted()) &&
11029          "DefineImplicitCopyAssignment called for wrong function");
11030 
11031   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
11032 
11033   if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
11034     CopyAssignOperator->setInvalidDecl();
11035     return;
11036   }
11037 
11038   // C++11 [class.copy]p18:
11039   //   The [definition of an implicitly declared copy assignment operator] is
11040   //   deprecated if the class has a user-declared copy constructor or a
11041   //   user-declared destructor.
11042   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
11043     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
11044 
11045   CopyAssignOperator->markUsed(Context);
11046 
11047   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
11048   DiagnosticErrorTrap Trap(Diags);
11049 
11050   // C++0x [class.copy]p30:
11051   //   The implicitly-defined or explicitly-defaulted copy assignment operator
11052   //   for a non-union class X performs memberwise copy assignment of its
11053   //   subobjects. The direct base classes of X are assigned first, in the
11054   //   order of their declaration in the base-specifier-list, and then the
11055   //   immediate non-static data members of X are assigned, in the order in
11056   //   which they were declared in the class definition.
11057 
11058   // The statements that form the synthesized function body.
11059   SmallVector<Stmt*, 8> Statements;
11060 
11061   // The parameter for the "other" object, which we are copying from.
11062   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
11063   Qualifiers OtherQuals = Other->getType().getQualifiers();
11064   QualType OtherRefType = Other->getType();
11065   if (const LValueReferenceType *OtherRef
11066                                 = OtherRefType->getAs<LValueReferenceType>()) {
11067     OtherRefType = OtherRef->getPointeeType();
11068     OtherQuals = OtherRefType.getQualifiers();
11069   }
11070 
11071   // Our location for everything implicitly-generated.
11072   SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
11073                            ? CopyAssignOperator->getLocEnd()
11074                            : CopyAssignOperator->getLocation();
11075 
11076   // Builds a DeclRefExpr for the "other" object.
11077   RefBuilder OtherRef(Other, OtherRefType);
11078 
11079   // Builds the "this" pointer.
11080   ThisBuilder This;
11081 
11082   // Assign base classes.
11083   bool Invalid = false;
11084   for (auto &Base : ClassDecl->bases()) {
11085     // Form the assignment:
11086     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
11087     QualType BaseType = Base.getType().getUnqualifiedType();
11088     if (!BaseType->isRecordType()) {
11089       Invalid = true;
11090       continue;
11091     }
11092 
11093     CXXCastPath BasePath;
11094     BasePath.push_back(&Base);
11095 
11096     // Construct the "from" expression, which is an implicit cast to the
11097     // appropriately-qualified base type.
11098     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
11099                      VK_LValue, BasePath);
11100 
11101     // Dereference "this".
11102     DerefBuilder DerefThis(This);
11103     CastBuilder To(DerefThis,
11104                    Context.getCVRQualifiedType(
11105                        BaseType, CopyAssignOperator->getTypeQualifiers()),
11106                    VK_LValue, BasePath);
11107 
11108     // Build the copy.
11109     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
11110                                             To, From,
11111                                             /*CopyingBaseSubobject=*/true,
11112                                             /*Copying=*/true);
11113     if (Copy.isInvalid()) {
11114       Diag(CurrentLocation, diag::note_member_synthesized_at)
11115         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11116       CopyAssignOperator->setInvalidDecl();
11117       return;
11118     }
11119 
11120     // Success! Record the copy.
11121     Statements.push_back(Copy.getAs<Expr>());
11122   }
11123 
11124   // Assign non-static members.
11125   for (auto *Field : ClassDecl->fields()) {
11126     // FIXME: We should form some kind of AST representation for the implied
11127     // memcpy in a union copy operation.
11128     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
11129       continue;
11130 
11131     if (Field->isInvalidDecl()) {
11132       Invalid = true;
11133       continue;
11134     }
11135 
11136     // Check for members of reference type; we can't copy those.
11137     if (Field->getType()->isReferenceType()) {
11138       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11139         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11140       Diag(Field->getLocation(), diag::note_declared_at);
11141       Diag(CurrentLocation, diag::note_member_synthesized_at)
11142         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11143       Invalid = true;
11144       continue;
11145     }
11146 
11147     // Check for members of const-qualified, non-class type.
11148     QualType BaseType = Context.getBaseElementType(Field->getType());
11149     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11150       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11151         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11152       Diag(Field->getLocation(), diag::note_declared_at);
11153       Diag(CurrentLocation, diag::note_member_synthesized_at)
11154         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11155       Invalid = true;
11156       continue;
11157     }
11158 
11159     // Suppress assigning zero-width bitfields.
11160     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
11161       continue;
11162 
11163     QualType FieldType = Field->getType().getNonReferenceType();
11164     if (FieldType->isIncompleteArrayType()) {
11165       assert(ClassDecl->hasFlexibleArrayMember() &&
11166              "Incomplete array type is not valid");
11167       continue;
11168     }
11169 
11170     // Build references to the field in the object we're copying from and to.
11171     CXXScopeSpec SS; // Intentionally empty
11172     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11173                               LookupMemberName);
11174     MemberLookup.addDecl(Field);
11175     MemberLookup.resolveKind();
11176 
11177     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
11178 
11179     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
11180 
11181     // Build the copy of this field.
11182     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
11183                                             To, From,
11184                                             /*CopyingBaseSubobject=*/false,
11185                                             /*Copying=*/true);
11186     if (Copy.isInvalid()) {
11187       Diag(CurrentLocation, diag::note_member_synthesized_at)
11188         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11189       CopyAssignOperator->setInvalidDecl();
11190       return;
11191     }
11192 
11193     // Success! Record the copy.
11194     Statements.push_back(Copy.getAs<Stmt>());
11195   }
11196 
11197   if (!Invalid) {
11198     // Add a "return *this;"
11199     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
11200 
11201     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
11202     if (Return.isInvalid())
11203       Invalid = true;
11204     else {
11205       Statements.push_back(Return.getAs<Stmt>());
11206 
11207       if (Trap.hasErrorOccurred()) {
11208         Diag(CurrentLocation, diag::note_member_synthesized_at)
11209           << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11210         Invalid = true;
11211       }
11212     }
11213   }
11214 
11215   // The exception specification is needed because we are defining the
11216   // function.
11217   ResolveExceptionSpec(CurrentLocation,
11218                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
11219 
11220   if (Invalid) {
11221     CopyAssignOperator->setInvalidDecl();
11222     return;
11223   }
11224 
11225   StmtResult Body;
11226   {
11227     CompoundScopeRAII CompoundScope(*this);
11228     Body = ActOnCompoundStmt(Loc, Loc, Statements,
11229                              /*isStmtExpr=*/false);
11230     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11231   }
11232   CopyAssignOperator->setBody(Body.getAs<Stmt>());
11233 
11234   if (ASTMutationListener *L = getASTMutationListener()) {
11235     L->CompletedImplicitDefinition(CopyAssignOperator);
11236   }
11237 }
11238 
11239 Sema::ImplicitExceptionSpecification
11240 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
11241   CXXRecordDecl *ClassDecl = MD->getParent();
11242 
11243   ImplicitExceptionSpecification ExceptSpec(*this);
11244   if (ClassDecl->isInvalidDecl())
11245     return ExceptSpec;
11246 
11247   // C++0x [except.spec]p14:
11248   //   An implicitly declared special member function (Clause 12) shall have an
11249   //   exception-specification. [...]
11250 
11251   // It is unspecified whether or not an implicit move assignment operator
11252   // attempts to deduplicate calls to assignment operators of virtual bases are
11253   // made. As such, this exception specification is effectively unspecified.
11254   // Based on a similar decision made for constness in C++0x, we're erring on
11255   // the side of assuming such calls to be made regardless of whether they
11256   // actually happen.
11257   // Note that a move constructor is not implicitly declared when there are
11258   // virtual bases, but it can still be user-declared and explicitly defaulted.
11259   for (const auto &Base : ClassDecl->bases()) {
11260     if (Base.isVirtual())
11261       continue;
11262 
11263     CXXRecordDecl *BaseClassDecl
11264       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
11265     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
11266                                                            0, false, 0))
11267       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
11268   }
11269 
11270   for (const auto &Base : ClassDecl->vbases()) {
11271     CXXRecordDecl *BaseClassDecl
11272       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
11273     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
11274                                                            0, false, 0))
11275       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
11276   }
11277 
11278   for (const auto *Field : ClassDecl->fields()) {
11279     QualType FieldType = Context.getBaseElementType(Field->getType());
11280     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
11281       if (CXXMethodDecl *MoveAssign =
11282               LookupMovingAssignment(FieldClassDecl,
11283                                      FieldType.getCVRQualifiers(),
11284                                      false, 0))
11285         ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
11286     }
11287   }
11288 
11289   return ExceptSpec;
11290 }
11291 
11292 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
11293   assert(ClassDecl->needsImplicitMoveAssignment());
11294 
11295   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
11296   if (DSM.isAlreadyBeingDeclared())
11297     return nullptr;
11298 
11299   // Note: The following rules are largely analoguous to the move
11300   // constructor rules.
11301 
11302   QualType ArgType = Context.getTypeDeclType(ClassDecl);
11303   QualType RetType = Context.getLValueReferenceType(ArgType);
11304   ArgType = Context.getRValueReferenceType(ArgType);
11305 
11306   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11307                                                      CXXMoveAssignment,
11308                                                      false);
11309 
11310   //   An implicitly-declared move assignment operator is an inline public
11311   //   member of its class.
11312   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11313   SourceLocation ClassLoc = ClassDecl->getLocation();
11314   DeclarationNameInfo NameInfo(Name, ClassLoc);
11315   CXXMethodDecl *MoveAssignment =
11316       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11317                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11318                             /*isInline=*/true, Constexpr, SourceLocation());
11319   MoveAssignment->setAccess(AS_public);
11320   MoveAssignment->setDefaulted();
11321   MoveAssignment->setImplicit();
11322 
11323   if (getLangOpts().CUDA) {
11324     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
11325                                             MoveAssignment,
11326                                             /* ConstRHS */ false,
11327                                             /* Diagnose */ false);
11328   }
11329 
11330   // Build an exception specification pointing back at this member.
11331   FunctionProtoType::ExtProtoInfo EPI =
11332       getImplicitMethodEPI(*this, MoveAssignment);
11333   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
11334 
11335   // Add the parameter to the operator.
11336   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
11337                                                ClassLoc, ClassLoc,
11338                                                /*Id=*/nullptr, ArgType,
11339                                                /*TInfo=*/nullptr, SC_None,
11340                                                nullptr);
11341   MoveAssignment->setParams(FromParam);
11342 
11343   MoveAssignment->setTrivial(
11344     ClassDecl->needsOverloadResolutionForMoveAssignment()
11345       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
11346       : ClassDecl->hasTrivialMoveAssignment());
11347 
11348   // Note that we have added this copy-assignment operator.
11349   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
11350 
11351   Scope *S = getScopeForContext(ClassDecl);
11352   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
11353 
11354   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
11355     ClassDecl->setImplicitMoveAssignmentIsDeleted();
11356     SetDeclDeleted(MoveAssignment, ClassLoc);
11357   }
11358 
11359   if (S)
11360     PushOnScopeChains(MoveAssignment, S, false);
11361   ClassDecl->addDecl(MoveAssignment);
11362 
11363   return MoveAssignment;
11364 }
11365 
11366 /// Check if we're implicitly defining a move assignment operator for a class
11367 /// with virtual bases. Such a move assignment might move-assign the virtual
11368 /// base multiple times.
11369 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
11370                                                SourceLocation CurrentLocation) {
11371   assert(!Class->isDependentContext() && "should not define dependent move");
11372 
11373   // Only a virtual base could get implicitly move-assigned multiple times.
11374   // Only a non-trivial move assignment can observe this. We only want to
11375   // diagnose if we implicitly define an assignment operator that assigns
11376   // two base classes, both of which move-assign the same virtual base.
11377   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
11378       Class->getNumBases() < 2)
11379     return;
11380 
11381   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
11382   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
11383   VBaseMap VBases;
11384 
11385   for (auto &BI : Class->bases()) {
11386     Worklist.push_back(&BI);
11387     while (!Worklist.empty()) {
11388       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
11389       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
11390 
11391       // If the base has no non-trivial move assignment operators,
11392       // we don't care about moves from it.
11393       if (!Base->hasNonTrivialMoveAssignment())
11394         continue;
11395 
11396       // If there's nothing virtual here, skip it.
11397       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
11398         continue;
11399 
11400       // If we're not actually going to call a move assignment for this base,
11401       // or the selected move assignment is trivial, skip it.
11402       Sema::SpecialMemberOverloadResult *SMOR =
11403         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
11404                               /*ConstArg*/false, /*VolatileArg*/false,
11405                               /*RValueThis*/true, /*ConstThis*/false,
11406                               /*VolatileThis*/false);
11407       if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
11408           !SMOR->getMethod()->isMoveAssignmentOperator())
11409         continue;
11410 
11411       if (BaseSpec->isVirtual()) {
11412         // We're going to move-assign this virtual base, and its move
11413         // assignment operator is not trivial. If this can happen for
11414         // multiple distinct direct bases of Class, diagnose it. (If it
11415         // only happens in one base, we'll diagnose it when synthesizing
11416         // that base class's move assignment operator.)
11417         CXXBaseSpecifier *&Existing =
11418             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
11419                 .first->second;
11420         if (Existing && Existing != &BI) {
11421           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
11422             << Class << Base;
11423           S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
11424             << (Base->getCanonicalDecl() ==
11425                 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
11426             << Base << Existing->getType() << Existing->getSourceRange();
11427           S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
11428             << (Base->getCanonicalDecl() ==
11429                 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
11430             << Base << BI.getType() << BaseSpec->getSourceRange();
11431 
11432           // Only diagnose each vbase once.
11433           Existing = nullptr;
11434         }
11435       } else {
11436         // Only walk over bases that have defaulted move assignment operators.
11437         // We assume that any user-provided move assignment operator handles
11438         // the multiple-moves-of-vbase case itself somehow.
11439         if (!SMOR->getMethod()->isDefaulted())
11440           continue;
11441 
11442         // We're going to move the base classes of Base. Add them to the list.
11443         for (auto &BI : Base->bases())
11444           Worklist.push_back(&BI);
11445       }
11446     }
11447   }
11448 }
11449 
11450 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
11451                                         CXXMethodDecl *MoveAssignOperator) {
11452   assert((MoveAssignOperator->isDefaulted() &&
11453           MoveAssignOperator->isOverloadedOperator() &&
11454           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
11455           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
11456           !MoveAssignOperator->isDeleted()) &&
11457          "DefineImplicitMoveAssignment called for wrong function");
11458 
11459   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
11460 
11461   if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
11462     MoveAssignOperator->setInvalidDecl();
11463     return;
11464   }
11465 
11466   MoveAssignOperator->markUsed(Context);
11467 
11468   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
11469   DiagnosticErrorTrap Trap(Diags);
11470 
11471   // C++0x [class.copy]p28:
11472   //   The implicitly-defined or move assignment operator for a non-union class
11473   //   X performs memberwise move assignment of its subobjects. The direct base
11474   //   classes of X are assigned first, in the order of their declaration in the
11475   //   base-specifier-list, and then the immediate non-static data members of X
11476   //   are assigned, in the order in which they were declared in the class
11477   //   definition.
11478 
11479   // Issue a warning if our implicit move assignment operator will move
11480   // from a virtual base more than once.
11481   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
11482 
11483   // The statements that form the synthesized function body.
11484   SmallVector<Stmt*, 8> Statements;
11485 
11486   // The parameter for the "other" object, which we are move from.
11487   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
11488   QualType OtherRefType = Other->getType()->
11489       getAs<RValueReferenceType>()->getPointeeType();
11490   assert(!OtherRefType.getQualifiers() &&
11491          "Bad argument type of defaulted move assignment");
11492 
11493   // Our location for everything implicitly-generated.
11494   SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
11495                            ? MoveAssignOperator->getLocEnd()
11496                            : MoveAssignOperator->getLocation();
11497 
11498   // Builds a reference to the "other" object.
11499   RefBuilder OtherRef(Other, OtherRefType);
11500   // Cast to rvalue.
11501   MoveCastBuilder MoveOther(OtherRef);
11502 
11503   // Builds the "this" pointer.
11504   ThisBuilder This;
11505 
11506   // Assign base classes.
11507   bool Invalid = false;
11508   for (auto &Base : ClassDecl->bases()) {
11509     // C++11 [class.copy]p28:
11510     //   It is unspecified whether subobjects representing virtual base classes
11511     //   are assigned more than once by the implicitly-defined copy assignment
11512     //   operator.
11513     // FIXME: Do not assign to a vbase that will be assigned by some other base
11514     // class. For a move-assignment, this can result in the vbase being moved
11515     // multiple times.
11516 
11517     // Form the assignment:
11518     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
11519     QualType BaseType = Base.getType().getUnqualifiedType();
11520     if (!BaseType->isRecordType()) {
11521       Invalid = true;
11522       continue;
11523     }
11524 
11525     CXXCastPath BasePath;
11526     BasePath.push_back(&Base);
11527 
11528     // Construct the "from" expression, which is an implicit cast to the
11529     // appropriately-qualified base type.
11530     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
11531 
11532     // Dereference "this".
11533     DerefBuilder DerefThis(This);
11534 
11535     // Implicitly cast "this" to the appropriately-qualified base type.
11536     CastBuilder To(DerefThis,
11537                    Context.getCVRQualifiedType(
11538                        BaseType, MoveAssignOperator->getTypeQualifiers()),
11539                    VK_LValue, BasePath);
11540 
11541     // Build the move.
11542     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
11543                                             To, From,
11544                                             /*CopyingBaseSubobject=*/true,
11545                                             /*Copying=*/false);
11546     if (Move.isInvalid()) {
11547       Diag(CurrentLocation, diag::note_member_synthesized_at)
11548         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11549       MoveAssignOperator->setInvalidDecl();
11550       return;
11551     }
11552 
11553     // Success! Record the move.
11554     Statements.push_back(Move.getAs<Expr>());
11555   }
11556 
11557   // Assign non-static members.
11558   for (auto *Field : ClassDecl->fields()) {
11559     // FIXME: We should form some kind of AST representation for the implied
11560     // memcpy in a union copy operation.
11561     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
11562       continue;
11563 
11564     if (Field->isInvalidDecl()) {
11565       Invalid = true;
11566       continue;
11567     }
11568 
11569     // Check for members of reference type; we can't move those.
11570     if (Field->getType()->isReferenceType()) {
11571       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11572         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11573       Diag(Field->getLocation(), diag::note_declared_at);
11574       Diag(CurrentLocation, diag::note_member_synthesized_at)
11575         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11576       Invalid = true;
11577       continue;
11578     }
11579 
11580     // Check for members of const-qualified, non-class type.
11581     QualType BaseType = Context.getBaseElementType(Field->getType());
11582     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11583       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11584         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11585       Diag(Field->getLocation(), diag::note_declared_at);
11586       Diag(CurrentLocation, diag::note_member_synthesized_at)
11587         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11588       Invalid = true;
11589       continue;
11590     }
11591 
11592     // Suppress assigning zero-width bitfields.
11593     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
11594       continue;
11595 
11596     QualType FieldType = Field->getType().getNonReferenceType();
11597     if (FieldType->isIncompleteArrayType()) {
11598       assert(ClassDecl->hasFlexibleArrayMember() &&
11599              "Incomplete array type is not valid");
11600       continue;
11601     }
11602 
11603     // Build references to the field in the object we're copying from and to.
11604     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11605                               LookupMemberName);
11606     MemberLookup.addDecl(Field);
11607     MemberLookup.resolveKind();
11608     MemberBuilder From(MoveOther, OtherRefType,
11609                        /*IsArrow=*/false, MemberLookup);
11610     MemberBuilder To(This, getCurrentThisType(),
11611                      /*IsArrow=*/true, MemberLookup);
11612 
11613     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
11614         "Member reference with rvalue base must be rvalue except for reference "
11615         "members, which aren't allowed for move assignment.");
11616 
11617     // Build the move of this field.
11618     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
11619                                             To, From,
11620                                             /*CopyingBaseSubobject=*/false,
11621                                             /*Copying=*/false);
11622     if (Move.isInvalid()) {
11623       Diag(CurrentLocation, diag::note_member_synthesized_at)
11624         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11625       MoveAssignOperator->setInvalidDecl();
11626       return;
11627     }
11628 
11629     // Success! Record the copy.
11630     Statements.push_back(Move.getAs<Stmt>());
11631   }
11632 
11633   if (!Invalid) {
11634     // Add a "return *this;"
11635     ExprResult ThisObj =
11636         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
11637 
11638     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
11639     if (Return.isInvalid())
11640       Invalid = true;
11641     else {
11642       Statements.push_back(Return.getAs<Stmt>());
11643 
11644       if (Trap.hasErrorOccurred()) {
11645         Diag(CurrentLocation, diag::note_member_synthesized_at)
11646           << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11647         Invalid = true;
11648       }
11649     }
11650   }
11651 
11652   // The exception specification is needed because we are defining the
11653   // function.
11654   ResolveExceptionSpec(CurrentLocation,
11655                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
11656 
11657   if (Invalid) {
11658     MoveAssignOperator->setInvalidDecl();
11659     return;
11660   }
11661 
11662   StmtResult Body;
11663   {
11664     CompoundScopeRAII CompoundScope(*this);
11665     Body = ActOnCompoundStmt(Loc, Loc, Statements,
11666                              /*isStmtExpr=*/false);
11667     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11668   }
11669   MoveAssignOperator->setBody(Body.getAs<Stmt>());
11670 
11671   if (ASTMutationListener *L = getASTMutationListener()) {
11672     L->CompletedImplicitDefinition(MoveAssignOperator);
11673   }
11674 }
11675 
11676 Sema::ImplicitExceptionSpecification
11677 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
11678   CXXRecordDecl *ClassDecl = MD->getParent();
11679 
11680   ImplicitExceptionSpecification ExceptSpec(*this);
11681   if (ClassDecl->isInvalidDecl())
11682     return ExceptSpec;
11683 
11684   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
11685   assert(T->getNumParams() >= 1 && "not a copy ctor");
11686   unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
11687 
11688   // C++ [except.spec]p14:
11689   //   An implicitly declared special member function (Clause 12) shall have an
11690   //   exception-specification. [...]
11691   for (const auto &Base : ClassDecl->bases()) {
11692     // Virtual bases are handled below.
11693     if (Base.isVirtual())
11694       continue;
11695 
11696     CXXRecordDecl *BaseClassDecl
11697       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
11698     if (CXXConstructorDecl *CopyConstructor =
11699           LookupCopyingConstructor(BaseClassDecl, Quals))
11700       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
11701   }
11702   for (const auto &Base : ClassDecl->vbases()) {
11703     CXXRecordDecl *BaseClassDecl
11704       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
11705     if (CXXConstructorDecl *CopyConstructor =
11706           LookupCopyingConstructor(BaseClassDecl, Quals))
11707       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
11708   }
11709   for (const auto *Field : ClassDecl->fields()) {
11710     QualType FieldType = Context.getBaseElementType(Field->getType());
11711     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
11712       if (CXXConstructorDecl *CopyConstructor =
11713               LookupCopyingConstructor(FieldClassDecl,
11714                                        Quals | FieldType.getCVRQualifiers()))
11715       ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
11716     }
11717   }
11718 
11719   return ExceptSpec;
11720 }
11721 
11722 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
11723                                                     CXXRecordDecl *ClassDecl) {
11724   // C++ [class.copy]p4:
11725   //   If the class definition does not explicitly declare a copy
11726   //   constructor, one is declared implicitly.
11727   assert(ClassDecl->needsImplicitCopyConstructor());
11728 
11729   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
11730   if (DSM.isAlreadyBeingDeclared())
11731     return nullptr;
11732 
11733   QualType ClassType = Context.getTypeDeclType(ClassDecl);
11734   QualType ArgType = ClassType;
11735   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
11736   if (Const)
11737     ArgType = ArgType.withConst();
11738   ArgType = Context.getLValueReferenceType(ArgType);
11739 
11740   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11741                                                      CXXCopyConstructor,
11742                                                      Const);
11743 
11744   DeclarationName Name
11745     = Context.DeclarationNames.getCXXConstructorName(
11746                                            Context.getCanonicalType(ClassType));
11747   SourceLocation ClassLoc = ClassDecl->getLocation();
11748   DeclarationNameInfo NameInfo(Name, ClassLoc);
11749 
11750   //   An implicitly-declared copy constructor is an inline public
11751   //   member of its class.
11752   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
11753       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
11754       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
11755       Constexpr);
11756   CopyConstructor->setAccess(AS_public);
11757   CopyConstructor->setDefaulted();
11758 
11759   if (getLangOpts().CUDA) {
11760     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
11761                                             CopyConstructor,
11762                                             /* ConstRHS */ Const,
11763                                             /* Diagnose */ false);
11764   }
11765 
11766   // Build an exception specification pointing back at this member.
11767   FunctionProtoType::ExtProtoInfo EPI =
11768       getImplicitMethodEPI(*this, CopyConstructor);
11769   CopyConstructor->setType(
11770       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
11771 
11772   // Add the parameter to the constructor.
11773   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
11774                                                ClassLoc, ClassLoc,
11775                                                /*IdentifierInfo=*/nullptr,
11776                                                ArgType, /*TInfo=*/nullptr,
11777                                                SC_None, nullptr);
11778   CopyConstructor->setParams(FromParam);
11779 
11780   CopyConstructor->setTrivial(
11781     ClassDecl->needsOverloadResolutionForCopyConstructor()
11782       ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
11783       : ClassDecl->hasTrivialCopyConstructor());
11784 
11785   // Note that we have declared this constructor.
11786   ++ASTContext::NumImplicitCopyConstructorsDeclared;
11787 
11788   Scope *S = getScopeForContext(ClassDecl);
11789   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
11790 
11791   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
11792     SetDeclDeleted(CopyConstructor, ClassLoc);
11793 
11794   if (S)
11795     PushOnScopeChains(CopyConstructor, S, false);
11796   ClassDecl->addDecl(CopyConstructor);
11797 
11798   return CopyConstructor;
11799 }
11800 
11801 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
11802                                    CXXConstructorDecl *CopyConstructor) {
11803   assert((CopyConstructor->isDefaulted() &&
11804           CopyConstructor->isCopyConstructor() &&
11805           !CopyConstructor->doesThisDeclarationHaveABody() &&
11806           !CopyConstructor->isDeleted()) &&
11807          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
11808 
11809   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
11810   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
11811 
11812   // C++11 [class.copy]p7:
11813   //   The [definition of an implicitly declared copy constructor] is
11814   //   deprecated if the class has a user-declared copy assignment operator
11815   //   or a user-declared destructor.
11816   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
11817     diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
11818 
11819   SynthesizedFunctionScope Scope(*this, CopyConstructor);
11820   DiagnosticErrorTrap Trap(Diags);
11821 
11822   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
11823       Trap.hasErrorOccurred()) {
11824     Diag(CurrentLocation, diag::note_member_synthesized_at)
11825       << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
11826     CopyConstructor->setInvalidDecl();
11827   }  else {
11828     SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
11829                              ? CopyConstructor->getLocEnd()
11830                              : CopyConstructor->getLocation();
11831     Sema::CompoundScopeRAII CompoundScope(*this);
11832     CopyConstructor->setBody(
11833         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
11834   }
11835 
11836   // The exception specification is needed because we are defining the
11837   // function.
11838   ResolveExceptionSpec(CurrentLocation,
11839                        CopyConstructor->getType()->castAs<FunctionProtoType>());
11840 
11841   CopyConstructor->markUsed(Context);
11842   MarkVTableUsed(CurrentLocation, ClassDecl);
11843 
11844   if (ASTMutationListener *L = getASTMutationListener()) {
11845     L->CompletedImplicitDefinition(CopyConstructor);
11846   }
11847 }
11848 
11849 Sema::ImplicitExceptionSpecification
11850 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
11851   CXXRecordDecl *ClassDecl = MD->getParent();
11852 
11853   // C++ [except.spec]p14:
11854   //   An implicitly declared special member function (Clause 12) shall have an
11855   //   exception-specification. [...]
11856   ImplicitExceptionSpecification ExceptSpec(*this);
11857   if (ClassDecl->isInvalidDecl())
11858     return ExceptSpec;
11859 
11860   // Direct base-class constructors.
11861   for (const auto &B : ClassDecl->bases()) {
11862     if (B.isVirtual()) // Handled below.
11863       continue;
11864 
11865     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
11866       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
11867       CXXConstructorDecl *Constructor =
11868           LookupMovingConstructor(BaseClassDecl, 0);
11869       // If this is a deleted function, add it anyway. This might be conformant
11870       // with the standard. This might not. I'm not sure. It might not matter.
11871       if (Constructor)
11872         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
11873     }
11874   }
11875 
11876   // Virtual base-class constructors.
11877   for (const auto &B : ClassDecl->vbases()) {
11878     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
11879       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
11880       CXXConstructorDecl *Constructor =
11881           LookupMovingConstructor(BaseClassDecl, 0);
11882       // If this is a deleted function, add it anyway. This might be conformant
11883       // with the standard. This might not. I'm not sure. It might not matter.
11884       if (Constructor)
11885         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
11886     }
11887   }
11888 
11889   // Field constructors.
11890   for (const auto *F : ClassDecl->fields()) {
11891     QualType FieldType = Context.getBaseElementType(F->getType());
11892     if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
11893       CXXConstructorDecl *Constructor =
11894           LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
11895       // If this is a deleted function, add it anyway. This might be conformant
11896       // with the standard. This might not. I'm not sure. It might not matter.
11897       // In particular, the problem is that this function never gets called. It
11898       // might just be ill-formed because this function attempts to refer to
11899       // a deleted function here.
11900       if (Constructor)
11901         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
11902     }
11903   }
11904 
11905   return ExceptSpec;
11906 }
11907 
11908 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
11909                                                     CXXRecordDecl *ClassDecl) {
11910   assert(ClassDecl->needsImplicitMoveConstructor());
11911 
11912   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
11913   if (DSM.isAlreadyBeingDeclared())
11914     return nullptr;
11915 
11916   QualType ClassType = Context.getTypeDeclType(ClassDecl);
11917   QualType ArgType = Context.getRValueReferenceType(ClassType);
11918 
11919   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11920                                                      CXXMoveConstructor,
11921                                                      false);
11922 
11923   DeclarationName Name
11924     = Context.DeclarationNames.getCXXConstructorName(
11925                                            Context.getCanonicalType(ClassType));
11926   SourceLocation ClassLoc = ClassDecl->getLocation();
11927   DeclarationNameInfo NameInfo(Name, ClassLoc);
11928 
11929   // C++11 [class.copy]p11:
11930   //   An implicitly-declared copy/move constructor is an inline public
11931   //   member of its class.
11932   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
11933       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
11934       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
11935       Constexpr);
11936   MoveConstructor->setAccess(AS_public);
11937   MoveConstructor->setDefaulted();
11938 
11939   if (getLangOpts().CUDA) {
11940     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
11941                                             MoveConstructor,
11942                                             /* ConstRHS */ false,
11943                                             /* Diagnose */ false);
11944   }
11945 
11946   // Build an exception specification pointing back at this member.
11947   FunctionProtoType::ExtProtoInfo EPI =
11948       getImplicitMethodEPI(*this, MoveConstructor);
11949   MoveConstructor->setType(
11950       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
11951 
11952   // Add the parameter to the constructor.
11953   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
11954                                                ClassLoc, ClassLoc,
11955                                                /*IdentifierInfo=*/nullptr,
11956                                                ArgType, /*TInfo=*/nullptr,
11957                                                SC_None, nullptr);
11958   MoveConstructor->setParams(FromParam);
11959 
11960   MoveConstructor->setTrivial(
11961     ClassDecl->needsOverloadResolutionForMoveConstructor()
11962       ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
11963       : ClassDecl->hasTrivialMoveConstructor());
11964 
11965   // Note that we have declared this constructor.
11966   ++ASTContext::NumImplicitMoveConstructorsDeclared;
11967 
11968   Scope *S = getScopeForContext(ClassDecl);
11969   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
11970 
11971   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
11972     ClassDecl->setImplicitMoveConstructorIsDeleted();
11973     SetDeclDeleted(MoveConstructor, ClassLoc);
11974   }
11975 
11976   if (S)
11977     PushOnScopeChains(MoveConstructor, S, false);
11978   ClassDecl->addDecl(MoveConstructor);
11979 
11980   return MoveConstructor;
11981 }
11982 
11983 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
11984                                    CXXConstructorDecl *MoveConstructor) {
11985   assert((MoveConstructor->isDefaulted() &&
11986           MoveConstructor->isMoveConstructor() &&
11987           !MoveConstructor->doesThisDeclarationHaveABody() &&
11988           !MoveConstructor->isDeleted()) &&
11989          "DefineImplicitMoveConstructor - call it for implicit move ctor");
11990 
11991   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
11992   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
11993 
11994   SynthesizedFunctionScope Scope(*this, MoveConstructor);
11995   DiagnosticErrorTrap Trap(Diags);
11996 
11997   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
11998       Trap.hasErrorOccurred()) {
11999     Diag(CurrentLocation, diag::note_member_synthesized_at)
12000       << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
12001     MoveConstructor->setInvalidDecl();
12002   }  else {
12003     SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
12004                              ? MoveConstructor->getLocEnd()
12005                              : MoveConstructor->getLocation();
12006     Sema::CompoundScopeRAII CompoundScope(*this);
12007     MoveConstructor->setBody(ActOnCompoundStmt(
12008         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
12009   }
12010 
12011   // The exception specification is needed because we are defining the
12012   // function.
12013   ResolveExceptionSpec(CurrentLocation,
12014                        MoveConstructor->getType()->castAs<FunctionProtoType>());
12015 
12016   MoveConstructor->markUsed(Context);
12017   MarkVTableUsed(CurrentLocation, ClassDecl);
12018 
12019   if (ASTMutationListener *L = getASTMutationListener()) {
12020     L->CompletedImplicitDefinition(MoveConstructor);
12021   }
12022 }
12023 
12024 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
12025   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
12026 }
12027 
12028 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
12029                             SourceLocation CurrentLocation,
12030                             CXXConversionDecl *Conv) {
12031   CXXRecordDecl *Lambda = Conv->getParent();
12032   CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
12033   // If we are defining a specialization of a conversion to function-ptr
12034   // cache the deduced template arguments for this specialization
12035   // so that we can use them to retrieve the corresponding call-operator
12036   // and static-invoker.
12037   const TemplateArgumentList *DeducedTemplateArgs = nullptr;
12038 
12039   // Retrieve the corresponding call-operator specialization.
12040   if (Lambda->isGenericLambda()) {
12041     assert(Conv->isFunctionTemplateSpecialization());
12042     FunctionTemplateDecl *CallOpTemplate =
12043         CallOp->getDescribedFunctionTemplate();
12044     DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
12045     void *InsertPos = nullptr;
12046     FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
12047                                                 DeducedTemplateArgs->asArray(),
12048                                                 InsertPos);
12049     assert(CallOpSpec &&
12050           "Conversion operator must have a corresponding call operator");
12051     CallOp = cast<CXXMethodDecl>(CallOpSpec);
12052   }
12053   // Mark the call operator referenced (and add to pending instantiations
12054   // if necessary).
12055   // For both the conversion and static-invoker template specializations
12056   // we construct their body's in this function, so no need to add them
12057   // to the PendingInstantiations.
12058   MarkFunctionReferenced(CurrentLocation, CallOp);
12059 
12060   SynthesizedFunctionScope Scope(*this, Conv);
12061   DiagnosticErrorTrap Trap(Diags);
12062 
12063   // Retrieve the static invoker...
12064   CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
12065   // ... and get the corresponding specialization for a generic lambda.
12066   if (Lambda->isGenericLambda()) {
12067     assert(DeducedTemplateArgs &&
12068       "Must have deduced template arguments from Conversion Operator");
12069     FunctionTemplateDecl *InvokeTemplate =
12070                           Invoker->getDescribedFunctionTemplate();
12071     void *InsertPos = nullptr;
12072     FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
12073                                                 DeducedTemplateArgs->asArray(),
12074                                                 InsertPos);
12075     assert(InvokeSpec &&
12076       "Must have a corresponding static invoker specialization");
12077     Invoker = cast<CXXMethodDecl>(InvokeSpec);
12078   }
12079   // Construct the body of the conversion function { return __invoke; }.
12080   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
12081                                         VK_LValue, Conv->getLocation()).get();
12082    assert(FunctionRef && "Can't refer to __invoke function?");
12083    Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
12084    Conv->setBody(new (Context) CompoundStmt(Context, Return,
12085                                             Conv->getLocation(),
12086                                             Conv->getLocation()));
12087 
12088   Conv->markUsed(Context);
12089   Conv->setReferenced();
12090 
12091   // Fill in the __invoke function with a dummy implementation. IR generation
12092   // will fill in the actual details.
12093   Invoker->markUsed(Context);
12094   Invoker->setReferenced();
12095   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12096 
12097   if (ASTMutationListener *L = getASTMutationListener()) {
12098     L->CompletedImplicitDefinition(Conv);
12099     L->CompletedImplicitDefinition(Invoker);
12100    }
12101 }
12102 
12103 
12104 
12105 void Sema::DefineImplicitLambdaToBlockPointerConversion(
12106        SourceLocation CurrentLocation,
12107        CXXConversionDecl *Conv)
12108 {
12109   assert(!Conv->getParent()->isGenericLambda());
12110 
12111   Conv->markUsed(Context);
12112 
12113   SynthesizedFunctionScope Scope(*this, Conv);
12114   DiagnosticErrorTrap Trap(Diags);
12115 
12116   // Copy-initialize the lambda object as needed to capture it.
12117   Expr *This = ActOnCXXThis(CurrentLocation).get();
12118   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
12119 
12120   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12121                                                         Conv->getLocation(),
12122                                                         Conv, DerefThis);
12123 
12124   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12125   // behavior.  Note that only the general conversion function does this
12126   // (since it's unusable otherwise); in the case where we inline the
12127   // block literal, it has block literal lifetime semantics.
12128   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
12129     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12130                                           CK_CopyAndAutoreleaseBlockObject,
12131                                           BuildBlock.get(), nullptr, VK_RValue);
12132 
12133   if (BuildBlock.isInvalid()) {
12134     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12135     Conv->setInvalidDecl();
12136     return;
12137   }
12138 
12139   // Create the return statement that returns the block from the conversion
12140   // function.
12141   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
12142   if (Return.isInvalid()) {
12143     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12144     Conv->setInvalidDecl();
12145     return;
12146   }
12147 
12148   // Set the body of the conversion function.
12149   Stmt *ReturnS = Return.get();
12150   Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
12151                                            Conv->getLocation(),
12152                                            Conv->getLocation()));
12153 
12154   // We're done; notify the mutation listener, if any.
12155   if (ASTMutationListener *L = getASTMutationListener()) {
12156     L->CompletedImplicitDefinition(Conv);
12157   }
12158 }
12159 
12160 /// \brief Determine whether the given list arguments contains exactly one
12161 /// "real" (non-default) argument.
12162 static bool hasOneRealArgument(MultiExprArg Args) {
12163   switch (Args.size()) {
12164   case 0:
12165     return false;
12166 
12167   default:
12168     if (!Args[1]->isDefaultArgument())
12169       return false;
12170 
12171     // fall through
12172   case 1:
12173     return !Args[0]->isDefaultArgument();
12174   }
12175 
12176   return false;
12177 }
12178 
12179 ExprResult
12180 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12181                             NamedDecl *FoundDecl,
12182                             CXXConstructorDecl *Constructor,
12183                             MultiExprArg ExprArgs,
12184                             bool HadMultipleCandidates,
12185                             bool IsListInitialization,
12186                             bool IsStdInitListInitialization,
12187                             bool RequiresZeroInit,
12188                             unsigned ConstructKind,
12189                             SourceRange ParenRange) {
12190   bool Elidable = false;
12191 
12192   // C++0x [class.copy]p34:
12193   //   When certain criteria are met, an implementation is allowed to
12194   //   omit the copy/move construction of a class object, even if the
12195   //   copy/move constructor and/or destructor for the object have
12196   //   side effects. [...]
12197   //     - when a temporary class object that has not been bound to a
12198   //       reference (12.2) would be copied/moved to a class object
12199   //       with the same cv-unqualified type, the copy/move operation
12200   //       can be omitted by constructing the temporary object
12201   //       directly into the target of the omitted copy/move
12202   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
12203       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
12204     Expr *SubExpr = ExprArgs[0];
12205     Elidable = SubExpr->isTemporaryObject(
12206         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
12207   }
12208 
12209   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
12210                                FoundDecl, Constructor,
12211                                Elidable, ExprArgs, HadMultipleCandidates,
12212                                IsListInitialization,
12213                                IsStdInitListInitialization, RequiresZeroInit,
12214                                ConstructKind, ParenRange);
12215 }
12216 
12217 ExprResult
12218 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12219                             NamedDecl *FoundDecl,
12220                             CXXConstructorDecl *Constructor,
12221                             bool Elidable,
12222                             MultiExprArg ExprArgs,
12223                             bool HadMultipleCandidates,
12224                             bool IsListInitialization,
12225                             bool IsStdInitListInitialization,
12226                             bool RequiresZeroInit,
12227                             unsigned ConstructKind,
12228                             SourceRange ParenRange) {
12229   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
12230     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
12231     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
12232       return ExprError();
12233   }
12234 
12235   return BuildCXXConstructExpr(
12236       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
12237       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
12238       RequiresZeroInit, ConstructKind, ParenRange);
12239 }
12240 
12241 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
12242 /// including handling of its default argument expressions.
12243 ExprResult
12244 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12245                             CXXConstructorDecl *Constructor,
12246                             bool Elidable,
12247                             MultiExprArg ExprArgs,
12248                             bool HadMultipleCandidates,
12249                             bool IsListInitialization,
12250                             bool IsStdInitListInitialization,
12251                             bool RequiresZeroInit,
12252                             unsigned ConstructKind,
12253                             SourceRange ParenRange) {
12254   assert(declaresSameEntity(
12255              Constructor->getParent(),
12256              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
12257          "given constructor for wrong type");
12258   MarkFunctionReferenced(ConstructLoc, Constructor);
12259 
12260   return CXXConstructExpr::Create(
12261       Context, DeclInitType, ConstructLoc, Constructor, Elidable,
12262       ExprArgs, HadMultipleCandidates, IsListInitialization,
12263       IsStdInitListInitialization, RequiresZeroInit,
12264       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
12265       ParenRange);
12266 }
12267 
12268 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
12269   assert(Field->hasInClassInitializer());
12270 
12271   // If we already have the in-class initializer nothing needs to be done.
12272   if (Field->getInClassInitializer())
12273     return CXXDefaultInitExpr::Create(Context, Loc, Field);
12274 
12275   // Maybe we haven't instantiated the in-class initializer. Go check the
12276   // pattern FieldDecl to see if it has one.
12277   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
12278 
12279   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
12280     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
12281     DeclContext::lookup_result Lookup =
12282         ClassPattern->lookup(Field->getDeclName());
12283 
12284     // Lookup can return at most two results: the pattern for the field, or the
12285     // injected class name of the parent record. No other member can have the
12286     // same name as the field.
12287     assert(!Lookup.empty() && Lookup.size() <= 2 &&
12288            "more than two lookup results for field name");
12289     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
12290     if (!Pattern) {
12291       assert(isa<CXXRecordDecl>(Lookup[0]) &&
12292              "cannot have other non-field member with same name");
12293       Pattern = cast<FieldDecl>(Lookup[1]);
12294     }
12295 
12296     if (InstantiateInClassInitializer(Loc, Field, Pattern,
12297                                       getTemplateInstantiationArgs(Field)))
12298       return ExprError();
12299     return CXXDefaultInitExpr::Create(Context, Loc, Field);
12300   }
12301 
12302   // DR1351:
12303   //   If the brace-or-equal-initializer of a non-static data member
12304   //   invokes a defaulted default constructor of its class or of an
12305   //   enclosing class in a potentially evaluated subexpression, the
12306   //   program is ill-formed.
12307   //
12308   // This resolution is unworkable: the exception specification of the
12309   // default constructor can be needed in an unevaluated context, in
12310   // particular, in the operand of a noexcept-expression, and we can be
12311   // unable to compute an exception specification for an enclosed class.
12312   //
12313   // Any attempt to resolve the exception specification of a defaulted default
12314   // constructor before the initializer is lexically complete will ultimately
12315   // come here at which point we can diagnose it.
12316   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
12317   if (OutermostClass == ParentRD) {
12318     Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
12319         << ParentRD << Field;
12320   } else {
12321     Diag(Field->getLocEnd(),
12322          diag::err_in_class_initializer_not_yet_parsed_outer_class)
12323         << ParentRD << OutermostClass << Field;
12324   }
12325 
12326   return ExprError();
12327 }
12328 
12329 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
12330   if (VD->isInvalidDecl()) return;
12331 
12332   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
12333   if (ClassDecl->isInvalidDecl()) return;
12334   if (ClassDecl->hasIrrelevantDestructor()) return;
12335   if (ClassDecl->isDependentContext()) return;
12336 
12337   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12338   MarkFunctionReferenced(VD->getLocation(), Destructor);
12339   CheckDestructorAccess(VD->getLocation(), Destructor,
12340                         PDiag(diag::err_access_dtor_var)
12341                         << VD->getDeclName()
12342                         << VD->getType());
12343   DiagnoseUseOfDecl(Destructor, VD->getLocation());
12344 
12345   if (Destructor->isTrivial()) return;
12346   if (!VD->hasGlobalStorage()) return;
12347 
12348   // Emit warning for non-trivial dtor in global scope (a real global,
12349   // class-static, function-static).
12350   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
12351 
12352   // TODO: this should be re-enabled for static locals by !CXAAtExit
12353   if (!VD->isStaticLocal())
12354     Diag(VD->getLocation(), diag::warn_global_destructor);
12355 }
12356 
12357 /// \brief Given a constructor and the set of arguments provided for the
12358 /// constructor, convert the arguments and add any required default arguments
12359 /// to form a proper call to this constructor.
12360 ///
12361 /// \returns true if an error occurred, false otherwise.
12362 bool
12363 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
12364                               MultiExprArg ArgsPtr,
12365                               SourceLocation Loc,
12366                               SmallVectorImpl<Expr*> &ConvertedArgs,
12367                               bool AllowExplicit,
12368                               bool IsListInitialization) {
12369   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
12370   unsigned NumArgs = ArgsPtr.size();
12371   Expr **Args = ArgsPtr.data();
12372 
12373   const FunctionProtoType *Proto
12374     = Constructor->getType()->getAs<FunctionProtoType>();
12375   assert(Proto && "Constructor without a prototype?");
12376   unsigned NumParams = Proto->getNumParams();
12377 
12378   // If too few arguments are available, we'll fill in the rest with defaults.
12379   if (NumArgs < NumParams)
12380     ConvertedArgs.reserve(NumParams);
12381   else
12382     ConvertedArgs.reserve(NumArgs);
12383 
12384   VariadicCallType CallType =
12385     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
12386   SmallVector<Expr *, 8> AllArgs;
12387   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
12388                                         Proto, 0,
12389                                         llvm::makeArrayRef(Args, NumArgs),
12390                                         AllArgs,
12391                                         CallType, AllowExplicit,
12392                                         IsListInitialization);
12393   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
12394 
12395   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
12396 
12397   CheckConstructorCall(Constructor,
12398                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
12399                        Proto, Loc);
12400 
12401   return Invalid;
12402 }
12403 
12404 static inline bool
12405 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
12406                                        const FunctionDecl *FnDecl) {
12407   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
12408   if (isa<NamespaceDecl>(DC)) {
12409     return SemaRef.Diag(FnDecl->getLocation(),
12410                         diag::err_operator_new_delete_declared_in_namespace)
12411       << FnDecl->getDeclName();
12412   }
12413 
12414   if (isa<TranslationUnitDecl>(DC) &&
12415       FnDecl->getStorageClass() == SC_Static) {
12416     return SemaRef.Diag(FnDecl->getLocation(),
12417                         diag::err_operator_new_delete_declared_static)
12418       << FnDecl->getDeclName();
12419   }
12420 
12421   return false;
12422 }
12423 
12424 static inline bool
12425 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
12426                             CanQualType ExpectedResultType,
12427                             CanQualType ExpectedFirstParamType,
12428                             unsigned DependentParamTypeDiag,
12429                             unsigned InvalidParamTypeDiag) {
12430   QualType ResultType =
12431       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
12432 
12433   // Check that the result type is not dependent.
12434   if (ResultType->isDependentType())
12435     return SemaRef.Diag(FnDecl->getLocation(),
12436                         diag::err_operator_new_delete_dependent_result_type)
12437     << FnDecl->getDeclName() << ExpectedResultType;
12438 
12439   // Check that the result type is what we expect.
12440   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
12441     return SemaRef.Diag(FnDecl->getLocation(),
12442                         diag::err_operator_new_delete_invalid_result_type)
12443     << FnDecl->getDeclName() << ExpectedResultType;
12444 
12445   // A function template must have at least 2 parameters.
12446   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
12447     return SemaRef.Diag(FnDecl->getLocation(),
12448                       diag::err_operator_new_delete_template_too_few_parameters)
12449         << FnDecl->getDeclName();
12450 
12451   // The function decl must have at least 1 parameter.
12452   if (FnDecl->getNumParams() == 0)
12453     return SemaRef.Diag(FnDecl->getLocation(),
12454                         diag::err_operator_new_delete_too_few_parameters)
12455       << FnDecl->getDeclName();
12456 
12457   // Check the first parameter type is not dependent.
12458   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
12459   if (FirstParamType->isDependentType())
12460     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
12461       << FnDecl->getDeclName() << ExpectedFirstParamType;
12462 
12463   // Check that the first parameter type is what we expect.
12464   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
12465       ExpectedFirstParamType)
12466     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
12467     << FnDecl->getDeclName() << ExpectedFirstParamType;
12468 
12469   return false;
12470 }
12471 
12472 static bool
12473 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
12474   // C++ [basic.stc.dynamic.allocation]p1:
12475   //   A program is ill-formed if an allocation function is declared in a
12476   //   namespace scope other than global scope or declared static in global
12477   //   scope.
12478   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12479     return true;
12480 
12481   CanQualType SizeTy =
12482     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
12483 
12484   // C++ [basic.stc.dynamic.allocation]p1:
12485   //  The return type shall be void*. The first parameter shall have type
12486   //  std::size_t.
12487   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
12488                                   SizeTy,
12489                                   diag::err_operator_new_dependent_param_type,
12490                                   diag::err_operator_new_param_type))
12491     return true;
12492 
12493   // C++ [basic.stc.dynamic.allocation]p1:
12494   //  The first parameter shall not have an associated default argument.
12495   if (FnDecl->getParamDecl(0)->hasDefaultArg())
12496     return SemaRef.Diag(FnDecl->getLocation(),
12497                         diag::err_operator_new_default_arg)
12498       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
12499 
12500   return false;
12501 }
12502 
12503 static bool
12504 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
12505   // C++ [basic.stc.dynamic.deallocation]p1:
12506   //   A program is ill-formed if deallocation functions are declared in a
12507   //   namespace scope other than global scope or declared static in global
12508   //   scope.
12509   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12510     return true;
12511 
12512   // C++ [basic.stc.dynamic.deallocation]p2:
12513   //   Each deallocation function shall return void and its first parameter
12514   //   shall be void*.
12515   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
12516                                   SemaRef.Context.VoidPtrTy,
12517                                  diag::err_operator_delete_dependent_param_type,
12518                                  diag::err_operator_delete_param_type))
12519     return true;
12520 
12521   return false;
12522 }
12523 
12524 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
12525 /// of this overloaded operator is well-formed. If so, returns false;
12526 /// otherwise, emits appropriate diagnostics and returns true.
12527 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
12528   assert(FnDecl && FnDecl->isOverloadedOperator() &&
12529          "Expected an overloaded operator declaration");
12530 
12531   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
12532 
12533   // C++ [over.oper]p5:
12534   //   The allocation and deallocation functions, operator new,
12535   //   operator new[], operator delete and operator delete[], are
12536   //   described completely in 3.7.3. The attributes and restrictions
12537   //   found in the rest of this subclause do not apply to them unless
12538   //   explicitly stated in 3.7.3.
12539   if (Op == OO_Delete || Op == OO_Array_Delete)
12540     return CheckOperatorDeleteDeclaration(*this, FnDecl);
12541 
12542   if (Op == OO_New || Op == OO_Array_New)
12543     return CheckOperatorNewDeclaration(*this, FnDecl);
12544 
12545   // C++ [over.oper]p6:
12546   //   An operator function shall either be a non-static member
12547   //   function or be a non-member function and have at least one
12548   //   parameter whose type is a class, a reference to a class, an
12549   //   enumeration, or a reference to an enumeration.
12550   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
12551     if (MethodDecl->isStatic())
12552       return Diag(FnDecl->getLocation(),
12553                   diag::err_operator_overload_static) << FnDecl->getDeclName();
12554   } else {
12555     bool ClassOrEnumParam = false;
12556     for (auto Param : FnDecl->parameters()) {
12557       QualType ParamType = Param->getType().getNonReferenceType();
12558       if (ParamType->isDependentType() || ParamType->isRecordType() ||
12559           ParamType->isEnumeralType()) {
12560         ClassOrEnumParam = true;
12561         break;
12562       }
12563     }
12564 
12565     if (!ClassOrEnumParam)
12566       return Diag(FnDecl->getLocation(),
12567                   diag::err_operator_overload_needs_class_or_enum)
12568         << FnDecl->getDeclName();
12569   }
12570 
12571   // C++ [over.oper]p8:
12572   //   An operator function cannot have default arguments (8.3.6),
12573   //   except where explicitly stated below.
12574   //
12575   // Only the function-call operator allows default arguments
12576   // (C++ [over.call]p1).
12577   if (Op != OO_Call) {
12578     for (auto Param : FnDecl->parameters()) {
12579       if (Param->hasDefaultArg())
12580         return Diag(Param->getLocation(),
12581                     diag::err_operator_overload_default_arg)
12582           << FnDecl->getDeclName() << Param->getDefaultArgRange();
12583     }
12584   }
12585 
12586   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
12587     { false, false, false }
12588 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
12589     , { Unary, Binary, MemberOnly }
12590 #include "clang/Basic/OperatorKinds.def"
12591   };
12592 
12593   bool CanBeUnaryOperator = OperatorUses[Op][0];
12594   bool CanBeBinaryOperator = OperatorUses[Op][1];
12595   bool MustBeMemberOperator = OperatorUses[Op][2];
12596 
12597   // C++ [over.oper]p8:
12598   //   [...] Operator functions cannot have more or fewer parameters
12599   //   than the number required for the corresponding operator, as
12600   //   described in the rest of this subclause.
12601   unsigned NumParams = FnDecl->getNumParams()
12602                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
12603   if (Op != OO_Call &&
12604       ((NumParams == 1 && !CanBeUnaryOperator) ||
12605        (NumParams == 2 && !CanBeBinaryOperator) ||
12606        (NumParams < 1) || (NumParams > 2))) {
12607     // We have the wrong number of parameters.
12608     unsigned ErrorKind;
12609     if (CanBeUnaryOperator && CanBeBinaryOperator) {
12610       ErrorKind = 2;  // 2 -> unary or binary.
12611     } else if (CanBeUnaryOperator) {
12612       ErrorKind = 0;  // 0 -> unary
12613     } else {
12614       assert(CanBeBinaryOperator &&
12615              "All non-call overloaded operators are unary or binary!");
12616       ErrorKind = 1;  // 1 -> binary
12617     }
12618 
12619     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
12620       << FnDecl->getDeclName() << NumParams << ErrorKind;
12621   }
12622 
12623   // Overloaded operators other than operator() cannot be variadic.
12624   if (Op != OO_Call &&
12625       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
12626     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
12627       << FnDecl->getDeclName();
12628   }
12629 
12630   // Some operators must be non-static member functions.
12631   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
12632     return Diag(FnDecl->getLocation(),
12633                 diag::err_operator_overload_must_be_member)
12634       << FnDecl->getDeclName();
12635   }
12636 
12637   // C++ [over.inc]p1:
12638   //   The user-defined function called operator++ implements the
12639   //   prefix and postfix ++ operator. If this function is a member
12640   //   function with no parameters, or a non-member function with one
12641   //   parameter of class or enumeration type, it defines the prefix
12642   //   increment operator ++ for objects of that type. If the function
12643   //   is a member function with one parameter (which shall be of type
12644   //   int) or a non-member function with two parameters (the second
12645   //   of which shall be of type int), it defines the postfix
12646   //   increment operator ++ for objects of that type.
12647   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
12648     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
12649     QualType ParamType = LastParam->getType();
12650 
12651     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
12652         !ParamType->isDependentType())
12653       return Diag(LastParam->getLocation(),
12654                   diag::err_operator_overload_post_incdec_must_be_int)
12655         << LastParam->getType() << (Op == OO_MinusMinus);
12656   }
12657 
12658   return false;
12659 }
12660 
12661 static bool
12662 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
12663                                           FunctionTemplateDecl *TpDecl) {
12664   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
12665 
12666   // Must have one or two template parameters.
12667   if (TemplateParams->size() == 1) {
12668     NonTypeTemplateParmDecl *PmDecl =
12669         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
12670 
12671     // The template parameter must be a char parameter pack.
12672     if (PmDecl && PmDecl->isTemplateParameterPack() &&
12673         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
12674       return false;
12675 
12676   } else if (TemplateParams->size() == 2) {
12677     TemplateTypeParmDecl *PmType =
12678         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
12679     NonTypeTemplateParmDecl *PmArgs =
12680         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
12681 
12682     // The second template parameter must be a parameter pack with the
12683     // first template parameter as its type.
12684     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
12685         PmArgs->isTemplateParameterPack()) {
12686       const TemplateTypeParmType *TArgs =
12687           PmArgs->getType()->getAs<TemplateTypeParmType>();
12688       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
12689           TArgs->getIndex() == PmType->getIndex()) {
12690         if (SemaRef.ActiveTemplateInstantiations.empty())
12691           SemaRef.Diag(TpDecl->getLocation(),
12692                        diag::ext_string_literal_operator_template);
12693         return false;
12694       }
12695     }
12696   }
12697 
12698   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
12699                diag::err_literal_operator_template)
12700       << TpDecl->getTemplateParameters()->getSourceRange();
12701   return true;
12702 }
12703 
12704 /// CheckLiteralOperatorDeclaration - Check whether the declaration
12705 /// of this literal operator function is well-formed. If so, returns
12706 /// false; otherwise, emits appropriate diagnostics and returns true.
12707 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
12708   if (isa<CXXMethodDecl>(FnDecl)) {
12709     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
12710       << FnDecl->getDeclName();
12711     return true;
12712   }
12713 
12714   if (FnDecl->isExternC()) {
12715     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
12716     return true;
12717   }
12718 
12719   // This might be the definition of a literal operator template.
12720   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
12721 
12722   // This might be a specialization of a literal operator template.
12723   if (!TpDecl)
12724     TpDecl = FnDecl->getPrimaryTemplate();
12725 
12726   // template <char...> type operator "" name() and
12727   // template <class T, T...> type operator "" name() are the only valid
12728   // template signatures, and the only valid signatures with no parameters.
12729   if (TpDecl) {
12730     if (FnDecl->param_size() != 0) {
12731       Diag(FnDecl->getLocation(),
12732            diag::err_literal_operator_template_with_params);
12733       return true;
12734     }
12735 
12736     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
12737       return true;
12738 
12739   } else if (FnDecl->param_size() == 1) {
12740     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
12741 
12742     QualType ParamType = Param->getType().getUnqualifiedType();
12743 
12744     // Only unsigned long long int, long double, any character type, and const
12745     // char * are allowed as the only parameters.
12746     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
12747         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
12748         Context.hasSameType(ParamType, Context.CharTy) ||
12749         Context.hasSameType(ParamType, Context.WideCharTy) ||
12750         Context.hasSameType(ParamType, Context.Char16Ty) ||
12751         Context.hasSameType(ParamType, Context.Char32Ty)) {
12752     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
12753       QualType InnerType = Ptr->getPointeeType();
12754 
12755       // Pointer parameter must be a const char *.
12756       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
12757                                 Context.CharTy) &&
12758             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
12759         Diag(Param->getSourceRange().getBegin(),
12760              diag::err_literal_operator_param)
12761             << ParamType << "'const char *'" << Param->getSourceRange();
12762         return true;
12763       }
12764 
12765     } else if (ParamType->isRealFloatingType()) {
12766       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
12767           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
12768       return true;
12769 
12770     } else if (ParamType->isIntegerType()) {
12771       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
12772           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
12773       return true;
12774 
12775     } else {
12776       Diag(Param->getSourceRange().getBegin(),
12777            diag::err_literal_operator_invalid_param)
12778           << ParamType << Param->getSourceRange();
12779       return true;
12780     }
12781 
12782   } else if (FnDecl->param_size() == 2) {
12783     FunctionDecl::param_iterator Param = FnDecl->param_begin();
12784 
12785     // First, verify that the first parameter is correct.
12786 
12787     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
12788 
12789     // Two parameter function must have a pointer to const as a
12790     // first parameter; let's strip those qualifiers.
12791     const PointerType *PT = FirstParamType->getAs<PointerType>();
12792 
12793     if (!PT) {
12794       Diag((*Param)->getSourceRange().getBegin(),
12795            diag::err_literal_operator_param)
12796           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12797       return true;
12798     }
12799 
12800     QualType PointeeType = PT->getPointeeType();
12801     // First parameter must be const
12802     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
12803       Diag((*Param)->getSourceRange().getBegin(),
12804            diag::err_literal_operator_param)
12805           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12806       return true;
12807     }
12808 
12809     QualType InnerType = PointeeType.getUnqualifiedType();
12810     // Only const char *, const wchar_t*, const char16_t*, and const char32_t*
12811     // are allowed as the first parameter to a two-parameter function
12812     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
12813           Context.hasSameType(InnerType, Context.WideCharTy) ||
12814           Context.hasSameType(InnerType, Context.Char16Ty) ||
12815           Context.hasSameType(InnerType, Context.Char32Ty))) {
12816       Diag((*Param)->getSourceRange().getBegin(),
12817            diag::err_literal_operator_param)
12818           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12819       return true;
12820     }
12821 
12822     // Move on to the second and final parameter.
12823     ++Param;
12824 
12825     // The second parameter must be a std::size_t.
12826     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
12827     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
12828       Diag((*Param)->getSourceRange().getBegin(),
12829            diag::err_literal_operator_param)
12830           << SecondParamType << Context.getSizeType()
12831           << (*Param)->getSourceRange();
12832       return true;
12833     }
12834   } else {
12835     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
12836     return true;
12837   }
12838 
12839   // Parameters are good.
12840 
12841   // A parameter-declaration-clause containing a default argument is not
12842   // equivalent to any of the permitted forms.
12843   for (auto Param : FnDecl->parameters()) {
12844     if (Param->hasDefaultArg()) {
12845       Diag(Param->getDefaultArgRange().getBegin(),
12846            diag::err_literal_operator_default_argument)
12847         << Param->getDefaultArgRange();
12848       break;
12849     }
12850   }
12851 
12852   StringRef LiteralName
12853     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
12854   if (LiteralName[0] != '_') {
12855     // C++11 [usrlit.suffix]p1:
12856     //   Literal suffix identifiers that do not start with an underscore
12857     //   are reserved for future standardization.
12858     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
12859       << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
12860   }
12861 
12862   return false;
12863 }
12864 
12865 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
12866 /// linkage specification, including the language and (if present)
12867 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
12868 /// language string literal. LBraceLoc, if valid, provides the location of
12869 /// the '{' brace. Otherwise, this linkage specification does not
12870 /// have any braces.
12871 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
12872                                            Expr *LangStr,
12873                                            SourceLocation LBraceLoc) {
12874   StringLiteral *Lit = cast<StringLiteral>(LangStr);
12875   if (!Lit->isAscii()) {
12876     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
12877       << LangStr->getSourceRange();
12878     return nullptr;
12879   }
12880 
12881   StringRef Lang = Lit->getString();
12882   LinkageSpecDecl::LanguageIDs Language;
12883   if (Lang == "C")
12884     Language = LinkageSpecDecl::lang_c;
12885   else if (Lang == "C++")
12886     Language = LinkageSpecDecl::lang_cxx;
12887   else {
12888     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
12889       << LangStr->getSourceRange();
12890     return nullptr;
12891   }
12892 
12893   // FIXME: Add all the various semantics of linkage specifications
12894 
12895   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
12896                                                LangStr->getExprLoc(), Language,
12897                                                LBraceLoc.isValid());
12898   CurContext->addDecl(D);
12899   PushDeclContext(S, D);
12900   return D;
12901 }
12902 
12903 /// ActOnFinishLinkageSpecification - Complete the definition of
12904 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
12905 /// valid, it's the position of the closing '}' brace in a linkage
12906 /// specification that uses braces.
12907 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
12908                                             Decl *LinkageSpec,
12909                                             SourceLocation RBraceLoc) {
12910   if (RBraceLoc.isValid()) {
12911     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
12912     LSDecl->setRBraceLoc(RBraceLoc);
12913   }
12914   PopDeclContext();
12915   return LinkageSpec;
12916 }
12917 
12918 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
12919                                   AttributeList *AttrList,
12920                                   SourceLocation SemiLoc) {
12921   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
12922   // Attribute declarations appertain to empty declaration so we handle
12923   // them here.
12924   if (AttrList)
12925     ProcessDeclAttributeList(S, ED, AttrList);
12926 
12927   CurContext->addDecl(ED);
12928   return ED;
12929 }
12930 
12931 /// \brief Perform semantic analysis for the variable declaration that
12932 /// occurs within a C++ catch clause, returning the newly-created
12933 /// variable.
12934 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
12935                                          TypeSourceInfo *TInfo,
12936                                          SourceLocation StartLoc,
12937                                          SourceLocation Loc,
12938                                          IdentifierInfo *Name) {
12939   bool Invalid = false;
12940   QualType ExDeclType = TInfo->getType();
12941 
12942   // Arrays and functions decay.
12943   if (ExDeclType->isArrayType())
12944     ExDeclType = Context.getArrayDecayedType(ExDeclType);
12945   else if (ExDeclType->isFunctionType())
12946     ExDeclType = Context.getPointerType(ExDeclType);
12947 
12948   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
12949   // The exception-declaration shall not denote a pointer or reference to an
12950   // incomplete type, other than [cv] void*.
12951   // N2844 forbids rvalue references.
12952   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
12953     Diag(Loc, diag::err_catch_rvalue_ref);
12954     Invalid = true;
12955   }
12956 
12957   if (ExDeclType->isVariablyModifiedType()) {
12958     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
12959     Invalid = true;
12960   }
12961 
12962   QualType BaseType = ExDeclType;
12963   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
12964   unsigned DK = diag::err_catch_incomplete;
12965   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
12966     BaseType = Ptr->getPointeeType();
12967     Mode = 1;
12968     DK = diag::err_catch_incomplete_ptr;
12969   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
12970     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
12971     BaseType = Ref->getPointeeType();
12972     Mode = 2;
12973     DK = diag::err_catch_incomplete_ref;
12974   }
12975   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
12976       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
12977     Invalid = true;
12978 
12979   if (!Invalid && !ExDeclType->isDependentType() &&
12980       RequireNonAbstractType(Loc, ExDeclType,
12981                              diag::err_abstract_type_in_decl,
12982                              AbstractVariableType))
12983     Invalid = true;
12984 
12985   // Only the non-fragile NeXT runtime currently supports C++ catches
12986   // of ObjC types, and no runtime supports catching ObjC types by value.
12987   if (!Invalid && getLangOpts().ObjC1) {
12988     QualType T = ExDeclType;
12989     if (const ReferenceType *RT = T->getAs<ReferenceType>())
12990       T = RT->getPointeeType();
12991 
12992     if (T->isObjCObjectType()) {
12993       Diag(Loc, diag::err_objc_object_catch);
12994       Invalid = true;
12995     } else if (T->isObjCObjectPointerType()) {
12996       // FIXME: should this be a test for macosx-fragile specifically?
12997       if (getLangOpts().ObjCRuntime.isFragile())
12998         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
12999     }
13000   }
13001 
13002   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
13003                                     ExDeclType, TInfo, SC_None);
13004   ExDecl->setExceptionVariable(true);
13005 
13006   // In ARC, infer 'retaining' for variables of retainable type.
13007   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
13008     Invalid = true;
13009 
13010   if (!Invalid && !ExDeclType->isDependentType()) {
13011     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
13012       // Insulate this from anything else we might currently be parsing.
13013       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
13014 
13015       // C++ [except.handle]p16:
13016       //   The object declared in an exception-declaration or, if the
13017       //   exception-declaration does not specify a name, a temporary (12.2) is
13018       //   copy-initialized (8.5) from the exception object. [...]
13019       //   The object is destroyed when the handler exits, after the destruction
13020       //   of any automatic objects initialized within the handler.
13021       //
13022       // We just pretend to initialize the object with itself, then make sure
13023       // it can be destroyed later.
13024       QualType initType = Context.getExceptionObjectType(ExDeclType);
13025 
13026       InitializedEntity entity =
13027         InitializedEntity::InitializeVariable(ExDecl);
13028       InitializationKind initKind =
13029         InitializationKind::CreateCopy(Loc, SourceLocation());
13030 
13031       Expr *opaqueValue =
13032         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
13033       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13034       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
13035       if (result.isInvalid())
13036         Invalid = true;
13037       else {
13038         // If the constructor used was non-trivial, set this as the
13039         // "initializer".
13040         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
13041         if (!construct->getConstructor()->isTrivial()) {
13042           Expr *init = MaybeCreateExprWithCleanups(construct);
13043           ExDecl->setInit(init);
13044         }
13045 
13046         // And make sure it's destructable.
13047         FinalizeVarWithDestructor(ExDecl, recordType);
13048       }
13049     }
13050   }
13051 
13052   if (Invalid)
13053     ExDecl->setInvalidDecl();
13054 
13055   return ExDecl;
13056 }
13057 
13058 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13059 /// handler.
13060 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
13061   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13062   bool Invalid = D.isInvalidType();
13063 
13064   // Check for unexpanded parameter packs.
13065   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13066                                       UPPC_ExceptionType)) {
13067     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13068                                              D.getIdentifierLoc());
13069     Invalid = true;
13070   }
13071 
13072   IdentifierInfo *II = D.getIdentifier();
13073   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
13074                                              LookupOrdinaryName,
13075                                              ForRedeclaration)) {
13076     // The scope should be freshly made just for us. There is just no way
13077     // it contains any previous declaration, except for function parameters in
13078     // a function-try-block's catch statement.
13079     assert(!S->isDeclScope(PrevDecl));
13080     if (isDeclInScope(PrevDecl, CurContext, S)) {
13081       Diag(D.getIdentifierLoc(), diag::err_redefinition)
13082         << D.getIdentifier();
13083       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13084       Invalid = true;
13085     } else if (PrevDecl->isTemplateParameter())
13086       // Maybe we will complain about the shadowed template parameter.
13087       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13088   }
13089 
13090   if (D.getCXXScopeSpec().isSet() && !Invalid) {
13091     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13092       << D.getCXXScopeSpec().getRange();
13093     Invalid = true;
13094   }
13095 
13096   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
13097                                               D.getLocStart(),
13098                                               D.getIdentifierLoc(),
13099                                               D.getIdentifier());
13100   if (Invalid)
13101     ExDecl->setInvalidDecl();
13102 
13103   // Add the exception declaration into this scope.
13104   if (II)
13105     PushOnScopeChains(ExDecl, S);
13106   else
13107     CurContext->addDecl(ExDecl);
13108 
13109   ProcessDeclAttributes(S, ExDecl, D);
13110   return ExDecl;
13111 }
13112 
13113 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13114                                          Expr *AssertExpr,
13115                                          Expr *AssertMessageExpr,
13116                                          SourceLocation RParenLoc) {
13117   StringLiteral *AssertMessage =
13118       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
13119 
13120   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
13121     return nullptr;
13122 
13123   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
13124                                       AssertMessage, RParenLoc, false);
13125 }
13126 
13127 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13128                                          Expr *AssertExpr,
13129                                          StringLiteral *AssertMessage,
13130                                          SourceLocation RParenLoc,
13131                                          bool Failed) {
13132   assert(AssertExpr != nullptr && "Expected non-null condition");
13133   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
13134       !Failed) {
13135     // In a static_assert-declaration, the constant-expression shall be a
13136     // constant expression that can be contextually converted to bool.
13137     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
13138     if (Converted.isInvalid())
13139       Failed = true;
13140 
13141     llvm::APSInt Cond;
13142     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
13143           diag::err_static_assert_expression_is_not_constant,
13144           /*AllowFold=*/false).isInvalid())
13145       Failed = true;
13146 
13147     if (!Failed && !Cond) {
13148       SmallString<256> MsgBuffer;
13149       llvm::raw_svector_ostream Msg(MsgBuffer);
13150       if (AssertMessage)
13151         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
13152       Diag(StaticAssertLoc, diag::err_static_assert_failed)
13153         << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
13154       Failed = true;
13155     }
13156   }
13157 
13158   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
13159                                         AssertExpr, AssertMessage, RParenLoc,
13160                                         Failed);
13161 
13162   CurContext->addDecl(Decl);
13163   return Decl;
13164 }
13165 
13166 /// \brief Perform semantic analysis of the given friend type declaration.
13167 ///
13168 /// \returns A friend declaration that.
13169 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
13170                                       SourceLocation FriendLoc,
13171                                       TypeSourceInfo *TSInfo) {
13172   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
13173 
13174   QualType T = TSInfo->getType();
13175   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
13176 
13177   // C++03 [class.friend]p2:
13178   //   An elaborated-type-specifier shall be used in a friend declaration
13179   //   for a class.*
13180   //
13181   //   * The class-key of the elaborated-type-specifier is required.
13182   if (!ActiveTemplateInstantiations.empty()) {
13183     // Do not complain about the form of friend template types during
13184     // template instantiation; we will already have complained when the
13185     // template was declared.
13186   } else {
13187     if (!T->isElaboratedTypeSpecifier()) {
13188       // If we evaluated the type to a record type, suggest putting
13189       // a tag in front.
13190       if (const RecordType *RT = T->getAs<RecordType>()) {
13191         RecordDecl *RD = RT->getDecl();
13192 
13193         SmallString<16> InsertionText(" ");
13194         InsertionText += RD->getKindName();
13195 
13196         Diag(TypeRange.getBegin(),
13197              getLangOpts().CPlusPlus11 ?
13198                diag::warn_cxx98_compat_unelaborated_friend_type :
13199                diag::ext_unelaborated_friend_type)
13200           << (unsigned) RD->getTagKind()
13201           << T
13202           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
13203                                         InsertionText);
13204       } else {
13205         Diag(FriendLoc,
13206              getLangOpts().CPlusPlus11 ?
13207                diag::warn_cxx98_compat_nonclass_type_friend :
13208                diag::ext_nonclass_type_friend)
13209           << T
13210           << TypeRange;
13211       }
13212     } else if (T->getAs<EnumType>()) {
13213       Diag(FriendLoc,
13214            getLangOpts().CPlusPlus11 ?
13215              diag::warn_cxx98_compat_enum_friend :
13216              diag::ext_enum_friend)
13217         << T
13218         << TypeRange;
13219     }
13220 
13221     // C++11 [class.friend]p3:
13222     //   A friend declaration that does not declare a function shall have one
13223     //   of the following forms:
13224     //     friend elaborated-type-specifier ;
13225     //     friend simple-type-specifier ;
13226     //     friend typename-specifier ;
13227     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
13228       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
13229   }
13230 
13231   //   If the type specifier in a friend declaration designates a (possibly
13232   //   cv-qualified) class type, that class is declared as a friend; otherwise,
13233   //   the friend declaration is ignored.
13234   return FriendDecl::Create(Context, CurContext,
13235                             TSInfo->getTypeLoc().getLocStart(), TSInfo,
13236                             FriendLoc);
13237 }
13238 
13239 /// Handle a friend tag declaration where the scope specifier was
13240 /// templated.
13241 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
13242                                     unsigned TagSpec, SourceLocation TagLoc,
13243                                     CXXScopeSpec &SS,
13244                                     IdentifierInfo *Name,
13245                                     SourceLocation NameLoc,
13246                                     AttributeList *Attr,
13247                                     MultiTemplateParamsArg TempParamLists) {
13248   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13249 
13250   bool isExplicitSpecialization = false;
13251   bool Invalid = false;
13252 
13253   if (TemplateParameterList *TemplateParams =
13254           MatchTemplateParametersToScopeSpecifier(
13255               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
13256               isExplicitSpecialization, Invalid)) {
13257     if (TemplateParams->size() > 0) {
13258       // This is a declaration of a class template.
13259       if (Invalid)
13260         return nullptr;
13261 
13262       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
13263                                 NameLoc, Attr, TemplateParams, AS_public,
13264                                 /*ModulePrivateLoc=*/SourceLocation(),
13265                                 FriendLoc, TempParamLists.size() - 1,
13266                                 TempParamLists.data()).get();
13267     } else {
13268       // The "template<>" header is extraneous.
13269       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13270         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13271       isExplicitSpecialization = true;
13272     }
13273   }
13274 
13275   if (Invalid) return nullptr;
13276 
13277   bool isAllExplicitSpecializations = true;
13278   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
13279     if (TempParamLists[I]->size()) {
13280       isAllExplicitSpecializations = false;
13281       break;
13282     }
13283   }
13284 
13285   // FIXME: don't ignore attributes.
13286 
13287   // If it's explicit specializations all the way down, just forget
13288   // about the template header and build an appropriate non-templated
13289   // friend.  TODO: for source fidelity, remember the headers.
13290   if (isAllExplicitSpecializations) {
13291     if (SS.isEmpty()) {
13292       bool Owned = false;
13293       bool IsDependent = false;
13294       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
13295                       Attr, AS_public,
13296                       /*ModulePrivateLoc=*/SourceLocation(),
13297                       MultiTemplateParamsArg(), Owned, IsDependent,
13298                       /*ScopedEnumKWLoc=*/SourceLocation(),
13299                       /*ScopedEnumUsesClassTag=*/false,
13300                       /*UnderlyingType=*/TypeResult(),
13301                       /*IsTypeSpecifier=*/false);
13302     }
13303 
13304     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
13305     ElaboratedTypeKeyword Keyword
13306       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13307     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
13308                                    *Name, NameLoc);
13309     if (T.isNull())
13310       return nullptr;
13311 
13312     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13313     if (isa<DependentNameType>(T)) {
13314       DependentNameTypeLoc TL =
13315           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
13316       TL.setElaboratedKeywordLoc(TagLoc);
13317       TL.setQualifierLoc(QualifierLoc);
13318       TL.setNameLoc(NameLoc);
13319     } else {
13320       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
13321       TL.setElaboratedKeywordLoc(TagLoc);
13322       TL.setQualifierLoc(QualifierLoc);
13323       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
13324     }
13325 
13326     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
13327                                             TSI, FriendLoc, TempParamLists);
13328     Friend->setAccess(AS_public);
13329     CurContext->addDecl(Friend);
13330     return Friend;
13331   }
13332 
13333   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
13334 
13335 
13336 
13337   // Handle the case of a templated-scope friend class.  e.g.
13338   //   template <class T> class A<T>::B;
13339   // FIXME: we don't support these right now.
13340   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
13341     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
13342   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13343   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
13344   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13345   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
13346   TL.setElaboratedKeywordLoc(TagLoc);
13347   TL.setQualifierLoc(SS.getWithLocInContext(Context));
13348   TL.setNameLoc(NameLoc);
13349 
13350   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
13351                                           TSI, FriendLoc, TempParamLists);
13352   Friend->setAccess(AS_public);
13353   Friend->setUnsupportedFriend(true);
13354   CurContext->addDecl(Friend);
13355   return Friend;
13356 }
13357 
13358 
13359 /// Handle a friend type declaration.  This works in tandem with
13360 /// ActOnTag.
13361 ///
13362 /// Notes on friend class templates:
13363 ///
13364 /// We generally treat friend class declarations as if they were
13365 /// declaring a class.  So, for example, the elaborated type specifier
13366 /// in a friend declaration is required to obey the restrictions of a
13367 /// class-head (i.e. no typedefs in the scope chain), template
13368 /// parameters are required to match up with simple template-ids, &c.
13369 /// However, unlike when declaring a template specialization, it's
13370 /// okay to refer to a template specialization without an empty
13371 /// template parameter declaration, e.g.
13372 ///   friend class A<T>::B<unsigned>;
13373 /// We permit this as a special case; if there are any template
13374 /// parameters present at all, require proper matching, i.e.
13375 ///   template <> template \<class T> friend class A<int>::B;
13376 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
13377                                 MultiTemplateParamsArg TempParams) {
13378   SourceLocation Loc = DS.getLocStart();
13379 
13380   assert(DS.isFriendSpecified());
13381   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13382 
13383   // Try to convert the decl specifier to a type.  This works for
13384   // friend templates because ActOnTag never produces a ClassTemplateDecl
13385   // for a TUK_Friend.
13386   Declarator TheDeclarator(DS, Declarator::MemberContext);
13387   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
13388   QualType T = TSI->getType();
13389   if (TheDeclarator.isInvalidType())
13390     return nullptr;
13391 
13392   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
13393     return nullptr;
13394 
13395   // This is definitely an error in C++98.  It's probably meant to
13396   // be forbidden in C++0x, too, but the specification is just
13397   // poorly written.
13398   //
13399   // The problem is with declarations like the following:
13400   //   template <T> friend A<T>::foo;
13401   // where deciding whether a class C is a friend or not now hinges
13402   // on whether there exists an instantiation of A that causes
13403   // 'foo' to equal C.  There are restrictions on class-heads
13404   // (which we declare (by fiat) elaborated friend declarations to
13405   // be) that makes this tractable.
13406   //
13407   // FIXME: handle "template <> friend class A<T>;", which
13408   // is possibly well-formed?  Who even knows?
13409   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
13410     Diag(Loc, diag::err_tagless_friend_type_template)
13411       << DS.getSourceRange();
13412     return nullptr;
13413   }
13414 
13415   // C++98 [class.friend]p1: A friend of a class is a function
13416   //   or class that is not a member of the class . . .
13417   // This is fixed in DR77, which just barely didn't make the C++03
13418   // deadline.  It's also a very silly restriction that seriously
13419   // affects inner classes and which nobody else seems to implement;
13420   // thus we never diagnose it, not even in -pedantic.
13421   //
13422   // But note that we could warn about it: it's always useless to
13423   // friend one of your own members (it's not, however, worthless to
13424   // friend a member of an arbitrary specialization of your template).
13425 
13426   Decl *D;
13427   if (!TempParams.empty())
13428     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
13429                                    TempParams,
13430                                    TSI,
13431                                    DS.getFriendSpecLoc());
13432   else
13433     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
13434 
13435   if (!D)
13436     return nullptr;
13437 
13438   D->setAccess(AS_public);
13439   CurContext->addDecl(D);
13440 
13441   return D;
13442 }
13443 
13444 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
13445                                         MultiTemplateParamsArg TemplateParams) {
13446   const DeclSpec &DS = D.getDeclSpec();
13447 
13448   assert(DS.isFriendSpecified());
13449   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13450 
13451   SourceLocation Loc = D.getIdentifierLoc();
13452   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13453 
13454   // C++ [class.friend]p1
13455   //   A friend of a class is a function or class....
13456   // Note that this sees through typedefs, which is intended.
13457   // It *doesn't* see through dependent types, which is correct
13458   // according to [temp.arg.type]p3:
13459   //   If a declaration acquires a function type through a
13460   //   type dependent on a template-parameter and this causes
13461   //   a declaration that does not use the syntactic form of a
13462   //   function declarator to have a function type, the program
13463   //   is ill-formed.
13464   if (!TInfo->getType()->isFunctionType()) {
13465     Diag(Loc, diag::err_unexpected_friend);
13466 
13467     // It might be worthwhile to try to recover by creating an
13468     // appropriate declaration.
13469     return nullptr;
13470   }
13471 
13472   // C++ [namespace.memdef]p3
13473   //  - If a friend declaration in a non-local class first declares a
13474   //    class or function, the friend class or function is a member
13475   //    of the innermost enclosing namespace.
13476   //  - The name of the friend is not found by simple name lookup
13477   //    until a matching declaration is provided in that namespace
13478   //    scope (either before or after the class declaration granting
13479   //    friendship).
13480   //  - If a friend function is called, its name may be found by the
13481   //    name lookup that considers functions from namespaces and
13482   //    classes associated with the types of the function arguments.
13483   //  - When looking for a prior declaration of a class or a function
13484   //    declared as a friend, scopes outside the innermost enclosing
13485   //    namespace scope are not considered.
13486 
13487   CXXScopeSpec &SS = D.getCXXScopeSpec();
13488   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
13489   DeclarationName Name = NameInfo.getName();
13490   assert(Name);
13491 
13492   // Check for unexpanded parameter packs.
13493   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
13494       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
13495       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
13496     return nullptr;
13497 
13498   // The context we found the declaration in, or in which we should
13499   // create the declaration.
13500   DeclContext *DC;
13501   Scope *DCScope = S;
13502   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13503                         ForRedeclaration);
13504 
13505   // There are five cases here.
13506   //   - There's no scope specifier and we're in a local class. Only look
13507   //     for functions declared in the immediately-enclosing block scope.
13508   // We recover from invalid scope qualifiers as if they just weren't there.
13509   FunctionDecl *FunctionContainingLocalClass = nullptr;
13510   if ((SS.isInvalid() || !SS.isSet()) &&
13511       (FunctionContainingLocalClass =
13512            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
13513     // C++11 [class.friend]p11:
13514     //   If a friend declaration appears in a local class and the name
13515     //   specified is an unqualified name, a prior declaration is
13516     //   looked up without considering scopes that are outside the
13517     //   innermost enclosing non-class scope. For a friend function
13518     //   declaration, if there is no prior declaration, the program is
13519     //   ill-formed.
13520 
13521     // Find the innermost enclosing non-class scope. This is the block
13522     // scope containing the local class definition (or for a nested class,
13523     // the outer local class).
13524     DCScope = S->getFnParent();
13525 
13526     // Look up the function name in the scope.
13527     Previous.clear(LookupLocalFriendName);
13528     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
13529 
13530     if (!Previous.empty()) {
13531       // All possible previous declarations must have the same context:
13532       // either they were declared at block scope or they are members of
13533       // one of the enclosing local classes.
13534       DC = Previous.getRepresentativeDecl()->getDeclContext();
13535     } else {
13536       // This is ill-formed, but provide the context that we would have
13537       // declared the function in, if we were permitted to, for error recovery.
13538       DC = FunctionContainingLocalClass;
13539     }
13540     adjustContextForLocalExternDecl(DC);
13541 
13542     // C++ [class.friend]p6:
13543     //   A function can be defined in a friend declaration of a class if and
13544     //   only if the class is a non-local class (9.8), the function name is
13545     //   unqualified, and the function has namespace scope.
13546     if (D.isFunctionDefinition()) {
13547       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
13548     }
13549 
13550   //   - There's no scope specifier, in which case we just go to the
13551   //     appropriate scope and look for a function or function template
13552   //     there as appropriate.
13553   } else if (SS.isInvalid() || !SS.isSet()) {
13554     // C++11 [namespace.memdef]p3:
13555     //   If the name in a friend declaration is neither qualified nor
13556     //   a template-id and the declaration is a function or an
13557     //   elaborated-type-specifier, the lookup to determine whether
13558     //   the entity has been previously declared shall not consider
13559     //   any scopes outside the innermost enclosing namespace.
13560     bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
13561 
13562     // Find the appropriate context according to the above.
13563     DC = CurContext;
13564 
13565     // Skip class contexts.  If someone can cite chapter and verse
13566     // for this behavior, that would be nice --- it's what GCC and
13567     // EDG do, and it seems like a reasonable intent, but the spec
13568     // really only says that checks for unqualified existing
13569     // declarations should stop at the nearest enclosing namespace,
13570     // not that they should only consider the nearest enclosing
13571     // namespace.
13572     while (DC->isRecord())
13573       DC = DC->getParent();
13574 
13575     DeclContext *LookupDC = DC;
13576     while (LookupDC->isTransparentContext())
13577       LookupDC = LookupDC->getParent();
13578 
13579     while (true) {
13580       LookupQualifiedName(Previous, LookupDC);
13581 
13582       if (!Previous.empty()) {
13583         DC = LookupDC;
13584         break;
13585       }
13586 
13587       if (isTemplateId) {
13588         if (isa<TranslationUnitDecl>(LookupDC)) break;
13589       } else {
13590         if (LookupDC->isFileContext()) break;
13591       }
13592       LookupDC = LookupDC->getParent();
13593     }
13594 
13595     DCScope = getScopeForDeclContext(S, DC);
13596 
13597   //   - There's a non-dependent scope specifier, in which case we
13598   //     compute it and do a previous lookup there for a function
13599   //     or function template.
13600   } else if (!SS.getScopeRep()->isDependent()) {
13601     DC = computeDeclContext(SS);
13602     if (!DC) return nullptr;
13603 
13604     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
13605 
13606     LookupQualifiedName(Previous, DC);
13607 
13608     // Ignore things found implicitly in the wrong scope.
13609     // TODO: better diagnostics for this case.  Suggesting the right
13610     // qualified scope would be nice...
13611     LookupResult::Filter F = Previous.makeFilter();
13612     while (F.hasNext()) {
13613       NamedDecl *D = F.next();
13614       if (!DC->InEnclosingNamespaceSetOf(
13615               D->getDeclContext()->getRedeclContext()))
13616         F.erase();
13617     }
13618     F.done();
13619 
13620     if (Previous.empty()) {
13621       D.setInvalidType();
13622       Diag(Loc, diag::err_qualified_friend_not_found)
13623           << Name << TInfo->getType();
13624       return nullptr;
13625     }
13626 
13627     // C++ [class.friend]p1: A friend of a class is a function or
13628     //   class that is not a member of the class . . .
13629     if (DC->Equals(CurContext))
13630       Diag(DS.getFriendSpecLoc(),
13631            getLangOpts().CPlusPlus11 ?
13632              diag::warn_cxx98_compat_friend_is_member :
13633              diag::err_friend_is_member);
13634 
13635     if (D.isFunctionDefinition()) {
13636       // C++ [class.friend]p6:
13637       //   A function can be defined in a friend declaration of a class if and
13638       //   only if the class is a non-local class (9.8), the function name is
13639       //   unqualified, and the function has namespace scope.
13640       SemaDiagnosticBuilder DB
13641         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
13642 
13643       DB << SS.getScopeRep();
13644       if (DC->isFileContext())
13645         DB << FixItHint::CreateRemoval(SS.getRange());
13646       SS.clear();
13647     }
13648 
13649   //   - There's a scope specifier that does not match any template
13650   //     parameter lists, in which case we use some arbitrary context,
13651   //     create a method or method template, and wait for instantiation.
13652   //   - There's a scope specifier that does match some template
13653   //     parameter lists, which we don't handle right now.
13654   } else {
13655     if (D.isFunctionDefinition()) {
13656       // C++ [class.friend]p6:
13657       //   A function can be defined in a friend declaration of a class if and
13658       //   only if the class is a non-local class (9.8), the function name is
13659       //   unqualified, and the function has namespace scope.
13660       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
13661         << SS.getScopeRep();
13662     }
13663 
13664     DC = CurContext;
13665     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
13666   }
13667 
13668   if (!DC->isRecord()) {
13669     int DiagArg = -1;
13670     switch (D.getName().getKind()) {
13671     case UnqualifiedId::IK_ConstructorTemplateId:
13672     case UnqualifiedId::IK_ConstructorName:
13673       DiagArg = 0;
13674       break;
13675     case UnqualifiedId::IK_DestructorName:
13676       DiagArg = 1;
13677       break;
13678     case UnqualifiedId::IK_ConversionFunctionId:
13679       DiagArg = 2;
13680       break;
13681     case UnqualifiedId::IK_Identifier:
13682     case UnqualifiedId::IK_ImplicitSelfParam:
13683     case UnqualifiedId::IK_LiteralOperatorId:
13684     case UnqualifiedId::IK_OperatorFunctionId:
13685     case UnqualifiedId::IK_TemplateId:
13686       break;
13687     }
13688     // This implies that it has to be an operator or function.
13689     if (DiagArg >= 0) {
13690       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
13691       return nullptr;
13692     }
13693   }
13694 
13695   // FIXME: This is an egregious hack to cope with cases where the scope stack
13696   // does not contain the declaration context, i.e., in an out-of-line
13697   // definition of a class.
13698   Scope FakeDCScope(S, Scope::DeclScope, Diags);
13699   if (!DCScope) {
13700     FakeDCScope.setEntity(DC);
13701     DCScope = &FakeDCScope;
13702   }
13703 
13704   bool AddToScope = true;
13705   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
13706                                           TemplateParams, AddToScope);
13707   if (!ND) return nullptr;
13708 
13709   assert(ND->getLexicalDeclContext() == CurContext);
13710 
13711   // If we performed typo correction, we might have added a scope specifier
13712   // and changed the decl context.
13713   DC = ND->getDeclContext();
13714 
13715   // Add the function declaration to the appropriate lookup tables,
13716   // adjusting the redeclarations list as necessary.  We don't
13717   // want to do this yet if the friending class is dependent.
13718   //
13719   // Also update the scope-based lookup if the target context's
13720   // lookup context is in lexical scope.
13721   if (!CurContext->isDependentContext()) {
13722     DC = DC->getRedeclContext();
13723     DC->makeDeclVisibleInContext(ND);
13724     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
13725       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
13726   }
13727 
13728   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
13729                                        D.getIdentifierLoc(), ND,
13730                                        DS.getFriendSpecLoc());
13731   FrD->setAccess(AS_public);
13732   CurContext->addDecl(FrD);
13733 
13734   if (ND->isInvalidDecl()) {
13735     FrD->setInvalidDecl();
13736   } else {
13737     if (DC->isRecord()) CheckFriendAccess(ND);
13738 
13739     FunctionDecl *FD;
13740     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
13741       FD = FTD->getTemplatedDecl();
13742     else
13743       FD = cast<FunctionDecl>(ND);
13744 
13745     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
13746     // default argument expression, that declaration shall be a definition
13747     // and shall be the only declaration of the function or function
13748     // template in the translation unit.
13749     if (functionDeclHasDefaultArgument(FD)) {
13750       if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
13751         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
13752         Diag(OldFD->getLocation(), diag::note_previous_declaration);
13753       } else if (!D.isFunctionDefinition())
13754         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
13755     }
13756 
13757     // Mark templated-scope function declarations as unsupported.
13758     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
13759       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
13760         << SS.getScopeRep() << SS.getRange()
13761         << cast<CXXRecordDecl>(CurContext);
13762       FrD->setUnsupportedFriend(true);
13763     }
13764   }
13765 
13766   return ND;
13767 }
13768 
13769 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
13770   AdjustDeclIfTemplate(Dcl);
13771 
13772   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
13773   if (!Fn) {
13774     Diag(DelLoc, diag::err_deleted_non_function);
13775     return;
13776   }
13777 
13778   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
13779     // Don't consider the implicit declaration we generate for explicit
13780     // specializations. FIXME: Do not generate these implicit declarations.
13781     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
13782          Prev->getPreviousDecl()) &&
13783         !Prev->isDefined()) {
13784       Diag(DelLoc, diag::err_deleted_decl_not_first);
13785       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
13786            Prev->isImplicit() ? diag::note_previous_implicit_declaration
13787                               : diag::note_previous_declaration);
13788     }
13789     // If the declaration wasn't the first, we delete the function anyway for
13790     // recovery.
13791     Fn = Fn->getCanonicalDecl();
13792   }
13793 
13794   // dllimport/dllexport cannot be deleted.
13795   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
13796     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
13797     Fn->setInvalidDecl();
13798   }
13799 
13800   if (Fn->isDeleted())
13801     return;
13802 
13803   // See if we're deleting a function which is already known to override a
13804   // non-deleted virtual function.
13805   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
13806     bool IssuedDiagnostic = false;
13807     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
13808                                         E = MD->end_overridden_methods();
13809          I != E; ++I) {
13810       if (!(*MD->begin_overridden_methods())->isDeleted()) {
13811         if (!IssuedDiagnostic) {
13812           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
13813           IssuedDiagnostic = true;
13814         }
13815         Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
13816       }
13817     }
13818   }
13819 
13820   // C++11 [basic.start.main]p3:
13821   //   A program that defines main as deleted [...] is ill-formed.
13822   if (Fn->isMain())
13823     Diag(DelLoc, diag::err_deleted_main);
13824 
13825   Fn->setDeletedAsWritten();
13826 }
13827 
13828 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
13829   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
13830 
13831   if (MD) {
13832     if (MD->getParent()->isDependentType()) {
13833       MD->setDefaulted();
13834       MD->setExplicitlyDefaulted();
13835       return;
13836     }
13837 
13838     CXXSpecialMember Member = getSpecialMember(MD);
13839     if (Member == CXXInvalid) {
13840       if (!MD->isInvalidDecl())
13841         Diag(DefaultLoc, diag::err_default_special_members);
13842       return;
13843     }
13844 
13845     MD->setDefaulted();
13846     MD->setExplicitlyDefaulted();
13847 
13848     // If this definition appears within the record, do the checking when
13849     // the record is complete.
13850     const FunctionDecl *Primary = MD;
13851     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
13852       // Ask the template instantiation pattern that actually had the
13853       // '= default' on it.
13854       Primary = Pattern;
13855 
13856     // If the method was defaulted on its first declaration, we will have
13857     // already performed the checking in CheckCompletedCXXClass. Such a
13858     // declaration doesn't trigger an implicit definition.
13859     if (Primary->getCanonicalDecl()->isDefaulted())
13860       return;
13861 
13862     CheckExplicitlyDefaultedSpecialMember(MD);
13863 
13864     if (!MD->isInvalidDecl())
13865       DefineImplicitSpecialMember(*this, MD, DefaultLoc);
13866   } else {
13867     Diag(DefaultLoc, diag::err_default_special_members);
13868   }
13869 }
13870 
13871 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
13872   for (Stmt *SubStmt : S->children()) {
13873     if (!SubStmt)
13874       continue;
13875     if (isa<ReturnStmt>(SubStmt))
13876       Self.Diag(SubStmt->getLocStart(),
13877            diag::err_return_in_constructor_handler);
13878     if (!isa<Expr>(SubStmt))
13879       SearchForReturnInStmt(Self, SubStmt);
13880   }
13881 }
13882 
13883 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
13884   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
13885     CXXCatchStmt *Handler = TryBlock->getHandler(I);
13886     SearchForReturnInStmt(*this, Handler);
13887   }
13888 }
13889 
13890 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
13891                                              const CXXMethodDecl *Old) {
13892   const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
13893   const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
13894 
13895   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
13896 
13897   // If the calling conventions match, everything is fine
13898   if (NewCC == OldCC)
13899     return false;
13900 
13901   // If the calling conventions mismatch because the new function is static,
13902   // suppress the calling convention mismatch error; the error about static
13903   // function override (err_static_overrides_virtual from
13904   // Sema::CheckFunctionDeclaration) is more clear.
13905   if (New->getStorageClass() == SC_Static)
13906     return false;
13907 
13908   Diag(New->getLocation(),
13909        diag::err_conflicting_overriding_cc_attributes)
13910     << New->getDeclName() << New->getType() << Old->getType();
13911   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
13912   return true;
13913 }
13914 
13915 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
13916                                              const CXXMethodDecl *Old) {
13917   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
13918   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
13919 
13920   if (Context.hasSameType(NewTy, OldTy) ||
13921       NewTy->isDependentType() || OldTy->isDependentType())
13922     return false;
13923 
13924   // Check if the return types are covariant
13925   QualType NewClassTy, OldClassTy;
13926 
13927   /// Both types must be pointers or references to classes.
13928   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
13929     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
13930       NewClassTy = NewPT->getPointeeType();
13931       OldClassTy = OldPT->getPointeeType();
13932     }
13933   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
13934     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
13935       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
13936         NewClassTy = NewRT->getPointeeType();
13937         OldClassTy = OldRT->getPointeeType();
13938       }
13939     }
13940   }
13941 
13942   // The return types aren't either both pointers or references to a class type.
13943   if (NewClassTy.isNull()) {
13944     Diag(New->getLocation(),
13945          diag::err_different_return_type_for_overriding_virtual_function)
13946         << New->getDeclName() << NewTy << OldTy
13947         << New->getReturnTypeSourceRange();
13948     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13949         << Old->getReturnTypeSourceRange();
13950 
13951     return true;
13952   }
13953 
13954   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
13955     // C++14 [class.virtual]p8:
13956     //   If the class type in the covariant return type of D::f differs from
13957     //   that of B::f, the class type in the return type of D::f shall be
13958     //   complete at the point of declaration of D::f or shall be the class
13959     //   type D.
13960     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
13961       if (!RT->isBeingDefined() &&
13962           RequireCompleteType(New->getLocation(), NewClassTy,
13963                               diag::err_covariant_return_incomplete,
13964                               New->getDeclName()))
13965         return true;
13966     }
13967 
13968     // Check if the new class derives from the old class.
13969     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
13970       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
13971           << New->getDeclName() << NewTy << OldTy
13972           << New->getReturnTypeSourceRange();
13973       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13974           << Old->getReturnTypeSourceRange();
13975       return true;
13976     }
13977 
13978     // Check if we the conversion from derived to base is valid.
13979     if (CheckDerivedToBaseConversion(
13980             NewClassTy, OldClassTy,
13981             diag::err_covariant_return_inaccessible_base,
13982             diag::err_covariant_return_ambiguous_derived_to_base_conv,
13983             New->getLocation(), New->getReturnTypeSourceRange(),
13984             New->getDeclName(), nullptr)) {
13985       // FIXME: this note won't trigger for delayed access control
13986       // diagnostics, and it's impossible to get an undelayed error
13987       // here from access control during the original parse because
13988       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
13989       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13990           << Old->getReturnTypeSourceRange();
13991       return true;
13992     }
13993   }
13994 
13995   // The qualifiers of the return types must be the same.
13996   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
13997     Diag(New->getLocation(),
13998          diag::err_covariant_return_type_different_qualifications)
13999         << New->getDeclName() << NewTy << OldTy
14000         << New->getReturnTypeSourceRange();
14001     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14002         << Old->getReturnTypeSourceRange();
14003     return true;
14004   }
14005 
14006 
14007   // The new class type must have the same or less qualifiers as the old type.
14008   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14009     Diag(New->getLocation(),
14010          diag::err_covariant_return_type_class_type_more_qualified)
14011         << New->getDeclName() << NewTy << OldTy
14012         << New->getReturnTypeSourceRange();
14013     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14014         << Old->getReturnTypeSourceRange();
14015     return true;
14016   }
14017 
14018   return false;
14019 }
14020 
14021 /// \brief Mark the given method pure.
14022 ///
14023 /// \param Method the method to be marked pure.
14024 ///
14025 /// \param InitRange the source range that covers the "0" initializer.
14026 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
14027   SourceLocation EndLoc = InitRange.getEnd();
14028   if (EndLoc.isValid())
14029     Method->setRangeEnd(EndLoc);
14030 
14031   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14032     Method->setPure();
14033     return false;
14034   }
14035 
14036   if (!Method->isInvalidDecl())
14037     Diag(Method->getLocation(), diag::err_non_virtual_pure)
14038       << Method->getDeclName() << InitRange;
14039   return true;
14040 }
14041 
14042 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
14043   if (D->getFriendObjectKind())
14044     Diag(D->getLocation(), diag::err_pure_friend);
14045   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14046     CheckPureMethod(M, ZeroLoc);
14047   else
14048     Diag(D->getLocation(), diag::err_illegal_initializer);
14049 }
14050 
14051 /// \brief Determine whether the given declaration is a static data member.
14052 static bool isStaticDataMember(const Decl *D) {
14053   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
14054     return Var->isStaticDataMember();
14055 
14056   return false;
14057 }
14058 
14059 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
14060 /// an initializer for the out-of-line declaration 'Dcl'.  The scope
14061 /// is a fresh scope pushed for just this purpose.
14062 ///
14063 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
14064 /// static data member of class X, names should be looked up in the scope of
14065 /// class X.
14066 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
14067   // If there is no declaration, there was an error parsing it.
14068   if (!D || D->isInvalidDecl())
14069     return;
14070 
14071   // We will always have a nested name specifier here, but this declaration
14072   // might not be out of line if the specifier names the current namespace:
14073   //   extern int n;
14074   //   int ::n = 0;
14075   if (D->isOutOfLine())
14076     EnterDeclaratorContext(S, D->getDeclContext());
14077 
14078   // If we are parsing the initializer for a static data member, push a
14079   // new expression evaluation context that is associated with this static
14080   // data member.
14081   if (isStaticDataMember(D))
14082     PushExpressionEvaluationContext(PotentiallyEvaluated, D);
14083 }
14084 
14085 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
14086 /// initializer for the out-of-line declaration 'D'.
14087 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
14088   // If there is no declaration, there was an error parsing it.
14089   if (!D || D->isInvalidDecl())
14090     return;
14091 
14092   if (isStaticDataMember(D))
14093     PopExpressionEvaluationContext();
14094 
14095   if (D->isOutOfLine())
14096     ExitDeclaratorContext(S);
14097 }
14098 
14099 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
14100 /// C++ if/switch/while/for statement.
14101 /// e.g: "if (int x = f()) {...}"
14102 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
14103   // C++ 6.4p2:
14104   // The declarator shall not specify a function or an array.
14105   // The type-specifier-seq shall not contain typedef and shall not declare a
14106   // new class or enumeration.
14107   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
14108          "Parser allowed 'typedef' as storage class of condition decl.");
14109 
14110   Decl *Dcl = ActOnDeclarator(S, D);
14111   if (!Dcl)
14112     return true;
14113 
14114   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
14115     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
14116       << D.getSourceRange();
14117     return true;
14118   }
14119 
14120   return Dcl;
14121 }
14122 
14123 void Sema::LoadExternalVTableUses() {
14124   if (!ExternalSource)
14125     return;
14126 
14127   SmallVector<ExternalVTableUse, 4> VTables;
14128   ExternalSource->ReadUsedVTables(VTables);
14129   SmallVector<VTableUse, 4> NewUses;
14130   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
14131     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
14132       = VTablesUsed.find(VTables[I].Record);
14133     // Even if a definition wasn't required before, it may be required now.
14134     if (Pos != VTablesUsed.end()) {
14135       if (!Pos->second && VTables[I].DefinitionRequired)
14136         Pos->second = true;
14137       continue;
14138     }
14139 
14140     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
14141     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
14142   }
14143 
14144   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
14145 }
14146 
14147 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
14148                           bool DefinitionRequired) {
14149   // Ignore any vtable uses in unevaluated operands or for classes that do
14150   // not have a vtable.
14151   if (!Class->isDynamicClass() || Class->isDependentContext() ||
14152       CurContext->isDependentContext() || isUnevaluatedContext())
14153     return;
14154 
14155   // Try to insert this class into the map.
14156   LoadExternalVTableUses();
14157   Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
14158   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
14159     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
14160   if (!Pos.second) {
14161     // If we already had an entry, check to see if we are promoting this vtable
14162     // to require a definition. If so, we need to reappend to the VTableUses
14163     // list, since we may have already processed the first entry.
14164     if (DefinitionRequired && !Pos.first->second) {
14165       Pos.first->second = true;
14166     } else {
14167       // Otherwise, we can early exit.
14168       return;
14169     }
14170   } else {
14171     // The Microsoft ABI requires that we perform the destructor body
14172     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
14173     // the deleting destructor is emitted with the vtable, not with the
14174     // destructor definition as in the Itanium ABI.
14175     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14176       CXXDestructorDecl *DD = Class->getDestructor();
14177       if (DD && DD->isVirtual() && !DD->isDeleted()) {
14178         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
14179           // If this is an out-of-line declaration, marking it referenced will
14180           // not do anything. Manually call CheckDestructor to look up operator
14181           // delete().
14182           ContextRAII SavedContext(*this, DD);
14183           CheckDestructor(DD);
14184         } else {
14185           MarkFunctionReferenced(Loc, Class->getDestructor());
14186         }
14187       }
14188     }
14189   }
14190 
14191   // Local classes need to have their virtual members marked
14192   // immediately. For all other classes, we mark their virtual members
14193   // at the end of the translation unit.
14194   if (Class->isLocalClass())
14195     MarkVirtualMembersReferenced(Loc, Class);
14196   else
14197     VTableUses.push_back(std::make_pair(Class, Loc));
14198 }
14199 
14200 bool Sema::DefineUsedVTables() {
14201   LoadExternalVTableUses();
14202   if (VTableUses.empty())
14203     return false;
14204 
14205   // Note: The VTableUses vector could grow as a result of marking
14206   // the members of a class as "used", so we check the size each
14207   // time through the loop and prefer indices (which are stable) to
14208   // iterators (which are not).
14209   bool DefinedAnything = false;
14210   for (unsigned I = 0; I != VTableUses.size(); ++I) {
14211     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
14212     if (!Class)
14213       continue;
14214 
14215     SourceLocation Loc = VTableUses[I].second;
14216 
14217     bool DefineVTable = true;
14218 
14219     // If this class has a key function, but that key function is
14220     // defined in another translation unit, we don't need to emit the
14221     // vtable even though we're using it.
14222     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
14223     if (KeyFunction && !KeyFunction->hasBody()) {
14224       // The key function is in another translation unit.
14225       DefineVTable = false;
14226       TemplateSpecializationKind TSK =
14227           KeyFunction->getTemplateSpecializationKind();
14228       assert(TSK != TSK_ExplicitInstantiationDefinition &&
14229              TSK != TSK_ImplicitInstantiation &&
14230              "Instantiations don't have key functions");
14231       (void)TSK;
14232     } else if (!KeyFunction) {
14233       // If we have a class with no key function that is the subject
14234       // of an explicit instantiation declaration, suppress the
14235       // vtable; it will live with the explicit instantiation
14236       // definition.
14237       bool IsExplicitInstantiationDeclaration
14238         = Class->getTemplateSpecializationKind()
14239                                       == TSK_ExplicitInstantiationDeclaration;
14240       for (auto R : Class->redecls()) {
14241         TemplateSpecializationKind TSK
14242           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
14243         if (TSK == TSK_ExplicitInstantiationDeclaration)
14244           IsExplicitInstantiationDeclaration = true;
14245         else if (TSK == TSK_ExplicitInstantiationDefinition) {
14246           IsExplicitInstantiationDeclaration = false;
14247           break;
14248         }
14249       }
14250 
14251       if (IsExplicitInstantiationDeclaration)
14252         DefineVTable = false;
14253     }
14254 
14255     // The exception specifications for all virtual members may be needed even
14256     // if we are not providing an authoritative form of the vtable in this TU.
14257     // We may choose to emit it available_externally anyway.
14258     if (!DefineVTable) {
14259       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
14260       continue;
14261     }
14262 
14263     // Mark all of the virtual members of this class as referenced, so
14264     // that we can build a vtable. Then, tell the AST consumer that a
14265     // vtable for this class is required.
14266     DefinedAnything = true;
14267     MarkVirtualMembersReferenced(Loc, Class);
14268     CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
14269     if (VTablesUsed[Canonical])
14270       Consumer.HandleVTable(Class);
14271 
14272     // Optionally warn if we're emitting a weak vtable.
14273     if (Class->isExternallyVisible() &&
14274         Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
14275       const FunctionDecl *KeyFunctionDef = nullptr;
14276       if (!KeyFunction ||
14277           (KeyFunction->hasBody(KeyFunctionDef) &&
14278            KeyFunctionDef->isInlined()))
14279         Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
14280              TSK_ExplicitInstantiationDefinition
14281              ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
14282           << Class;
14283     }
14284   }
14285   VTableUses.clear();
14286 
14287   return DefinedAnything;
14288 }
14289 
14290 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
14291                                                  const CXXRecordDecl *RD) {
14292   for (const auto *I : RD->methods())
14293     if (I->isVirtual() && !I->isPure())
14294       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
14295 }
14296 
14297 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
14298                                         const CXXRecordDecl *RD) {
14299   // Mark all functions which will appear in RD's vtable as used.
14300   CXXFinalOverriderMap FinalOverriders;
14301   RD->getFinalOverriders(FinalOverriders);
14302   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
14303                                             E = FinalOverriders.end();
14304        I != E; ++I) {
14305     for (OverridingMethods::const_iterator OI = I->second.begin(),
14306                                            OE = I->second.end();
14307          OI != OE; ++OI) {
14308       assert(OI->second.size() > 0 && "no final overrider");
14309       CXXMethodDecl *Overrider = OI->second.front().Method;
14310 
14311       // C++ [basic.def.odr]p2:
14312       //   [...] A virtual member function is used if it is not pure. [...]
14313       if (!Overrider->isPure())
14314         MarkFunctionReferenced(Loc, Overrider);
14315     }
14316   }
14317 
14318   // Only classes that have virtual bases need a VTT.
14319   if (RD->getNumVBases() == 0)
14320     return;
14321 
14322   for (const auto &I : RD->bases()) {
14323     const CXXRecordDecl *Base =
14324         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
14325     if (Base->getNumVBases() == 0)
14326       continue;
14327     MarkVirtualMembersReferenced(Loc, Base);
14328   }
14329 }
14330 
14331 /// SetIvarInitializers - This routine builds initialization ASTs for the
14332 /// Objective-C implementation whose ivars need be initialized.
14333 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
14334   if (!getLangOpts().CPlusPlus)
14335     return;
14336   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
14337     SmallVector<ObjCIvarDecl*, 8> ivars;
14338     CollectIvarsToConstructOrDestruct(OID, ivars);
14339     if (ivars.empty())
14340       return;
14341     SmallVector<CXXCtorInitializer*, 32> AllToInit;
14342     for (unsigned i = 0; i < ivars.size(); i++) {
14343       FieldDecl *Field = ivars[i];
14344       if (Field->isInvalidDecl())
14345         continue;
14346 
14347       CXXCtorInitializer *Member;
14348       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
14349       InitializationKind InitKind =
14350         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
14351 
14352       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
14353       ExprResult MemberInit =
14354         InitSeq.Perform(*this, InitEntity, InitKind, None);
14355       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
14356       // Note, MemberInit could actually come back empty if no initialization
14357       // is required (e.g., because it would call a trivial default constructor)
14358       if (!MemberInit.get() || MemberInit.isInvalid())
14359         continue;
14360 
14361       Member =
14362         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
14363                                          SourceLocation(),
14364                                          MemberInit.getAs<Expr>(),
14365                                          SourceLocation());
14366       AllToInit.push_back(Member);
14367 
14368       // Be sure that the destructor is accessible and is marked as referenced.
14369       if (const RecordType *RecordTy =
14370               Context.getBaseElementType(Field->getType())
14371                   ->getAs<RecordType>()) {
14372         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
14373         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
14374           MarkFunctionReferenced(Field->getLocation(), Destructor);
14375           CheckDestructorAccess(Field->getLocation(), Destructor,
14376                             PDiag(diag::err_access_dtor_ivar)
14377                               << Context.getBaseElementType(Field->getType()));
14378         }
14379       }
14380     }
14381     ObjCImplementation->setIvarInitializers(Context,
14382                                             AllToInit.data(), AllToInit.size());
14383   }
14384 }
14385 
14386 static
14387 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
14388                            llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
14389                            llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
14390                            llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
14391                            Sema &S) {
14392   if (Ctor->isInvalidDecl())
14393     return;
14394 
14395   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
14396 
14397   // Target may not be determinable yet, for instance if this is a dependent
14398   // call in an uninstantiated template.
14399   if (Target) {
14400     const FunctionDecl *FNTarget = nullptr;
14401     (void)Target->hasBody(FNTarget);
14402     Target = const_cast<CXXConstructorDecl*>(
14403       cast_or_null<CXXConstructorDecl>(FNTarget));
14404   }
14405 
14406   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
14407                      // Avoid dereferencing a null pointer here.
14408                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
14409 
14410   if (!Current.insert(Canonical).second)
14411     return;
14412 
14413   // We know that beyond here, we aren't chaining into a cycle.
14414   if (!Target || !Target->isDelegatingConstructor() ||
14415       Target->isInvalidDecl() || Valid.count(TCanonical)) {
14416     Valid.insert(Current.begin(), Current.end());
14417     Current.clear();
14418   // We've hit a cycle.
14419   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
14420              Current.count(TCanonical)) {
14421     // If we haven't diagnosed this cycle yet, do so now.
14422     if (!Invalid.count(TCanonical)) {
14423       S.Diag((*Ctor->init_begin())->getSourceLocation(),
14424              diag::warn_delegating_ctor_cycle)
14425         << Ctor;
14426 
14427       // Don't add a note for a function delegating directly to itself.
14428       if (TCanonical != Canonical)
14429         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
14430 
14431       CXXConstructorDecl *C = Target;
14432       while (C->getCanonicalDecl() != Canonical) {
14433         const FunctionDecl *FNTarget = nullptr;
14434         (void)C->getTargetConstructor()->hasBody(FNTarget);
14435         assert(FNTarget && "Ctor cycle through bodiless function");
14436 
14437         C = const_cast<CXXConstructorDecl*>(
14438           cast<CXXConstructorDecl>(FNTarget));
14439         S.Diag(C->getLocation(), diag::note_which_delegates_to);
14440       }
14441     }
14442 
14443     Invalid.insert(Current.begin(), Current.end());
14444     Current.clear();
14445   } else {
14446     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
14447   }
14448 }
14449 
14450 
14451 void Sema::CheckDelegatingCtorCycles() {
14452   llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
14453 
14454   for (DelegatingCtorDeclsType::iterator
14455          I = DelegatingCtorDecls.begin(ExternalSource),
14456          E = DelegatingCtorDecls.end();
14457        I != E; ++I)
14458     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
14459 
14460   for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
14461                                                          CE = Invalid.end();
14462        CI != CE; ++CI)
14463     (*CI)->setInvalidDecl();
14464 }
14465 
14466 namespace {
14467   /// \brief AST visitor that finds references to the 'this' expression.
14468   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
14469     Sema &S;
14470 
14471   public:
14472     explicit FindCXXThisExpr(Sema &S) : S(S) { }
14473 
14474     bool VisitCXXThisExpr(CXXThisExpr *E) {
14475       S.Diag(E->getLocation(), diag::err_this_static_member_func)
14476         << E->isImplicit();
14477       return false;
14478     }
14479   };
14480 }
14481 
14482 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
14483   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14484   if (!TSInfo)
14485     return false;
14486 
14487   TypeLoc TL = TSInfo->getTypeLoc();
14488   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
14489   if (!ProtoTL)
14490     return false;
14491 
14492   // C++11 [expr.prim.general]p3:
14493   //   [The expression this] shall not appear before the optional
14494   //   cv-qualifier-seq and it shall not appear within the declaration of a
14495   //   static member function (although its type and value category are defined
14496   //   within a static member function as they are within a non-static member
14497   //   function). [ Note: this is because declaration matching does not occur
14498   //  until the complete declarator is known. - end note ]
14499   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
14500   FindCXXThisExpr Finder(*this);
14501 
14502   // If the return type came after the cv-qualifier-seq, check it now.
14503   if (Proto->hasTrailingReturn() &&
14504       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
14505     return true;
14506 
14507   // Check the exception specification.
14508   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
14509     return true;
14510 
14511   return checkThisInStaticMemberFunctionAttributes(Method);
14512 }
14513 
14514 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
14515   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14516   if (!TSInfo)
14517     return false;
14518 
14519   TypeLoc TL = TSInfo->getTypeLoc();
14520   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
14521   if (!ProtoTL)
14522     return false;
14523 
14524   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
14525   FindCXXThisExpr Finder(*this);
14526 
14527   switch (Proto->getExceptionSpecType()) {
14528   case EST_Unparsed:
14529   case EST_Uninstantiated:
14530   case EST_Unevaluated:
14531   case EST_BasicNoexcept:
14532   case EST_DynamicNone:
14533   case EST_MSAny:
14534   case EST_None:
14535     break;
14536 
14537   case EST_ComputedNoexcept:
14538     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
14539       return true;
14540 
14541   case EST_Dynamic:
14542     for (const auto &E : Proto->exceptions()) {
14543       if (!Finder.TraverseType(E))
14544         return true;
14545     }
14546     break;
14547   }
14548 
14549   return false;
14550 }
14551 
14552 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
14553   FindCXXThisExpr Finder(*this);
14554 
14555   // Check attributes.
14556   for (const auto *A : Method->attrs()) {
14557     // FIXME: This should be emitted by tblgen.
14558     Expr *Arg = nullptr;
14559     ArrayRef<Expr *> Args;
14560     if (const auto *G = dyn_cast<GuardedByAttr>(A))
14561       Arg = G->getArg();
14562     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
14563       Arg = G->getArg();
14564     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
14565       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
14566     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
14567       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
14568     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
14569       Arg = ETLF->getSuccessValue();
14570       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
14571     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
14572       Arg = STLF->getSuccessValue();
14573       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
14574     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
14575       Arg = LR->getArg();
14576     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
14577       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
14578     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
14579       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
14580     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
14581       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
14582     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
14583       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
14584     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
14585       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
14586 
14587     if (Arg && !Finder.TraverseStmt(Arg))
14588       return true;
14589 
14590     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
14591       if (!Finder.TraverseStmt(Args[I]))
14592         return true;
14593     }
14594   }
14595 
14596   return false;
14597 }
14598 
14599 void Sema::checkExceptionSpecification(
14600     bool IsTopLevel, ExceptionSpecificationType EST,
14601     ArrayRef<ParsedType> DynamicExceptions,
14602     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
14603     SmallVectorImpl<QualType> &Exceptions,
14604     FunctionProtoType::ExceptionSpecInfo &ESI) {
14605   Exceptions.clear();
14606   ESI.Type = EST;
14607   if (EST == EST_Dynamic) {
14608     Exceptions.reserve(DynamicExceptions.size());
14609     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
14610       // FIXME: Preserve type source info.
14611       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
14612 
14613       if (IsTopLevel) {
14614         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
14615         collectUnexpandedParameterPacks(ET, Unexpanded);
14616         if (!Unexpanded.empty()) {
14617           DiagnoseUnexpandedParameterPacks(
14618               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
14619               Unexpanded);
14620           continue;
14621         }
14622       }
14623 
14624       // Check that the type is valid for an exception spec, and
14625       // drop it if not.
14626       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
14627         Exceptions.push_back(ET);
14628     }
14629     ESI.Exceptions = Exceptions;
14630     return;
14631   }
14632 
14633   if (EST == EST_ComputedNoexcept) {
14634     // If an error occurred, there's no expression here.
14635     if (NoexceptExpr) {
14636       assert((NoexceptExpr->isTypeDependent() ||
14637               NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
14638               Context.BoolTy) &&
14639              "Parser should have made sure that the expression is boolean");
14640       if (IsTopLevel && NoexceptExpr &&
14641           DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
14642         ESI.Type = EST_BasicNoexcept;
14643         return;
14644       }
14645 
14646       if (!NoexceptExpr->isValueDependent())
14647         NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
14648                          diag::err_noexcept_needs_constant_expression,
14649                          /*AllowFold*/ false).get();
14650       ESI.NoexceptExpr = NoexceptExpr;
14651     }
14652     return;
14653   }
14654 }
14655 
14656 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
14657              ExceptionSpecificationType EST,
14658              SourceRange SpecificationRange,
14659              ArrayRef<ParsedType> DynamicExceptions,
14660              ArrayRef<SourceRange> DynamicExceptionRanges,
14661              Expr *NoexceptExpr) {
14662   if (!MethodD)
14663     return;
14664 
14665   // Dig out the method we're referring to.
14666   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
14667     MethodD = FunTmpl->getTemplatedDecl();
14668 
14669   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
14670   if (!Method)
14671     return;
14672 
14673   // Check the exception specification.
14674   llvm::SmallVector<QualType, 4> Exceptions;
14675   FunctionProtoType::ExceptionSpecInfo ESI;
14676   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
14677                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
14678                               ESI);
14679 
14680   // Update the exception specification on the function type.
14681   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
14682 
14683   if (Method->isStatic())
14684     checkThisInStaticMemberFunctionExceptionSpec(Method);
14685 
14686   if (Method->isVirtual()) {
14687     // Check overrides, which we previously had to delay.
14688     for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
14689                                      OEnd = Method->end_overridden_methods();
14690          O != OEnd; ++O)
14691       CheckOverridingFunctionExceptionSpec(Method, *O);
14692   }
14693 }
14694 
14695 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
14696 ///
14697 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
14698                                        SourceLocation DeclStart,
14699                                        Declarator &D, Expr *BitWidth,
14700                                        InClassInitStyle InitStyle,
14701                                        AccessSpecifier AS,
14702                                        AttributeList *MSPropertyAttr) {
14703   IdentifierInfo *II = D.getIdentifier();
14704   if (!II) {
14705     Diag(DeclStart, diag::err_anonymous_property);
14706     return nullptr;
14707   }
14708   SourceLocation Loc = D.getIdentifierLoc();
14709 
14710   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14711   QualType T = TInfo->getType();
14712   if (getLangOpts().CPlusPlus) {
14713     CheckExtraCXXDefaultArguments(D);
14714 
14715     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14716                                         UPPC_DataMemberType)) {
14717       D.setInvalidType();
14718       T = Context.IntTy;
14719       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
14720     }
14721   }
14722 
14723   DiagnoseFunctionSpecifiers(D.getDeclSpec());
14724 
14725   if (D.getDeclSpec().isInlineSpecified())
14726     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14727         << getLangOpts().CPlusPlus1z;
14728   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
14729     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
14730          diag::err_invalid_thread)
14731       << DeclSpec::getSpecifierName(TSCS);
14732 
14733   // Check to see if this name was declared as a member previously
14734   NamedDecl *PrevDecl = nullptr;
14735   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
14736   LookupName(Previous, S);
14737   switch (Previous.getResultKind()) {
14738   case LookupResult::Found:
14739   case LookupResult::FoundUnresolvedValue:
14740     PrevDecl = Previous.getAsSingle<NamedDecl>();
14741     break;
14742 
14743   case LookupResult::FoundOverloaded:
14744     PrevDecl = Previous.getRepresentativeDecl();
14745     break;
14746 
14747   case LookupResult::NotFound:
14748   case LookupResult::NotFoundInCurrentInstantiation:
14749   case LookupResult::Ambiguous:
14750     break;
14751   }
14752 
14753   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14754     // Maybe we will complain about the shadowed template parameter.
14755     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14756     // Just pretend that we didn't see the previous declaration.
14757     PrevDecl = nullptr;
14758   }
14759 
14760   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
14761     PrevDecl = nullptr;
14762 
14763   SourceLocation TSSL = D.getLocStart();
14764   const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
14765   MSPropertyDecl *NewPD = MSPropertyDecl::Create(
14766       Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
14767   ProcessDeclAttributes(TUScope, NewPD, D);
14768   NewPD->setAccess(AS);
14769 
14770   if (NewPD->isInvalidDecl())
14771     Record->setInvalidDecl();
14772 
14773   if (D.getDeclSpec().isModulePrivateSpecified())
14774     NewPD->setModulePrivate();
14775 
14776   if (NewPD->isInvalidDecl() && PrevDecl) {
14777     // Don't introduce NewFD into scope; there's already something
14778     // with the same name in the same scope.
14779   } else if (II) {
14780     PushOnScopeChains(NewPD, S);
14781   } else
14782     Record->addDecl(NewPD);
14783 
14784   return NewPD;
14785 }
14786