1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for C++ declarations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/EvaluatedExprVisitor.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/RecordLayout.h"
23 #include "clang/AST/RecursiveASTVisitor.h"
24 #include "clang/AST/StmtVisitor.h"
25 #include "clang/AST/TypeLoc.h"
26 #include "clang/AST/TypeOrdering.h"
27 #include "clang/Basic/PartialDiagnostic.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Lex/LiteralSupport.h"
30 #include "clang/Lex/Preprocessor.h"
31 #include "clang/Sema/CXXFieldCollector.h"
32 #include "clang/Sema/DeclSpec.h"
33 #include "clang/Sema/Initialization.h"
34 #include "clang/Sema/Lookup.h"
35 #include "clang/Sema/ParsedTemplate.h"
36 #include "clang/Sema/Scope.h"
37 #include "clang/Sema/ScopeInfo.h"
38 #include "clang/Sema/SemaInternal.h"
39 #include "clang/Sema/Template.h"
40 #include "llvm/ADT/STLExtras.h"
41 #include "llvm/ADT/SmallString.h"
42 #include "llvm/ADT/StringExtras.h"
43 #include <map>
44 #include <set>
45 
46 using namespace clang;
47 
48 //===----------------------------------------------------------------------===//
49 // CheckDefaultArgumentVisitor
50 //===----------------------------------------------------------------------===//
51 
52 namespace {
53   /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
54   /// the default argument of a parameter to determine whether it
55   /// contains any ill-formed subexpressions. For example, this will
56   /// diagnose the use of local variables or parameters within the
57   /// default argument expression.
58   class CheckDefaultArgumentVisitor
59     : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
60     Expr *DefaultArg;
61     Sema *S;
62 
63   public:
64     CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
65       : DefaultArg(defarg), S(s) {}
66 
67     bool VisitExpr(Expr *Node);
68     bool VisitDeclRefExpr(DeclRefExpr *DRE);
69     bool VisitCXXThisExpr(CXXThisExpr *ThisE);
70     bool VisitLambdaExpr(LambdaExpr *Lambda);
71     bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
72   };
73 
74   /// VisitExpr - Visit all of the children of this expression.
75   bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
76     bool IsInvalid = false;
77     for (Stmt *SubStmt : Node->children())
78       IsInvalid |= Visit(SubStmt);
79     return IsInvalid;
80   }
81 
82   /// VisitDeclRefExpr - Visit a reference to a declaration, to
83   /// determine whether this declaration can be used in the default
84   /// argument expression.
85   bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
86     NamedDecl *Decl = DRE->getDecl();
87     if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
88       // C++ [dcl.fct.default]p9
89       //   Default arguments are evaluated each time the function is
90       //   called. The order of evaluation of function arguments is
91       //   unspecified. Consequently, parameters of a function shall not
92       //   be used in default argument expressions, even if they are not
93       //   evaluated. Parameters of a function declared before a default
94       //   argument expression are in scope and can hide namespace and
95       //   class member names.
96       return S->Diag(DRE->getLocStart(),
97                      diag::err_param_default_argument_references_param)
98          << Param->getDeclName() << DefaultArg->getSourceRange();
99     } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
100       // C++ [dcl.fct.default]p7
101       //   Local variables shall not be used in default argument
102       //   expressions.
103       if (VDecl->isLocalVarDecl())
104         return S->Diag(DRE->getLocStart(),
105                        diag::err_param_default_argument_references_local)
106           << VDecl->getDeclName() << DefaultArg->getSourceRange();
107     }
108 
109     return false;
110   }
111 
112   /// VisitCXXThisExpr - Visit a C++ "this" expression.
113   bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
114     // C++ [dcl.fct.default]p8:
115     //   The keyword this shall not be used in a default argument of a
116     //   member function.
117     return S->Diag(ThisE->getLocStart(),
118                    diag::err_param_default_argument_references_this)
119                << ThisE->getSourceRange();
120   }
121 
122   bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
123     bool Invalid = false;
124     for (PseudoObjectExpr::semantics_iterator
125            i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
126       Expr *E = *i;
127 
128       // Look through bindings.
129       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
130         E = OVE->getSourceExpr();
131         assert(E && "pseudo-object binding without source expression?");
132       }
133 
134       Invalid |= Visit(E);
135     }
136     return Invalid;
137   }
138 
139   bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
140     // C++11 [expr.lambda.prim]p13:
141     //   A lambda-expression appearing in a default argument shall not
142     //   implicitly or explicitly capture any entity.
143     if (Lambda->capture_begin() == Lambda->capture_end())
144       return false;
145 
146     return S->Diag(Lambda->getLocStart(),
147                    diag::err_lambda_capture_default_arg);
148   }
149 }
150 
151 void
152 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
153                                                  const CXXMethodDecl *Method) {
154   // If we have an MSAny spec already, don't bother.
155   if (!Method || ComputedEST == EST_MSAny)
156     return;
157 
158   const FunctionProtoType *Proto
159     = Method->getType()->getAs<FunctionProtoType>();
160   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
161   if (!Proto)
162     return;
163 
164   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
165 
166   // If we have a throw-all spec at this point, ignore the function.
167   if (ComputedEST == EST_None)
168     return;
169 
170   switch(EST) {
171   // If this function can throw any exceptions, make a note of that.
172   case EST_MSAny:
173   case EST_None:
174     ClearExceptions();
175     ComputedEST = EST;
176     return;
177   // FIXME: If the call to this decl is using any of its default arguments, we
178   // need to search them for potentially-throwing calls.
179   // If this function has a basic noexcept, it doesn't affect the outcome.
180   case EST_BasicNoexcept:
181     return;
182   // If we're still at noexcept(true) and there's a nothrow() callee,
183   // change to that specification.
184   case EST_DynamicNone:
185     if (ComputedEST == EST_BasicNoexcept)
186       ComputedEST = EST_DynamicNone;
187     return;
188   // Check out noexcept specs.
189   case EST_ComputedNoexcept:
190   {
191     FunctionProtoType::NoexceptResult NR =
192         Proto->getNoexceptSpec(Self->Context);
193     assert(NR != FunctionProtoType::NR_NoNoexcept &&
194            "Must have noexcept result for EST_ComputedNoexcept.");
195     assert(NR != FunctionProtoType::NR_Dependent &&
196            "Should not generate implicit declarations for dependent cases, "
197            "and don't know how to handle them anyway.");
198     // noexcept(false) -> no spec on the new function
199     if (NR == FunctionProtoType::NR_Throw) {
200       ClearExceptions();
201       ComputedEST = EST_None;
202     }
203     // noexcept(true) won't change anything either.
204     return;
205   }
206   default:
207     break;
208   }
209   assert(EST == EST_Dynamic && "EST case not considered earlier.");
210   assert(ComputedEST != EST_None &&
211          "Shouldn't collect exceptions when throw-all is guaranteed.");
212   ComputedEST = EST_Dynamic;
213   // Record the exceptions in this function's exception specification.
214   for (const auto &E : Proto->exceptions())
215     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
216       Exceptions.push_back(E);
217 }
218 
219 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
220   if (!E || ComputedEST == EST_MSAny)
221     return;
222 
223   // FIXME:
224   //
225   // C++0x [except.spec]p14:
226   //   [An] implicit exception-specification specifies the type-id T if and
227   // only if T is allowed by the exception-specification of a function directly
228   // invoked by f's implicit definition; f shall allow all exceptions if any
229   // function it directly invokes allows all exceptions, and f shall allow no
230   // exceptions if every function it directly invokes allows no exceptions.
231   //
232   // Note in particular that if an implicit exception-specification is generated
233   // for a function containing a throw-expression, that specification can still
234   // be noexcept(true).
235   //
236   // Note also that 'directly invoked' is not defined in the standard, and there
237   // is no indication that we should only consider potentially-evaluated calls.
238   //
239   // Ultimately we should implement the intent of the standard: the exception
240   // specification should be the set of exceptions which can be thrown by the
241   // implicit definition. For now, we assume that any non-nothrow expression can
242   // throw any exception.
243 
244   if (Self->canThrow(E))
245     ComputedEST = EST_None;
246 }
247 
248 bool
249 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
250                               SourceLocation EqualLoc) {
251   if (RequireCompleteType(Param->getLocation(), Param->getType(),
252                           diag::err_typecheck_decl_incomplete_type)) {
253     Param->setInvalidDecl();
254     return true;
255   }
256 
257   // C++ [dcl.fct.default]p5
258   //   A default argument expression is implicitly converted (clause
259   //   4) to the parameter type. The default argument expression has
260   //   the same semantic constraints as the initializer expression in
261   //   a declaration of a variable of the parameter type, using the
262   //   copy-initialization semantics (8.5).
263   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
264                                                                     Param);
265   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
266                                                            EqualLoc);
267   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
268   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
269   if (Result.isInvalid())
270     return true;
271   Arg = Result.getAs<Expr>();
272 
273   CheckCompletedExpr(Arg, EqualLoc);
274   Arg = MaybeCreateExprWithCleanups(Arg);
275 
276   // Okay: add the default argument to the parameter
277   Param->setDefaultArg(Arg);
278 
279   // We have already instantiated this parameter; provide each of the
280   // instantiations with the uninstantiated default argument.
281   UnparsedDefaultArgInstantiationsMap::iterator InstPos
282     = UnparsedDefaultArgInstantiations.find(Param);
283   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
284     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
285       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
286 
287     // We're done tracking this parameter's instantiations.
288     UnparsedDefaultArgInstantiations.erase(InstPos);
289   }
290 
291   return false;
292 }
293 
294 /// ActOnParamDefaultArgument - Check whether the default argument
295 /// provided for a function parameter is well-formed. If so, attach it
296 /// to the parameter declaration.
297 void
298 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
299                                 Expr *DefaultArg) {
300   if (!param || !DefaultArg)
301     return;
302 
303   ParmVarDecl *Param = cast<ParmVarDecl>(param);
304   UnparsedDefaultArgLocs.erase(Param);
305 
306   // Default arguments are only permitted in C++
307   if (!getLangOpts().CPlusPlus) {
308     Diag(EqualLoc, diag::err_param_default_argument)
309       << DefaultArg->getSourceRange();
310     Param->setInvalidDecl();
311     return;
312   }
313 
314   // Check for unexpanded parameter packs.
315   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
316     Param->setInvalidDecl();
317     return;
318   }
319 
320   // C++11 [dcl.fct.default]p3
321   //   A default argument expression [...] shall not be specified for a
322   //   parameter pack.
323   if (Param->isParameterPack()) {
324     Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
325         << DefaultArg->getSourceRange();
326     return;
327   }
328 
329   // Check that the default argument is well-formed
330   CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
331   if (DefaultArgChecker.Visit(DefaultArg)) {
332     Param->setInvalidDecl();
333     return;
334   }
335 
336   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
337 }
338 
339 /// ActOnParamUnparsedDefaultArgument - We've seen a default
340 /// argument for a function parameter, but we can't parse it yet
341 /// because we're inside a class definition. Note that this default
342 /// argument will be parsed later.
343 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
344                                              SourceLocation EqualLoc,
345                                              SourceLocation ArgLoc) {
346   if (!param)
347     return;
348 
349   ParmVarDecl *Param = cast<ParmVarDecl>(param);
350   Param->setUnparsedDefaultArg();
351   UnparsedDefaultArgLocs[Param] = ArgLoc;
352 }
353 
354 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
355 /// the default argument for the parameter param failed.
356 void Sema::ActOnParamDefaultArgumentError(Decl *param,
357                                           SourceLocation EqualLoc) {
358   if (!param)
359     return;
360 
361   ParmVarDecl *Param = cast<ParmVarDecl>(param);
362   Param->setInvalidDecl();
363   UnparsedDefaultArgLocs.erase(Param);
364   Param->setDefaultArg(new(Context)
365                        OpaqueValueExpr(EqualLoc,
366                                        Param->getType().getNonReferenceType(),
367                                        VK_RValue));
368 }
369 
370 /// CheckExtraCXXDefaultArguments - Check for any extra default
371 /// arguments in the declarator, which is not a function declaration
372 /// or definition and therefore is not permitted to have default
373 /// arguments. This routine should be invoked for every declarator
374 /// that is not a function declaration or definition.
375 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
376   // C++ [dcl.fct.default]p3
377   //   A default argument expression shall be specified only in the
378   //   parameter-declaration-clause of a function declaration or in a
379   //   template-parameter (14.1). It shall not be specified for a
380   //   parameter pack. If it is specified in a
381   //   parameter-declaration-clause, it shall not occur within a
382   //   declarator or abstract-declarator of a parameter-declaration.
383   bool MightBeFunction = D.isFunctionDeclarationContext();
384   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
385     DeclaratorChunk &chunk = D.getTypeObject(i);
386     if (chunk.Kind == DeclaratorChunk::Function) {
387       if (MightBeFunction) {
388         // This is a function declaration. It can have default arguments, but
389         // keep looking in case its return type is a function type with default
390         // arguments.
391         MightBeFunction = false;
392         continue;
393       }
394       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
395            ++argIdx) {
396         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
397         if (Param->hasUnparsedDefaultArg()) {
398           CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
399           SourceRange SR;
400           if (Toks->size() > 1)
401             SR = SourceRange((*Toks)[1].getLocation(),
402                              Toks->back().getLocation());
403           else
404             SR = UnparsedDefaultArgLocs[Param];
405           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
406             << SR;
407           delete Toks;
408           chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
409         } else if (Param->getDefaultArg()) {
410           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
411             << Param->getDefaultArg()->getSourceRange();
412           Param->setDefaultArg(nullptr);
413         }
414       }
415     } else if (chunk.Kind != DeclaratorChunk::Paren) {
416       MightBeFunction = false;
417     }
418   }
419 }
420 
421 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
422   for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
423     const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
424     if (!PVD->hasDefaultArg())
425       return false;
426     if (!PVD->hasInheritedDefaultArg())
427       return true;
428   }
429   return false;
430 }
431 
432 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
433 /// function, once we already know that they have the same
434 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
435 /// error, false otherwise.
436 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
437                                 Scope *S) {
438   bool Invalid = false;
439 
440   // The declaration context corresponding to the scope is the semantic
441   // parent, unless this is a local function declaration, in which case
442   // it is that surrounding function.
443   DeclContext *ScopeDC = New->isLocalExternDecl()
444                              ? New->getLexicalDeclContext()
445                              : New->getDeclContext();
446 
447   // Find the previous declaration for the purpose of default arguments.
448   FunctionDecl *PrevForDefaultArgs = Old;
449   for (/**/; PrevForDefaultArgs;
450        // Don't bother looking back past the latest decl if this is a local
451        // extern declaration; nothing else could work.
452        PrevForDefaultArgs = New->isLocalExternDecl()
453                                 ? nullptr
454                                 : PrevForDefaultArgs->getPreviousDecl()) {
455     // Ignore hidden declarations.
456     if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
457       continue;
458 
459     if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
460         !New->isCXXClassMember()) {
461       // Ignore default arguments of old decl if they are not in
462       // the same scope and this is not an out-of-line definition of
463       // a member function.
464       continue;
465     }
466 
467     if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
468       // If only one of these is a local function declaration, then they are
469       // declared in different scopes, even though isDeclInScope may think
470       // they're in the same scope. (If both are local, the scope check is
471       // sufficent, and if neither is local, then they are in the same scope.)
472       continue;
473     }
474 
475     // We found the right previous declaration.
476     break;
477   }
478 
479   // C++ [dcl.fct.default]p4:
480   //   For non-template functions, default arguments can be added in
481   //   later declarations of a function in the same
482   //   scope. Declarations in different scopes have completely
483   //   distinct sets of default arguments. That is, declarations in
484   //   inner scopes do not acquire default arguments from
485   //   declarations in outer scopes, and vice versa. In a given
486   //   function declaration, all parameters subsequent to a
487   //   parameter with a default argument shall have default
488   //   arguments supplied in this or previous declarations. A
489   //   default argument shall not be redefined by a later
490   //   declaration (not even to the same value).
491   //
492   // C++ [dcl.fct.default]p6:
493   //   Except for member functions of class templates, the default arguments
494   //   in a member function definition that appears outside of the class
495   //   definition are added to the set of default arguments provided by the
496   //   member function declaration in the class definition.
497   for (unsigned p = 0, NumParams = PrevForDefaultArgs
498                                        ? PrevForDefaultArgs->getNumParams()
499                                        : 0;
500        p < NumParams; ++p) {
501     ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
502     ParmVarDecl *NewParam = New->getParamDecl(p);
503 
504     bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
505     bool NewParamHasDfl = NewParam->hasDefaultArg();
506 
507     if (OldParamHasDfl && NewParamHasDfl) {
508       unsigned DiagDefaultParamID =
509         diag::err_param_default_argument_redefinition;
510 
511       // MSVC accepts that default parameters be redefined for member functions
512       // of template class. The new default parameter's value is ignored.
513       Invalid = true;
514       if (getLangOpts().MicrosoftExt) {
515         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
516         if (MD && MD->getParent()->getDescribedClassTemplate()) {
517           // Merge the old default argument into the new parameter.
518           NewParam->setHasInheritedDefaultArg();
519           if (OldParam->hasUninstantiatedDefaultArg())
520             NewParam->setUninstantiatedDefaultArg(
521                                       OldParam->getUninstantiatedDefaultArg());
522           else
523             NewParam->setDefaultArg(OldParam->getInit());
524           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
525           Invalid = false;
526         }
527       }
528 
529       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
530       // hint here. Alternatively, we could walk the type-source information
531       // for NewParam to find the last source location in the type... but it
532       // isn't worth the effort right now. This is the kind of test case that
533       // is hard to get right:
534       //   int f(int);
535       //   void g(int (*fp)(int) = f);
536       //   void g(int (*fp)(int) = &f);
537       Diag(NewParam->getLocation(), DiagDefaultParamID)
538         << NewParam->getDefaultArgRange();
539 
540       // Look for the function declaration where the default argument was
541       // actually written, which may be a declaration prior to Old.
542       for (auto Older = PrevForDefaultArgs;
543            OldParam->hasInheritedDefaultArg(); /**/) {
544         Older = Older->getPreviousDecl();
545         OldParam = Older->getParamDecl(p);
546       }
547 
548       Diag(OldParam->getLocation(), diag::note_previous_definition)
549         << OldParam->getDefaultArgRange();
550     } else if (OldParamHasDfl) {
551       // Merge the old default argument into the new parameter.
552       // It's important to use getInit() here;  getDefaultArg()
553       // strips off any top-level ExprWithCleanups.
554       NewParam->setHasInheritedDefaultArg();
555       if (OldParam->hasUnparsedDefaultArg())
556         NewParam->setUnparsedDefaultArg();
557       else if (OldParam->hasUninstantiatedDefaultArg())
558         NewParam->setUninstantiatedDefaultArg(
559                                       OldParam->getUninstantiatedDefaultArg());
560       else
561         NewParam->setDefaultArg(OldParam->getInit());
562     } else if (NewParamHasDfl) {
563       if (New->getDescribedFunctionTemplate()) {
564         // Paragraph 4, quoted above, only applies to non-template functions.
565         Diag(NewParam->getLocation(),
566              diag::err_param_default_argument_template_redecl)
567           << NewParam->getDefaultArgRange();
568         Diag(PrevForDefaultArgs->getLocation(),
569              diag::note_template_prev_declaration)
570             << false;
571       } else if (New->getTemplateSpecializationKind()
572                    != TSK_ImplicitInstantiation &&
573                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
574         // C++ [temp.expr.spec]p21:
575         //   Default function arguments shall not be specified in a declaration
576         //   or a definition for one of the following explicit specializations:
577         //     - the explicit specialization of a function template;
578         //     - the explicit specialization of a member function template;
579         //     - the explicit specialization of a member function of a class
580         //       template where the class template specialization to which the
581         //       member function specialization belongs is implicitly
582         //       instantiated.
583         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
584           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
585           << New->getDeclName()
586           << NewParam->getDefaultArgRange();
587       } else if (New->getDeclContext()->isDependentContext()) {
588         // C++ [dcl.fct.default]p6 (DR217):
589         //   Default arguments for a member function of a class template shall
590         //   be specified on the initial declaration of the member function
591         //   within the class template.
592         //
593         // Reading the tea leaves a bit in DR217 and its reference to DR205
594         // leads me to the conclusion that one cannot add default function
595         // arguments for an out-of-line definition of a member function of a
596         // dependent type.
597         int WhichKind = 2;
598         if (CXXRecordDecl *Record
599               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
600           if (Record->getDescribedClassTemplate())
601             WhichKind = 0;
602           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
603             WhichKind = 1;
604           else
605             WhichKind = 2;
606         }
607 
608         Diag(NewParam->getLocation(),
609              diag::err_param_default_argument_member_template_redecl)
610           << WhichKind
611           << NewParam->getDefaultArgRange();
612       }
613     }
614   }
615 
616   // DR1344: If a default argument is added outside a class definition and that
617   // default argument makes the function a special member function, the program
618   // is ill-formed. This can only happen for constructors.
619   if (isa<CXXConstructorDecl>(New) &&
620       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
621     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
622                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
623     if (NewSM != OldSM) {
624       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
625       assert(NewParam->hasDefaultArg());
626       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
627         << NewParam->getDefaultArgRange() << NewSM;
628       Diag(Old->getLocation(), diag::note_previous_declaration);
629     }
630   }
631 
632   const FunctionDecl *Def;
633   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
634   // template has a constexpr specifier then all its declarations shall
635   // contain the constexpr specifier.
636   if (New->isConstexpr() != Old->isConstexpr()) {
637     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
638       << New << New->isConstexpr();
639     Diag(Old->getLocation(), diag::note_previous_declaration);
640     Invalid = true;
641   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
642              Old->isDefined(Def)) {
643     // C++11 [dcl.fcn.spec]p4:
644     //   If the definition of a function appears in a translation unit before its
645     //   first declaration as inline, the program is ill-formed.
646     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
647     Diag(Def->getLocation(), diag::note_previous_definition);
648     Invalid = true;
649   }
650 
651   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
652   // argument expression, that declaration shall be a definition and shall be
653   // the only declaration of the function or function template in the
654   // translation unit.
655   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
656       functionDeclHasDefaultArgument(Old)) {
657     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
658     Diag(Old->getLocation(), diag::note_previous_declaration);
659     Invalid = true;
660   }
661 
662   if (CheckEquivalentExceptionSpec(Old, New))
663     Invalid = true;
664 
665   return Invalid;
666 }
667 
668 NamedDecl *
669 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
670                                    MultiTemplateParamsArg TemplateParamLists) {
671   assert(D.isDecompositionDeclarator());
672   const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
673 
674   // The syntax only allows a decomposition declarator as a simple-declaration
675   // or a for-range-declaration, but we parse it in more cases than that.
676   if (!D.mayHaveDecompositionDeclarator()) {
677     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
678       << Decomp.getSourceRange();
679     return nullptr;
680   }
681 
682   if (!TemplateParamLists.empty()) {
683     // FIXME: There's no rule against this, but there are also no rules that
684     // would actually make it usable, so we reject it for now.
685     Diag(TemplateParamLists.front()->getTemplateLoc(),
686          diag::err_decomp_decl_template);
687     return nullptr;
688   }
689 
690   Diag(Decomp.getLSquareLoc(), getLangOpts().CPlusPlus1z
691                                    ? diag::warn_cxx14_compat_decomp_decl
692                                    : diag::ext_decomp_decl)
693       << Decomp.getSourceRange();
694 
695   // The semantic context is always just the current context.
696   DeclContext *const DC = CurContext;
697 
698   // C++1z [dcl.dcl]/8:
699   //   The decl-specifier-seq shall contain only the type-specifier auto
700   //   and cv-qualifiers.
701   auto &DS = D.getDeclSpec();
702   {
703     SmallVector<StringRef, 8> BadSpecifiers;
704     SmallVector<SourceLocation, 8> BadSpecifierLocs;
705     if (auto SCS = DS.getStorageClassSpec()) {
706       BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
707       BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
708     }
709     if (auto TSCS = DS.getThreadStorageClassSpec()) {
710       BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS));
711       BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
712     }
713     if (DS.isConstexprSpecified()) {
714       BadSpecifiers.push_back("constexpr");
715       BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
716     }
717     if (DS.isInlineSpecified()) {
718       BadSpecifiers.push_back("inline");
719       BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
720     }
721     if (!BadSpecifiers.empty()) {
722       auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
723       Err << (int)BadSpecifiers.size()
724           << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
725       // Don't add FixItHints to remove the specifiers; we do still respect
726       // them when building the underlying variable.
727       for (auto Loc : BadSpecifierLocs)
728         Err << SourceRange(Loc, Loc);
729     }
730     // We can't recover from it being declared as a typedef.
731     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
732       return nullptr;
733   }
734 
735   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
736   QualType R = TInfo->getType();
737 
738   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
739                                       UPPC_DeclarationType))
740     D.setInvalidType();
741 
742   // The syntax only allows a single ref-qualifier prior to the decomposition
743   // declarator. No other declarator chunks are permitted. Also check the type
744   // specifier here.
745   if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
746       D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
747       (D.getNumTypeObjects() == 1 &&
748        D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
749     Diag(Decomp.getLSquareLoc(),
750          (D.hasGroupingParens() ||
751           (D.getNumTypeObjects() &&
752            D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
753              ? diag::err_decomp_decl_parens
754              : diag::err_decomp_decl_type)
755         << R;
756 
757     // In most cases, there's no actual problem with an explicitly-specified
758     // type, but a function type won't work here, and ActOnVariableDeclarator
759     // shouldn't be called for such a type.
760     if (R->isFunctionType())
761       D.setInvalidType();
762   }
763 
764   // Build the BindingDecls.
765   SmallVector<BindingDecl*, 8> Bindings;
766 
767   // Build the BindingDecls.
768   for (auto &B : D.getDecompositionDeclarator().bindings()) {
769     // Check for name conflicts.
770     DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
771     LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
772                           ForRedeclaration);
773     LookupName(Previous, S,
774                /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
775 
776     // It's not permitted to shadow a template parameter name.
777     if (Previous.isSingleResult() &&
778         Previous.getFoundDecl()->isTemplateParameter()) {
779       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
780                                       Previous.getFoundDecl());
781       Previous.clear();
782     }
783 
784     bool ConsiderLinkage = DC->isFunctionOrMethod() &&
785                            DS.getStorageClassSpec() == DeclSpec::SCS_extern;
786     FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
787                          /*AllowInlineNamespace*/false);
788     if (!Previous.empty()) {
789       auto *Old = Previous.getRepresentativeDecl();
790       Diag(B.NameLoc, diag::err_redefinition) << B.Name;
791       Diag(Old->getLocation(), diag::note_previous_definition);
792     }
793 
794     auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
795     PushOnScopeChains(BD, S, true);
796     Bindings.push_back(BD);
797     ParsingInitForAutoVars.insert(BD);
798   }
799 
800   // There are no prior lookup results for the variable itself, because it
801   // is unnamed.
802   DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
803                                Decomp.getLSquareLoc());
804   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
805 
806   // Build the variable that holds the non-decomposed object.
807   bool AddToScope = true;
808   NamedDecl *New =
809       ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
810                               MultiTemplateParamsArg(), AddToScope, Bindings);
811   CurContext->addHiddenDecl(New);
812 
813   if (isInOpenMPDeclareTargetContext())
814     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
815 
816   return New;
817 }
818 
819 static bool checkSimpleDecomposition(
820     Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
821     QualType DecompType, llvm::APSInt NumElems, QualType ElemType,
822     llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
823   if ((int64_t)Bindings.size() != NumElems) {
824     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
825         << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
826         << (NumElems < Bindings.size());
827     return true;
828   }
829 
830   unsigned I = 0;
831   for (auto *B : Bindings) {
832     SourceLocation Loc = B->getLocation();
833     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
834     if (E.isInvalid())
835       return true;
836     E = GetInit(Loc, E.get(), I++);
837     if (E.isInvalid())
838       return true;
839     B->setBinding(ElemType, E.get());
840   }
841 
842   return false;
843 }
844 
845 static bool checkArrayLikeDecomposition(Sema &S,
846                                         ArrayRef<BindingDecl *> Bindings,
847                                         ValueDecl *Src, QualType DecompType,
848                                         llvm::APSInt NumElems,
849                                         QualType ElemType) {
850   return checkSimpleDecomposition(
851       S, Bindings, Src, DecompType, NumElems, ElemType,
852       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
853         ExprResult E = S.ActOnIntegerConstant(Loc, I);
854         if (E.isInvalid())
855           return ExprError();
856         return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
857       });
858 }
859 
860 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
861                                     ValueDecl *Src, QualType DecompType,
862                                     const ConstantArrayType *CAT) {
863   return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
864                                      llvm::APSInt(CAT->getSize()),
865                                      CAT->getElementType());
866 }
867 
868 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
869                                      ValueDecl *Src, QualType DecompType,
870                                      const VectorType *VT) {
871   return checkArrayLikeDecomposition(
872       S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
873       S.Context.getQualifiedType(VT->getElementType(),
874                                  DecompType.getQualifiers()));
875 }
876 
877 static bool checkComplexDecomposition(Sema &S,
878                                       ArrayRef<BindingDecl *> Bindings,
879                                       ValueDecl *Src, QualType DecompType,
880                                       const ComplexType *CT) {
881   return checkSimpleDecomposition(
882       S, Bindings, Src, DecompType, llvm::APSInt::get(2),
883       S.Context.getQualifiedType(CT->getElementType(),
884                                  DecompType.getQualifiers()),
885       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
886         return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
887       });
888 }
889 
890 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
891                                      TemplateArgumentListInfo &Args) {
892   SmallString<128> SS;
893   llvm::raw_svector_ostream OS(SS);
894   bool First = true;
895   for (auto &Arg : Args.arguments()) {
896     if (!First)
897       OS << ", ";
898     Arg.getArgument().print(PrintingPolicy, OS);
899     First = false;
900   }
901   return OS.str();
902 }
903 
904 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
905                                      SourceLocation Loc, StringRef Trait,
906                                      TemplateArgumentListInfo &Args,
907                                      unsigned DiagID) {
908   auto DiagnoseMissing = [&] {
909     if (DiagID)
910       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
911                                                Args);
912     return true;
913   };
914 
915   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
916   NamespaceDecl *Std = S.getStdNamespace();
917   if (!Std)
918     return DiagnoseMissing();
919 
920   // Look up the trait itself, within namespace std. We can diagnose various
921   // problems with this lookup even if we've been asked to not diagnose a
922   // missing specialization, because this can only fail if the user has been
923   // declaring their own names in namespace std or we don't support the
924   // standard library implementation in use.
925   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
926                       Loc, Sema::LookupOrdinaryName);
927   if (!S.LookupQualifiedName(Result, Std))
928     return DiagnoseMissing();
929   if (Result.isAmbiguous())
930     return true;
931 
932   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
933   if (!TraitTD) {
934     Result.suppressDiagnostics();
935     NamedDecl *Found = *Result.begin();
936     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
937     S.Diag(Found->getLocation(), diag::note_declared_at);
938     return true;
939   }
940 
941   // Build the template-id.
942   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
943   if (TraitTy.isNull())
944     return true;
945   if (!S.isCompleteType(Loc, TraitTy)) {
946     if (DiagID)
947       S.RequireCompleteType(
948           Loc, TraitTy, DiagID,
949           printTemplateArgs(S.Context.getPrintingPolicy(), Args));
950     return true;
951   }
952 
953   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
954   assert(RD && "specialization of class template is not a class?");
955 
956   // Look up the member of the trait type.
957   S.LookupQualifiedName(TraitMemberLookup, RD);
958   return TraitMemberLookup.isAmbiguous();
959 }
960 
961 static TemplateArgumentLoc
962 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
963                                    uint64_t I) {
964   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
965   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
966 }
967 
968 static TemplateArgumentLoc
969 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
970   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
971 }
972 
973 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
974 
975 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
976                                llvm::APSInt &Size) {
977   EnterExpressionEvaluationContext ContextRAII(S, Sema::ConstantEvaluated);
978 
979   DeclarationName Value = S.PP.getIdentifierInfo("value");
980   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
981 
982   // Form template argument list for tuple_size<T>.
983   TemplateArgumentListInfo Args(Loc, Loc);
984   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
985 
986   // If there's no tuple_size specialization, it's not tuple-like.
987   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0))
988     return IsTupleLike::NotTupleLike;
989 
990   // FIXME: According to the standard, we're not supposed to diagnose if any
991   // of the steps below fail (or if lookup for ::value is ambiguous or otherwise
992   // results in an error), but this is subject to a pending CWG issue / NB
993   // comment, which says we do diagnose if tuple_size<T> is complete but
994   // tuple_size<T>::value is not an ICE.
995 
996   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
997     LookupResult &R;
998     TemplateArgumentListInfo &Args;
999     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1000         : R(R), Args(Args) {}
1001     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1002       S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1003           << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1004     }
1005   } Diagnoser(R, Args);
1006 
1007   if (R.empty()) {
1008     Diagnoser.diagnoseNotICE(S, Loc, SourceRange());
1009     return IsTupleLike::Error;
1010   }
1011 
1012   ExprResult E =
1013       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1014   if (E.isInvalid())
1015     return IsTupleLike::Error;
1016 
1017   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1018   if (E.isInvalid())
1019     return IsTupleLike::Error;
1020 
1021   return IsTupleLike::TupleLike;
1022 }
1023 
1024 /// \return std::tuple_element<I, T>::type.
1025 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1026                                         unsigned I, QualType T) {
1027   // Form template argument list for tuple_element<I, T>.
1028   TemplateArgumentListInfo Args(Loc, Loc);
1029   Args.addArgument(
1030       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1031   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1032 
1033   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1034   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1035   if (lookupStdTypeTraitMember(
1036           S, R, Loc, "tuple_element", Args,
1037           diag::err_decomp_decl_std_tuple_element_not_specialized))
1038     return QualType();
1039 
1040   auto *TD = R.getAsSingle<TypeDecl>();
1041   if (!TD) {
1042     R.suppressDiagnostics();
1043     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1044       << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1045     if (!R.empty())
1046       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1047     return QualType();
1048   }
1049 
1050   return S.Context.getTypeDeclType(TD);
1051 }
1052 
1053 namespace {
1054 struct BindingDiagnosticTrap {
1055   Sema &S;
1056   DiagnosticErrorTrap Trap;
1057   BindingDecl *BD;
1058 
1059   BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1060       : S(S), Trap(S.Diags), BD(BD) {}
1061   ~BindingDiagnosticTrap() {
1062     if (Trap.hasErrorOccurred())
1063       S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1064   }
1065 };
1066 }
1067 
1068 static bool checkTupleLikeDecomposition(Sema &S,
1069                                         ArrayRef<BindingDecl *> Bindings,
1070                                         VarDecl *Src, QualType DecompType,
1071                                         llvm::APSInt TupleSize) {
1072   if ((int64_t)Bindings.size() != TupleSize) {
1073     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1074         << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1075         << (TupleSize < Bindings.size());
1076     return true;
1077   }
1078 
1079   if (Bindings.empty())
1080     return false;
1081 
1082   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1083 
1084   // [dcl.decomp]p3:
1085   //   The unqualified-id get is looked up in the scope of E by class member
1086   //   access lookup
1087   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1088   bool UseMemberGet = false;
1089   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1090     if (auto *RD = DecompType->getAsCXXRecordDecl())
1091       S.LookupQualifiedName(MemberGet, RD);
1092     if (MemberGet.isAmbiguous())
1093       return true;
1094     UseMemberGet = !MemberGet.empty();
1095     S.FilterAcceptableTemplateNames(MemberGet);
1096   }
1097 
1098   unsigned I = 0;
1099   for (auto *B : Bindings) {
1100     BindingDiagnosticTrap Trap(S, B);
1101     SourceLocation Loc = B->getLocation();
1102 
1103     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1104     if (E.isInvalid())
1105       return true;
1106 
1107     //   e is an lvalue if the type of the entity is an lvalue reference and
1108     //   an xvalue otherwise
1109     if (!Src->getType()->isLValueReferenceType())
1110       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1111                                    E.get(), nullptr, VK_XValue);
1112 
1113     TemplateArgumentListInfo Args(Loc, Loc);
1114     Args.addArgument(
1115         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1116 
1117     if (UseMemberGet) {
1118       //   if [lookup of member get] finds at least one declaration, the
1119       //   initializer is e.get<i-1>().
1120       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1121                                      CXXScopeSpec(), SourceLocation(), nullptr,
1122                                      MemberGet, &Args, nullptr);
1123       if (E.isInvalid())
1124         return true;
1125 
1126       E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc);
1127     } else {
1128       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1129       //   in the associated namespaces.
1130       Expr *Get = UnresolvedLookupExpr::Create(
1131           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1132           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1133           UnresolvedSetIterator(), UnresolvedSetIterator());
1134 
1135       Expr *Arg = E.get();
1136       E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc);
1137     }
1138     if (E.isInvalid())
1139       return true;
1140     Expr *Init = E.get();
1141 
1142     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1143     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1144     if (T.isNull())
1145       return true;
1146 
1147     //   each vi is a variable of type "reference to T" initialized with the
1148     //   initializer, where the reference is an lvalue reference if the
1149     //   initializer is an lvalue and an rvalue reference otherwise
1150     QualType RefType =
1151         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1152     if (RefType.isNull())
1153       return true;
1154     auto *RefVD = VarDecl::Create(
1155         S.Context, Src->getDeclContext(), Loc, Loc,
1156         B->getDeclName().getAsIdentifierInfo(), RefType,
1157         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1158     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1159     RefVD->setTSCSpec(Src->getTSCSpec());
1160     RefVD->setImplicit();
1161     if (Src->isInlineSpecified())
1162       RefVD->setInlineSpecified();
1163     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1164 
1165     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1166     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1167     InitializationSequence Seq(S, Entity, Kind, Init);
1168     E = Seq.Perform(S, Entity, Kind, Init);
1169     if (E.isInvalid())
1170       return true;
1171     E = S.ActOnFinishFullExpr(E.get(), Loc);
1172     if (E.isInvalid())
1173       return true;
1174     RefVD->setInit(E.get());
1175     RefVD->checkInitIsICE();
1176 
1177     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1178                                    DeclarationNameInfo(B->getDeclName(), Loc),
1179                                    RefVD);
1180     if (E.isInvalid())
1181       return true;
1182 
1183     B->setBinding(T, E.get());
1184     I++;
1185   }
1186 
1187   return false;
1188 }
1189 
1190 /// Find the base class to decompose in a built-in decomposition of a class type.
1191 /// This base class search is, unfortunately, not quite like any other that we
1192 /// perform anywhere else in C++.
1193 static const CXXRecordDecl *findDecomposableBaseClass(Sema &S,
1194                                                       SourceLocation Loc,
1195                                                       const CXXRecordDecl *RD,
1196                                                       CXXCastPath &BasePath) {
1197   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1198                           CXXBasePath &Path) {
1199     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1200   };
1201 
1202   const CXXRecordDecl *ClassWithFields = nullptr;
1203   if (RD->hasDirectFields())
1204     // [dcl.decomp]p4:
1205     //   Otherwise, all of E's non-static data members shall be public direct
1206     //   members of E ...
1207     ClassWithFields = RD;
1208   else {
1209     //   ... or of ...
1210     CXXBasePaths Paths;
1211     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1212     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1213       // If no classes have fields, just decompose RD itself. (This will work
1214       // if and only if zero bindings were provided.)
1215       return RD;
1216     }
1217 
1218     CXXBasePath *BestPath = nullptr;
1219     for (auto &P : Paths) {
1220       if (!BestPath)
1221         BestPath = &P;
1222       else if (!S.Context.hasSameType(P.back().Base->getType(),
1223                                       BestPath->back().Base->getType())) {
1224         //   ... the same ...
1225         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1226           << false << RD << BestPath->back().Base->getType()
1227           << P.back().Base->getType();
1228         return nullptr;
1229       } else if (P.Access < BestPath->Access) {
1230         BestPath = &P;
1231       }
1232     }
1233 
1234     //   ... unambiguous ...
1235     QualType BaseType = BestPath->back().Base->getType();
1236     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1237       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1238         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1239       return nullptr;
1240     }
1241 
1242     //   ... public base class of E.
1243     if (BestPath->Access != AS_public) {
1244       S.Diag(Loc, diag::err_decomp_decl_non_public_base)
1245         << RD << BaseType;
1246       for (auto &BS : *BestPath) {
1247         if (BS.Base->getAccessSpecifier() != AS_public) {
1248           S.Diag(BS.Base->getLocStart(), diag::note_access_constrained_by_path)
1249             << (BS.Base->getAccessSpecifier() == AS_protected)
1250             << (BS.Base->getAccessSpecifierAsWritten() == AS_none);
1251           break;
1252         }
1253       }
1254       return nullptr;
1255     }
1256 
1257     ClassWithFields = BaseType->getAsCXXRecordDecl();
1258     S.BuildBasePathArray(Paths, BasePath);
1259   }
1260 
1261   // The above search did not check whether the selected class itself has base
1262   // classes with fields, so check that now.
1263   CXXBasePaths Paths;
1264   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1265     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1266       << (ClassWithFields == RD) << RD << ClassWithFields
1267       << Paths.front().back().Base->getType();
1268     return nullptr;
1269   }
1270 
1271   return ClassWithFields;
1272 }
1273 
1274 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1275                                      ValueDecl *Src, QualType DecompType,
1276                                      const CXXRecordDecl *RD) {
1277   CXXCastPath BasePath;
1278   RD = findDecomposableBaseClass(S, Src->getLocation(), RD, BasePath);
1279   if (!RD)
1280     return true;
1281   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1282                                                  DecompType.getQualifiers());
1283 
1284   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1285     unsigned NumFields = std::distance(RD->field_begin(), RD->field_end());
1286     assert(Bindings.size() != NumFields);
1287     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1288         << DecompType << (unsigned)Bindings.size() << NumFields
1289         << (NumFields < Bindings.size());
1290     return true;
1291   };
1292 
1293   //   all of E's non-static data members shall be public [...] members,
1294   //   E shall not have an anonymous union member, ...
1295   unsigned I = 0;
1296   for (auto *FD : RD->fields()) {
1297     if (FD->isUnnamedBitfield())
1298       continue;
1299 
1300     if (FD->isAnonymousStructOrUnion()) {
1301       S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1302         << DecompType << FD->getType()->isUnionType();
1303       S.Diag(FD->getLocation(), diag::note_declared_at);
1304       return true;
1305     }
1306 
1307     // We have a real field to bind.
1308     if (I >= Bindings.size())
1309       return DiagnoseBadNumberOfBindings();
1310     auto *B = Bindings[I++];
1311 
1312     SourceLocation Loc = B->getLocation();
1313     if (FD->getAccess() != AS_public) {
1314       S.Diag(Loc, diag::err_decomp_decl_non_public_member) << FD << DecompType;
1315 
1316       // Determine whether the access specifier was explicit.
1317       bool Implicit = true;
1318       for (const auto *D : RD->decls()) {
1319         if (declaresSameEntity(D, FD))
1320           break;
1321         if (isa<AccessSpecDecl>(D)) {
1322           Implicit = false;
1323           break;
1324         }
1325       }
1326 
1327       S.Diag(FD->getLocation(), diag::note_access_natural)
1328         << (FD->getAccess() == AS_protected) << Implicit;
1329       return true;
1330     }
1331 
1332     // Initialize the binding to Src.FD.
1333     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1334     if (E.isInvalid())
1335       return true;
1336     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1337                             VK_LValue, &BasePath);
1338     if (E.isInvalid())
1339       return true;
1340     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1341                                   CXXScopeSpec(), FD,
1342                                   DeclAccessPair::make(FD, FD->getAccess()),
1343                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1344     if (E.isInvalid())
1345       return true;
1346 
1347     // If the type of the member is T, the referenced type is cv T, where cv is
1348     // the cv-qualification of the decomposition expression.
1349     //
1350     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1351     // 'const' to the type of the field.
1352     Qualifiers Q = DecompType.getQualifiers();
1353     if (FD->isMutable())
1354       Q.removeConst();
1355     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1356   }
1357 
1358   if (I != Bindings.size())
1359     return DiagnoseBadNumberOfBindings();
1360 
1361   return false;
1362 }
1363 
1364 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1365   QualType DecompType = DD->getType();
1366 
1367   // If the type of the decomposition is dependent, then so is the type of
1368   // each binding.
1369   if (DecompType->isDependentType()) {
1370     for (auto *B : DD->bindings())
1371       B->setType(Context.DependentTy);
1372     return;
1373   }
1374 
1375   DecompType = DecompType.getNonReferenceType();
1376   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1377 
1378   // C++1z [dcl.decomp]/2:
1379   //   If E is an array type [...]
1380   // As an extension, we also support decomposition of built-in complex and
1381   // vector types.
1382   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1383     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1384       DD->setInvalidDecl();
1385     return;
1386   }
1387   if (auto *VT = DecompType->getAs<VectorType>()) {
1388     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1389       DD->setInvalidDecl();
1390     return;
1391   }
1392   if (auto *CT = DecompType->getAs<ComplexType>()) {
1393     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1394       DD->setInvalidDecl();
1395     return;
1396   }
1397 
1398   // C++1z [dcl.decomp]/3:
1399   //   if the expression std::tuple_size<E>::value is a well-formed integral
1400   //   constant expression, [...]
1401   llvm::APSInt TupleSize(32);
1402   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1403   case IsTupleLike::Error:
1404     DD->setInvalidDecl();
1405     return;
1406 
1407   case IsTupleLike::TupleLike:
1408     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1409       DD->setInvalidDecl();
1410     return;
1411 
1412   case IsTupleLike::NotTupleLike:
1413     break;
1414   }
1415 
1416   // C++1z [dcl.dcl]/8:
1417   //   [E shall be of array or non-union class type]
1418   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1419   if (!RD || RD->isUnion()) {
1420     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1421         << DD << !RD << DecompType;
1422     DD->setInvalidDecl();
1423     return;
1424   }
1425 
1426   // C++1z [dcl.decomp]/4:
1427   //   all of E's non-static data members shall be [...] direct members of
1428   //   E or of the same unambiguous public base class of E, ...
1429   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1430     DD->setInvalidDecl();
1431 }
1432 
1433 /// \brief Merge the exception specifications of two variable declarations.
1434 ///
1435 /// This is called when there's a redeclaration of a VarDecl. The function
1436 /// checks if the redeclaration might have an exception specification and
1437 /// validates compatibility and merges the specs if necessary.
1438 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1439   // Shortcut if exceptions are disabled.
1440   if (!getLangOpts().CXXExceptions)
1441     return;
1442 
1443   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1444          "Should only be called if types are otherwise the same.");
1445 
1446   QualType NewType = New->getType();
1447   QualType OldType = Old->getType();
1448 
1449   // We're only interested in pointers and references to functions, as well
1450   // as pointers to member functions.
1451   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1452     NewType = R->getPointeeType();
1453     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1454   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1455     NewType = P->getPointeeType();
1456     OldType = OldType->getAs<PointerType>()->getPointeeType();
1457   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1458     NewType = M->getPointeeType();
1459     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1460   }
1461 
1462   if (!NewType->isFunctionProtoType())
1463     return;
1464 
1465   // There's lots of special cases for functions. For function pointers, system
1466   // libraries are hopefully not as broken so that we don't need these
1467   // workarounds.
1468   if (CheckEquivalentExceptionSpec(
1469         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1470         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1471     New->setInvalidDecl();
1472   }
1473 }
1474 
1475 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1476 /// function declaration are well-formed according to C++
1477 /// [dcl.fct.default].
1478 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1479   unsigned NumParams = FD->getNumParams();
1480   unsigned p;
1481 
1482   // Find first parameter with a default argument
1483   for (p = 0; p < NumParams; ++p) {
1484     ParmVarDecl *Param = FD->getParamDecl(p);
1485     if (Param->hasDefaultArg())
1486       break;
1487   }
1488 
1489   // C++11 [dcl.fct.default]p4:
1490   //   In a given function declaration, each parameter subsequent to a parameter
1491   //   with a default argument shall have a default argument supplied in this or
1492   //   a previous declaration or shall be a function parameter pack. A default
1493   //   argument shall not be redefined by a later declaration (not even to the
1494   //   same value).
1495   unsigned LastMissingDefaultArg = 0;
1496   for (; p < NumParams; ++p) {
1497     ParmVarDecl *Param = FD->getParamDecl(p);
1498     if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
1499       if (Param->isInvalidDecl())
1500         /* We already complained about this parameter. */;
1501       else if (Param->getIdentifier())
1502         Diag(Param->getLocation(),
1503              diag::err_param_default_argument_missing_name)
1504           << Param->getIdentifier();
1505       else
1506         Diag(Param->getLocation(),
1507              diag::err_param_default_argument_missing);
1508 
1509       LastMissingDefaultArg = p;
1510     }
1511   }
1512 
1513   if (LastMissingDefaultArg > 0) {
1514     // Some default arguments were missing. Clear out all of the
1515     // default arguments up to (and including) the last missing
1516     // default argument, so that we leave the function parameters
1517     // in a semantically valid state.
1518     for (p = 0; p <= LastMissingDefaultArg; ++p) {
1519       ParmVarDecl *Param = FD->getParamDecl(p);
1520       if (Param->hasDefaultArg()) {
1521         Param->setDefaultArg(nullptr);
1522       }
1523     }
1524   }
1525 }
1526 
1527 // CheckConstexprParameterTypes - Check whether a function's parameter types
1528 // are all literal types. If so, return true. If not, produce a suitable
1529 // diagnostic and return false.
1530 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1531                                          const FunctionDecl *FD) {
1532   unsigned ArgIndex = 0;
1533   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
1534   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1535                                               e = FT->param_type_end();
1536        i != e; ++i, ++ArgIndex) {
1537     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1538     SourceLocation ParamLoc = PD->getLocation();
1539     if (!(*i)->isDependentType() &&
1540         SemaRef.RequireLiteralType(ParamLoc, *i,
1541                                    diag::err_constexpr_non_literal_param,
1542                                    ArgIndex+1, PD->getSourceRange(),
1543                                    isa<CXXConstructorDecl>(FD)))
1544       return false;
1545   }
1546   return true;
1547 }
1548 
1549 /// \brief Get diagnostic %select index for tag kind for
1550 /// record diagnostic message.
1551 /// WARNING: Indexes apply to particular diagnostics only!
1552 ///
1553 /// \returns diagnostic %select index.
1554 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1555   switch (Tag) {
1556   case TTK_Struct: return 0;
1557   case TTK_Interface: return 1;
1558   case TTK_Class:  return 2;
1559   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1560   }
1561 }
1562 
1563 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
1564 // the requirements of a constexpr function definition or a constexpr
1565 // constructor definition. If so, return true. If not, produce appropriate
1566 // diagnostics and return false.
1567 //
1568 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1569 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
1570   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1571   if (MD && MD->isInstance()) {
1572     // C++11 [dcl.constexpr]p4:
1573     //  The definition of a constexpr constructor shall satisfy the following
1574     //  constraints:
1575     //  - the class shall not have any virtual base classes;
1576     const CXXRecordDecl *RD = MD->getParent();
1577     if (RD->getNumVBases()) {
1578       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1579         << isa<CXXConstructorDecl>(NewFD)
1580         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1581       for (const auto &I : RD->vbases())
1582         Diag(I.getLocStart(),
1583              diag::note_constexpr_virtual_base_here) << I.getSourceRange();
1584       return false;
1585     }
1586   }
1587 
1588   if (!isa<CXXConstructorDecl>(NewFD)) {
1589     // C++11 [dcl.constexpr]p3:
1590     //  The definition of a constexpr function shall satisfy the following
1591     //  constraints:
1592     // - it shall not be virtual;
1593     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1594     if (Method && Method->isVirtual()) {
1595       Method = Method->getCanonicalDecl();
1596       Diag(Method->getLocation(), diag::err_constexpr_virtual);
1597 
1598       // If it's not obvious why this function is virtual, find an overridden
1599       // function which uses the 'virtual' keyword.
1600       const CXXMethodDecl *WrittenVirtual = Method;
1601       while (!WrittenVirtual->isVirtualAsWritten())
1602         WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1603       if (WrittenVirtual != Method)
1604         Diag(WrittenVirtual->getLocation(),
1605              diag::note_overridden_virtual_function);
1606       return false;
1607     }
1608 
1609     // - its return type shall be a literal type;
1610     QualType RT = NewFD->getReturnType();
1611     if (!RT->isDependentType() &&
1612         RequireLiteralType(NewFD->getLocation(), RT,
1613                            diag::err_constexpr_non_literal_return))
1614       return false;
1615   }
1616 
1617   // - each of its parameter types shall be a literal type;
1618   if (!CheckConstexprParameterTypes(*this, NewFD))
1619     return false;
1620 
1621   return true;
1622 }
1623 
1624 /// Check the given declaration statement is legal within a constexpr function
1625 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1626 ///
1627 /// \return true if the body is OK (maybe only as an extension), false if we
1628 ///         have diagnosed a problem.
1629 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1630                                    DeclStmt *DS, SourceLocation &Cxx1yLoc) {
1631   // C++11 [dcl.constexpr]p3 and p4:
1632   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1633   //  contain only
1634   for (const auto *DclIt : DS->decls()) {
1635     switch (DclIt->getKind()) {
1636     case Decl::StaticAssert:
1637     case Decl::Using:
1638     case Decl::UsingShadow:
1639     case Decl::UsingDirective:
1640     case Decl::UnresolvedUsingTypename:
1641     case Decl::UnresolvedUsingValue:
1642       //   - static_assert-declarations
1643       //   - using-declarations,
1644       //   - using-directives,
1645       continue;
1646 
1647     case Decl::Typedef:
1648     case Decl::TypeAlias: {
1649       //   - typedef declarations and alias-declarations that do not define
1650       //     classes or enumerations,
1651       const auto *TN = cast<TypedefNameDecl>(DclIt);
1652       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1653         // Don't allow variably-modified types in constexpr functions.
1654         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1655         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1656           << TL.getSourceRange() << TL.getType()
1657           << isa<CXXConstructorDecl>(Dcl);
1658         return false;
1659       }
1660       continue;
1661     }
1662 
1663     case Decl::Enum:
1664     case Decl::CXXRecord:
1665       // C++1y allows types to be defined, not just declared.
1666       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
1667         SemaRef.Diag(DS->getLocStart(),
1668                      SemaRef.getLangOpts().CPlusPlus14
1669                        ? diag::warn_cxx11_compat_constexpr_type_definition
1670                        : diag::ext_constexpr_type_definition)
1671           << isa<CXXConstructorDecl>(Dcl);
1672       continue;
1673 
1674     case Decl::EnumConstant:
1675     case Decl::IndirectField:
1676     case Decl::ParmVar:
1677       // These can only appear with other declarations which are banned in
1678       // C++11 and permitted in C++1y, so ignore them.
1679       continue;
1680 
1681     case Decl::Var:
1682     case Decl::Decomposition: {
1683       // C++1y [dcl.constexpr]p3 allows anything except:
1684       //   a definition of a variable of non-literal type or of static or
1685       //   thread storage duration or for which no initialization is performed.
1686       const auto *VD = cast<VarDecl>(DclIt);
1687       if (VD->isThisDeclarationADefinition()) {
1688         if (VD->isStaticLocal()) {
1689           SemaRef.Diag(VD->getLocation(),
1690                        diag::err_constexpr_local_var_static)
1691             << isa<CXXConstructorDecl>(Dcl)
1692             << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1693           return false;
1694         }
1695         if (!VD->getType()->isDependentType() &&
1696             SemaRef.RequireLiteralType(
1697               VD->getLocation(), VD->getType(),
1698               diag::err_constexpr_local_var_non_literal_type,
1699               isa<CXXConstructorDecl>(Dcl)))
1700           return false;
1701         if (!VD->getType()->isDependentType() &&
1702             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1703           SemaRef.Diag(VD->getLocation(),
1704                        diag::err_constexpr_local_var_no_init)
1705             << isa<CXXConstructorDecl>(Dcl);
1706           return false;
1707         }
1708       }
1709       SemaRef.Diag(VD->getLocation(),
1710                    SemaRef.getLangOpts().CPlusPlus14
1711                     ? diag::warn_cxx11_compat_constexpr_local_var
1712                     : diag::ext_constexpr_local_var)
1713         << isa<CXXConstructorDecl>(Dcl);
1714       continue;
1715     }
1716 
1717     case Decl::NamespaceAlias:
1718     case Decl::Function:
1719       // These are disallowed in C++11 and permitted in C++1y. Allow them
1720       // everywhere as an extension.
1721       if (!Cxx1yLoc.isValid())
1722         Cxx1yLoc = DS->getLocStart();
1723       continue;
1724 
1725     default:
1726       SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1727         << isa<CXXConstructorDecl>(Dcl);
1728       return false;
1729     }
1730   }
1731 
1732   return true;
1733 }
1734 
1735 /// Check that the given field is initialized within a constexpr constructor.
1736 ///
1737 /// \param Dcl The constexpr constructor being checked.
1738 /// \param Field The field being checked. This may be a member of an anonymous
1739 ///        struct or union nested within the class being checked.
1740 /// \param Inits All declarations, including anonymous struct/union members and
1741 ///        indirect members, for which any initialization was provided.
1742 /// \param Diagnosed Set to true if an error is produced.
1743 static void CheckConstexprCtorInitializer(Sema &SemaRef,
1744                                           const FunctionDecl *Dcl,
1745                                           FieldDecl *Field,
1746                                           llvm::SmallSet<Decl*, 16> &Inits,
1747                                           bool &Diagnosed) {
1748   if (Field->isInvalidDecl())
1749     return;
1750 
1751   if (Field->isUnnamedBitfield())
1752     return;
1753 
1754   // Anonymous unions with no variant members and empty anonymous structs do not
1755   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1756   // indirect fields don't need initializing.
1757   if (Field->isAnonymousStructOrUnion() &&
1758       (Field->getType()->isUnionType()
1759            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1760            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1761     return;
1762 
1763   if (!Inits.count(Field)) {
1764     if (!Diagnosed) {
1765       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1766       Diagnosed = true;
1767     }
1768     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1769   } else if (Field->isAnonymousStructOrUnion()) {
1770     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1771     for (auto *I : RD->fields())
1772       // If an anonymous union contains an anonymous struct of which any member
1773       // is initialized, all members must be initialized.
1774       if (!RD->isUnion() || Inits.count(I))
1775         CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
1776   }
1777 }
1778 
1779 /// Check the provided statement is allowed in a constexpr function
1780 /// definition.
1781 static bool
1782 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1783                            SmallVectorImpl<SourceLocation> &ReturnStmts,
1784                            SourceLocation &Cxx1yLoc) {
1785   // - its function-body shall be [...] a compound-statement that contains only
1786   switch (S->getStmtClass()) {
1787   case Stmt::NullStmtClass:
1788     //   - null statements,
1789     return true;
1790 
1791   case Stmt::DeclStmtClass:
1792     //   - static_assert-declarations
1793     //   - using-declarations,
1794     //   - using-directives,
1795     //   - typedef declarations and alias-declarations that do not define
1796     //     classes or enumerations,
1797     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1798       return false;
1799     return true;
1800 
1801   case Stmt::ReturnStmtClass:
1802     //   - and exactly one return statement;
1803     if (isa<CXXConstructorDecl>(Dcl)) {
1804       // C++1y allows return statements in constexpr constructors.
1805       if (!Cxx1yLoc.isValid())
1806         Cxx1yLoc = S->getLocStart();
1807       return true;
1808     }
1809 
1810     ReturnStmts.push_back(S->getLocStart());
1811     return true;
1812 
1813   case Stmt::CompoundStmtClass: {
1814     // C++1y allows compound-statements.
1815     if (!Cxx1yLoc.isValid())
1816       Cxx1yLoc = S->getLocStart();
1817 
1818     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1819     for (auto *BodyIt : CompStmt->body()) {
1820       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1821                                       Cxx1yLoc))
1822         return false;
1823     }
1824     return true;
1825   }
1826 
1827   case Stmt::AttributedStmtClass:
1828     if (!Cxx1yLoc.isValid())
1829       Cxx1yLoc = S->getLocStart();
1830     return true;
1831 
1832   case Stmt::IfStmtClass: {
1833     // C++1y allows if-statements.
1834     if (!Cxx1yLoc.isValid())
1835       Cxx1yLoc = S->getLocStart();
1836 
1837     IfStmt *If = cast<IfStmt>(S);
1838     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1839                                     Cxx1yLoc))
1840       return false;
1841     if (If->getElse() &&
1842         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1843                                     Cxx1yLoc))
1844       return false;
1845     return true;
1846   }
1847 
1848   case Stmt::WhileStmtClass:
1849   case Stmt::DoStmtClass:
1850   case Stmt::ForStmtClass:
1851   case Stmt::CXXForRangeStmtClass:
1852   case Stmt::ContinueStmtClass:
1853     // C++1y allows all of these. We don't allow them as extensions in C++11,
1854     // because they don't make sense without variable mutation.
1855     if (!SemaRef.getLangOpts().CPlusPlus14)
1856       break;
1857     if (!Cxx1yLoc.isValid())
1858       Cxx1yLoc = S->getLocStart();
1859     for (Stmt *SubStmt : S->children())
1860       if (SubStmt &&
1861           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1862                                       Cxx1yLoc))
1863         return false;
1864     return true;
1865 
1866   case Stmt::SwitchStmtClass:
1867   case Stmt::CaseStmtClass:
1868   case Stmt::DefaultStmtClass:
1869   case Stmt::BreakStmtClass:
1870     // C++1y allows switch-statements, and since they don't need variable
1871     // mutation, we can reasonably allow them in C++11 as an extension.
1872     if (!Cxx1yLoc.isValid())
1873       Cxx1yLoc = S->getLocStart();
1874     for (Stmt *SubStmt : S->children())
1875       if (SubStmt &&
1876           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1877                                       Cxx1yLoc))
1878         return false;
1879     return true;
1880 
1881   default:
1882     if (!isa<Expr>(S))
1883       break;
1884 
1885     // C++1y allows expression-statements.
1886     if (!Cxx1yLoc.isValid())
1887       Cxx1yLoc = S->getLocStart();
1888     return true;
1889   }
1890 
1891   SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1892     << isa<CXXConstructorDecl>(Dcl);
1893   return false;
1894 }
1895 
1896 /// Check the body for the given constexpr function declaration only contains
1897 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1898 ///
1899 /// \return true if the body is OK, false if we have diagnosed a problem.
1900 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1901   if (isa<CXXTryStmt>(Body)) {
1902     // C++11 [dcl.constexpr]p3:
1903     //  The definition of a constexpr function shall satisfy the following
1904     //  constraints: [...]
1905     // - its function-body shall be = delete, = default, or a
1906     //   compound-statement
1907     //
1908     // C++11 [dcl.constexpr]p4:
1909     //  In the definition of a constexpr constructor, [...]
1910     // - its function-body shall not be a function-try-block;
1911     Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1912       << isa<CXXConstructorDecl>(Dcl);
1913     return false;
1914   }
1915 
1916   SmallVector<SourceLocation, 4> ReturnStmts;
1917 
1918   // - its function-body shall be [...] a compound-statement that contains only
1919   //   [... list of cases ...]
1920   CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1921   SourceLocation Cxx1yLoc;
1922   for (auto *BodyIt : CompBody->body()) {
1923     if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
1924       return false;
1925   }
1926 
1927   if (Cxx1yLoc.isValid())
1928     Diag(Cxx1yLoc,
1929          getLangOpts().CPlusPlus14
1930            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1931            : diag::ext_constexpr_body_invalid_stmt)
1932       << isa<CXXConstructorDecl>(Dcl);
1933 
1934   if (const CXXConstructorDecl *Constructor
1935         = dyn_cast<CXXConstructorDecl>(Dcl)) {
1936     const CXXRecordDecl *RD = Constructor->getParent();
1937     // DR1359:
1938     // - every non-variant non-static data member and base class sub-object
1939     //   shall be initialized;
1940     // DR1460:
1941     // - if the class is a union having variant members, exactly one of them
1942     //   shall be initialized;
1943     if (RD->isUnion()) {
1944       if (Constructor->getNumCtorInitializers() == 0 &&
1945           RD->hasVariantMembers()) {
1946         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1947         return false;
1948       }
1949     } else if (!Constructor->isDependentContext() &&
1950                !Constructor->isDelegatingConstructor()) {
1951       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1952 
1953       // Skip detailed checking if we have enough initializers, and we would
1954       // allow at most one initializer per member.
1955       bool AnyAnonStructUnionMembers = false;
1956       unsigned Fields = 0;
1957       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1958            E = RD->field_end(); I != E; ++I, ++Fields) {
1959         if (I->isAnonymousStructOrUnion()) {
1960           AnyAnonStructUnionMembers = true;
1961           break;
1962         }
1963       }
1964       // DR1460:
1965       // - if the class is a union-like class, but is not a union, for each of
1966       //   its anonymous union members having variant members, exactly one of
1967       //   them shall be initialized;
1968       if (AnyAnonStructUnionMembers ||
1969           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1970         // Check initialization of non-static data members. Base classes are
1971         // always initialized so do not need to be checked. Dependent bases
1972         // might not have initializers in the member initializer list.
1973         llvm::SmallSet<Decl*, 16> Inits;
1974         for (const auto *I: Constructor->inits()) {
1975           if (FieldDecl *FD = I->getMember())
1976             Inits.insert(FD);
1977           else if (IndirectFieldDecl *ID = I->getIndirectMember())
1978             Inits.insert(ID->chain_begin(), ID->chain_end());
1979         }
1980 
1981         bool Diagnosed = false;
1982         for (auto *I : RD->fields())
1983           CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
1984         if (Diagnosed)
1985           return false;
1986       }
1987     }
1988   } else {
1989     if (ReturnStmts.empty()) {
1990       // C++1y doesn't require constexpr functions to contain a 'return'
1991       // statement. We still do, unless the return type might be void, because
1992       // otherwise if there's no return statement, the function cannot
1993       // be used in a core constant expression.
1994       bool OK = getLangOpts().CPlusPlus14 &&
1995                 (Dcl->getReturnType()->isVoidType() ||
1996                  Dcl->getReturnType()->isDependentType());
1997       Diag(Dcl->getLocation(),
1998            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1999               : diag::err_constexpr_body_no_return);
2000       if (!OK)
2001         return false;
2002     } else if (ReturnStmts.size() > 1) {
2003       Diag(ReturnStmts.back(),
2004            getLangOpts().CPlusPlus14
2005              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2006              : diag::ext_constexpr_body_multiple_return);
2007       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2008         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
2009     }
2010   }
2011 
2012   // C++11 [dcl.constexpr]p5:
2013   //   if no function argument values exist such that the function invocation
2014   //   substitution would produce a constant expression, the program is
2015   //   ill-formed; no diagnostic required.
2016   // C++11 [dcl.constexpr]p3:
2017   //   - every constructor call and implicit conversion used in initializing the
2018   //     return value shall be one of those allowed in a constant expression.
2019   // C++11 [dcl.constexpr]p4:
2020   //   - every constructor involved in initializing non-static data members and
2021   //     base class sub-objects shall be a constexpr constructor.
2022   SmallVector<PartialDiagnosticAt, 8> Diags;
2023   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
2024     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
2025       << isa<CXXConstructorDecl>(Dcl);
2026     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2027       Diag(Diags[I].first, Diags[I].second);
2028     // Don't return false here: we allow this for compatibility in
2029     // system headers.
2030   }
2031 
2032   return true;
2033 }
2034 
2035 /// isCurrentClassName - Determine whether the identifier II is the
2036 /// name of the class type currently being defined. In the case of
2037 /// nested classes, this will only return true if II is the name of
2038 /// the innermost class.
2039 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
2040                               const CXXScopeSpec *SS) {
2041   assert(getLangOpts().CPlusPlus && "No class names in C!");
2042 
2043   CXXRecordDecl *CurDecl;
2044   if (SS && SS->isSet() && !SS->isInvalid()) {
2045     DeclContext *DC = computeDeclContext(*SS, true);
2046     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2047   } else
2048     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2049 
2050   if (CurDecl && CurDecl->getIdentifier())
2051     return &II == CurDecl->getIdentifier();
2052   return false;
2053 }
2054 
2055 /// \brief Determine whether the identifier II is a typo for the name of
2056 /// the class type currently being defined. If so, update it to the identifier
2057 /// that should have been used.
2058 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2059   assert(getLangOpts().CPlusPlus && "No class names in C!");
2060 
2061   if (!getLangOpts().SpellChecking)
2062     return false;
2063 
2064   CXXRecordDecl *CurDecl;
2065   if (SS && SS->isSet() && !SS->isInvalid()) {
2066     DeclContext *DC = computeDeclContext(*SS, true);
2067     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2068   } else
2069     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2070 
2071   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2072       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2073           < II->getLength()) {
2074     II = CurDecl->getIdentifier();
2075     return true;
2076   }
2077 
2078   return false;
2079 }
2080 
2081 /// \brief Determine whether the given class is a base class of the given
2082 /// class, including looking at dependent bases.
2083 static bool findCircularInheritance(const CXXRecordDecl *Class,
2084                                     const CXXRecordDecl *Current) {
2085   SmallVector<const CXXRecordDecl*, 8> Queue;
2086 
2087   Class = Class->getCanonicalDecl();
2088   while (true) {
2089     for (const auto &I : Current->bases()) {
2090       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2091       if (!Base)
2092         continue;
2093 
2094       Base = Base->getDefinition();
2095       if (!Base)
2096         continue;
2097 
2098       if (Base->getCanonicalDecl() == Class)
2099         return true;
2100 
2101       Queue.push_back(Base);
2102     }
2103 
2104     if (Queue.empty())
2105       return false;
2106 
2107     Current = Queue.pop_back_val();
2108   }
2109 
2110   return false;
2111 }
2112 
2113 /// \brief Check the validity of a C++ base class specifier.
2114 ///
2115 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2116 /// and returns NULL otherwise.
2117 CXXBaseSpecifier *
2118 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2119                          SourceRange SpecifierRange,
2120                          bool Virtual, AccessSpecifier Access,
2121                          TypeSourceInfo *TInfo,
2122                          SourceLocation EllipsisLoc) {
2123   QualType BaseType = TInfo->getType();
2124 
2125   // C++ [class.union]p1:
2126   //   A union shall not have base classes.
2127   if (Class->isUnion()) {
2128     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2129       << SpecifierRange;
2130     return nullptr;
2131   }
2132 
2133   if (EllipsisLoc.isValid() &&
2134       !TInfo->getType()->containsUnexpandedParameterPack()) {
2135     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2136       << TInfo->getTypeLoc().getSourceRange();
2137     EllipsisLoc = SourceLocation();
2138   }
2139 
2140   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2141 
2142   if (BaseType->isDependentType()) {
2143     // Make sure that we don't have circular inheritance among our dependent
2144     // bases. For non-dependent bases, the check for completeness below handles
2145     // this.
2146     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2147       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2148           ((BaseDecl = BaseDecl->getDefinition()) &&
2149            findCircularInheritance(Class, BaseDecl))) {
2150         Diag(BaseLoc, diag::err_circular_inheritance)
2151           << BaseType << Context.getTypeDeclType(Class);
2152 
2153         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2154           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2155             << BaseType;
2156 
2157         return nullptr;
2158       }
2159     }
2160 
2161     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2162                                           Class->getTagKind() == TTK_Class,
2163                                           Access, TInfo, EllipsisLoc);
2164   }
2165 
2166   // Base specifiers must be record types.
2167   if (!BaseType->isRecordType()) {
2168     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2169     return nullptr;
2170   }
2171 
2172   // C++ [class.union]p1:
2173   //   A union shall not be used as a base class.
2174   if (BaseType->isUnionType()) {
2175     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2176     return nullptr;
2177   }
2178 
2179   // For the MS ABI, propagate DLL attributes to base class templates.
2180   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2181     if (Attr *ClassAttr = getDLLAttr(Class)) {
2182       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2183               BaseType->getAsCXXRecordDecl())) {
2184         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2185                                             BaseLoc);
2186       }
2187     }
2188   }
2189 
2190   // C++ [class.derived]p2:
2191   //   The class-name in a base-specifier shall not be an incompletely
2192   //   defined class.
2193   if (RequireCompleteType(BaseLoc, BaseType,
2194                           diag::err_incomplete_base_class, SpecifierRange)) {
2195     Class->setInvalidDecl();
2196     return nullptr;
2197   }
2198 
2199   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2200   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
2201   assert(BaseDecl && "Record type has no declaration");
2202   BaseDecl = BaseDecl->getDefinition();
2203   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2204   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2205   assert(CXXBaseDecl && "Base type is not a C++ type");
2206 
2207   // A class which contains a flexible array member is not suitable for use as a
2208   // base class:
2209   //   - If the layout determines that a base comes before another base,
2210   //     the flexible array member would index into the subsequent base.
2211   //   - If the layout determines that base comes before the derived class,
2212   //     the flexible array member would index into the derived class.
2213   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2214     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2215       << CXXBaseDecl->getDeclName();
2216     return nullptr;
2217   }
2218 
2219   // C++ [class]p3:
2220   //   If a class is marked final and it appears as a base-type-specifier in
2221   //   base-clause, the program is ill-formed.
2222   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2223     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2224       << CXXBaseDecl->getDeclName()
2225       << FA->isSpelledAsSealed();
2226     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2227         << CXXBaseDecl->getDeclName() << FA->getRange();
2228     return nullptr;
2229   }
2230 
2231   if (BaseDecl->isInvalidDecl())
2232     Class->setInvalidDecl();
2233 
2234   // Create the base specifier.
2235   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2236                                         Class->getTagKind() == TTK_Class,
2237                                         Access, TInfo, EllipsisLoc);
2238 }
2239 
2240 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2241 /// one entry in the base class list of a class specifier, for
2242 /// example:
2243 ///    class foo : public bar, virtual private baz {
2244 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2245 BaseResult
2246 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2247                          ParsedAttributes &Attributes,
2248                          bool Virtual, AccessSpecifier Access,
2249                          ParsedType basetype, SourceLocation BaseLoc,
2250                          SourceLocation EllipsisLoc) {
2251   if (!classdecl)
2252     return true;
2253 
2254   AdjustDeclIfTemplate(classdecl);
2255   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2256   if (!Class)
2257     return true;
2258 
2259   // We haven't yet attached the base specifiers.
2260   Class->setIsParsingBaseSpecifiers();
2261 
2262   // We do not support any C++11 attributes on base-specifiers yet.
2263   // Diagnose any attributes we see.
2264   if (!Attributes.empty()) {
2265     for (AttributeList *Attr = Attributes.getList(); Attr;
2266          Attr = Attr->getNext()) {
2267       if (Attr->isInvalid() ||
2268           Attr->getKind() == AttributeList::IgnoredAttribute)
2269         continue;
2270       Diag(Attr->getLoc(),
2271            Attr->getKind() == AttributeList::UnknownAttribute
2272              ? diag::warn_unknown_attribute_ignored
2273              : diag::err_base_specifier_attribute)
2274         << Attr->getName();
2275     }
2276   }
2277 
2278   TypeSourceInfo *TInfo = nullptr;
2279   GetTypeFromParser(basetype, &TInfo);
2280 
2281   if (EllipsisLoc.isInvalid() &&
2282       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2283                                       UPPC_BaseType))
2284     return true;
2285 
2286   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2287                                                       Virtual, Access, TInfo,
2288                                                       EllipsisLoc))
2289     return BaseSpec;
2290   else
2291     Class->setInvalidDecl();
2292 
2293   return true;
2294 }
2295 
2296 /// Use small set to collect indirect bases.  As this is only used
2297 /// locally, there's no need to abstract the small size parameter.
2298 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2299 
2300 /// \brief Recursively add the bases of Type.  Don't add Type itself.
2301 static void
2302 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2303                   const QualType &Type)
2304 {
2305   // Even though the incoming type is a base, it might not be
2306   // a class -- it could be a template parm, for instance.
2307   if (auto Rec = Type->getAs<RecordType>()) {
2308     auto Decl = Rec->getAsCXXRecordDecl();
2309 
2310     // Iterate over its bases.
2311     for (const auto &BaseSpec : Decl->bases()) {
2312       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2313         .getUnqualifiedType();
2314       if (Set.insert(Base).second)
2315         // If we've not already seen it, recurse.
2316         NoteIndirectBases(Context, Set, Base);
2317     }
2318   }
2319 }
2320 
2321 /// \brief Performs the actual work of attaching the given base class
2322 /// specifiers to a C++ class.
2323 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2324                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2325  if (Bases.empty())
2326     return false;
2327 
2328   // Used to keep track of which base types we have already seen, so
2329   // that we can properly diagnose redundant direct base types. Note
2330   // that the key is always the unqualified canonical type of the base
2331   // class.
2332   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2333 
2334   // Used to track indirect bases so we can see if a direct base is
2335   // ambiguous.
2336   IndirectBaseSet IndirectBaseTypes;
2337 
2338   // Copy non-redundant base specifiers into permanent storage.
2339   unsigned NumGoodBases = 0;
2340   bool Invalid = false;
2341   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2342     QualType NewBaseType
2343       = Context.getCanonicalType(Bases[idx]->getType());
2344     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2345 
2346     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2347     if (KnownBase) {
2348       // C++ [class.mi]p3:
2349       //   A class shall not be specified as a direct base class of a
2350       //   derived class more than once.
2351       Diag(Bases[idx]->getLocStart(),
2352            diag::err_duplicate_base_class)
2353         << KnownBase->getType()
2354         << Bases[idx]->getSourceRange();
2355 
2356       // Delete the duplicate base class specifier; we're going to
2357       // overwrite its pointer later.
2358       Context.Deallocate(Bases[idx]);
2359 
2360       Invalid = true;
2361     } else {
2362       // Okay, add this new base class.
2363       KnownBase = Bases[idx];
2364       Bases[NumGoodBases++] = Bases[idx];
2365 
2366       // Note this base's direct & indirect bases, if there could be ambiguity.
2367       if (Bases.size() > 1)
2368         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2369 
2370       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2371         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2372         if (Class->isInterface() &&
2373               (!RD->isInterface() ||
2374                KnownBase->getAccessSpecifier() != AS_public)) {
2375           // The Microsoft extension __interface does not permit bases that
2376           // are not themselves public interfaces.
2377           Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
2378             << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
2379             << RD->getSourceRange();
2380           Invalid = true;
2381         }
2382         if (RD->hasAttr<WeakAttr>())
2383           Class->addAttr(WeakAttr::CreateImplicit(Context));
2384       }
2385     }
2386   }
2387 
2388   // Attach the remaining base class specifiers to the derived class.
2389   Class->setBases(Bases.data(), NumGoodBases);
2390 
2391   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2392     // Check whether this direct base is inaccessible due to ambiguity.
2393     QualType BaseType = Bases[idx]->getType();
2394     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2395       .getUnqualifiedType();
2396 
2397     if (IndirectBaseTypes.count(CanonicalBase)) {
2398       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2399                          /*DetectVirtual=*/true);
2400       bool found
2401         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2402       assert(found);
2403       (void)found;
2404 
2405       if (Paths.isAmbiguous(CanonicalBase))
2406         Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
2407           << BaseType << getAmbiguousPathsDisplayString(Paths)
2408           << Bases[idx]->getSourceRange();
2409       else
2410         assert(Bases[idx]->isVirtual());
2411     }
2412 
2413     // Delete the base class specifier, since its data has been copied
2414     // into the CXXRecordDecl.
2415     Context.Deallocate(Bases[idx]);
2416   }
2417 
2418   return Invalid;
2419 }
2420 
2421 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2422 /// class, after checking whether there are any duplicate base
2423 /// classes.
2424 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2425                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2426   if (!ClassDecl || Bases.empty())
2427     return;
2428 
2429   AdjustDeclIfTemplate(ClassDecl);
2430   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2431 }
2432 
2433 /// \brief Determine whether the type \p Derived is a C++ class that is
2434 /// derived from the type \p Base.
2435 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2436   if (!getLangOpts().CPlusPlus)
2437     return false;
2438 
2439   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2440   if (!DerivedRD)
2441     return false;
2442 
2443   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2444   if (!BaseRD)
2445     return false;
2446 
2447   // If either the base or the derived type is invalid, don't try to
2448   // check whether one is derived from the other.
2449   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2450     return false;
2451 
2452   // FIXME: In a modules build, do we need the entire path to be visible for us
2453   // to be able to use the inheritance relationship?
2454   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2455     return false;
2456 
2457   return DerivedRD->isDerivedFrom(BaseRD);
2458 }
2459 
2460 /// \brief Determine whether the type \p Derived is a C++ class that is
2461 /// derived from the type \p Base.
2462 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2463                          CXXBasePaths &Paths) {
2464   if (!getLangOpts().CPlusPlus)
2465     return false;
2466 
2467   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2468   if (!DerivedRD)
2469     return false;
2470 
2471   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2472   if (!BaseRD)
2473     return false;
2474 
2475   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2476     return false;
2477 
2478   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2479 }
2480 
2481 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2482                               CXXCastPath &BasePathArray) {
2483   assert(BasePathArray.empty() && "Base path array must be empty!");
2484   assert(Paths.isRecordingPaths() && "Must record paths!");
2485 
2486   const CXXBasePath &Path = Paths.front();
2487 
2488   // We first go backward and check if we have a virtual base.
2489   // FIXME: It would be better if CXXBasePath had the base specifier for
2490   // the nearest virtual base.
2491   unsigned Start = 0;
2492   for (unsigned I = Path.size(); I != 0; --I) {
2493     if (Path[I - 1].Base->isVirtual()) {
2494       Start = I - 1;
2495       break;
2496     }
2497   }
2498 
2499   // Now add all bases.
2500   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2501     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2502 }
2503 
2504 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2505 /// conversion (where Derived and Base are class types) is
2506 /// well-formed, meaning that the conversion is unambiguous (and
2507 /// that all of the base classes are accessible). Returns true
2508 /// and emits a diagnostic if the code is ill-formed, returns false
2509 /// otherwise. Loc is the location where this routine should point to
2510 /// if there is an error, and Range is the source range to highlight
2511 /// if there is an error.
2512 ///
2513 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2514 /// diagnostic for the respective type of error will be suppressed, but the
2515 /// check for ill-formed code will still be performed.
2516 bool
2517 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2518                                    unsigned InaccessibleBaseID,
2519                                    unsigned AmbigiousBaseConvID,
2520                                    SourceLocation Loc, SourceRange Range,
2521                                    DeclarationName Name,
2522                                    CXXCastPath *BasePath,
2523                                    bool IgnoreAccess) {
2524   // First, determine whether the path from Derived to Base is
2525   // ambiguous. This is slightly more expensive than checking whether
2526   // the Derived to Base conversion exists, because here we need to
2527   // explore multiple paths to determine if there is an ambiguity.
2528   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2529                      /*DetectVirtual=*/false);
2530   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2531   assert(DerivationOkay &&
2532          "Can only be used with a derived-to-base conversion");
2533   (void)DerivationOkay;
2534 
2535   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
2536     if (!IgnoreAccess) {
2537       // Check that the base class can be accessed.
2538       switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
2539                                    InaccessibleBaseID)) {
2540         case AR_inaccessible:
2541           return true;
2542         case AR_accessible:
2543         case AR_dependent:
2544         case AR_delayed:
2545           break;
2546       }
2547     }
2548 
2549     // Build a base path if necessary.
2550     if (BasePath)
2551       BuildBasePathArray(Paths, *BasePath);
2552     return false;
2553   }
2554 
2555   if (AmbigiousBaseConvID) {
2556     // We know that the derived-to-base conversion is ambiguous, and
2557     // we're going to produce a diagnostic. Perform the derived-to-base
2558     // search just one more time to compute all of the possible paths so
2559     // that we can print them out. This is more expensive than any of
2560     // the previous derived-to-base checks we've done, but at this point
2561     // performance isn't as much of an issue.
2562     Paths.clear();
2563     Paths.setRecordingPaths(true);
2564     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2565     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2566     (void)StillOkay;
2567 
2568     // Build up a textual representation of the ambiguous paths, e.g.,
2569     // D -> B -> A, that will be used to illustrate the ambiguous
2570     // conversions in the diagnostic. We only print one of the paths
2571     // to each base class subobject.
2572     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2573 
2574     Diag(Loc, AmbigiousBaseConvID)
2575     << Derived << Base << PathDisplayStr << Range << Name;
2576   }
2577   return true;
2578 }
2579 
2580 bool
2581 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2582                                    SourceLocation Loc, SourceRange Range,
2583                                    CXXCastPath *BasePath,
2584                                    bool IgnoreAccess) {
2585   return CheckDerivedToBaseConversion(
2586       Derived, Base, diag::err_upcast_to_inaccessible_base,
2587       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2588       BasePath, IgnoreAccess);
2589 }
2590 
2591 
2592 /// @brief Builds a string representing ambiguous paths from a
2593 /// specific derived class to different subobjects of the same base
2594 /// class.
2595 ///
2596 /// This function builds a string that can be used in error messages
2597 /// to show the different paths that one can take through the
2598 /// inheritance hierarchy to go from the derived class to different
2599 /// subobjects of a base class. The result looks something like this:
2600 /// @code
2601 /// struct D -> struct B -> struct A
2602 /// struct D -> struct C -> struct A
2603 /// @endcode
2604 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2605   std::string PathDisplayStr;
2606   std::set<unsigned> DisplayedPaths;
2607   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2608        Path != Paths.end(); ++Path) {
2609     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2610       // We haven't displayed a path to this particular base
2611       // class subobject yet.
2612       PathDisplayStr += "\n    ";
2613       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2614       for (CXXBasePath::const_iterator Element = Path->begin();
2615            Element != Path->end(); ++Element)
2616         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2617     }
2618   }
2619 
2620   return PathDisplayStr;
2621 }
2622 
2623 //===----------------------------------------------------------------------===//
2624 // C++ class member Handling
2625 //===----------------------------------------------------------------------===//
2626 
2627 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2628 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
2629                                 SourceLocation ASLoc,
2630                                 SourceLocation ColonLoc,
2631                                 AttributeList *Attrs) {
2632   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2633   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2634                                                   ASLoc, ColonLoc);
2635   CurContext->addHiddenDecl(ASDecl);
2636   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2637 }
2638 
2639 /// CheckOverrideControl - Check C++11 override control semantics.
2640 void Sema::CheckOverrideControl(NamedDecl *D) {
2641   if (D->isInvalidDecl())
2642     return;
2643 
2644   // We only care about "override" and "final" declarations.
2645   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2646     return;
2647 
2648   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2649 
2650   // We can't check dependent instance methods.
2651   if (MD && MD->isInstance() &&
2652       (MD->getParent()->hasAnyDependentBases() ||
2653        MD->getType()->isDependentType()))
2654     return;
2655 
2656   if (MD && !MD->isVirtual()) {
2657     // If we have a non-virtual method, check if if hides a virtual method.
2658     // (In that case, it's most likely the method has the wrong type.)
2659     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2660     FindHiddenVirtualMethods(MD, OverloadedMethods);
2661 
2662     if (!OverloadedMethods.empty()) {
2663       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2664         Diag(OA->getLocation(),
2665              diag::override_keyword_hides_virtual_member_function)
2666           << "override" << (OverloadedMethods.size() > 1);
2667       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2668         Diag(FA->getLocation(),
2669              diag::override_keyword_hides_virtual_member_function)
2670           << (FA->isSpelledAsSealed() ? "sealed" : "final")
2671           << (OverloadedMethods.size() > 1);
2672       }
2673       NoteHiddenVirtualMethods(MD, OverloadedMethods);
2674       MD->setInvalidDecl();
2675       return;
2676     }
2677     // Fall through into the general case diagnostic.
2678     // FIXME: We might want to attempt typo correction here.
2679   }
2680 
2681   if (!MD || !MD->isVirtual()) {
2682     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2683       Diag(OA->getLocation(),
2684            diag::override_keyword_only_allowed_on_virtual_member_functions)
2685         << "override" << FixItHint::CreateRemoval(OA->getLocation());
2686       D->dropAttr<OverrideAttr>();
2687     }
2688     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2689       Diag(FA->getLocation(),
2690            diag::override_keyword_only_allowed_on_virtual_member_functions)
2691         << (FA->isSpelledAsSealed() ? "sealed" : "final")
2692         << FixItHint::CreateRemoval(FA->getLocation());
2693       D->dropAttr<FinalAttr>();
2694     }
2695     return;
2696   }
2697 
2698   // C++11 [class.virtual]p5:
2699   //   If a function is marked with the virt-specifier override and
2700   //   does not override a member function of a base class, the program is
2701   //   ill-formed.
2702   bool HasOverriddenMethods =
2703     MD->begin_overridden_methods() != MD->end_overridden_methods();
2704   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2705     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2706       << MD->getDeclName();
2707 }
2708 
2709 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2710   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2711     return;
2712   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2713   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
2714       isa<CXXDestructorDecl>(MD))
2715     return;
2716 
2717   SourceLocation Loc = MD->getLocation();
2718   SourceLocation SpellingLoc = Loc;
2719   if (getSourceManager().isMacroArgExpansion(Loc))
2720     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
2721   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2722   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
2723       return;
2724 
2725   if (MD->size_overridden_methods() > 0) {
2726     Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
2727       << MD->getDeclName();
2728     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2729     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2730   }
2731 }
2732 
2733 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
2734 /// function overrides a virtual member function marked 'final', according to
2735 /// C++11 [class.virtual]p4.
2736 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2737                                                   const CXXMethodDecl *Old) {
2738   FinalAttr *FA = Old->getAttr<FinalAttr>();
2739   if (!FA)
2740     return false;
2741 
2742   Diag(New->getLocation(), diag::err_final_function_overridden)
2743     << New->getDeclName()
2744     << FA->isSpelledAsSealed();
2745   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2746   return true;
2747 }
2748 
2749 static bool InitializationHasSideEffects(const FieldDecl &FD) {
2750   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2751   // FIXME: Destruction of ObjC lifetime types has side-effects.
2752   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2753     return !RD->isCompleteDefinition() ||
2754            !RD->hasTrivialDefaultConstructor() ||
2755            !RD->hasTrivialDestructor();
2756   return false;
2757 }
2758 
2759 static AttributeList *getMSPropertyAttr(AttributeList *list) {
2760   for (AttributeList *it = list; it != nullptr; it = it->getNext())
2761     if (it->isDeclspecPropertyAttribute())
2762       return it;
2763   return nullptr;
2764 }
2765 
2766 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2767 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2768 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
2769 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2770 /// present (but parsing it has been deferred).
2771 NamedDecl *
2772 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2773                                MultiTemplateParamsArg TemplateParameterLists,
2774                                Expr *BW, const VirtSpecifiers &VS,
2775                                InClassInitStyle InitStyle) {
2776   const DeclSpec &DS = D.getDeclSpec();
2777   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2778   DeclarationName Name = NameInfo.getName();
2779   SourceLocation Loc = NameInfo.getLoc();
2780 
2781   // For anonymous bitfields, the location should point to the type.
2782   if (Loc.isInvalid())
2783     Loc = D.getLocStart();
2784 
2785   Expr *BitWidth = static_cast<Expr*>(BW);
2786 
2787   assert(isa<CXXRecordDecl>(CurContext));
2788   assert(!DS.isFriendSpecified());
2789 
2790   bool isFunc = D.isDeclarationOfFunction();
2791 
2792   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2793     // The Microsoft extension __interface only permits public member functions
2794     // and prohibits constructors, destructors, operators, non-public member
2795     // functions, static methods and data members.
2796     unsigned InvalidDecl;
2797     bool ShowDeclName = true;
2798     if (!isFunc)
2799       InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
2800     else if (AS != AS_public)
2801       InvalidDecl = 2;
2802     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2803       InvalidDecl = 3;
2804     else switch (Name.getNameKind()) {
2805       case DeclarationName::CXXConstructorName:
2806         InvalidDecl = 4;
2807         ShowDeclName = false;
2808         break;
2809 
2810       case DeclarationName::CXXDestructorName:
2811         InvalidDecl = 5;
2812         ShowDeclName = false;
2813         break;
2814 
2815       case DeclarationName::CXXOperatorName:
2816       case DeclarationName::CXXConversionFunctionName:
2817         InvalidDecl = 6;
2818         break;
2819 
2820       default:
2821         InvalidDecl = 0;
2822         break;
2823     }
2824 
2825     if (InvalidDecl) {
2826       if (ShowDeclName)
2827         Diag(Loc, diag::err_invalid_member_in_interface)
2828           << (InvalidDecl-1) << Name;
2829       else
2830         Diag(Loc, diag::err_invalid_member_in_interface)
2831           << (InvalidDecl-1) << "";
2832       return nullptr;
2833     }
2834   }
2835 
2836   // C++ 9.2p6: A member shall not be declared to have automatic storage
2837   // duration (auto, register) or with the extern storage-class-specifier.
2838   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2839   // data members and cannot be applied to names declared const or static,
2840   // and cannot be applied to reference members.
2841   switch (DS.getStorageClassSpec()) {
2842   case DeclSpec::SCS_unspecified:
2843   case DeclSpec::SCS_typedef:
2844   case DeclSpec::SCS_static:
2845     break;
2846   case DeclSpec::SCS_mutable:
2847     if (isFunc) {
2848       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2849 
2850       // FIXME: It would be nicer if the keyword was ignored only for this
2851       // declarator. Otherwise we could get follow-up errors.
2852       D.getMutableDeclSpec().ClearStorageClassSpecs();
2853     }
2854     break;
2855   default:
2856     Diag(DS.getStorageClassSpecLoc(),
2857          diag::err_storageclass_invalid_for_member);
2858     D.getMutableDeclSpec().ClearStorageClassSpecs();
2859     break;
2860   }
2861 
2862   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2863                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
2864                       !isFunc);
2865 
2866   if (DS.isConstexprSpecified() && isInstField) {
2867     SemaDiagnosticBuilder B =
2868         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2869     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2870     if (InitStyle == ICIS_NoInit) {
2871       B << 0 << 0;
2872       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2873         B << FixItHint::CreateRemoval(ConstexprLoc);
2874       else {
2875         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2876         D.getMutableDeclSpec().ClearConstexprSpec();
2877         const char *PrevSpec;
2878         unsigned DiagID;
2879         bool Failed = D.getMutableDeclSpec().SetTypeQual(
2880             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2881         (void)Failed;
2882         assert(!Failed && "Making a constexpr member const shouldn't fail");
2883       }
2884     } else {
2885       B << 1;
2886       const char *PrevSpec;
2887       unsigned DiagID;
2888       if (D.getMutableDeclSpec().SetStorageClassSpec(
2889           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2890           Context.getPrintingPolicy())) {
2891         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
2892                "This is the only DeclSpec that should fail to be applied");
2893         B << 1;
2894       } else {
2895         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2896         isInstField = false;
2897       }
2898     }
2899   }
2900 
2901   NamedDecl *Member;
2902   if (isInstField) {
2903     CXXScopeSpec &SS = D.getCXXScopeSpec();
2904 
2905     // Data members must have identifiers for names.
2906     if (!Name.isIdentifier()) {
2907       Diag(Loc, diag::err_bad_variable_name)
2908         << Name;
2909       return nullptr;
2910     }
2911 
2912     IdentifierInfo *II = Name.getAsIdentifierInfo();
2913 
2914     // Member field could not be with "template" keyword.
2915     // So TemplateParameterLists should be empty in this case.
2916     if (TemplateParameterLists.size()) {
2917       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
2918       if (TemplateParams->size()) {
2919         // There is no such thing as a member field template.
2920         Diag(D.getIdentifierLoc(), diag::err_template_member)
2921             << II
2922             << SourceRange(TemplateParams->getTemplateLoc(),
2923                 TemplateParams->getRAngleLoc());
2924       } else {
2925         // There is an extraneous 'template<>' for this member.
2926         Diag(TemplateParams->getTemplateLoc(),
2927             diag::err_template_member_noparams)
2928             << II
2929             << SourceRange(TemplateParams->getTemplateLoc(),
2930                 TemplateParams->getRAngleLoc());
2931       }
2932       return nullptr;
2933     }
2934 
2935     if (SS.isSet() && !SS.isInvalid()) {
2936       // The user provided a superfluous scope specifier inside a class
2937       // definition:
2938       //
2939       // class X {
2940       //   int X::member;
2941       // };
2942       if (DeclContext *DC = computeDeclContext(SS, false))
2943         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
2944       else
2945         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2946           << Name << SS.getRange();
2947 
2948       SS.clear();
2949     }
2950 
2951     AttributeList *MSPropertyAttr =
2952       getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
2953     if (MSPropertyAttr) {
2954       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2955                                 BitWidth, InitStyle, AS, MSPropertyAttr);
2956       if (!Member)
2957         return nullptr;
2958       isInstField = false;
2959     } else {
2960       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2961                                 BitWidth, InitStyle, AS);
2962       if (!Member)
2963         return nullptr;
2964     }
2965   } else {
2966     Member = HandleDeclarator(S, D, TemplateParameterLists);
2967     if (!Member)
2968       return nullptr;
2969 
2970     // Non-instance-fields can't have a bitfield.
2971     if (BitWidth) {
2972       if (Member->isInvalidDecl()) {
2973         // don't emit another diagnostic.
2974       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
2975         // C++ 9.6p3: A bit-field shall not be a static member.
2976         // "static member 'A' cannot be a bit-field"
2977         Diag(Loc, diag::err_static_not_bitfield)
2978           << Name << BitWidth->getSourceRange();
2979       } else if (isa<TypedefDecl>(Member)) {
2980         // "typedef member 'x' cannot be a bit-field"
2981         Diag(Loc, diag::err_typedef_not_bitfield)
2982           << Name << BitWidth->getSourceRange();
2983       } else {
2984         // A function typedef ("typedef int f(); f a;").
2985         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2986         Diag(Loc, diag::err_not_integral_type_bitfield)
2987           << Name << cast<ValueDecl>(Member)->getType()
2988           << BitWidth->getSourceRange();
2989       }
2990 
2991       BitWidth = nullptr;
2992       Member->setInvalidDecl();
2993     }
2994 
2995     Member->setAccess(AS);
2996 
2997     // If we have declared a member function template or static data member
2998     // template, set the access of the templated declaration as well.
2999     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3000       FunTmpl->getTemplatedDecl()->setAccess(AS);
3001     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3002       VarTmpl->getTemplatedDecl()->setAccess(AS);
3003   }
3004 
3005   if (VS.isOverrideSpecified())
3006     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
3007   if (VS.isFinalSpecified())
3008     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3009                                             VS.isFinalSpelledSealed()));
3010 
3011   if (VS.getLastLocation().isValid()) {
3012     // Update the end location of a method that has a virt-specifiers.
3013     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3014       MD->setRangeEnd(VS.getLastLocation());
3015   }
3016 
3017   CheckOverrideControl(Member);
3018 
3019   assert((Name || isInstField) && "No identifier for non-field ?");
3020 
3021   if (isInstField) {
3022     FieldDecl *FD = cast<FieldDecl>(Member);
3023     FieldCollector->Add(FD);
3024 
3025     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3026       // Remember all explicit private FieldDecls that have a name, no side
3027       // effects and are not part of a dependent type declaration.
3028       if (!FD->isImplicit() && FD->getDeclName() &&
3029           FD->getAccess() == AS_private &&
3030           !FD->hasAttr<UnusedAttr>() &&
3031           !FD->getParent()->isDependentContext() &&
3032           !InitializationHasSideEffects(*FD))
3033         UnusedPrivateFields.insert(FD);
3034     }
3035   }
3036 
3037   return Member;
3038 }
3039 
3040 namespace {
3041   class UninitializedFieldVisitor
3042       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3043     Sema &S;
3044     // List of Decls to generate a warning on.  Also remove Decls that become
3045     // initialized.
3046     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3047     // List of base classes of the record.  Classes are removed after their
3048     // initializers.
3049     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3050     // Vector of decls to be removed from the Decl set prior to visiting the
3051     // nodes.  These Decls may have been initialized in the prior initializer.
3052     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3053     // If non-null, add a note to the warning pointing back to the constructor.
3054     const CXXConstructorDecl *Constructor;
3055     // Variables to hold state when processing an initializer list.  When
3056     // InitList is true, special case initialization of FieldDecls matching
3057     // InitListFieldDecl.
3058     bool InitList;
3059     FieldDecl *InitListFieldDecl;
3060     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3061 
3062   public:
3063     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3064     UninitializedFieldVisitor(Sema &S,
3065                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3066                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3067       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3068         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3069 
3070     // Returns true if the use of ME is not an uninitialized use.
3071     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3072                                          bool CheckReferenceOnly) {
3073       llvm::SmallVector<FieldDecl*, 4> Fields;
3074       bool ReferenceField = false;
3075       while (ME) {
3076         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3077         if (!FD)
3078           return false;
3079         Fields.push_back(FD);
3080         if (FD->getType()->isReferenceType())
3081           ReferenceField = true;
3082         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3083       }
3084 
3085       // Binding a reference to an unintialized field is not an
3086       // uninitialized use.
3087       if (CheckReferenceOnly && !ReferenceField)
3088         return true;
3089 
3090       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3091       // Discard the first field since it is the field decl that is being
3092       // initialized.
3093       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3094         UsedFieldIndex.push_back((*I)->getFieldIndex());
3095       }
3096 
3097       for (auto UsedIter = UsedFieldIndex.begin(),
3098                 UsedEnd = UsedFieldIndex.end(),
3099                 OrigIter = InitFieldIndex.begin(),
3100                 OrigEnd = InitFieldIndex.end();
3101            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3102         if (*UsedIter < *OrigIter)
3103           return true;
3104         if (*UsedIter > *OrigIter)
3105           break;
3106       }
3107 
3108       return false;
3109     }
3110 
3111     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3112                           bool AddressOf) {
3113       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3114         return;
3115 
3116       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3117       // or union.
3118       MemberExpr *FieldME = ME;
3119 
3120       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3121 
3122       Expr *Base = ME;
3123       while (MemberExpr *SubME =
3124                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3125 
3126         if (isa<VarDecl>(SubME->getMemberDecl()))
3127           return;
3128 
3129         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3130           if (!FD->isAnonymousStructOrUnion())
3131             FieldME = SubME;
3132 
3133         if (!FieldME->getType().isPODType(S.Context))
3134           AllPODFields = false;
3135 
3136         Base = SubME->getBase();
3137       }
3138 
3139       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3140         return;
3141 
3142       if (AddressOf && AllPODFields)
3143         return;
3144 
3145       ValueDecl* FoundVD = FieldME->getMemberDecl();
3146 
3147       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3148         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3149           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3150         }
3151 
3152         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3153           QualType T = BaseCast->getType();
3154           if (T->isPointerType() &&
3155               BaseClasses.count(T->getPointeeType())) {
3156             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3157                 << T->getPointeeType() << FoundVD;
3158           }
3159         }
3160       }
3161 
3162       if (!Decls.count(FoundVD))
3163         return;
3164 
3165       const bool IsReference = FoundVD->getType()->isReferenceType();
3166 
3167       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3168         // Special checking for initializer lists.
3169         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3170           return;
3171         }
3172       } else {
3173         // Prevent double warnings on use of unbounded references.
3174         if (CheckReferenceOnly && !IsReference)
3175           return;
3176       }
3177 
3178       unsigned diag = IsReference
3179           ? diag::warn_reference_field_is_uninit
3180           : diag::warn_field_is_uninit;
3181       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3182       if (Constructor)
3183         S.Diag(Constructor->getLocation(),
3184                diag::note_uninit_in_this_constructor)
3185           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3186 
3187     }
3188 
3189     void HandleValue(Expr *E, bool AddressOf) {
3190       E = E->IgnoreParens();
3191 
3192       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3193         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3194                          AddressOf /*AddressOf*/);
3195         return;
3196       }
3197 
3198       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3199         Visit(CO->getCond());
3200         HandleValue(CO->getTrueExpr(), AddressOf);
3201         HandleValue(CO->getFalseExpr(), AddressOf);
3202         return;
3203       }
3204 
3205       if (BinaryConditionalOperator *BCO =
3206               dyn_cast<BinaryConditionalOperator>(E)) {
3207         Visit(BCO->getCond());
3208         HandleValue(BCO->getFalseExpr(), AddressOf);
3209         return;
3210       }
3211 
3212       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3213         HandleValue(OVE->getSourceExpr(), AddressOf);
3214         return;
3215       }
3216 
3217       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3218         switch (BO->getOpcode()) {
3219         default:
3220           break;
3221         case(BO_PtrMemD):
3222         case(BO_PtrMemI):
3223           HandleValue(BO->getLHS(), AddressOf);
3224           Visit(BO->getRHS());
3225           return;
3226         case(BO_Comma):
3227           Visit(BO->getLHS());
3228           HandleValue(BO->getRHS(), AddressOf);
3229           return;
3230         }
3231       }
3232 
3233       Visit(E);
3234     }
3235 
3236     void CheckInitListExpr(InitListExpr *ILE) {
3237       InitFieldIndex.push_back(0);
3238       for (auto Child : ILE->children()) {
3239         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3240           CheckInitListExpr(SubList);
3241         } else {
3242           Visit(Child);
3243         }
3244         ++InitFieldIndex.back();
3245       }
3246       InitFieldIndex.pop_back();
3247     }
3248 
3249     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3250                           FieldDecl *Field, const Type *BaseClass) {
3251       // Remove Decls that may have been initialized in the previous
3252       // initializer.
3253       for (ValueDecl* VD : DeclsToRemove)
3254         Decls.erase(VD);
3255       DeclsToRemove.clear();
3256 
3257       Constructor = FieldConstructor;
3258       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3259 
3260       if (ILE && Field) {
3261         InitList = true;
3262         InitListFieldDecl = Field;
3263         InitFieldIndex.clear();
3264         CheckInitListExpr(ILE);
3265       } else {
3266         InitList = false;
3267         Visit(E);
3268       }
3269 
3270       if (Field)
3271         Decls.erase(Field);
3272       if (BaseClass)
3273         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3274     }
3275 
3276     void VisitMemberExpr(MemberExpr *ME) {
3277       // All uses of unbounded reference fields will warn.
3278       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3279     }
3280 
3281     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3282       if (E->getCastKind() == CK_LValueToRValue) {
3283         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3284         return;
3285       }
3286 
3287       Inherited::VisitImplicitCastExpr(E);
3288     }
3289 
3290     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3291       if (E->getConstructor()->isCopyConstructor()) {
3292         Expr *ArgExpr = E->getArg(0);
3293         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3294           if (ILE->getNumInits() == 1)
3295             ArgExpr = ILE->getInit(0);
3296         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3297           if (ICE->getCastKind() == CK_NoOp)
3298             ArgExpr = ICE->getSubExpr();
3299         HandleValue(ArgExpr, false /*AddressOf*/);
3300         return;
3301       }
3302       Inherited::VisitCXXConstructExpr(E);
3303     }
3304 
3305     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3306       Expr *Callee = E->getCallee();
3307       if (isa<MemberExpr>(Callee)) {
3308         HandleValue(Callee, false /*AddressOf*/);
3309         for (auto Arg : E->arguments())
3310           Visit(Arg);
3311         return;
3312       }
3313 
3314       Inherited::VisitCXXMemberCallExpr(E);
3315     }
3316 
3317     void VisitCallExpr(CallExpr *E) {
3318       // Treat std::move as a use.
3319       if (E->getNumArgs() == 1) {
3320         if (FunctionDecl *FD = E->getDirectCallee()) {
3321           if (FD->isInStdNamespace() && FD->getIdentifier() &&
3322               FD->getIdentifier()->isStr("move")) {
3323             HandleValue(E->getArg(0), false /*AddressOf*/);
3324             return;
3325           }
3326         }
3327       }
3328 
3329       Inherited::VisitCallExpr(E);
3330     }
3331 
3332     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3333       Expr *Callee = E->getCallee();
3334 
3335       if (isa<UnresolvedLookupExpr>(Callee))
3336         return Inherited::VisitCXXOperatorCallExpr(E);
3337 
3338       Visit(Callee);
3339       for (auto Arg : E->arguments())
3340         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3341     }
3342 
3343     void VisitBinaryOperator(BinaryOperator *E) {
3344       // If a field assignment is detected, remove the field from the
3345       // uninitiailized field set.
3346       if (E->getOpcode() == BO_Assign)
3347         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3348           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3349             if (!FD->getType()->isReferenceType())
3350               DeclsToRemove.push_back(FD);
3351 
3352       if (E->isCompoundAssignmentOp()) {
3353         HandleValue(E->getLHS(), false /*AddressOf*/);
3354         Visit(E->getRHS());
3355         return;
3356       }
3357 
3358       Inherited::VisitBinaryOperator(E);
3359     }
3360 
3361     void VisitUnaryOperator(UnaryOperator *E) {
3362       if (E->isIncrementDecrementOp()) {
3363         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3364         return;
3365       }
3366       if (E->getOpcode() == UO_AddrOf) {
3367         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3368           HandleValue(ME->getBase(), true /*AddressOf*/);
3369           return;
3370         }
3371       }
3372 
3373       Inherited::VisitUnaryOperator(E);
3374     }
3375   };
3376 
3377   // Diagnose value-uses of fields to initialize themselves, e.g.
3378   //   foo(foo)
3379   // where foo is not also a parameter to the constructor.
3380   // Also diagnose across field uninitialized use such as
3381   //   x(y), y(x)
3382   // TODO: implement -Wuninitialized and fold this into that framework.
3383   static void DiagnoseUninitializedFields(
3384       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3385 
3386     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3387                                            Constructor->getLocation())) {
3388       return;
3389     }
3390 
3391     if (Constructor->isInvalidDecl())
3392       return;
3393 
3394     const CXXRecordDecl *RD = Constructor->getParent();
3395 
3396     if (RD->getDescribedClassTemplate())
3397       return;
3398 
3399     // Holds fields that are uninitialized.
3400     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3401 
3402     // At the beginning, all fields are uninitialized.
3403     for (auto *I : RD->decls()) {
3404       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3405         UninitializedFields.insert(FD);
3406       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3407         UninitializedFields.insert(IFD->getAnonField());
3408       }
3409     }
3410 
3411     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3412     for (auto I : RD->bases())
3413       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3414 
3415     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3416       return;
3417 
3418     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3419                                                    UninitializedFields,
3420                                                    UninitializedBaseClasses);
3421 
3422     for (const auto *FieldInit : Constructor->inits()) {
3423       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3424         break;
3425 
3426       Expr *InitExpr = FieldInit->getInit();
3427       if (!InitExpr)
3428         continue;
3429 
3430       if (CXXDefaultInitExpr *Default =
3431               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3432         InitExpr = Default->getExpr();
3433         if (!InitExpr)
3434           continue;
3435         // In class initializers will point to the constructor.
3436         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3437                                               FieldInit->getAnyMember(),
3438                                               FieldInit->getBaseClass());
3439       } else {
3440         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3441                                               FieldInit->getAnyMember(),
3442                                               FieldInit->getBaseClass());
3443       }
3444     }
3445   }
3446 } // namespace
3447 
3448 /// \brief Enter a new C++ default initializer scope. After calling this, the
3449 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3450 /// parsing or instantiating the initializer failed.
3451 void Sema::ActOnStartCXXInClassMemberInitializer() {
3452   // Create a synthetic function scope to represent the call to the constructor
3453   // that notionally surrounds a use of this initializer.
3454   PushFunctionScope();
3455 }
3456 
3457 /// \brief This is invoked after parsing an in-class initializer for a
3458 /// non-static C++ class member, and after instantiating an in-class initializer
3459 /// in a class template. Such actions are deferred until the class is complete.
3460 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3461                                                   SourceLocation InitLoc,
3462                                                   Expr *InitExpr) {
3463   // Pop the notional constructor scope we created earlier.
3464   PopFunctionScopeInfo(nullptr, D);
3465 
3466   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3467   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3468          "must set init style when field is created");
3469 
3470   if (!InitExpr) {
3471     D->setInvalidDecl();
3472     if (FD)
3473       FD->removeInClassInitializer();
3474     return;
3475   }
3476 
3477   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3478     FD->setInvalidDecl();
3479     FD->removeInClassInitializer();
3480     return;
3481   }
3482 
3483   ExprResult Init = InitExpr;
3484   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3485     InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
3486     InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
3487         ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
3488         : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
3489     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3490     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3491     if (Init.isInvalid()) {
3492       FD->setInvalidDecl();
3493       return;
3494     }
3495   }
3496 
3497   // C++11 [class.base.init]p7:
3498   //   The initialization of each base and member constitutes a
3499   //   full-expression.
3500   Init = ActOnFinishFullExpr(Init.get(), InitLoc);
3501   if (Init.isInvalid()) {
3502     FD->setInvalidDecl();
3503     return;
3504   }
3505 
3506   InitExpr = Init.get();
3507 
3508   FD->setInClassInitializer(InitExpr);
3509 }
3510 
3511 /// \brief Find the direct and/or virtual base specifiers that
3512 /// correspond to the given base type, for use in base initialization
3513 /// within a constructor.
3514 static bool FindBaseInitializer(Sema &SemaRef,
3515                                 CXXRecordDecl *ClassDecl,
3516                                 QualType BaseType,
3517                                 const CXXBaseSpecifier *&DirectBaseSpec,
3518                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
3519   // First, check for a direct base class.
3520   DirectBaseSpec = nullptr;
3521   for (const auto &Base : ClassDecl->bases()) {
3522     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3523       // We found a direct base of this type. That's what we're
3524       // initializing.
3525       DirectBaseSpec = &Base;
3526       break;
3527     }
3528   }
3529 
3530   // Check for a virtual base class.
3531   // FIXME: We might be able to short-circuit this if we know in advance that
3532   // there are no virtual bases.
3533   VirtualBaseSpec = nullptr;
3534   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3535     // We haven't found a base yet; search the class hierarchy for a
3536     // virtual base class.
3537     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3538                        /*DetectVirtual=*/false);
3539     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3540                               SemaRef.Context.getTypeDeclType(ClassDecl),
3541                               BaseType, Paths)) {
3542       for (CXXBasePaths::paths_iterator Path = Paths.begin();
3543            Path != Paths.end(); ++Path) {
3544         if (Path->back().Base->isVirtual()) {
3545           VirtualBaseSpec = Path->back().Base;
3546           break;
3547         }
3548       }
3549     }
3550   }
3551 
3552   return DirectBaseSpec || VirtualBaseSpec;
3553 }
3554 
3555 /// \brief Handle a C++ member initializer using braced-init-list syntax.
3556 MemInitResult
3557 Sema::ActOnMemInitializer(Decl *ConstructorD,
3558                           Scope *S,
3559                           CXXScopeSpec &SS,
3560                           IdentifierInfo *MemberOrBase,
3561                           ParsedType TemplateTypeTy,
3562                           const DeclSpec &DS,
3563                           SourceLocation IdLoc,
3564                           Expr *InitList,
3565                           SourceLocation EllipsisLoc) {
3566   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3567                              DS, IdLoc, InitList,
3568                              EllipsisLoc);
3569 }
3570 
3571 /// \brief Handle a C++ member initializer using parentheses syntax.
3572 MemInitResult
3573 Sema::ActOnMemInitializer(Decl *ConstructorD,
3574                           Scope *S,
3575                           CXXScopeSpec &SS,
3576                           IdentifierInfo *MemberOrBase,
3577                           ParsedType TemplateTypeTy,
3578                           const DeclSpec &DS,
3579                           SourceLocation IdLoc,
3580                           SourceLocation LParenLoc,
3581                           ArrayRef<Expr *> Args,
3582                           SourceLocation RParenLoc,
3583                           SourceLocation EllipsisLoc) {
3584   Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
3585                                            Args, RParenLoc);
3586   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3587                              DS, IdLoc, List, EllipsisLoc);
3588 }
3589 
3590 namespace {
3591 
3592 // Callback to only accept typo corrections that can be a valid C++ member
3593 // intializer: either a non-static field member or a base class.
3594 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
3595 public:
3596   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3597       : ClassDecl(ClassDecl) {}
3598 
3599   bool ValidateCandidate(const TypoCorrection &candidate) override {
3600     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3601       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3602         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
3603       return isa<TypeDecl>(ND);
3604     }
3605     return false;
3606   }
3607 
3608 private:
3609   CXXRecordDecl *ClassDecl;
3610 };
3611 
3612 }
3613 
3614 /// \brief Handle a C++ member initializer.
3615 MemInitResult
3616 Sema::BuildMemInitializer(Decl *ConstructorD,
3617                           Scope *S,
3618                           CXXScopeSpec &SS,
3619                           IdentifierInfo *MemberOrBase,
3620                           ParsedType TemplateTypeTy,
3621                           const DeclSpec &DS,
3622                           SourceLocation IdLoc,
3623                           Expr *Init,
3624                           SourceLocation EllipsisLoc) {
3625   ExprResult Res = CorrectDelayedTyposInExpr(Init);
3626   if (!Res.isUsable())
3627     return true;
3628   Init = Res.get();
3629 
3630   if (!ConstructorD)
3631     return true;
3632 
3633   AdjustDeclIfTemplate(ConstructorD);
3634 
3635   CXXConstructorDecl *Constructor
3636     = dyn_cast<CXXConstructorDecl>(ConstructorD);
3637   if (!Constructor) {
3638     // The user wrote a constructor initializer on a function that is
3639     // not a C++ constructor. Ignore the error for now, because we may
3640     // have more member initializers coming; we'll diagnose it just
3641     // once in ActOnMemInitializers.
3642     return true;
3643   }
3644 
3645   CXXRecordDecl *ClassDecl = Constructor->getParent();
3646 
3647   // C++ [class.base.init]p2:
3648   //   Names in a mem-initializer-id are looked up in the scope of the
3649   //   constructor's class and, if not found in that scope, are looked
3650   //   up in the scope containing the constructor's definition.
3651   //   [Note: if the constructor's class contains a member with the
3652   //   same name as a direct or virtual base class of the class, a
3653   //   mem-initializer-id naming the member or base class and composed
3654   //   of a single identifier refers to the class member. A
3655   //   mem-initializer-id for the hidden base class may be specified
3656   //   using a qualified name. ]
3657   if (!SS.getScopeRep() && !TemplateTypeTy) {
3658     // Look for a member, first.
3659     DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
3660     if (!Result.empty()) {
3661       ValueDecl *Member;
3662       if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3663           (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
3664         if (EllipsisLoc.isValid())
3665           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
3666             << MemberOrBase
3667             << SourceRange(IdLoc, Init->getSourceRange().getEnd());
3668 
3669         return BuildMemberInitializer(Member, Init, IdLoc);
3670       }
3671     }
3672   }
3673   // It didn't name a member, so see if it names a class.
3674   QualType BaseType;
3675   TypeSourceInfo *TInfo = nullptr;
3676 
3677   if (TemplateTypeTy) {
3678     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
3679   } else if (DS.getTypeSpecType() == TST_decltype) {
3680     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
3681   } else {
3682     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3683     LookupParsedName(R, S, &SS);
3684 
3685     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3686     if (!TyD) {
3687       if (R.isAmbiguous()) return true;
3688 
3689       // We don't want access-control diagnostics here.
3690       R.suppressDiagnostics();
3691 
3692       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3693         bool NotUnknownSpecialization = false;
3694         DeclContext *DC = computeDeclContext(SS, false);
3695         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3696           NotUnknownSpecialization = !Record->hasAnyDependentBases();
3697 
3698         if (!NotUnknownSpecialization) {
3699           // When the scope specifier can refer to a member of an unknown
3700           // specialization, we take it as a type name.
3701           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3702                                        SS.getWithLocInContext(Context),
3703                                        *MemberOrBase, IdLoc);
3704           if (BaseType.isNull())
3705             return true;
3706 
3707           R.clear();
3708           R.setLookupName(MemberOrBase);
3709         }
3710       }
3711 
3712       // If no results were found, try to correct typos.
3713       TypoCorrection Corr;
3714       if (R.empty() && BaseType.isNull() &&
3715           (Corr = CorrectTypo(
3716                R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3717                llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
3718                CTK_ErrorRecovery, ClassDecl))) {
3719         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
3720           // We have found a non-static data member with a similar
3721           // name to what was typed; complain and initialize that
3722           // member.
3723           diagnoseTypo(Corr,
3724                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
3725                          << MemberOrBase << true);
3726           return BuildMemberInitializer(Member, Init, IdLoc);
3727         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
3728           const CXXBaseSpecifier *DirectBaseSpec;
3729           const CXXBaseSpecifier *VirtualBaseSpec;
3730           if (FindBaseInitializer(*this, ClassDecl,
3731                                   Context.getTypeDeclType(Type),
3732                                   DirectBaseSpec, VirtualBaseSpec)) {
3733             // We have found a direct or virtual base class with a
3734             // similar name to what was typed; complain and initialize
3735             // that base class.
3736             diagnoseTypo(Corr,
3737                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
3738                            << MemberOrBase << false,
3739                          PDiag() /*Suppress note, we provide our own.*/);
3740 
3741             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3742                                                               : VirtualBaseSpec;
3743             Diag(BaseSpec->getLocStart(),
3744                  diag::note_base_class_specified_here)
3745               << BaseSpec->getType()
3746               << BaseSpec->getSourceRange();
3747 
3748             TyD = Type;
3749           }
3750         }
3751       }
3752 
3753       if (!TyD && BaseType.isNull()) {
3754         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
3755           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
3756         return true;
3757       }
3758     }
3759 
3760     if (BaseType.isNull()) {
3761       BaseType = Context.getTypeDeclType(TyD);
3762       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
3763       if (SS.isSet()) {
3764         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3765                                              BaseType);
3766         TInfo = Context.CreateTypeSourceInfo(BaseType);
3767         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3768         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3769         TL.setElaboratedKeywordLoc(SourceLocation());
3770         TL.setQualifierLoc(SS.getWithLocInContext(Context));
3771       }
3772     }
3773   }
3774 
3775   if (!TInfo)
3776     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
3777 
3778   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
3779 }
3780 
3781 /// Checks a member initializer expression for cases where reference (or
3782 /// pointer) members are bound to by-value parameters (or their addresses).
3783 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3784                                                Expr *Init,
3785                                                SourceLocation IdLoc) {
3786   QualType MemberTy = Member->getType();
3787 
3788   // We only handle pointers and references currently.
3789   // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3790   if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3791     return;
3792 
3793   const bool IsPointer = MemberTy->isPointerType();
3794   if (IsPointer) {
3795     if (const UnaryOperator *Op
3796           = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3797       // The only case we're worried about with pointers requires taking the
3798       // address.
3799       if (Op->getOpcode() != UO_AddrOf)
3800         return;
3801 
3802       Init = Op->getSubExpr();
3803     } else {
3804       // We only handle address-of expression initializers for pointers.
3805       return;
3806     }
3807   }
3808 
3809   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
3810     // We only warn when referring to a non-reference parameter declaration.
3811     const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3812     if (!Parameter || Parameter->getType()->isReferenceType())
3813       return;
3814 
3815     S.Diag(Init->getExprLoc(),
3816            IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3817                      : diag::warn_bind_ref_member_to_parameter)
3818       << Member << Parameter << Init->getSourceRange();
3819   } else {
3820     // Other initializers are fine.
3821     return;
3822   }
3823 
3824   S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3825     << (unsigned)IsPointer;
3826 }
3827 
3828 MemInitResult
3829 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3830                              SourceLocation IdLoc) {
3831   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3832   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3833   assert((DirectMember || IndirectMember) &&
3834          "Member must be a FieldDecl or IndirectFieldDecl");
3835 
3836   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3837     return true;
3838 
3839   if (Member->isInvalidDecl())
3840     return true;
3841 
3842   MultiExprArg Args;
3843   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3844     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3845   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3846     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
3847   } else {
3848     // Template instantiation doesn't reconstruct ParenListExprs for us.
3849     Args = Init;
3850   }
3851 
3852   SourceRange InitRange = Init->getSourceRange();
3853 
3854   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
3855     // Can't check initialization for a member of dependent type or when
3856     // any of the arguments are type-dependent expressions.
3857     DiscardCleanupsInEvaluationContext();
3858   } else {
3859     bool InitList = false;
3860     if (isa<InitListExpr>(Init)) {
3861       InitList = true;
3862       Args = Init;
3863     }
3864 
3865     // Initialize the member.
3866     InitializedEntity MemberEntity =
3867       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3868                    : InitializedEntity::InitializeMember(IndirectMember,
3869                                                          nullptr);
3870     InitializationKind Kind =
3871       InitList ? InitializationKind::CreateDirectList(IdLoc)
3872                : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3873                                                   InitRange.getEnd());
3874 
3875     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
3876     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3877                                             nullptr);
3878     if (MemberInit.isInvalid())
3879       return true;
3880 
3881     CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3882 
3883     // C++11 [class.base.init]p7:
3884     //   The initialization of each base and member constitutes a
3885     //   full-expression.
3886     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
3887     if (MemberInit.isInvalid())
3888       return true;
3889 
3890     Init = MemberInit.get();
3891   }
3892 
3893   if (DirectMember) {
3894     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3895                                             InitRange.getBegin(), Init,
3896                                             InitRange.getEnd());
3897   } else {
3898     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3899                                             InitRange.getBegin(), Init,
3900                                             InitRange.getEnd());
3901   }
3902 }
3903 
3904 MemInitResult
3905 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
3906                                  CXXRecordDecl *ClassDecl) {
3907   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
3908   if (!LangOpts.CPlusPlus11)
3909     return Diag(NameLoc, diag::err_delegating_ctor)
3910       << TInfo->getTypeLoc().getLocalSourceRange();
3911   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
3912 
3913   bool InitList = true;
3914   MultiExprArg Args = Init;
3915   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3916     InitList = false;
3917     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3918   }
3919 
3920   SourceRange InitRange = Init->getSourceRange();
3921   // Initialize the object.
3922   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3923                                      QualType(ClassDecl->getTypeForDecl(), 0));
3924   InitializationKind Kind =
3925     InitList ? InitializationKind::CreateDirectList(NameLoc)
3926              : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3927                                                 InitRange.getEnd());
3928   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
3929   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
3930                                               Args, nullptr);
3931   if (DelegationInit.isInvalid())
3932     return true;
3933 
3934   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3935          "Delegating constructor with no target?");
3936 
3937   // C++11 [class.base.init]p7:
3938   //   The initialization of each base and member constitutes a
3939   //   full-expression.
3940   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
3941                                        InitRange.getBegin());
3942   if (DelegationInit.isInvalid())
3943     return true;
3944 
3945   // If we are in a dependent context, template instantiation will
3946   // perform this type-checking again. Just save the arguments that we
3947   // received in a ParenListExpr.
3948   // FIXME: This isn't quite ideal, since our ASTs don't capture all
3949   // of the information that we have about the base
3950   // initializer. However, deconstructing the ASTs is a dicey process,
3951   // and this approach is far more likely to get the corner cases right.
3952   if (CurContext->isDependentContext())
3953     DelegationInit = Init;
3954 
3955   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
3956                                           DelegationInit.getAs<Expr>(),
3957                                           InitRange.getEnd());
3958 }
3959 
3960 MemInitResult
3961 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
3962                            Expr *Init, CXXRecordDecl *ClassDecl,
3963                            SourceLocation EllipsisLoc) {
3964   SourceLocation BaseLoc
3965     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
3966 
3967   if (!BaseType->isDependentType() && !BaseType->isRecordType())
3968     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
3969              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3970 
3971   // C++ [class.base.init]p2:
3972   //   [...] Unless the mem-initializer-id names a nonstatic data
3973   //   member of the constructor's class or a direct or virtual base
3974   //   of that class, the mem-initializer is ill-formed. A
3975   //   mem-initializer-list can initialize a base class using any
3976   //   name that denotes that base class type.
3977   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
3978 
3979   SourceRange InitRange = Init->getSourceRange();
3980   if (EllipsisLoc.isValid()) {
3981     // This is a pack expansion.
3982     if (!BaseType->containsUnexpandedParameterPack())  {
3983       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
3984         << SourceRange(BaseLoc, InitRange.getEnd());
3985 
3986       EllipsisLoc = SourceLocation();
3987     }
3988   } else {
3989     // Check for any unexpanded parameter packs.
3990     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
3991       return true;
3992 
3993     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3994       return true;
3995   }
3996 
3997   // Check for direct and virtual base classes.
3998   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
3999   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4000   if (!Dependent) {
4001     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4002                                        BaseType))
4003       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4004 
4005     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4006                         VirtualBaseSpec);
4007 
4008     // C++ [base.class.init]p2:
4009     // Unless the mem-initializer-id names a nonstatic data member of the
4010     // constructor's class or a direct or virtual base of that class, the
4011     // mem-initializer is ill-formed.
4012     if (!DirectBaseSpec && !VirtualBaseSpec) {
4013       // If the class has any dependent bases, then it's possible that
4014       // one of those types will resolve to the same type as
4015       // BaseType. Therefore, just treat this as a dependent base
4016       // class initialization.  FIXME: Should we try to check the
4017       // initialization anyway? It seems odd.
4018       if (ClassDecl->hasAnyDependentBases())
4019         Dependent = true;
4020       else
4021         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4022           << BaseType << Context.getTypeDeclType(ClassDecl)
4023           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4024     }
4025   }
4026 
4027   if (Dependent) {
4028     DiscardCleanupsInEvaluationContext();
4029 
4030     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4031                                             /*IsVirtual=*/false,
4032                                             InitRange.getBegin(), Init,
4033                                             InitRange.getEnd(), EllipsisLoc);
4034   }
4035 
4036   // C++ [base.class.init]p2:
4037   //   If a mem-initializer-id is ambiguous because it designates both
4038   //   a direct non-virtual base class and an inherited virtual base
4039   //   class, the mem-initializer is ill-formed.
4040   if (DirectBaseSpec && VirtualBaseSpec)
4041     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4042       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4043 
4044   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4045   if (!BaseSpec)
4046     BaseSpec = VirtualBaseSpec;
4047 
4048   // Initialize the base.
4049   bool InitList = true;
4050   MultiExprArg Args = Init;
4051   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4052     InitList = false;
4053     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4054   }
4055 
4056   InitializedEntity BaseEntity =
4057     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4058   InitializationKind Kind =
4059     InitList ? InitializationKind::CreateDirectList(BaseLoc)
4060              : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4061                                                 InitRange.getEnd());
4062   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4063   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4064   if (BaseInit.isInvalid())
4065     return true;
4066 
4067   // C++11 [class.base.init]p7:
4068   //   The initialization of each base and member constitutes a
4069   //   full-expression.
4070   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
4071   if (BaseInit.isInvalid())
4072     return true;
4073 
4074   // If we are in a dependent context, template instantiation will
4075   // perform this type-checking again. Just save the arguments that we
4076   // received in a ParenListExpr.
4077   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4078   // of the information that we have about the base
4079   // initializer. However, deconstructing the ASTs is a dicey process,
4080   // and this approach is far more likely to get the corner cases right.
4081   if (CurContext->isDependentContext())
4082     BaseInit = Init;
4083 
4084   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4085                                           BaseSpec->isVirtual(),
4086                                           InitRange.getBegin(),
4087                                           BaseInit.getAs<Expr>(),
4088                                           InitRange.getEnd(), EllipsisLoc);
4089 }
4090 
4091 // Create a static_cast\<T&&>(expr).
4092 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4093   if (T.isNull()) T = E->getType();
4094   QualType TargetType = SemaRef.BuildReferenceType(
4095       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4096   SourceLocation ExprLoc = E->getLocStart();
4097   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4098       TargetType, ExprLoc);
4099 
4100   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4101                                    SourceRange(ExprLoc, ExprLoc),
4102                                    E->getSourceRange()).get();
4103 }
4104 
4105 /// ImplicitInitializerKind - How an implicit base or member initializer should
4106 /// initialize its base or member.
4107 enum ImplicitInitializerKind {
4108   IIK_Default,
4109   IIK_Copy,
4110   IIK_Move,
4111   IIK_Inherit
4112 };
4113 
4114 static bool
4115 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4116                              ImplicitInitializerKind ImplicitInitKind,
4117                              CXXBaseSpecifier *BaseSpec,
4118                              bool IsInheritedVirtualBase,
4119                              CXXCtorInitializer *&CXXBaseInit) {
4120   InitializedEntity InitEntity
4121     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4122                                         IsInheritedVirtualBase);
4123 
4124   ExprResult BaseInit;
4125 
4126   switch (ImplicitInitKind) {
4127   case IIK_Inherit:
4128   case IIK_Default: {
4129     InitializationKind InitKind
4130       = InitializationKind::CreateDefault(Constructor->getLocation());
4131     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4132     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4133     break;
4134   }
4135 
4136   case IIK_Move:
4137   case IIK_Copy: {
4138     bool Moving = ImplicitInitKind == IIK_Move;
4139     ParmVarDecl *Param = Constructor->getParamDecl(0);
4140     QualType ParamType = Param->getType().getNonReferenceType();
4141 
4142     Expr *CopyCtorArg =
4143       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4144                           SourceLocation(), Param, false,
4145                           Constructor->getLocation(), ParamType,
4146                           VK_LValue, nullptr);
4147 
4148     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4149 
4150     // Cast to the base class to avoid ambiguities.
4151     QualType ArgTy =
4152       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4153                                        ParamType.getQualifiers());
4154 
4155     if (Moving) {
4156       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4157     }
4158 
4159     CXXCastPath BasePath;
4160     BasePath.push_back(BaseSpec);
4161     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4162                                             CK_UncheckedDerivedToBase,
4163                                             Moving ? VK_XValue : VK_LValue,
4164                                             &BasePath).get();
4165 
4166     InitializationKind InitKind
4167       = InitializationKind::CreateDirect(Constructor->getLocation(),
4168                                          SourceLocation(), SourceLocation());
4169     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4170     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4171     break;
4172   }
4173   }
4174 
4175   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4176   if (BaseInit.isInvalid())
4177     return true;
4178 
4179   CXXBaseInit =
4180     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4181                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4182                                                         SourceLocation()),
4183                                              BaseSpec->isVirtual(),
4184                                              SourceLocation(),
4185                                              BaseInit.getAs<Expr>(),
4186                                              SourceLocation(),
4187                                              SourceLocation());
4188 
4189   return false;
4190 }
4191 
4192 static bool RefersToRValueRef(Expr *MemRef) {
4193   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4194   return Referenced->getType()->isRValueReferenceType();
4195 }
4196 
4197 static bool
4198 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4199                                ImplicitInitializerKind ImplicitInitKind,
4200                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4201                                CXXCtorInitializer *&CXXMemberInit) {
4202   if (Field->isInvalidDecl())
4203     return true;
4204 
4205   SourceLocation Loc = Constructor->getLocation();
4206 
4207   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4208     bool Moving = ImplicitInitKind == IIK_Move;
4209     ParmVarDecl *Param = Constructor->getParamDecl(0);
4210     QualType ParamType = Param->getType().getNonReferenceType();
4211 
4212     // Suppress copying zero-width bitfields.
4213     if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
4214       return false;
4215 
4216     Expr *MemberExprBase =
4217       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4218                           SourceLocation(), Param, false,
4219                           Loc, ParamType, VK_LValue, nullptr);
4220 
4221     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4222 
4223     if (Moving) {
4224       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4225     }
4226 
4227     // Build a reference to this field within the parameter.
4228     CXXScopeSpec SS;
4229     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4230                               Sema::LookupMemberName);
4231     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4232                                   : cast<ValueDecl>(Field), AS_public);
4233     MemberLookup.resolveKind();
4234     ExprResult CtorArg
4235       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4236                                          ParamType, Loc,
4237                                          /*IsArrow=*/false,
4238                                          SS,
4239                                          /*TemplateKWLoc=*/SourceLocation(),
4240                                          /*FirstQualifierInScope=*/nullptr,
4241                                          MemberLookup,
4242                                          /*TemplateArgs=*/nullptr,
4243                                          /*S*/nullptr);
4244     if (CtorArg.isInvalid())
4245       return true;
4246 
4247     // C++11 [class.copy]p15:
4248     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4249     //     with static_cast<T&&>(x.m);
4250     if (RefersToRValueRef(CtorArg.get())) {
4251       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4252     }
4253 
4254     // When the field we are copying is an array, create index variables for
4255     // each dimension of the array. We use these index variables to subscript
4256     // the source array, and other clients (e.g., CodeGen) will perform the
4257     // necessary iteration with these index variables.
4258     SmallVector<VarDecl *, 4> IndexVariables;
4259     QualType BaseType = Field->getType();
4260     QualType SizeType = SemaRef.Context.getSizeType();
4261     bool InitializingArray = false;
4262     while (const ConstantArrayType *Array
4263                           = SemaRef.Context.getAsConstantArrayType(BaseType)) {
4264       InitializingArray = true;
4265       // Create the iteration variable for this array index.
4266       IdentifierInfo *IterationVarName = nullptr;
4267       {
4268         SmallString<8> Str;
4269         llvm::raw_svector_ostream OS(Str);
4270         OS << "__i" << IndexVariables.size();
4271         IterationVarName = &SemaRef.Context.Idents.get(OS.str());
4272       }
4273       VarDecl *IterationVar
4274         = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
4275                           IterationVarName, SizeType,
4276                         SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
4277                           SC_None);
4278       IndexVariables.push_back(IterationVar);
4279 
4280       // Create a reference to the iteration variable.
4281       ExprResult IterationVarRef
4282         = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
4283       assert(!IterationVarRef.isInvalid() &&
4284              "Reference to invented variable cannot fail!");
4285       IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
4286       assert(!IterationVarRef.isInvalid() &&
4287              "Conversion of invented variable cannot fail!");
4288 
4289       // Subscript the array with this iteration variable.
4290       CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
4291                                                         IterationVarRef.get(),
4292                                                         Loc);
4293       if (CtorArg.isInvalid())
4294         return true;
4295 
4296       BaseType = Array->getElementType();
4297     }
4298 
4299     // The array subscript expression is an lvalue, which is wrong for moving.
4300     if (Moving && InitializingArray)
4301       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4302 
4303     // Construct the entity that we will be initializing. For an array, this
4304     // will be first element in the array, which may require several levels
4305     // of array-subscript entities.
4306     SmallVector<InitializedEntity, 4> Entities;
4307     Entities.reserve(1 + IndexVariables.size());
4308     if (Indirect)
4309       Entities.push_back(InitializedEntity::InitializeMember(Indirect));
4310     else
4311       Entities.push_back(InitializedEntity::InitializeMember(Field));
4312     for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
4313       Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
4314                                                               0,
4315                                                               Entities.back()));
4316 
4317     // Direct-initialize to use the copy constructor.
4318     InitializationKind InitKind =
4319       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4320 
4321     Expr *CtorArgE = CtorArg.getAs<Expr>();
4322     InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
4323                                    CtorArgE);
4324 
4325     ExprResult MemberInit
4326       = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
4327                         MultiExprArg(&CtorArgE, 1));
4328     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4329     if (MemberInit.isInvalid())
4330       return true;
4331 
4332     if (Indirect) {
4333       assert(IndexVariables.size() == 0 &&
4334              "Indirect field improperly initialized");
4335       CXXMemberInit
4336         = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
4337                                                    Loc, Loc,
4338                                                    MemberInit.getAs<Expr>(),
4339                                                    Loc);
4340     } else
4341       CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
4342                                                  Loc, MemberInit.getAs<Expr>(),
4343                                                  Loc,
4344                                                  IndexVariables.data(),
4345                                                  IndexVariables.size());
4346     return false;
4347   }
4348 
4349   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4350          "Unhandled implicit init kind!");
4351 
4352   QualType FieldBaseElementType =
4353     SemaRef.Context.getBaseElementType(Field->getType());
4354 
4355   if (FieldBaseElementType->isRecordType()) {
4356     InitializedEntity InitEntity
4357       = Indirect? InitializedEntity::InitializeMember(Indirect)
4358                 : InitializedEntity::InitializeMember(Field);
4359     InitializationKind InitKind =
4360       InitializationKind::CreateDefault(Loc);
4361 
4362     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4363     ExprResult MemberInit =
4364       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4365 
4366     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4367     if (MemberInit.isInvalid())
4368       return true;
4369 
4370     if (Indirect)
4371       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4372                                                                Indirect, Loc,
4373                                                                Loc,
4374                                                                MemberInit.get(),
4375                                                                Loc);
4376     else
4377       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4378                                                                Field, Loc, Loc,
4379                                                                MemberInit.get(),
4380                                                                Loc);
4381     return false;
4382   }
4383 
4384   if (!Field->getParent()->isUnion()) {
4385     if (FieldBaseElementType->isReferenceType()) {
4386       SemaRef.Diag(Constructor->getLocation(),
4387                    diag::err_uninitialized_member_in_ctor)
4388       << (int)Constructor->isImplicit()
4389       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4390       << 0 << Field->getDeclName();
4391       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4392       return true;
4393     }
4394 
4395     if (FieldBaseElementType.isConstQualified()) {
4396       SemaRef.Diag(Constructor->getLocation(),
4397                    diag::err_uninitialized_member_in_ctor)
4398       << (int)Constructor->isImplicit()
4399       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4400       << 1 << Field->getDeclName();
4401       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4402       return true;
4403     }
4404   }
4405 
4406   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
4407       FieldBaseElementType->isObjCRetainableType() &&
4408       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
4409       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
4410     // ARC:
4411     //   Default-initialize Objective-C pointers to NULL.
4412     CXXMemberInit
4413       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4414                                                  Loc, Loc,
4415                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4416                                                  Loc);
4417     return false;
4418   }
4419 
4420   // Nothing to initialize.
4421   CXXMemberInit = nullptr;
4422   return false;
4423 }
4424 
4425 namespace {
4426 struct BaseAndFieldInfo {
4427   Sema &S;
4428   CXXConstructorDecl *Ctor;
4429   bool AnyErrorsInInits;
4430   ImplicitInitializerKind IIK;
4431   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4432   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4433   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4434 
4435   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4436     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4437     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4438     if (Ctor->getInheritedConstructor())
4439       IIK = IIK_Inherit;
4440     else if (Generated && Ctor->isCopyConstructor())
4441       IIK = IIK_Copy;
4442     else if (Generated && Ctor->isMoveConstructor())
4443       IIK = IIK_Move;
4444     else
4445       IIK = IIK_Default;
4446   }
4447 
4448   bool isImplicitCopyOrMove() const {
4449     switch (IIK) {
4450     case IIK_Copy:
4451     case IIK_Move:
4452       return true;
4453 
4454     case IIK_Default:
4455     case IIK_Inherit:
4456       return false;
4457     }
4458 
4459     llvm_unreachable("Invalid ImplicitInitializerKind!");
4460   }
4461 
4462   bool addFieldInitializer(CXXCtorInitializer *Init) {
4463     AllToInit.push_back(Init);
4464 
4465     // Check whether this initializer makes the field "used".
4466     if (Init->getInit()->HasSideEffects(S.Context))
4467       S.UnusedPrivateFields.remove(Init->getAnyMember());
4468 
4469     return false;
4470   }
4471 
4472   bool isInactiveUnionMember(FieldDecl *Field) {
4473     RecordDecl *Record = Field->getParent();
4474     if (!Record->isUnion())
4475       return false;
4476 
4477     if (FieldDecl *Active =
4478             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4479       return Active != Field->getCanonicalDecl();
4480 
4481     // In an implicit copy or move constructor, ignore any in-class initializer.
4482     if (isImplicitCopyOrMove())
4483       return true;
4484 
4485     // If there's no explicit initialization, the field is active only if it
4486     // has an in-class initializer...
4487     if (Field->hasInClassInitializer())
4488       return false;
4489     // ... or it's an anonymous struct or union whose class has an in-class
4490     // initializer.
4491     if (!Field->isAnonymousStructOrUnion())
4492       return true;
4493     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4494     return !FieldRD->hasInClassInitializer();
4495   }
4496 
4497   /// \brief Determine whether the given field is, or is within, a union member
4498   /// that is inactive (because there was an initializer given for a different
4499   /// member of the union, or because the union was not initialized at all).
4500   bool isWithinInactiveUnionMember(FieldDecl *Field,
4501                                    IndirectFieldDecl *Indirect) {
4502     if (!Indirect)
4503       return isInactiveUnionMember(Field);
4504 
4505     for (auto *C : Indirect->chain()) {
4506       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4507       if (Field && isInactiveUnionMember(Field))
4508         return true;
4509     }
4510     return false;
4511   }
4512 };
4513 }
4514 
4515 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
4516 /// array type.
4517 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4518   if (T->isIncompleteArrayType())
4519     return true;
4520 
4521   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4522     if (!ArrayT->getSize())
4523       return true;
4524 
4525     T = ArrayT->getElementType();
4526   }
4527 
4528   return false;
4529 }
4530 
4531 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4532                                     FieldDecl *Field,
4533                                     IndirectFieldDecl *Indirect = nullptr) {
4534   if (Field->isInvalidDecl())
4535     return false;
4536 
4537   // Overwhelmingly common case: we have a direct initializer for this field.
4538   if (CXXCtorInitializer *Init =
4539           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4540     return Info.addFieldInitializer(Init);
4541 
4542   // C++11 [class.base.init]p8:
4543   //   if the entity is a non-static data member that has a
4544   //   brace-or-equal-initializer and either
4545   //   -- the constructor's class is a union and no other variant member of that
4546   //      union is designated by a mem-initializer-id or
4547   //   -- the constructor's class is not a union, and, if the entity is a member
4548   //      of an anonymous union, no other member of that union is designated by
4549   //      a mem-initializer-id,
4550   //   the entity is initialized as specified in [dcl.init].
4551   //
4552   // We also apply the same rules to handle anonymous structs within anonymous
4553   // unions.
4554   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4555     return false;
4556 
4557   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4558     ExprResult DIE =
4559         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4560     if (DIE.isInvalid())
4561       return true;
4562     CXXCtorInitializer *Init;
4563     if (Indirect)
4564       Init = new (SemaRef.Context)
4565           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4566                              SourceLocation(), DIE.get(), SourceLocation());
4567     else
4568       Init = new (SemaRef.Context)
4569           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4570                              SourceLocation(), DIE.get(), SourceLocation());
4571     return Info.addFieldInitializer(Init);
4572   }
4573 
4574   // Don't initialize incomplete or zero-length arrays.
4575   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4576     return false;
4577 
4578   // Don't try to build an implicit initializer if there were semantic
4579   // errors in any of the initializers (and therefore we might be
4580   // missing some that the user actually wrote).
4581   if (Info.AnyErrorsInInits)
4582     return false;
4583 
4584   CXXCtorInitializer *Init = nullptr;
4585   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4586                                      Indirect, Init))
4587     return true;
4588 
4589   if (!Init)
4590     return false;
4591 
4592   return Info.addFieldInitializer(Init);
4593 }
4594 
4595 bool
4596 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4597                                CXXCtorInitializer *Initializer) {
4598   assert(Initializer->isDelegatingInitializer());
4599   Constructor->setNumCtorInitializers(1);
4600   CXXCtorInitializer **initializer =
4601     new (Context) CXXCtorInitializer*[1];
4602   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4603   Constructor->setCtorInitializers(initializer);
4604 
4605   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4606     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4607     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4608   }
4609 
4610   DelegatingCtorDecls.push_back(Constructor);
4611 
4612   DiagnoseUninitializedFields(*this, Constructor);
4613 
4614   return false;
4615 }
4616 
4617 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4618                                ArrayRef<CXXCtorInitializer *> Initializers) {
4619   if (Constructor->isDependentContext()) {
4620     // Just store the initializers as written, they will be checked during
4621     // instantiation.
4622     if (!Initializers.empty()) {
4623       Constructor->setNumCtorInitializers(Initializers.size());
4624       CXXCtorInitializer **baseOrMemberInitializers =
4625         new (Context) CXXCtorInitializer*[Initializers.size()];
4626       memcpy(baseOrMemberInitializers, Initializers.data(),
4627              Initializers.size() * sizeof(CXXCtorInitializer*));
4628       Constructor->setCtorInitializers(baseOrMemberInitializers);
4629     }
4630 
4631     // Let template instantiation know whether we had errors.
4632     if (AnyErrors)
4633       Constructor->setInvalidDecl();
4634 
4635     return false;
4636   }
4637 
4638   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4639 
4640   // We need to build the initializer AST according to order of construction
4641   // and not what user specified in the Initializers list.
4642   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4643   if (!ClassDecl)
4644     return true;
4645 
4646   bool HadError = false;
4647 
4648   for (unsigned i = 0; i < Initializers.size(); i++) {
4649     CXXCtorInitializer *Member = Initializers[i];
4650 
4651     if (Member->isBaseInitializer())
4652       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4653     else {
4654       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4655 
4656       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4657         for (auto *C : F->chain()) {
4658           FieldDecl *FD = dyn_cast<FieldDecl>(C);
4659           if (FD && FD->getParent()->isUnion())
4660             Info.ActiveUnionMember.insert(std::make_pair(
4661                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4662         }
4663       } else if (FieldDecl *FD = Member->getMember()) {
4664         if (FD->getParent()->isUnion())
4665           Info.ActiveUnionMember.insert(std::make_pair(
4666               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4667       }
4668     }
4669   }
4670 
4671   // Keep track of the direct virtual bases.
4672   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4673   for (auto &I : ClassDecl->bases()) {
4674     if (I.isVirtual())
4675       DirectVBases.insert(&I);
4676   }
4677 
4678   // Push virtual bases before others.
4679   for (auto &VBase : ClassDecl->vbases()) {
4680     if (CXXCtorInitializer *Value
4681         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
4682       // [class.base.init]p7, per DR257:
4683       //   A mem-initializer where the mem-initializer-id names a virtual base
4684       //   class is ignored during execution of a constructor of any class that
4685       //   is not the most derived class.
4686       if (ClassDecl->isAbstract()) {
4687         // FIXME: Provide a fixit to remove the base specifier. This requires
4688         // tracking the location of the associated comma for a base specifier.
4689         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
4690           << VBase.getType() << ClassDecl;
4691         DiagnoseAbstractType(ClassDecl);
4692       }
4693 
4694       Info.AllToInit.push_back(Value);
4695     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4696       // [class.base.init]p8, per DR257:
4697       //   If a given [...] base class is not named by a mem-initializer-id
4698       //   [...] and the entity is not a virtual base class of an abstract
4699       //   class, then [...] the entity is default-initialized.
4700       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
4701       CXXCtorInitializer *CXXBaseInit;
4702       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4703                                        &VBase, IsInheritedVirtualBase,
4704                                        CXXBaseInit)) {
4705         HadError = true;
4706         continue;
4707       }
4708 
4709       Info.AllToInit.push_back(CXXBaseInit);
4710     }
4711   }
4712 
4713   // Non-virtual bases.
4714   for (auto &Base : ClassDecl->bases()) {
4715     // Virtuals are in the virtual base list and already constructed.
4716     if (Base.isVirtual())
4717       continue;
4718 
4719     if (CXXCtorInitializer *Value
4720           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
4721       Info.AllToInit.push_back(Value);
4722     } else if (!AnyErrors) {
4723       CXXCtorInitializer *CXXBaseInit;
4724       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4725                                        &Base, /*IsInheritedVirtualBase=*/false,
4726                                        CXXBaseInit)) {
4727         HadError = true;
4728         continue;
4729       }
4730 
4731       Info.AllToInit.push_back(CXXBaseInit);
4732     }
4733   }
4734 
4735   // Fields.
4736   for (auto *Mem : ClassDecl->decls()) {
4737     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
4738       // C++ [class.bit]p2:
4739       //   A declaration for a bit-field that omits the identifier declares an
4740       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
4741       //   initialized.
4742       if (F->isUnnamedBitfield())
4743         continue;
4744 
4745       // If we're not generating the implicit copy/move constructor, then we'll
4746       // handle anonymous struct/union fields based on their individual
4747       // indirect fields.
4748       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4749         continue;
4750 
4751       if (CollectFieldInitializer(*this, Info, F))
4752         HadError = true;
4753       continue;
4754     }
4755 
4756     // Beyond this point, we only consider default initialization.
4757     if (Info.isImplicitCopyOrMove())
4758       continue;
4759 
4760     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4761       if (F->getType()->isIncompleteArrayType()) {
4762         assert(ClassDecl->hasFlexibleArrayMember() &&
4763                "Incomplete array type is not valid");
4764         continue;
4765       }
4766 
4767       // Initialize each field of an anonymous struct individually.
4768       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4769         HadError = true;
4770 
4771       continue;
4772     }
4773   }
4774 
4775   unsigned NumInitializers = Info.AllToInit.size();
4776   if (NumInitializers > 0) {
4777     Constructor->setNumCtorInitializers(NumInitializers);
4778     CXXCtorInitializer **baseOrMemberInitializers =
4779       new (Context) CXXCtorInitializer*[NumInitializers];
4780     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4781            NumInitializers * sizeof(CXXCtorInitializer*));
4782     Constructor->setCtorInitializers(baseOrMemberInitializers);
4783 
4784     // Constructors implicitly reference the base and member
4785     // destructors.
4786     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4787                                            Constructor->getParent());
4788   }
4789 
4790   return HadError;
4791 }
4792 
4793 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4794   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4795     const RecordDecl *RD = RT->getDecl();
4796     if (RD->isAnonymousStructOrUnion()) {
4797       for (auto *Field : RD->fields())
4798         PopulateKeysForFields(Field, IdealInits);
4799       return;
4800     }
4801   }
4802   IdealInits.push_back(Field->getCanonicalDecl());
4803 }
4804 
4805 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4806   return Context.getCanonicalType(BaseType).getTypePtr();
4807 }
4808 
4809 static const void *GetKeyForMember(ASTContext &Context,
4810                                    CXXCtorInitializer *Member) {
4811   if (!Member->isAnyMemberInitializer())
4812     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4813 
4814   return Member->getAnyMember()->getCanonicalDecl();
4815 }
4816 
4817 static void DiagnoseBaseOrMemInitializerOrder(
4818     Sema &SemaRef, const CXXConstructorDecl *Constructor,
4819     ArrayRef<CXXCtorInitializer *> Inits) {
4820   if (Constructor->getDeclContext()->isDependentContext())
4821     return;
4822 
4823   // Don't check initializers order unless the warning is enabled at the
4824   // location of at least one initializer.
4825   bool ShouldCheckOrder = false;
4826   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4827     CXXCtorInitializer *Init = Inits[InitIndex];
4828     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4829                                  Init->getSourceLocation())) {
4830       ShouldCheckOrder = true;
4831       break;
4832     }
4833   }
4834   if (!ShouldCheckOrder)
4835     return;
4836 
4837   // Build the list of bases and members in the order that they'll
4838   // actually be initialized.  The explicit initializers should be in
4839   // this same order but may be missing things.
4840   SmallVector<const void*, 32> IdealInitKeys;
4841 
4842   const CXXRecordDecl *ClassDecl = Constructor->getParent();
4843 
4844   // 1. Virtual bases.
4845   for (const auto &VBase : ClassDecl->vbases())
4846     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4847 
4848   // 2. Non-virtual bases.
4849   for (const auto &Base : ClassDecl->bases()) {
4850     if (Base.isVirtual())
4851       continue;
4852     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4853   }
4854 
4855   // 3. Direct fields.
4856   for (auto *Field : ClassDecl->fields()) {
4857     if (Field->isUnnamedBitfield())
4858       continue;
4859 
4860     PopulateKeysForFields(Field, IdealInitKeys);
4861   }
4862 
4863   unsigned NumIdealInits = IdealInitKeys.size();
4864   unsigned IdealIndex = 0;
4865 
4866   CXXCtorInitializer *PrevInit = nullptr;
4867   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4868     CXXCtorInitializer *Init = Inits[InitIndex];
4869     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4870 
4871     // Scan forward to try to find this initializer in the idealized
4872     // initializers list.
4873     for (; IdealIndex != NumIdealInits; ++IdealIndex)
4874       if (InitKey == IdealInitKeys[IdealIndex])
4875         break;
4876 
4877     // If we didn't find this initializer, it must be because we
4878     // scanned past it on a previous iteration.  That can only
4879     // happen if we're out of order;  emit a warning.
4880     if (IdealIndex == NumIdealInits && PrevInit) {
4881       Sema::SemaDiagnosticBuilder D =
4882         SemaRef.Diag(PrevInit->getSourceLocation(),
4883                      diag::warn_initializer_out_of_order);
4884 
4885       if (PrevInit->isAnyMemberInitializer())
4886         D << 0 << PrevInit->getAnyMember()->getDeclName();
4887       else
4888         D << 1 << PrevInit->getTypeSourceInfo()->getType();
4889 
4890       if (Init->isAnyMemberInitializer())
4891         D << 0 << Init->getAnyMember()->getDeclName();
4892       else
4893         D << 1 << Init->getTypeSourceInfo()->getType();
4894 
4895       // Move back to the initializer's location in the ideal list.
4896       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4897         if (InitKey == IdealInitKeys[IdealIndex])
4898           break;
4899 
4900       assert(IdealIndex < NumIdealInits &&
4901              "initializer not found in initializer list");
4902     }
4903 
4904     PrevInit = Init;
4905   }
4906 }
4907 
4908 namespace {
4909 bool CheckRedundantInit(Sema &S,
4910                         CXXCtorInitializer *Init,
4911                         CXXCtorInitializer *&PrevInit) {
4912   if (!PrevInit) {
4913     PrevInit = Init;
4914     return false;
4915   }
4916 
4917   if (FieldDecl *Field = Init->getAnyMember())
4918     S.Diag(Init->getSourceLocation(),
4919            diag::err_multiple_mem_initialization)
4920       << Field->getDeclName()
4921       << Init->getSourceRange();
4922   else {
4923     const Type *BaseClass = Init->getBaseClass();
4924     assert(BaseClass && "neither field nor base");
4925     S.Diag(Init->getSourceLocation(),
4926            diag::err_multiple_base_initialization)
4927       << QualType(BaseClass, 0)
4928       << Init->getSourceRange();
4929   }
4930   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4931     << 0 << PrevInit->getSourceRange();
4932 
4933   return true;
4934 }
4935 
4936 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
4937 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4938 
4939 bool CheckRedundantUnionInit(Sema &S,
4940                              CXXCtorInitializer *Init,
4941                              RedundantUnionMap &Unions) {
4942   FieldDecl *Field = Init->getAnyMember();
4943   RecordDecl *Parent = Field->getParent();
4944   NamedDecl *Child = Field;
4945 
4946   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
4947     if (Parent->isUnion()) {
4948       UnionEntry &En = Unions[Parent];
4949       if (En.first && En.first != Child) {
4950         S.Diag(Init->getSourceLocation(),
4951                diag::err_multiple_mem_union_initialization)
4952           << Field->getDeclName()
4953           << Init->getSourceRange();
4954         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4955           << 0 << En.second->getSourceRange();
4956         return true;
4957       }
4958       if (!En.first) {
4959         En.first = Child;
4960         En.second = Init;
4961       }
4962       if (!Parent->isAnonymousStructOrUnion())
4963         return false;
4964     }
4965 
4966     Child = Parent;
4967     Parent = cast<RecordDecl>(Parent->getDeclContext());
4968   }
4969 
4970   return false;
4971 }
4972 }
4973 
4974 /// ActOnMemInitializers - Handle the member initializers for a constructor.
4975 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
4976                                 SourceLocation ColonLoc,
4977                                 ArrayRef<CXXCtorInitializer*> MemInits,
4978                                 bool AnyErrors) {
4979   if (!ConstructorDecl)
4980     return;
4981 
4982   AdjustDeclIfTemplate(ConstructorDecl);
4983 
4984   CXXConstructorDecl *Constructor
4985     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
4986 
4987   if (!Constructor) {
4988     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4989     return;
4990   }
4991 
4992   // Mapping for the duplicate initializers check.
4993   // For member initializers, this is keyed with a FieldDecl*.
4994   // For base initializers, this is keyed with a Type*.
4995   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
4996 
4997   // Mapping for the inconsistent anonymous-union initializers check.
4998   RedundantUnionMap MemberUnions;
4999 
5000   bool HadError = false;
5001   for (unsigned i = 0; i < MemInits.size(); i++) {
5002     CXXCtorInitializer *Init = MemInits[i];
5003 
5004     // Set the source order index.
5005     Init->setSourceOrder(i);
5006 
5007     if (Init->isAnyMemberInitializer()) {
5008       const void *Key = GetKeyForMember(Context, Init);
5009       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5010           CheckRedundantUnionInit(*this, Init, MemberUnions))
5011         HadError = true;
5012     } else if (Init->isBaseInitializer()) {
5013       const void *Key = GetKeyForMember(Context, Init);
5014       if (CheckRedundantInit(*this, Init, Members[Key]))
5015         HadError = true;
5016     } else {
5017       assert(Init->isDelegatingInitializer());
5018       // This must be the only initializer
5019       if (MemInits.size() != 1) {
5020         Diag(Init->getSourceLocation(),
5021              diag::err_delegating_initializer_alone)
5022           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5023         // We will treat this as being the only initializer.
5024       }
5025       SetDelegatingInitializer(Constructor, MemInits[i]);
5026       // Return immediately as the initializer is set.
5027       return;
5028     }
5029   }
5030 
5031   if (HadError)
5032     return;
5033 
5034   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5035 
5036   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5037 
5038   DiagnoseUninitializedFields(*this, Constructor);
5039 }
5040 
5041 void
5042 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5043                                              CXXRecordDecl *ClassDecl) {
5044   // Ignore dependent contexts. Also ignore unions, since their members never
5045   // have destructors implicitly called.
5046   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5047     return;
5048 
5049   // FIXME: all the access-control diagnostics are positioned on the
5050   // field/base declaration.  That's probably good; that said, the
5051   // user might reasonably want to know why the destructor is being
5052   // emitted, and we currently don't say.
5053 
5054   // Non-static data members.
5055   for (auto *Field : ClassDecl->fields()) {
5056     if (Field->isInvalidDecl())
5057       continue;
5058 
5059     // Don't destroy incomplete or zero-length arrays.
5060     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5061       continue;
5062 
5063     QualType FieldType = Context.getBaseElementType(Field->getType());
5064 
5065     const RecordType* RT = FieldType->getAs<RecordType>();
5066     if (!RT)
5067       continue;
5068 
5069     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5070     if (FieldClassDecl->isInvalidDecl())
5071       continue;
5072     if (FieldClassDecl->hasIrrelevantDestructor())
5073       continue;
5074     // The destructor for an implicit anonymous union member is never invoked.
5075     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5076       continue;
5077 
5078     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5079     assert(Dtor && "No dtor found for FieldClassDecl!");
5080     CheckDestructorAccess(Field->getLocation(), Dtor,
5081                           PDiag(diag::err_access_dtor_field)
5082                             << Field->getDeclName()
5083                             << FieldType);
5084 
5085     MarkFunctionReferenced(Location, Dtor);
5086     DiagnoseUseOfDecl(Dtor, Location);
5087   }
5088 
5089   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5090 
5091   // Bases.
5092   for (const auto &Base : ClassDecl->bases()) {
5093     // Bases are always records in a well-formed non-dependent class.
5094     const RecordType *RT = Base.getType()->getAs<RecordType>();
5095 
5096     // Remember direct virtual bases.
5097     if (Base.isVirtual())
5098       DirectVirtualBases.insert(RT);
5099 
5100     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5101     // If our base class is invalid, we probably can't get its dtor anyway.
5102     if (BaseClassDecl->isInvalidDecl())
5103       continue;
5104     if (BaseClassDecl->hasIrrelevantDestructor())
5105       continue;
5106 
5107     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5108     assert(Dtor && "No dtor found for BaseClassDecl!");
5109 
5110     // FIXME: caret should be on the start of the class name
5111     CheckDestructorAccess(Base.getLocStart(), Dtor,
5112                           PDiag(diag::err_access_dtor_base)
5113                             << Base.getType()
5114                             << Base.getSourceRange(),
5115                           Context.getTypeDeclType(ClassDecl));
5116 
5117     MarkFunctionReferenced(Location, Dtor);
5118     DiagnoseUseOfDecl(Dtor, Location);
5119   }
5120 
5121   // Virtual bases.
5122   for (const auto &VBase : ClassDecl->vbases()) {
5123     // Bases are always records in a well-formed non-dependent class.
5124     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5125 
5126     // Ignore direct virtual bases.
5127     if (DirectVirtualBases.count(RT))
5128       continue;
5129 
5130     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5131     // If our base class is invalid, we probably can't get its dtor anyway.
5132     if (BaseClassDecl->isInvalidDecl())
5133       continue;
5134     if (BaseClassDecl->hasIrrelevantDestructor())
5135       continue;
5136 
5137     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5138     assert(Dtor && "No dtor found for BaseClassDecl!");
5139     if (CheckDestructorAccess(
5140             ClassDecl->getLocation(), Dtor,
5141             PDiag(diag::err_access_dtor_vbase)
5142                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5143             Context.getTypeDeclType(ClassDecl)) ==
5144         AR_accessible) {
5145       CheckDerivedToBaseConversion(
5146           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5147           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5148           SourceRange(), DeclarationName(), nullptr);
5149     }
5150 
5151     MarkFunctionReferenced(Location, Dtor);
5152     DiagnoseUseOfDecl(Dtor, Location);
5153   }
5154 }
5155 
5156 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5157   if (!CDtorDecl)
5158     return;
5159 
5160   if (CXXConstructorDecl *Constructor
5161       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5162     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5163     DiagnoseUninitializedFields(*this, Constructor);
5164   }
5165 }
5166 
5167 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5168   if (!getLangOpts().CPlusPlus)
5169     return false;
5170 
5171   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5172   if (!RD)
5173     return false;
5174 
5175   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5176   // class template specialization here, but doing so breaks a lot of code.
5177 
5178   // We can't answer whether something is abstract until it has a
5179   // definition. If it's currently being defined, we'll walk back
5180   // over all the declarations when we have a full definition.
5181   const CXXRecordDecl *Def = RD->getDefinition();
5182   if (!Def || Def->isBeingDefined())
5183     return false;
5184 
5185   return RD->isAbstract();
5186 }
5187 
5188 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5189                                   TypeDiagnoser &Diagnoser) {
5190   if (!isAbstractType(Loc, T))
5191     return false;
5192 
5193   T = Context.getBaseElementType(T);
5194   Diagnoser.diagnose(*this, Loc, T);
5195   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5196   return true;
5197 }
5198 
5199 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5200   // Check if we've already emitted the list of pure virtual functions
5201   // for this class.
5202   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5203     return;
5204 
5205   // If the diagnostic is suppressed, don't emit the notes. We're only
5206   // going to emit them once, so try to attach them to a diagnostic we're
5207   // actually going to show.
5208   if (Diags.isLastDiagnosticIgnored())
5209     return;
5210 
5211   CXXFinalOverriderMap FinalOverriders;
5212   RD->getFinalOverriders(FinalOverriders);
5213 
5214   // Keep a set of seen pure methods so we won't diagnose the same method
5215   // more than once.
5216   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5217 
5218   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5219                                    MEnd = FinalOverriders.end();
5220        M != MEnd;
5221        ++M) {
5222     for (OverridingMethods::iterator SO = M->second.begin(),
5223                                   SOEnd = M->second.end();
5224          SO != SOEnd; ++SO) {
5225       // C++ [class.abstract]p4:
5226       //   A class is abstract if it contains or inherits at least one
5227       //   pure virtual function for which the final overrider is pure
5228       //   virtual.
5229 
5230       //
5231       if (SO->second.size() != 1)
5232         continue;
5233 
5234       if (!SO->second.front().Method->isPure())
5235         continue;
5236 
5237       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5238         continue;
5239 
5240       Diag(SO->second.front().Method->getLocation(),
5241            diag::note_pure_virtual_function)
5242         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5243     }
5244   }
5245 
5246   if (!PureVirtualClassDiagSet)
5247     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5248   PureVirtualClassDiagSet->insert(RD);
5249 }
5250 
5251 namespace {
5252 struct AbstractUsageInfo {
5253   Sema &S;
5254   CXXRecordDecl *Record;
5255   CanQualType AbstractType;
5256   bool Invalid;
5257 
5258   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5259     : S(S), Record(Record),
5260       AbstractType(S.Context.getCanonicalType(
5261                    S.Context.getTypeDeclType(Record))),
5262       Invalid(false) {}
5263 
5264   void DiagnoseAbstractType() {
5265     if (Invalid) return;
5266     S.DiagnoseAbstractType(Record);
5267     Invalid = true;
5268   }
5269 
5270   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5271 };
5272 
5273 struct CheckAbstractUsage {
5274   AbstractUsageInfo &Info;
5275   const NamedDecl *Ctx;
5276 
5277   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5278     : Info(Info), Ctx(Ctx) {}
5279 
5280   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5281     switch (TL.getTypeLocClass()) {
5282 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5283 #define TYPELOC(CLASS, PARENT) \
5284     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5285 #include "clang/AST/TypeLocNodes.def"
5286     }
5287   }
5288 
5289   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5290     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5291     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5292       if (!TL.getParam(I))
5293         continue;
5294 
5295       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5296       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5297     }
5298   }
5299 
5300   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5301     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5302   }
5303 
5304   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5305     // Visit the type parameters from a permissive context.
5306     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5307       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5308       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5309         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5310           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5311       // TODO: other template argument types?
5312     }
5313   }
5314 
5315   // Visit pointee types from a permissive context.
5316 #define CheckPolymorphic(Type) \
5317   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5318     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5319   }
5320   CheckPolymorphic(PointerTypeLoc)
5321   CheckPolymorphic(ReferenceTypeLoc)
5322   CheckPolymorphic(MemberPointerTypeLoc)
5323   CheckPolymorphic(BlockPointerTypeLoc)
5324   CheckPolymorphic(AtomicTypeLoc)
5325 
5326   /// Handle all the types we haven't given a more specific
5327   /// implementation for above.
5328   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5329     // Every other kind of type that we haven't called out already
5330     // that has an inner type is either (1) sugar or (2) contains that
5331     // inner type in some way as a subobject.
5332     if (TypeLoc Next = TL.getNextTypeLoc())
5333       return Visit(Next, Sel);
5334 
5335     // If there's no inner type and we're in a permissive context,
5336     // don't diagnose.
5337     if (Sel == Sema::AbstractNone) return;
5338 
5339     // Check whether the type matches the abstract type.
5340     QualType T = TL.getType();
5341     if (T->isArrayType()) {
5342       Sel = Sema::AbstractArrayType;
5343       T = Info.S.Context.getBaseElementType(T);
5344     }
5345     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5346     if (CT != Info.AbstractType) return;
5347 
5348     // It matched; do some magic.
5349     if (Sel == Sema::AbstractArrayType) {
5350       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5351         << T << TL.getSourceRange();
5352     } else {
5353       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5354         << Sel << T << TL.getSourceRange();
5355     }
5356     Info.DiagnoseAbstractType();
5357   }
5358 };
5359 
5360 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5361                                   Sema::AbstractDiagSelID Sel) {
5362   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5363 }
5364 
5365 }
5366 
5367 /// Check for invalid uses of an abstract type in a method declaration.
5368 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5369                                     CXXMethodDecl *MD) {
5370   // No need to do the check on definitions, which require that
5371   // the return/param types be complete.
5372   if (MD->doesThisDeclarationHaveABody())
5373     return;
5374 
5375   // For safety's sake, just ignore it if we don't have type source
5376   // information.  This should never happen for non-implicit methods,
5377   // but...
5378   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5379     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5380 }
5381 
5382 /// Check for invalid uses of an abstract type within a class definition.
5383 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5384                                     CXXRecordDecl *RD) {
5385   for (auto *D : RD->decls()) {
5386     if (D->isImplicit()) continue;
5387 
5388     // Methods and method templates.
5389     if (isa<CXXMethodDecl>(D)) {
5390       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5391     } else if (isa<FunctionTemplateDecl>(D)) {
5392       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5393       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5394 
5395     // Fields and static variables.
5396     } else if (isa<FieldDecl>(D)) {
5397       FieldDecl *FD = cast<FieldDecl>(D);
5398       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5399         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5400     } else if (isa<VarDecl>(D)) {
5401       VarDecl *VD = cast<VarDecl>(D);
5402       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5403         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5404 
5405     // Nested classes and class templates.
5406     } else if (isa<CXXRecordDecl>(D)) {
5407       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5408     } else if (isa<ClassTemplateDecl>(D)) {
5409       CheckAbstractClassUsage(Info,
5410                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5411     }
5412   }
5413 }
5414 
5415 static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) {
5416   Attr *ClassAttr = getDLLAttr(Class);
5417   if (!ClassAttr)
5418     return;
5419 
5420   assert(ClassAttr->getKind() == attr::DLLExport);
5421 
5422   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5423 
5424   if (TSK == TSK_ExplicitInstantiationDeclaration)
5425     // Don't go any further if this is just an explicit instantiation
5426     // declaration.
5427     return;
5428 
5429   for (Decl *Member : Class->decls()) {
5430     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5431     if (!MD)
5432       continue;
5433 
5434     if (Member->getAttr<DLLExportAttr>()) {
5435       if (MD->isUserProvided()) {
5436         // Instantiate non-default class member functions ...
5437 
5438         // .. except for certain kinds of template specializations.
5439         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5440           continue;
5441 
5442         S.MarkFunctionReferenced(Class->getLocation(), MD);
5443 
5444         // The function will be passed to the consumer when its definition is
5445         // encountered.
5446       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5447                  MD->isCopyAssignmentOperator() ||
5448                  MD->isMoveAssignmentOperator()) {
5449         // Synthesize and instantiate non-trivial implicit methods, explicitly
5450         // defaulted methods, and the copy and move assignment operators. The
5451         // latter are exported even if they are trivial, because the address of
5452         // an operator can be taken and should compare equal accross libraries.
5453         DiagnosticErrorTrap Trap(S.Diags);
5454         S.MarkFunctionReferenced(Class->getLocation(), MD);
5455         if (Trap.hasErrorOccurred()) {
5456           S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5457               << Class->getName() << !S.getLangOpts().CPlusPlus11;
5458           break;
5459         }
5460 
5461         // There is no later point when we will see the definition of this
5462         // function, so pass it to the consumer now.
5463         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5464       }
5465     }
5466   }
5467 }
5468 
5469 /// \brief Check class-level dllimport/dllexport attribute.
5470 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
5471   Attr *ClassAttr = getDLLAttr(Class);
5472 
5473   // MSVC inherits DLL attributes to partial class template specializations.
5474   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5475     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5476       if (Attr *TemplateAttr =
5477               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5478         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5479         A->setInherited(true);
5480         ClassAttr = A;
5481       }
5482     }
5483   }
5484 
5485   if (!ClassAttr)
5486     return;
5487 
5488   if (!Class->isExternallyVisible()) {
5489     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5490         << Class << ClassAttr;
5491     return;
5492   }
5493 
5494   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5495       !ClassAttr->isInherited()) {
5496     // Diagnose dll attributes on members of class with dll attribute.
5497     for (Decl *Member : Class->decls()) {
5498       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5499         continue;
5500       InheritableAttr *MemberAttr = getDLLAttr(Member);
5501       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5502         continue;
5503 
5504       Diag(MemberAttr->getLocation(),
5505              diag::err_attribute_dll_member_of_dll_class)
5506           << MemberAttr << ClassAttr;
5507       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5508       Member->setInvalidDecl();
5509     }
5510   }
5511 
5512   if (Class->getDescribedClassTemplate())
5513     // Don't inherit dll attribute until the template is instantiated.
5514     return;
5515 
5516   // The class is either imported or exported.
5517   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5518 
5519   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5520 
5521   // Ignore explicit dllexport on explicit class template instantiation declarations.
5522   if (ClassExported && !ClassAttr->isInherited() &&
5523       TSK == TSK_ExplicitInstantiationDeclaration) {
5524     Class->dropAttr<DLLExportAttr>();
5525     return;
5526   }
5527 
5528   // Force declaration of implicit members so they can inherit the attribute.
5529   ForceDeclarationOfImplicitMembers(Class);
5530 
5531   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5532   // seem to be true in practice?
5533 
5534   for (Decl *Member : Class->decls()) {
5535     VarDecl *VD = dyn_cast<VarDecl>(Member);
5536     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5537 
5538     // Only methods and static fields inherit the attributes.
5539     if (!VD && !MD)
5540       continue;
5541 
5542     if (MD) {
5543       // Don't process deleted methods.
5544       if (MD->isDeleted())
5545         continue;
5546 
5547       if (MD->isInlined()) {
5548         // MinGW does not import or export inline methods.
5549         if (!Context.getTargetInfo().getCXXABI().isMicrosoft())
5550           continue;
5551 
5552         // MSVC versions before 2015 don't export the move assignment operators
5553         // and move constructor, so don't attempt to import/export them if
5554         // we have a definition.
5555         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5556         if ((MD->isMoveAssignmentOperator() ||
5557              (Ctor && Ctor->isMoveConstructor())) &&
5558             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5559           continue;
5560 
5561         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5562         // operator is exported anyway.
5563         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5564             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5565           continue;
5566       }
5567     }
5568 
5569     if (!cast<NamedDecl>(Member)->isExternallyVisible())
5570       continue;
5571 
5572     if (!getDLLAttr(Member)) {
5573       auto *NewAttr =
5574           cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5575       NewAttr->setInherited(true);
5576       Member->addAttr(NewAttr);
5577     }
5578   }
5579 
5580   if (ClassExported)
5581     DelayedDllExportClasses.push_back(Class);
5582 }
5583 
5584 /// \brief Perform propagation of DLL attributes from a derived class to a
5585 /// templated base class for MS compatibility.
5586 void Sema::propagateDLLAttrToBaseClassTemplate(
5587     CXXRecordDecl *Class, Attr *ClassAttr,
5588     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5589   if (getDLLAttr(
5590           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5591     // If the base class template has a DLL attribute, don't try to change it.
5592     return;
5593   }
5594 
5595   auto TSK = BaseTemplateSpec->getSpecializationKind();
5596   if (!getDLLAttr(BaseTemplateSpec) &&
5597       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5598        TSK == TSK_ImplicitInstantiation)) {
5599     // The template hasn't been instantiated yet (or it has, but only as an
5600     // explicit instantiation declaration or implicit instantiation, which means
5601     // we haven't codegenned any members yet), so propagate the attribute.
5602     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5603     NewAttr->setInherited(true);
5604     BaseTemplateSpec->addAttr(NewAttr);
5605 
5606     // If the template is already instantiated, checkDLLAttributeRedeclaration()
5607     // needs to be run again to work see the new attribute. Otherwise this will
5608     // get run whenever the template is instantiated.
5609     if (TSK != TSK_Undeclared)
5610       checkClassLevelDLLAttribute(BaseTemplateSpec);
5611 
5612     return;
5613   }
5614 
5615   if (getDLLAttr(BaseTemplateSpec)) {
5616     // The template has already been specialized or instantiated with an
5617     // attribute, explicitly or through propagation. We should not try to change
5618     // it.
5619     return;
5620   }
5621 
5622   // The template was previously instantiated or explicitly specialized without
5623   // a dll attribute, It's too late for us to add an attribute, so warn that
5624   // this is unsupported.
5625   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5626       << BaseTemplateSpec->isExplicitSpecialization();
5627   Diag(ClassAttr->getLocation(), diag::note_attribute);
5628   if (BaseTemplateSpec->isExplicitSpecialization()) {
5629     Diag(BaseTemplateSpec->getLocation(),
5630            diag::note_template_class_explicit_specialization_was_here)
5631         << BaseTemplateSpec;
5632   } else {
5633     Diag(BaseTemplateSpec->getPointOfInstantiation(),
5634            diag::note_template_class_instantiation_was_here)
5635         << BaseTemplateSpec;
5636   }
5637 }
5638 
5639 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5640                                         SourceLocation DefaultLoc) {
5641   switch (S.getSpecialMember(MD)) {
5642   case Sema::CXXDefaultConstructor:
5643     S.DefineImplicitDefaultConstructor(DefaultLoc,
5644                                        cast<CXXConstructorDecl>(MD));
5645     break;
5646   case Sema::CXXCopyConstructor:
5647     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5648     break;
5649   case Sema::CXXCopyAssignment:
5650     S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5651     break;
5652   case Sema::CXXDestructor:
5653     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5654     break;
5655   case Sema::CXXMoveConstructor:
5656     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5657     break;
5658   case Sema::CXXMoveAssignment:
5659     S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5660     break;
5661   case Sema::CXXInvalid:
5662     llvm_unreachable("Invalid special member.");
5663   }
5664 }
5665 
5666 /// \brief Perform semantic checks on a class definition that has been
5667 /// completing, introducing implicitly-declared members, checking for
5668 /// abstract types, etc.
5669 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
5670   if (!Record)
5671     return;
5672 
5673   if (Record->isAbstract() && !Record->isInvalidDecl()) {
5674     AbstractUsageInfo Info(*this, Record);
5675     CheckAbstractClassUsage(Info, Record);
5676   }
5677 
5678   // If this is not an aggregate type and has no user-declared constructor,
5679   // complain about any non-static data members of reference or const scalar
5680   // type, since they will never get initializers.
5681   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
5682       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
5683       !Record->isLambda()) {
5684     bool Complained = false;
5685     for (const auto *F : Record->fields()) {
5686       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
5687         continue;
5688 
5689       if (F->getType()->isReferenceType() ||
5690           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
5691         if (!Complained) {
5692           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
5693             << Record->getTagKind() << Record;
5694           Complained = true;
5695         }
5696 
5697         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
5698           << F->getType()->isReferenceType()
5699           << F->getDeclName();
5700       }
5701     }
5702   }
5703 
5704   if (Record->getIdentifier()) {
5705     // C++ [class.mem]p13:
5706     //   If T is the name of a class, then each of the following shall have a
5707     //   name different from T:
5708     //     - every member of every anonymous union that is a member of class T.
5709     //
5710     // C++ [class.mem]p14:
5711     //   In addition, if class T has a user-declared constructor (12.1), every
5712     //   non-static data member of class T shall have a name different from T.
5713     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
5714     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
5715          ++I) {
5716       NamedDecl *D = *I;
5717       if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
5718           isa<IndirectFieldDecl>(D)) {
5719         Diag(D->getLocation(), diag::err_member_name_of_class)
5720           << D->getDeclName();
5721         break;
5722       }
5723     }
5724   }
5725 
5726   // Warn if the class has virtual methods but non-virtual public destructor.
5727   if (Record->isPolymorphic() && !Record->isDependentType()) {
5728     CXXDestructorDecl *dtor = Record->getDestructor();
5729     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
5730         !Record->hasAttr<FinalAttr>())
5731       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
5732            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
5733   }
5734 
5735   if (Record->isAbstract()) {
5736     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
5737       Diag(Record->getLocation(), diag::warn_abstract_final_class)
5738         << FA->isSpelledAsSealed();
5739       DiagnoseAbstractType(Record);
5740     }
5741   }
5742 
5743   bool HasMethodWithOverrideControl = false,
5744        HasOverridingMethodWithoutOverrideControl = false;
5745   if (!Record->isDependentType()) {
5746     for (auto *M : Record->methods()) {
5747       // See if a method overloads virtual methods in a base
5748       // class without overriding any.
5749       if (!M->isStatic())
5750         DiagnoseHiddenVirtualMethods(M);
5751       if (M->hasAttr<OverrideAttr>())
5752         HasMethodWithOverrideControl = true;
5753       else if (M->size_overridden_methods() > 0)
5754         HasOverridingMethodWithoutOverrideControl = true;
5755       // Check whether the explicitly-defaulted special members are valid.
5756       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
5757         CheckExplicitlyDefaultedSpecialMember(M);
5758 
5759       // For an explicitly defaulted or deleted special member, we defer
5760       // determining triviality until the class is complete. That time is now!
5761       CXXSpecialMember CSM = getSpecialMember(M);
5762       if (!M->isImplicit() && !M->isUserProvided()) {
5763         if (CSM != CXXInvalid) {
5764           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
5765 
5766           // Inform the class that we've finished declaring this member.
5767           Record->finishedDefaultedOrDeletedMember(M);
5768         }
5769       }
5770 
5771       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
5772           M->hasAttr<DLLExportAttr>()) {
5773         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5774             M->isTrivial() &&
5775             (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
5776              CSM == CXXDestructor))
5777           M->dropAttr<DLLExportAttr>();
5778 
5779         if (M->hasAttr<DLLExportAttr>()) {
5780           DefineImplicitSpecialMember(*this, M, M->getLocation());
5781           ActOnFinishInlineFunctionDef(M);
5782         }
5783       }
5784     }
5785   }
5786 
5787   if (HasMethodWithOverrideControl &&
5788       HasOverridingMethodWithoutOverrideControl) {
5789     // At least one method has the 'override' control declared.
5790     // Diagnose all other overridden methods which do not have 'override' specified on them.
5791     for (auto *M : Record->methods())
5792       DiagnoseAbsenceOfOverrideControl(M);
5793   }
5794 
5795   // ms_struct is a request to use the same ABI rules as MSVC.  Check
5796   // whether this class uses any C++ features that are implemented
5797   // completely differently in MSVC, and if so, emit a diagnostic.
5798   // That diagnostic defaults to an error, but we allow projects to
5799   // map it down to a warning (or ignore it).  It's a fairly common
5800   // practice among users of the ms_struct pragma to mass-annotate
5801   // headers, sweeping up a bunch of types that the project doesn't
5802   // really rely on MSVC-compatible layout for.  We must therefore
5803   // support "ms_struct except for C++ stuff" as a secondary ABI.
5804   if (Record->isMsStruct(Context) &&
5805       (Record->isPolymorphic() || Record->getNumBases())) {
5806     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
5807   }
5808 
5809   checkClassLevelDLLAttribute(Record);
5810 }
5811 
5812 /// Look up the special member function that would be called by a special
5813 /// member function for a subobject of class type.
5814 ///
5815 /// \param Class The class type of the subobject.
5816 /// \param CSM The kind of special member function.
5817 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
5818 /// \param ConstRHS True if this is a copy operation with a const object
5819 ///        on its RHS, that is, if the argument to the outer special member
5820 ///        function is 'const' and this is not a field marked 'mutable'.
5821 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
5822     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
5823     unsigned FieldQuals, bool ConstRHS) {
5824   unsigned LHSQuals = 0;
5825   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
5826     LHSQuals = FieldQuals;
5827 
5828   unsigned RHSQuals = FieldQuals;
5829   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
5830     RHSQuals = 0;
5831   else if (ConstRHS)
5832     RHSQuals |= Qualifiers::Const;
5833 
5834   return S.LookupSpecialMember(Class, CSM,
5835                                RHSQuals & Qualifiers::Const,
5836                                RHSQuals & Qualifiers::Volatile,
5837                                false,
5838                                LHSQuals & Qualifiers::Const,
5839                                LHSQuals & Qualifiers::Volatile);
5840 }
5841 
5842 class Sema::InheritedConstructorInfo {
5843   Sema &S;
5844   SourceLocation UseLoc;
5845 
5846   /// A mapping from the base classes through which the constructor was
5847   /// inherited to the using shadow declaration in that base class (or a null
5848   /// pointer if the constructor was declared in that base class).
5849   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
5850       InheritedFromBases;
5851 
5852 public:
5853   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
5854                            ConstructorUsingShadowDecl *Shadow)
5855       : S(S), UseLoc(UseLoc) {
5856     bool DiagnosedMultipleConstructedBases = false;
5857     CXXRecordDecl *ConstructedBase = nullptr;
5858     UsingDecl *ConstructedBaseUsing = nullptr;
5859 
5860     // Find the set of such base class subobjects and check that there's a
5861     // unique constructed subobject.
5862     for (auto *D : Shadow->redecls()) {
5863       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
5864       auto *DNominatedBase = DShadow->getNominatedBaseClass();
5865       auto *DConstructedBase = DShadow->getConstructedBaseClass();
5866 
5867       InheritedFromBases.insert(
5868           std::make_pair(DNominatedBase->getCanonicalDecl(),
5869                          DShadow->getNominatedBaseClassShadowDecl()));
5870       if (DShadow->constructsVirtualBase())
5871         InheritedFromBases.insert(
5872             std::make_pair(DConstructedBase->getCanonicalDecl(),
5873                            DShadow->getConstructedBaseClassShadowDecl()));
5874       else
5875         assert(DNominatedBase == DConstructedBase);
5876 
5877       // [class.inhctor.init]p2:
5878       //   If the constructor was inherited from multiple base class subobjects
5879       //   of type B, the program is ill-formed.
5880       if (!ConstructedBase) {
5881         ConstructedBase = DConstructedBase;
5882         ConstructedBaseUsing = D->getUsingDecl();
5883       } else if (ConstructedBase != DConstructedBase &&
5884                  !Shadow->isInvalidDecl()) {
5885         if (!DiagnosedMultipleConstructedBases) {
5886           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
5887               << Shadow->getTargetDecl();
5888           S.Diag(ConstructedBaseUsing->getLocation(),
5889                diag::note_ambiguous_inherited_constructor_using)
5890               << ConstructedBase;
5891           DiagnosedMultipleConstructedBases = true;
5892         }
5893         S.Diag(D->getUsingDecl()->getLocation(),
5894                diag::note_ambiguous_inherited_constructor_using)
5895             << DConstructedBase;
5896       }
5897     }
5898 
5899     if (DiagnosedMultipleConstructedBases)
5900       Shadow->setInvalidDecl();
5901   }
5902 
5903   /// Find the constructor to use for inherited construction of a base class,
5904   /// and whether that base class constructor inherits the constructor from a
5905   /// virtual base class (in which case it won't actually invoke it).
5906   std::pair<CXXConstructorDecl *, bool>
5907   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
5908     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
5909     if (It == InheritedFromBases.end())
5910       return std::make_pair(nullptr, false);
5911 
5912     // This is an intermediary class.
5913     if (It->second)
5914       return std::make_pair(
5915           S.findInheritingConstructor(UseLoc, Ctor, It->second),
5916           It->second->constructsVirtualBase());
5917 
5918     // This is the base class from which the constructor was inherited.
5919     return std::make_pair(Ctor, false);
5920   }
5921 };
5922 
5923 /// Is the special member function which would be selected to perform the
5924 /// specified operation on the specified class type a constexpr constructor?
5925 static bool
5926 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5927                          Sema::CXXSpecialMember CSM, unsigned Quals,
5928                          bool ConstRHS,
5929                          CXXConstructorDecl *InheritedCtor = nullptr,
5930                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
5931   // If we're inheriting a constructor, see if we need to call it for this base
5932   // class.
5933   if (InheritedCtor) {
5934     assert(CSM == Sema::CXXDefaultConstructor);
5935     auto BaseCtor =
5936         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
5937     if (BaseCtor)
5938       return BaseCtor->isConstexpr();
5939   }
5940 
5941   if (CSM == Sema::CXXDefaultConstructor)
5942     return ClassDecl->hasConstexprDefaultConstructor();
5943 
5944   Sema::SpecialMemberOverloadResult *SMOR =
5945       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
5946   if (!SMOR || !SMOR->getMethod())
5947     // A constructor we wouldn't select can't be "involved in initializing"
5948     // anything.
5949     return true;
5950   return SMOR->getMethod()->isConstexpr();
5951 }
5952 
5953 /// Determine whether the specified special member function would be constexpr
5954 /// if it were implicitly defined.
5955 static bool defaultedSpecialMemberIsConstexpr(
5956     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
5957     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
5958     Sema::InheritedConstructorInfo *Inherited = nullptr) {
5959   if (!S.getLangOpts().CPlusPlus11)
5960     return false;
5961 
5962   // C++11 [dcl.constexpr]p4:
5963   // In the definition of a constexpr constructor [...]
5964   bool Ctor = true;
5965   switch (CSM) {
5966   case Sema::CXXDefaultConstructor:
5967     if (Inherited)
5968       break;
5969     // Since default constructor lookup is essentially trivial (and cannot
5970     // involve, for instance, template instantiation), we compute whether a
5971     // defaulted default constructor is constexpr directly within CXXRecordDecl.
5972     //
5973     // This is important for performance; we need to know whether the default
5974     // constructor is constexpr to determine whether the type is a literal type.
5975     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
5976 
5977   case Sema::CXXCopyConstructor:
5978   case Sema::CXXMoveConstructor:
5979     // For copy or move constructors, we need to perform overload resolution.
5980     break;
5981 
5982   case Sema::CXXCopyAssignment:
5983   case Sema::CXXMoveAssignment:
5984     if (!S.getLangOpts().CPlusPlus14)
5985       return false;
5986     // In C++1y, we need to perform overload resolution.
5987     Ctor = false;
5988     break;
5989 
5990   case Sema::CXXDestructor:
5991   case Sema::CXXInvalid:
5992     return false;
5993   }
5994 
5995   //   -- if the class is a non-empty union, or for each non-empty anonymous
5996   //      union member of a non-union class, exactly one non-static data member
5997   //      shall be initialized; [DR1359]
5998   //
5999   // If we squint, this is guaranteed, since exactly one non-static data member
6000   // will be initialized (if the constructor isn't deleted), we just don't know
6001   // which one.
6002   if (Ctor && ClassDecl->isUnion())
6003     return CSM == Sema::CXXDefaultConstructor
6004                ? ClassDecl->hasInClassInitializer() ||
6005                      !ClassDecl->hasVariantMembers()
6006                : true;
6007 
6008   //   -- the class shall not have any virtual base classes;
6009   if (Ctor && ClassDecl->getNumVBases())
6010     return false;
6011 
6012   // C++1y [class.copy]p26:
6013   //   -- [the class] is a literal type, and
6014   if (!Ctor && !ClassDecl->isLiteral())
6015     return false;
6016 
6017   //   -- every constructor involved in initializing [...] base class
6018   //      sub-objects shall be a constexpr constructor;
6019   //   -- the assignment operator selected to copy/move each direct base
6020   //      class is a constexpr function, and
6021   for (const auto &B : ClassDecl->bases()) {
6022     const RecordType *BaseType = B.getType()->getAs<RecordType>();
6023     if (!BaseType) continue;
6024 
6025     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6026     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6027                                   InheritedCtor, Inherited))
6028       return false;
6029   }
6030 
6031   //   -- every constructor involved in initializing non-static data members
6032   //      [...] shall be a constexpr constructor;
6033   //   -- every non-static data member and base class sub-object shall be
6034   //      initialized
6035   //   -- for each non-static data member of X that is of class type (or array
6036   //      thereof), the assignment operator selected to copy/move that member is
6037   //      a constexpr function
6038   for (const auto *F : ClassDecl->fields()) {
6039     if (F->isInvalidDecl())
6040       continue;
6041     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6042       continue;
6043     QualType BaseType = S.Context.getBaseElementType(F->getType());
6044     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
6045       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6046       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6047                                     BaseType.getCVRQualifiers(),
6048                                     ConstArg && !F->isMutable()))
6049         return false;
6050     } else if (CSM == Sema::CXXDefaultConstructor) {
6051       return false;
6052     }
6053   }
6054 
6055   // All OK, it's constexpr!
6056   return true;
6057 }
6058 
6059 static Sema::ImplicitExceptionSpecification
6060 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6061   switch (S.getSpecialMember(MD)) {
6062   case Sema::CXXDefaultConstructor:
6063     return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
6064   case Sema::CXXCopyConstructor:
6065     return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
6066   case Sema::CXXCopyAssignment:
6067     return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
6068   case Sema::CXXMoveConstructor:
6069     return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
6070   case Sema::CXXMoveAssignment:
6071     return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
6072   case Sema::CXXDestructor:
6073     return S.ComputeDefaultedDtorExceptionSpec(MD);
6074   case Sema::CXXInvalid:
6075     break;
6076   }
6077   assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
6078          "only special members have implicit exception specs");
6079   return S.ComputeInheritingCtorExceptionSpec(Loc,
6080                                               cast<CXXConstructorDecl>(MD));
6081 }
6082 
6083 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6084                                                             CXXMethodDecl *MD) {
6085   FunctionProtoType::ExtProtoInfo EPI;
6086 
6087   // Build an exception specification pointing back at this member.
6088   EPI.ExceptionSpec.Type = EST_Unevaluated;
6089   EPI.ExceptionSpec.SourceDecl = MD;
6090 
6091   // Set the calling convention to the default for C++ instance methods.
6092   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6093       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6094                                             /*IsCXXMethod=*/true));
6095   return EPI;
6096 }
6097 
6098 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6099   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6100   if (FPT->getExceptionSpecType() != EST_Unevaluated)
6101     return;
6102 
6103   // Evaluate the exception specification.
6104   auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
6105 
6106   // Update the type of the special member to use it.
6107   UpdateExceptionSpec(MD, ESI);
6108 
6109   // A user-provided destructor can be defined outside the class. When that
6110   // happens, be sure to update the exception specification on both
6111   // declarations.
6112   const FunctionProtoType *CanonicalFPT =
6113     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6114   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
6115     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
6116 }
6117 
6118 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6119   CXXRecordDecl *RD = MD->getParent();
6120   CXXSpecialMember CSM = getSpecialMember(MD);
6121 
6122   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6123          "not an explicitly-defaulted special member");
6124 
6125   // Whether this was the first-declared instance of the constructor.
6126   // This affects whether we implicitly add an exception spec and constexpr.
6127   bool First = MD == MD->getCanonicalDecl();
6128 
6129   bool HadError = false;
6130 
6131   // C++11 [dcl.fct.def.default]p1:
6132   //   A function that is explicitly defaulted shall
6133   //     -- be a special member function (checked elsewhere),
6134   //     -- have the same type (except for ref-qualifiers, and except that a
6135   //        copy operation can take a non-const reference) as an implicit
6136   //        declaration, and
6137   //     -- not have default arguments.
6138   unsigned ExpectedParams = 1;
6139   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6140     ExpectedParams = 0;
6141   if (MD->getNumParams() != ExpectedParams) {
6142     // This also checks for default arguments: a copy or move constructor with a
6143     // default argument is classified as a default constructor, and assignment
6144     // operations and destructors can't have default arguments.
6145     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6146       << CSM << MD->getSourceRange();
6147     HadError = true;
6148   } else if (MD->isVariadic()) {
6149     Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6150       << CSM << MD->getSourceRange();
6151     HadError = true;
6152   }
6153 
6154   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
6155 
6156   bool CanHaveConstParam = false;
6157   if (CSM == CXXCopyConstructor)
6158     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
6159   else if (CSM == CXXCopyAssignment)
6160     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
6161 
6162   QualType ReturnType = Context.VoidTy;
6163   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6164     // Check for return type matching.
6165     ReturnType = Type->getReturnType();
6166     QualType ExpectedReturnType =
6167         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
6168     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6169       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6170         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6171       HadError = true;
6172     }
6173 
6174     // A defaulted special member cannot have cv-qualifiers.
6175     if (Type->getTypeQuals()) {
6176       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
6177         << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
6178       HadError = true;
6179     }
6180   }
6181 
6182   // Check for parameter type matching.
6183   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
6184   bool HasConstParam = false;
6185   if (ExpectedParams && ArgType->isReferenceType()) {
6186     // Argument must be reference to possibly-const T.
6187     QualType ReferentType = ArgType->getPointeeType();
6188     HasConstParam = ReferentType.isConstQualified();
6189 
6190     if (ReferentType.isVolatileQualified()) {
6191       Diag(MD->getLocation(),
6192            diag::err_defaulted_special_member_volatile_param) << CSM;
6193       HadError = true;
6194     }
6195 
6196     if (HasConstParam && !CanHaveConstParam) {
6197       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6198         Diag(MD->getLocation(),
6199              diag::err_defaulted_special_member_copy_const_param)
6200           << (CSM == CXXCopyAssignment);
6201         // FIXME: Explain why this special member can't be const.
6202       } else {
6203         Diag(MD->getLocation(),
6204              diag::err_defaulted_special_member_move_const_param)
6205           << (CSM == CXXMoveAssignment);
6206       }
6207       HadError = true;
6208     }
6209   } else if (ExpectedParams) {
6210     // A copy assignment operator can take its argument by value, but a
6211     // defaulted one cannot.
6212     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
6213     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
6214     HadError = true;
6215   }
6216 
6217   // C++11 [dcl.fct.def.default]p2:
6218   //   An explicitly-defaulted function may be declared constexpr only if it
6219   //   would have been implicitly declared as constexpr,
6220   // Do not apply this rule to members of class templates, since core issue 1358
6221   // makes such functions always instantiate to constexpr functions. For
6222   // functions which cannot be constexpr (for non-constructors in C++11 and for
6223   // destructors in C++1y), this is checked elsewhere.
6224   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6225                                                      HasConstParam);
6226   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
6227                                  : isa<CXXConstructorDecl>(MD)) &&
6228       MD->isConstexpr() && !Constexpr &&
6229       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6230     Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
6231     // FIXME: Explain why the special member can't be constexpr.
6232     HadError = true;
6233   }
6234 
6235   //   and may have an explicit exception-specification only if it is compatible
6236   //   with the exception-specification on the implicit declaration.
6237   if (Type->hasExceptionSpec()) {
6238     // Delay the check if this is the first declaration of the special member,
6239     // since we may not have parsed some necessary in-class initializers yet.
6240     if (First) {
6241       // If the exception specification needs to be instantiated, do so now,
6242       // before we clobber it with an EST_Unevaluated specification below.
6243       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
6244         InstantiateExceptionSpec(MD->getLocStart(), MD);
6245         Type = MD->getType()->getAs<FunctionProtoType>();
6246       }
6247       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
6248     } else
6249       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
6250   }
6251 
6252   //   If a function is explicitly defaulted on its first declaration,
6253   if (First) {
6254     //  -- it is implicitly considered to be constexpr if the implicit
6255     //     definition would be,
6256     MD->setConstexpr(Constexpr);
6257 
6258     //  -- it is implicitly considered to have the same exception-specification
6259     //     as if it had been implicitly declared,
6260     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
6261     EPI.ExceptionSpec.Type = EST_Unevaluated;
6262     EPI.ExceptionSpec.SourceDecl = MD;
6263     MD->setType(Context.getFunctionType(ReturnType,
6264                                         llvm::makeArrayRef(&ArgType,
6265                                                            ExpectedParams),
6266                                         EPI));
6267   }
6268 
6269   if (ShouldDeleteSpecialMember(MD, CSM)) {
6270     if (First) {
6271       SetDeclDeleted(MD, MD->getLocation());
6272     } else {
6273       // C++11 [dcl.fct.def.default]p4:
6274       //   [For a] user-provided explicitly-defaulted function [...] if such a
6275       //   function is implicitly defined as deleted, the program is ill-formed.
6276       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
6277       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6278       HadError = true;
6279     }
6280   }
6281 
6282   if (HadError)
6283     MD->setInvalidDecl();
6284 }
6285 
6286 /// Check whether the exception specification provided for an
6287 /// explicitly-defaulted special member matches the exception specification
6288 /// that would have been generated for an implicit special member, per
6289 /// C++11 [dcl.fct.def.default]p2.
6290 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
6291     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
6292   // If the exception specification was explicitly specified but hadn't been
6293   // parsed when the method was defaulted, grab it now.
6294   if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
6295     SpecifiedType =
6296         MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
6297 
6298   // Compute the implicit exception specification.
6299   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6300                                                        /*IsCXXMethod=*/true);
6301   FunctionProtoType::ExtProtoInfo EPI(CC);
6302   EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
6303                           .getExceptionSpec();
6304   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
6305     Context.getFunctionType(Context.VoidTy, None, EPI));
6306 
6307   // Ensure that it matches.
6308   CheckEquivalentExceptionSpec(
6309     PDiag(diag::err_incorrect_defaulted_exception_spec)
6310       << getSpecialMember(MD), PDiag(),
6311     ImplicitType, SourceLocation(),
6312     SpecifiedType, MD->getLocation());
6313 }
6314 
6315 void Sema::CheckDelayedMemberExceptionSpecs() {
6316   decltype(DelayedExceptionSpecChecks) Checks;
6317   decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
6318 
6319   std::swap(Checks, DelayedExceptionSpecChecks);
6320   std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
6321 
6322   // Perform any deferred checking of exception specifications for virtual
6323   // destructors.
6324   for (auto &Check : Checks)
6325     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
6326 
6327   // Check that any explicitly-defaulted methods have exception specifications
6328   // compatible with their implicit exception specifications.
6329   for (auto &Spec : Specs)
6330     CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
6331 }
6332 
6333 namespace {
6334 struct SpecialMemberDeletionInfo {
6335   Sema &S;
6336   CXXMethodDecl *MD;
6337   Sema::CXXSpecialMember CSM;
6338   Sema::InheritedConstructorInfo *ICI;
6339   bool Diagnose;
6340 
6341   // Properties of the special member, computed for convenience.
6342   bool IsConstructor, IsAssignment, IsMove, ConstArg;
6343   SourceLocation Loc;
6344 
6345   bool AllFieldsAreConst;
6346 
6347   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
6348                             Sema::CXXSpecialMember CSM,
6349                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
6350       : S(S), MD(MD), CSM(CSM), ICI(ICI), Diagnose(Diagnose),
6351         IsConstructor(false), IsAssignment(false), IsMove(false),
6352         ConstArg(false), Loc(MD->getLocation()), AllFieldsAreConst(true) {
6353     switch (CSM) {
6354       case Sema::CXXDefaultConstructor:
6355       case Sema::CXXCopyConstructor:
6356         IsConstructor = true;
6357         break;
6358       case Sema::CXXMoveConstructor:
6359         IsConstructor = true;
6360         IsMove = true;
6361         break;
6362       case Sema::CXXCopyAssignment:
6363         IsAssignment = true;
6364         break;
6365       case Sema::CXXMoveAssignment:
6366         IsAssignment = true;
6367         IsMove = true;
6368         break;
6369       case Sema::CXXDestructor:
6370         break;
6371       case Sema::CXXInvalid:
6372         llvm_unreachable("invalid special member kind");
6373     }
6374 
6375     if (MD->getNumParams()) {
6376       if (const ReferenceType *RT =
6377               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6378         ConstArg = RT->getPointeeType().isConstQualified();
6379     }
6380   }
6381 
6382   bool inUnion() const { return MD->getParent()->isUnion(); }
6383 
6384   Sema::CXXSpecialMember getEffectiveCSM() {
6385     return ICI ? Sema::CXXInvalid : CSM;
6386   }
6387 
6388   /// Look up the corresponding special member in the given class.
6389   Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
6390                                               unsigned Quals, bool IsMutable) {
6391     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6392                                        ConstArg && !IsMutable);
6393   }
6394 
6395   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6396 
6397   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
6398   bool shouldDeleteForField(FieldDecl *FD);
6399   bool shouldDeleteForAllConstMembers();
6400 
6401   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6402                                      unsigned Quals);
6403   bool shouldDeleteForSubobjectCall(Subobject Subobj,
6404                                     Sema::SpecialMemberOverloadResult *SMOR,
6405                                     bool IsDtorCallInCtor);
6406 
6407   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
6408 };
6409 }
6410 
6411 /// Is the given special member inaccessible when used on the given
6412 /// sub-object.
6413 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6414                                              CXXMethodDecl *target) {
6415   /// If we're operating on a base class, the object type is the
6416   /// type of this special member.
6417   QualType objectTy;
6418   AccessSpecifier access = target->getAccess();
6419   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6420     objectTy = S.Context.getTypeDeclType(MD->getParent());
6421     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6422 
6423   // If we're operating on a field, the object type is the type of the field.
6424   } else {
6425     objectTy = S.Context.getTypeDeclType(target->getParent());
6426   }
6427 
6428   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6429 }
6430 
6431 /// Check whether we should delete a special member due to the implicit
6432 /// definition containing a call to a special member of a subobject.
6433 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
6434     Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
6435     bool IsDtorCallInCtor) {
6436   CXXMethodDecl *Decl = SMOR->getMethod();
6437   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6438 
6439   int DiagKind = -1;
6440 
6441   if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
6442     DiagKind = !Decl ? 0 : 1;
6443   else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6444     DiagKind = 2;
6445   else if (!isAccessible(Subobj, Decl))
6446     DiagKind = 3;
6447   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6448            !Decl->isTrivial()) {
6449     // A member of a union must have a trivial corresponding special member.
6450     // As a weird special case, a destructor call from a union's constructor
6451     // must be accessible and non-deleted, but need not be trivial. Such a
6452     // destructor is never actually called, but is semantically checked as
6453     // if it were.
6454     DiagKind = 4;
6455   }
6456 
6457   if (DiagKind == -1)
6458     return false;
6459 
6460   if (Diagnose) {
6461     if (Field) {
6462       S.Diag(Field->getLocation(),
6463              diag::note_deleted_special_member_class_subobject)
6464         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
6465         << Field << DiagKind << IsDtorCallInCtor;
6466     } else {
6467       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6468       S.Diag(Base->getLocStart(),
6469              diag::note_deleted_special_member_class_subobject)
6470         << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6471         << Base->getType() << DiagKind << IsDtorCallInCtor;
6472     }
6473 
6474     if (DiagKind == 1)
6475       S.NoteDeletedFunction(Decl);
6476     // FIXME: Explain inaccessibility if DiagKind == 3.
6477   }
6478 
6479   return true;
6480 }
6481 
6482 /// Check whether we should delete a special member function due to having a
6483 /// direct or virtual base class or non-static data member of class type M.
6484 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
6485     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
6486   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6487   bool IsMutable = Field && Field->isMutable();
6488 
6489   // C++11 [class.ctor]p5:
6490   // -- any direct or virtual base class, or non-static data member with no
6491   //    brace-or-equal-initializer, has class type M (or array thereof) and
6492   //    either M has no default constructor or overload resolution as applied
6493   //    to M's default constructor results in an ambiguity or in a function
6494   //    that is deleted or inaccessible
6495   // C++11 [class.copy]p11, C++11 [class.copy]p23:
6496   // -- a direct or virtual base class B that cannot be copied/moved because
6497   //    overload resolution, as applied to B's corresponding special member,
6498   //    results in an ambiguity or a function that is deleted or inaccessible
6499   //    from the defaulted special member
6500   // C++11 [class.dtor]p5:
6501   // -- any direct or virtual base class [...] has a type with a destructor
6502   //    that is deleted or inaccessible
6503   if (!(CSM == Sema::CXXDefaultConstructor &&
6504         Field && Field->hasInClassInitializer()) &&
6505       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
6506                                    false))
6507     return true;
6508 
6509   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
6510   // -- any direct or virtual base class or non-static data member has a
6511   //    type with a destructor that is deleted or inaccessible
6512   if (IsConstructor) {
6513     Sema::SpecialMemberOverloadResult *SMOR =
6514         S.LookupSpecialMember(Class, Sema::CXXDestructor,
6515                               false, false, false, false, false);
6516     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
6517       return true;
6518   }
6519 
6520   return false;
6521 }
6522 
6523 /// Check whether we should delete a special member function due to the class
6524 /// having a particular direct or virtual base class.
6525 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
6526   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
6527   // If program is correct, BaseClass cannot be null, but if it is, the error
6528   // must be reported elsewhere.
6529   if (!BaseClass)
6530     return false;
6531   // If we have an inheriting constructor, check whether we're calling an
6532   // inherited constructor instead of a default constructor.
6533   if (ICI) {
6534     assert(CSM == Sema::CXXDefaultConstructor);
6535     auto *BaseCtor =
6536         ICI->findConstructorForBase(BaseClass, cast<CXXConstructorDecl>(MD)
6537                                                    ->getInheritedConstructor()
6538                                                    .getConstructor())
6539             .first;
6540     if (BaseCtor) {
6541       if (BaseCtor->isDeleted() && Diagnose) {
6542         S.Diag(Base->getLocStart(),
6543                diag::note_deleted_special_member_class_subobject)
6544           << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6545           << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false;
6546         S.NoteDeletedFunction(BaseCtor);
6547       }
6548       return BaseCtor->isDeleted();
6549     }
6550   }
6551   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
6552 }
6553 
6554 /// Check whether we should delete a special member function due to the class
6555 /// having a particular non-static data member.
6556 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
6557   QualType FieldType = S.Context.getBaseElementType(FD->getType());
6558   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
6559 
6560   if (CSM == Sema::CXXDefaultConstructor) {
6561     // For a default constructor, all references must be initialized in-class
6562     // and, if a union, it must have a non-const member.
6563     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
6564       if (Diagnose)
6565         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
6566           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
6567       return true;
6568     }
6569     // C++11 [class.ctor]p5: any non-variant non-static data member of
6570     // const-qualified type (or array thereof) with no
6571     // brace-or-equal-initializer does not have a user-provided default
6572     // constructor.
6573     if (!inUnion() && FieldType.isConstQualified() &&
6574         !FD->hasInClassInitializer() &&
6575         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
6576       if (Diagnose)
6577         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
6578           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
6579       return true;
6580     }
6581 
6582     if (inUnion() && !FieldType.isConstQualified())
6583       AllFieldsAreConst = false;
6584   } else if (CSM == Sema::CXXCopyConstructor) {
6585     // For a copy constructor, data members must not be of rvalue reference
6586     // type.
6587     if (FieldType->isRValueReferenceType()) {
6588       if (Diagnose)
6589         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
6590           << MD->getParent() << FD << FieldType;
6591       return true;
6592     }
6593   } else if (IsAssignment) {
6594     // For an assignment operator, data members must not be of reference type.
6595     if (FieldType->isReferenceType()) {
6596       if (Diagnose)
6597         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
6598           << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
6599       return true;
6600     }
6601     if (!FieldRecord && FieldType.isConstQualified()) {
6602       // C++11 [class.copy]p23:
6603       // -- a non-static data member of const non-class type (or array thereof)
6604       if (Diagnose)
6605         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
6606           << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
6607       return true;
6608     }
6609   }
6610 
6611   if (FieldRecord) {
6612     // Some additional restrictions exist on the variant members.
6613     if (!inUnion() && FieldRecord->isUnion() &&
6614         FieldRecord->isAnonymousStructOrUnion()) {
6615       bool AllVariantFieldsAreConst = true;
6616 
6617       // FIXME: Handle anonymous unions declared within anonymous unions.
6618       for (auto *UI : FieldRecord->fields()) {
6619         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
6620 
6621         if (!UnionFieldType.isConstQualified())
6622           AllVariantFieldsAreConst = false;
6623 
6624         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
6625         if (UnionFieldRecord &&
6626             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
6627                                           UnionFieldType.getCVRQualifiers()))
6628           return true;
6629       }
6630 
6631       // At least one member in each anonymous union must be non-const
6632       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
6633           !FieldRecord->field_empty()) {
6634         if (Diagnose)
6635           S.Diag(FieldRecord->getLocation(),
6636                  diag::note_deleted_default_ctor_all_const)
6637             << !!ICI << MD->getParent() << /*anonymous union*/1;
6638         return true;
6639       }
6640 
6641       // Don't check the implicit member of the anonymous union type.
6642       // This is technically non-conformant, but sanity demands it.
6643       return false;
6644     }
6645 
6646     if (shouldDeleteForClassSubobject(FieldRecord, FD,
6647                                       FieldType.getCVRQualifiers()))
6648       return true;
6649   }
6650 
6651   return false;
6652 }
6653 
6654 /// C++11 [class.ctor] p5:
6655 ///   A defaulted default constructor for a class X is defined as deleted if
6656 /// X is a union and all of its variant members are of const-qualified type.
6657 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
6658   // This is a silly definition, because it gives an empty union a deleted
6659   // default constructor. Don't do that.
6660   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
6661       !MD->getParent()->field_empty()) {
6662     if (Diagnose)
6663       S.Diag(MD->getParent()->getLocation(),
6664              diag::note_deleted_default_ctor_all_const)
6665         << !!ICI << MD->getParent() << /*not anonymous union*/0;
6666     return true;
6667   }
6668   return false;
6669 }
6670 
6671 /// Determine whether a defaulted special member function should be defined as
6672 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
6673 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
6674 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
6675                                      InheritedConstructorInfo *ICI,
6676                                      bool Diagnose) {
6677   if (MD->isInvalidDecl())
6678     return false;
6679   CXXRecordDecl *RD = MD->getParent();
6680   assert(!RD->isDependentType() && "do deletion after instantiation");
6681   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
6682     return false;
6683 
6684   // C++11 [expr.lambda.prim]p19:
6685   //   The closure type associated with a lambda-expression has a
6686   //   deleted (8.4.3) default constructor and a deleted copy
6687   //   assignment operator.
6688   if (RD->isLambda() &&
6689       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
6690     if (Diagnose)
6691       Diag(RD->getLocation(), diag::note_lambda_decl);
6692     return true;
6693   }
6694 
6695   // For an anonymous struct or union, the copy and assignment special members
6696   // will never be used, so skip the check. For an anonymous union declared at
6697   // namespace scope, the constructor and destructor are used.
6698   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
6699       RD->isAnonymousStructOrUnion())
6700     return false;
6701 
6702   // C++11 [class.copy]p7, p18:
6703   //   If the class definition declares a move constructor or move assignment
6704   //   operator, an implicitly declared copy constructor or copy assignment
6705   //   operator is defined as deleted.
6706   if (MD->isImplicit() &&
6707       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
6708     CXXMethodDecl *UserDeclaredMove = nullptr;
6709 
6710     // In Microsoft mode, a user-declared move only causes the deletion of the
6711     // corresponding copy operation, not both copy operations.
6712     if (RD->hasUserDeclaredMoveConstructor() &&
6713         (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
6714       if (!Diagnose) return true;
6715 
6716       // Find any user-declared move constructor.
6717       for (auto *I : RD->ctors()) {
6718         if (I->isMoveConstructor()) {
6719           UserDeclaredMove = I;
6720           break;
6721         }
6722       }
6723       assert(UserDeclaredMove);
6724     } else if (RD->hasUserDeclaredMoveAssignment() &&
6725                (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
6726       if (!Diagnose) return true;
6727 
6728       // Find any user-declared move assignment operator.
6729       for (auto *I : RD->methods()) {
6730         if (I->isMoveAssignmentOperator()) {
6731           UserDeclaredMove = I;
6732           break;
6733         }
6734       }
6735       assert(UserDeclaredMove);
6736     }
6737 
6738     if (UserDeclaredMove) {
6739       Diag(UserDeclaredMove->getLocation(),
6740            diag::note_deleted_copy_user_declared_move)
6741         << (CSM == CXXCopyAssignment) << RD
6742         << UserDeclaredMove->isMoveAssignmentOperator();
6743       return true;
6744     }
6745   }
6746 
6747   // Do access control from the special member function
6748   ContextRAII MethodContext(*this, MD);
6749 
6750   // C++11 [class.dtor]p5:
6751   // -- for a virtual destructor, lookup of the non-array deallocation function
6752   //    results in an ambiguity or in a function that is deleted or inaccessible
6753   if (CSM == CXXDestructor && MD->isVirtual()) {
6754     FunctionDecl *OperatorDelete = nullptr;
6755     DeclarationName Name =
6756       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6757     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
6758                                  OperatorDelete, /*Diagnose*/false)) {
6759       if (Diagnose)
6760         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
6761       return true;
6762     }
6763   }
6764 
6765   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
6766 
6767   for (auto &BI : RD->bases())
6768     if ((SMI.IsAssignment || !BI.isVirtual()) &&
6769         SMI.shouldDeleteForBase(&BI))
6770       return true;
6771 
6772   // Per DR1611, do not consider virtual bases of constructors of abstract
6773   // classes, since we are not going to construct them. For assignment
6774   // operators, we only assign (and thus only consider) direct bases.
6775   if ((!RD->isAbstract() || !SMI.IsConstructor) && !SMI.IsAssignment) {
6776     for (auto &BI : RD->vbases())
6777       if (SMI.shouldDeleteForBase(&BI))
6778         return true;
6779   }
6780 
6781   for (auto *FI : RD->fields())
6782     if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
6783         SMI.shouldDeleteForField(FI))
6784       return true;
6785 
6786   if (SMI.shouldDeleteForAllConstMembers())
6787     return true;
6788 
6789   if (getLangOpts().CUDA) {
6790     // We should delete the special member in CUDA mode if target inference
6791     // failed.
6792     return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
6793                                                    Diagnose);
6794   }
6795 
6796   return false;
6797 }
6798 
6799 /// Perform lookup for a special member of the specified kind, and determine
6800 /// whether it is trivial. If the triviality can be determined without the
6801 /// lookup, skip it. This is intended for use when determining whether a
6802 /// special member of a containing object is trivial, and thus does not ever
6803 /// perform overload resolution for default constructors.
6804 ///
6805 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
6806 /// member that was most likely to be intended to be trivial, if any.
6807 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
6808                                      Sema::CXXSpecialMember CSM, unsigned Quals,
6809                                      bool ConstRHS, CXXMethodDecl **Selected) {
6810   if (Selected)
6811     *Selected = nullptr;
6812 
6813   switch (CSM) {
6814   case Sema::CXXInvalid:
6815     llvm_unreachable("not a special member");
6816 
6817   case Sema::CXXDefaultConstructor:
6818     // C++11 [class.ctor]p5:
6819     //   A default constructor is trivial if:
6820     //    - all the [direct subobjects] have trivial default constructors
6821     //
6822     // Note, no overload resolution is performed in this case.
6823     if (RD->hasTrivialDefaultConstructor())
6824       return true;
6825 
6826     if (Selected) {
6827       // If there's a default constructor which could have been trivial, dig it
6828       // out. Otherwise, if there's any user-provided default constructor, point
6829       // to that as an example of why there's not a trivial one.
6830       CXXConstructorDecl *DefCtor = nullptr;
6831       if (RD->needsImplicitDefaultConstructor())
6832         S.DeclareImplicitDefaultConstructor(RD);
6833       for (auto *CI : RD->ctors()) {
6834         if (!CI->isDefaultConstructor())
6835           continue;
6836         DefCtor = CI;
6837         if (!DefCtor->isUserProvided())
6838           break;
6839       }
6840 
6841       *Selected = DefCtor;
6842     }
6843 
6844     return false;
6845 
6846   case Sema::CXXDestructor:
6847     // C++11 [class.dtor]p5:
6848     //   A destructor is trivial if:
6849     //    - all the direct [subobjects] have trivial destructors
6850     if (RD->hasTrivialDestructor())
6851       return true;
6852 
6853     if (Selected) {
6854       if (RD->needsImplicitDestructor())
6855         S.DeclareImplicitDestructor(RD);
6856       *Selected = RD->getDestructor();
6857     }
6858 
6859     return false;
6860 
6861   case Sema::CXXCopyConstructor:
6862     // C++11 [class.copy]p12:
6863     //   A copy constructor is trivial if:
6864     //    - the constructor selected to copy each direct [subobject] is trivial
6865     if (RD->hasTrivialCopyConstructor()) {
6866       if (Quals == Qualifiers::Const)
6867         // We must either select the trivial copy constructor or reach an
6868         // ambiguity; no need to actually perform overload resolution.
6869         return true;
6870     } else if (!Selected) {
6871       return false;
6872     }
6873     // In C++98, we are not supposed to perform overload resolution here, but we
6874     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
6875     // cases like B as having a non-trivial copy constructor:
6876     //   struct A { template<typename T> A(T&); };
6877     //   struct B { mutable A a; };
6878     goto NeedOverloadResolution;
6879 
6880   case Sema::CXXCopyAssignment:
6881     // C++11 [class.copy]p25:
6882     //   A copy assignment operator is trivial if:
6883     //    - the assignment operator selected to copy each direct [subobject] is
6884     //      trivial
6885     if (RD->hasTrivialCopyAssignment()) {
6886       if (Quals == Qualifiers::Const)
6887         return true;
6888     } else if (!Selected) {
6889       return false;
6890     }
6891     // In C++98, we are not supposed to perform overload resolution here, but we
6892     // treat that as a language defect.
6893     goto NeedOverloadResolution;
6894 
6895   case Sema::CXXMoveConstructor:
6896   case Sema::CXXMoveAssignment:
6897   NeedOverloadResolution:
6898     Sema::SpecialMemberOverloadResult *SMOR =
6899         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
6900 
6901     // The standard doesn't describe how to behave if the lookup is ambiguous.
6902     // We treat it as not making the member non-trivial, just like the standard
6903     // mandates for the default constructor. This should rarely matter, because
6904     // the member will also be deleted.
6905     if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6906       return true;
6907 
6908     if (!SMOR->getMethod()) {
6909       assert(SMOR->getKind() ==
6910              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
6911       return false;
6912     }
6913 
6914     // We deliberately don't check if we found a deleted special member. We're
6915     // not supposed to!
6916     if (Selected)
6917       *Selected = SMOR->getMethod();
6918     return SMOR->getMethod()->isTrivial();
6919   }
6920 
6921   llvm_unreachable("unknown special method kind");
6922 }
6923 
6924 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
6925   for (auto *CI : RD->ctors())
6926     if (!CI->isImplicit())
6927       return CI;
6928 
6929   // Look for constructor templates.
6930   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
6931   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
6932     if (CXXConstructorDecl *CD =
6933           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
6934       return CD;
6935   }
6936 
6937   return nullptr;
6938 }
6939 
6940 /// The kind of subobject we are checking for triviality. The values of this
6941 /// enumeration are used in diagnostics.
6942 enum TrivialSubobjectKind {
6943   /// The subobject is a base class.
6944   TSK_BaseClass,
6945   /// The subobject is a non-static data member.
6946   TSK_Field,
6947   /// The object is actually the complete object.
6948   TSK_CompleteObject
6949 };
6950 
6951 /// Check whether the special member selected for a given type would be trivial.
6952 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
6953                                       QualType SubType, bool ConstRHS,
6954                                       Sema::CXXSpecialMember CSM,
6955                                       TrivialSubobjectKind Kind,
6956                                       bool Diagnose) {
6957   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
6958   if (!SubRD)
6959     return true;
6960 
6961   CXXMethodDecl *Selected;
6962   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
6963                                ConstRHS, Diagnose ? &Selected : nullptr))
6964     return true;
6965 
6966   if (Diagnose) {
6967     if (ConstRHS)
6968       SubType.addConst();
6969 
6970     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
6971       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
6972         << Kind << SubType.getUnqualifiedType();
6973       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
6974         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
6975     } else if (!Selected)
6976       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
6977         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
6978     else if (Selected->isUserProvided()) {
6979       if (Kind == TSK_CompleteObject)
6980         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
6981           << Kind << SubType.getUnqualifiedType() << CSM;
6982       else {
6983         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
6984           << Kind << SubType.getUnqualifiedType() << CSM;
6985         S.Diag(Selected->getLocation(), diag::note_declared_at);
6986       }
6987     } else {
6988       if (Kind != TSK_CompleteObject)
6989         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
6990           << Kind << SubType.getUnqualifiedType() << CSM;
6991 
6992       // Explain why the defaulted or deleted special member isn't trivial.
6993       S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
6994     }
6995   }
6996 
6997   return false;
6998 }
6999 
7000 /// Check whether the members of a class type allow a special member to be
7001 /// trivial.
7002 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7003                                      Sema::CXXSpecialMember CSM,
7004                                      bool ConstArg, bool Diagnose) {
7005   for (const auto *FI : RD->fields()) {
7006     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7007       continue;
7008 
7009     QualType FieldType = S.Context.getBaseElementType(FI->getType());
7010 
7011     // Pretend anonymous struct or union members are members of this class.
7012     if (FI->isAnonymousStructOrUnion()) {
7013       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7014                                     CSM, ConstArg, Diagnose))
7015         return false;
7016       continue;
7017     }
7018 
7019     // C++11 [class.ctor]p5:
7020     //   A default constructor is trivial if [...]
7021     //    -- no non-static data member of its class has a
7022     //       brace-or-equal-initializer
7023     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7024       if (Diagnose)
7025         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
7026       return false;
7027     }
7028 
7029     // Objective C ARC 4.3.5:
7030     //   [...] nontrivally ownership-qualified types are [...] not trivially
7031     //   default constructible, copy constructible, move constructible, copy
7032     //   assignable, move assignable, or destructible [...]
7033     if (S.getLangOpts().ObjCAutoRefCount &&
7034         FieldType.hasNonTrivialObjCLifetime()) {
7035       if (Diagnose)
7036         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7037           << RD << FieldType.getObjCLifetime();
7038       return false;
7039     }
7040 
7041     bool ConstRHS = ConstArg && !FI->isMutable();
7042     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7043                                    CSM, TSK_Field, Diagnose))
7044       return false;
7045   }
7046 
7047   return true;
7048 }
7049 
7050 /// Diagnose why the specified class does not have a trivial special member of
7051 /// the given kind.
7052 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7053   QualType Ty = Context.getRecordType(RD);
7054 
7055   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7056   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
7057                             TSK_CompleteObject, /*Diagnose*/true);
7058 }
7059 
7060 /// Determine whether a defaulted or deleted special member function is trivial,
7061 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7062 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7063 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7064                                   bool Diagnose) {
7065   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7066 
7067   CXXRecordDecl *RD = MD->getParent();
7068 
7069   bool ConstArg = false;
7070 
7071   // C++11 [class.copy]p12, p25: [DR1593]
7072   //   A [special member] is trivial if [...] its parameter-type-list is
7073   //   equivalent to the parameter-type-list of an implicit declaration [...]
7074   switch (CSM) {
7075   case CXXDefaultConstructor:
7076   case CXXDestructor:
7077     // Trivial default constructors and destructors cannot have parameters.
7078     break;
7079 
7080   case CXXCopyConstructor:
7081   case CXXCopyAssignment: {
7082     // Trivial copy operations always have const, non-volatile parameter types.
7083     ConstArg = true;
7084     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7085     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7086     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7087       if (Diagnose)
7088         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7089           << Param0->getSourceRange() << Param0->getType()
7090           << Context.getLValueReferenceType(
7091                Context.getRecordType(RD).withConst());
7092       return false;
7093     }
7094     break;
7095   }
7096 
7097   case CXXMoveConstructor:
7098   case CXXMoveAssignment: {
7099     // Trivial move operations always have non-cv-qualified parameters.
7100     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7101     const RValueReferenceType *RT =
7102       Param0->getType()->getAs<RValueReferenceType>();
7103     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7104       if (Diagnose)
7105         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7106           << Param0->getSourceRange() << Param0->getType()
7107           << Context.getRValueReferenceType(Context.getRecordType(RD));
7108       return false;
7109     }
7110     break;
7111   }
7112 
7113   case CXXInvalid:
7114     llvm_unreachable("not a special member");
7115   }
7116 
7117   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7118     if (Diagnose)
7119       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7120            diag::note_nontrivial_default_arg)
7121         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7122     return false;
7123   }
7124   if (MD->isVariadic()) {
7125     if (Diagnose)
7126       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7127     return false;
7128   }
7129 
7130   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7131   //   A copy/move [constructor or assignment operator] is trivial if
7132   //    -- the [member] selected to copy/move each direct base class subobject
7133   //       is trivial
7134   //
7135   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7136   //   A [default constructor or destructor] is trivial if
7137   //    -- all the direct base classes have trivial [default constructors or
7138   //       destructors]
7139   for (const auto &BI : RD->bases())
7140     if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
7141                                    ConstArg, CSM, TSK_BaseClass, Diagnose))
7142       return false;
7143 
7144   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7145   //   A copy/move [constructor or assignment operator] for a class X is
7146   //   trivial if
7147   //    -- for each non-static data member of X that is of class type (or array
7148   //       thereof), the constructor selected to copy/move that member is
7149   //       trivial
7150   //
7151   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7152   //   A [default constructor or destructor] is trivial if
7153   //    -- for all of the non-static data members of its class that are of class
7154   //       type (or array thereof), each such class has a trivial [default
7155   //       constructor or destructor]
7156   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
7157     return false;
7158 
7159   // C++11 [class.dtor]p5:
7160   //   A destructor is trivial if [...]
7161   //    -- the destructor is not virtual
7162   if (CSM == CXXDestructor && MD->isVirtual()) {
7163     if (Diagnose)
7164       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7165     return false;
7166   }
7167 
7168   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7169   //   A [special member] for class X is trivial if [...]
7170   //    -- class X has no virtual functions and no virtual base classes
7171   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7172     if (!Diagnose)
7173       return false;
7174 
7175     if (RD->getNumVBases()) {
7176       // Check for virtual bases. We already know that the corresponding
7177       // member in all bases is trivial, so vbases must all be direct.
7178       CXXBaseSpecifier &BS = *RD->vbases_begin();
7179       assert(BS.isVirtual());
7180       Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
7181       return false;
7182     }
7183 
7184     // Must have a virtual method.
7185     for (const auto *MI : RD->methods()) {
7186       if (MI->isVirtual()) {
7187         SourceLocation MLoc = MI->getLocStart();
7188         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7189         return false;
7190       }
7191     }
7192 
7193     llvm_unreachable("dynamic class with no vbases and no virtual functions");
7194   }
7195 
7196   // Looks like it's trivial!
7197   return true;
7198 }
7199 
7200 namespace {
7201 struct FindHiddenVirtualMethod {
7202   Sema *S;
7203   CXXMethodDecl *Method;
7204   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7205   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7206 
7207 private:
7208   /// Check whether any most overriden method from MD in Methods
7209   static bool CheckMostOverridenMethods(
7210       const CXXMethodDecl *MD,
7211       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7212     if (MD->size_overridden_methods() == 0)
7213       return Methods.count(MD->getCanonicalDecl());
7214     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7215                                         E = MD->end_overridden_methods();
7216          I != E; ++I)
7217       if (CheckMostOverridenMethods(*I, Methods))
7218         return true;
7219     return false;
7220   }
7221 
7222 public:
7223   /// Member lookup function that determines whether a given C++
7224   /// method overloads virtual methods in a base class without overriding any,
7225   /// to be used with CXXRecordDecl::lookupInBases().
7226   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7227     RecordDecl *BaseRecord =
7228         Specifier->getType()->getAs<RecordType>()->getDecl();
7229 
7230     DeclarationName Name = Method->getDeclName();
7231     assert(Name.getNameKind() == DeclarationName::Identifier);
7232 
7233     bool foundSameNameMethod = false;
7234     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7235     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7236          Path.Decls = Path.Decls.slice(1)) {
7237       NamedDecl *D = Path.Decls.front();
7238       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7239         MD = MD->getCanonicalDecl();
7240         foundSameNameMethod = true;
7241         // Interested only in hidden virtual methods.
7242         if (!MD->isVirtual())
7243           continue;
7244         // If the method we are checking overrides a method from its base
7245         // don't warn about the other overloaded methods. Clang deviates from
7246         // GCC by only diagnosing overloads of inherited virtual functions that
7247         // do not override any other virtual functions in the base. GCC's
7248         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7249         // function from a base class. These cases may be better served by a
7250         // warning (not specific to virtual functions) on call sites when the
7251         // call would select a different function from the base class, were it
7252         // visible.
7253         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7254         if (!S->IsOverload(Method, MD, false))
7255           return true;
7256         // Collect the overload only if its hidden.
7257         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7258           overloadedMethods.push_back(MD);
7259       }
7260     }
7261 
7262     if (foundSameNameMethod)
7263       OverloadedMethods.append(overloadedMethods.begin(),
7264                                overloadedMethods.end());
7265     return foundSameNameMethod;
7266   }
7267 };
7268 } // end anonymous namespace
7269 
7270 /// \brief Add the most overriden methods from MD to Methods
7271 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
7272                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
7273   if (MD->size_overridden_methods() == 0)
7274     Methods.insert(MD->getCanonicalDecl());
7275   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7276                                       E = MD->end_overridden_methods();
7277        I != E; ++I)
7278     AddMostOverridenMethods(*I, Methods);
7279 }
7280 
7281 /// \brief Check if a method overloads virtual methods in a base class without
7282 /// overriding any.
7283 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7284                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7285   if (!MD->getDeclName().isIdentifier())
7286     return;
7287 
7288   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7289                      /*bool RecordPaths=*/false,
7290                      /*bool DetectVirtual=*/false);
7291   FindHiddenVirtualMethod FHVM;
7292   FHVM.Method = MD;
7293   FHVM.S = this;
7294 
7295   // Keep the base methods that were overriden or introduced in the subclass
7296   // by 'using' in a set. A base method not in this set is hidden.
7297   CXXRecordDecl *DC = MD->getParent();
7298   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7299   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7300     NamedDecl *ND = *I;
7301     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
7302       ND = shad->getTargetDecl();
7303     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7304       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
7305   }
7306 
7307   if (DC->lookupInBases(FHVM, Paths))
7308     OverloadedMethods = FHVM.OverloadedMethods;
7309 }
7310 
7311 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7312                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7313   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7314     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7315     PartialDiagnostic PD = PDiag(
7316          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7317     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7318     Diag(overloadedMD->getLocation(), PD);
7319   }
7320 }
7321 
7322 /// \brief Diagnose methods which overload virtual methods in a base class
7323 /// without overriding any.
7324 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7325   if (MD->isInvalidDecl())
7326     return;
7327 
7328   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
7329     return;
7330 
7331   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7332   FindHiddenVirtualMethods(MD, OverloadedMethods);
7333   if (!OverloadedMethods.empty()) {
7334     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7335       << MD << (OverloadedMethods.size() > 1);
7336 
7337     NoteHiddenVirtualMethods(MD, OverloadedMethods);
7338   }
7339 }
7340 
7341 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
7342                                              Decl *TagDecl,
7343                                              SourceLocation LBrac,
7344                                              SourceLocation RBrac,
7345                                              AttributeList *AttrList) {
7346   if (!TagDecl)
7347     return;
7348 
7349   AdjustDeclIfTemplate(TagDecl);
7350 
7351   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
7352     if (l->getKind() != AttributeList::AT_Visibility)
7353       continue;
7354     l->setInvalid();
7355     Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
7356       l->getName();
7357   }
7358 
7359   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
7360               // strict aliasing violation!
7361               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
7362               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
7363 
7364   CheckCompletedCXXClass(
7365                         dyn_cast_or_null<CXXRecordDecl>(TagDecl));
7366 }
7367 
7368 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7369 /// special functions, such as the default constructor, copy
7370 /// constructor, or destructor, to the given C++ class (C++
7371 /// [special]p1).  This routine can only be executed just before the
7372 /// definition of the class is complete.
7373 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
7374   if (ClassDecl->needsImplicitDefaultConstructor()) {
7375     ++ASTContext::NumImplicitDefaultConstructors;
7376 
7377     if (ClassDecl->hasInheritedConstructor())
7378       DeclareImplicitDefaultConstructor(ClassDecl);
7379   }
7380 
7381   if (ClassDecl->needsImplicitCopyConstructor()) {
7382     ++ASTContext::NumImplicitCopyConstructors;
7383 
7384     // If the properties or semantics of the copy constructor couldn't be
7385     // determined while the class was being declared, force a declaration
7386     // of it now.
7387     if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7388         ClassDecl->hasInheritedConstructor())
7389       DeclareImplicitCopyConstructor(ClassDecl);
7390   }
7391 
7392   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
7393     ++ASTContext::NumImplicitMoveConstructors;
7394 
7395     if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7396         ClassDecl->hasInheritedConstructor())
7397       DeclareImplicitMoveConstructor(ClassDecl);
7398   }
7399 
7400   if (ClassDecl->needsImplicitCopyAssignment()) {
7401     ++ASTContext::NumImplicitCopyAssignmentOperators;
7402 
7403     // If we have a dynamic class, then the copy assignment operator may be
7404     // virtual, so we have to declare it immediately. This ensures that, e.g.,
7405     // it shows up in the right place in the vtable and that we diagnose
7406     // problems with the implicit exception specification.
7407     if (ClassDecl->isDynamicClass() ||
7408         ClassDecl->needsOverloadResolutionForCopyAssignment() ||
7409         ClassDecl->hasInheritedAssignment())
7410       DeclareImplicitCopyAssignment(ClassDecl);
7411   }
7412 
7413   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
7414     ++ASTContext::NumImplicitMoveAssignmentOperators;
7415 
7416     // Likewise for the move assignment operator.
7417     if (ClassDecl->isDynamicClass() ||
7418         ClassDecl->needsOverloadResolutionForMoveAssignment() ||
7419         ClassDecl->hasInheritedAssignment())
7420       DeclareImplicitMoveAssignment(ClassDecl);
7421   }
7422 
7423   if (ClassDecl->needsImplicitDestructor()) {
7424     ++ASTContext::NumImplicitDestructors;
7425 
7426     // If we have a dynamic class, then the destructor may be virtual, so we
7427     // have to declare the destructor immediately. This ensures that, e.g., it
7428     // shows up in the right place in the vtable and that we diagnose problems
7429     // with the implicit exception specification.
7430     if (ClassDecl->isDynamicClass() ||
7431         ClassDecl->needsOverloadResolutionForDestructor())
7432       DeclareImplicitDestructor(ClassDecl);
7433   }
7434 }
7435 
7436 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
7437   if (!D)
7438     return 0;
7439 
7440   // The order of template parameters is not important here. All names
7441   // get added to the same scope.
7442   SmallVector<TemplateParameterList *, 4> ParameterLists;
7443 
7444   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
7445     D = TD->getTemplatedDecl();
7446 
7447   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
7448     ParameterLists.push_back(PSD->getTemplateParameters());
7449 
7450   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
7451     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
7452       ParameterLists.push_back(DD->getTemplateParameterList(i));
7453 
7454     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7455       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
7456         ParameterLists.push_back(FTD->getTemplateParameters());
7457     }
7458   }
7459 
7460   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
7461     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
7462       ParameterLists.push_back(TD->getTemplateParameterList(i));
7463 
7464     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
7465       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
7466         ParameterLists.push_back(CTD->getTemplateParameters());
7467     }
7468   }
7469 
7470   unsigned Count = 0;
7471   for (TemplateParameterList *Params : ParameterLists) {
7472     if (Params->size() > 0)
7473       // Ignore explicit specializations; they don't contribute to the template
7474       // depth.
7475       ++Count;
7476     for (NamedDecl *Param : *Params) {
7477       if (Param->getDeclName()) {
7478         S->AddDecl(Param);
7479         IdResolver.AddDecl(Param);
7480       }
7481     }
7482   }
7483 
7484   return Count;
7485 }
7486 
7487 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7488   if (!RecordD) return;
7489   AdjustDeclIfTemplate(RecordD);
7490   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
7491   PushDeclContext(S, Record);
7492 }
7493 
7494 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7495   if (!RecordD) return;
7496   PopDeclContext();
7497 }
7498 
7499 /// This is used to implement the constant expression evaluation part of the
7500 /// attribute enable_if extension. There is nothing in standard C++ which would
7501 /// require reentering parameters.
7502 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
7503   if (!Param)
7504     return;
7505 
7506   S->AddDecl(Param);
7507   if (Param->getDeclName())
7508     IdResolver.AddDecl(Param);
7509 }
7510 
7511 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
7512 /// parsing a top-level (non-nested) C++ class, and we are now
7513 /// parsing those parts of the given Method declaration that could
7514 /// not be parsed earlier (C++ [class.mem]p2), such as default
7515 /// arguments. This action should enter the scope of the given
7516 /// Method declaration as if we had just parsed the qualified method
7517 /// name. However, it should not bring the parameters into scope;
7518 /// that will be performed by ActOnDelayedCXXMethodParameter.
7519 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
7520 }
7521 
7522 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
7523 /// C++ method declaration. We're (re-)introducing the given
7524 /// function parameter into scope for use in parsing later parts of
7525 /// the method declaration. For example, we could see an
7526 /// ActOnParamDefaultArgument event for this parameter.
7527 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
7528   if (!ParamD)
7529     return;
7530 
7531   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
7532 
7533   // If this parameter has an unparsed default argument, clear it out
7534   // to make way for the parsed default argument.
7535   if (Param->hasUnparsedDefaultArg())
7536     Param->setDefaultArg(nullptr);
7537 
7538   S->AddDecl(Param);
7539   if (Param->getDeclName())
7540     IdResolver.AddDecl(Param);
7541 }
7542 
7543 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
7544 /// processing the delayed method declaration for Method. The method
7545 /// declaration is now considered finished. There may be a separate
7546 /// ActOnStartOfFunctionDef action later (not necessarily
7547 /// immediately!) for this method, if it was also defined inside the
7548 /// class body.
7549 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
7550   if (!MethodD)
7551     return;
7552 
7553   AdjustDeclIfTemplate(MethodD);
7554 
7555   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
7556 
7557   // Now that we have our default arguments, check the constructor
7558   // again. It could produce additional diagnostics or affect whether
7559   // the class has implicitly-declared destructors, among other
7560   // things.
7561   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
7562     CheckConstructor(Constructor);
7563 
7564   // Check the default arguments, which we may have added.
7565   if (!Method->isInvalidDecl())
7566     CheckCXXDefaultArguments(Method);
7567 }
7568 
7569 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
7570 /// the well-formedness of the constructor declarator @p D with type @p
7571 /// R. If there are any errors in the declarator, this routine will
7572 /// emit diagnostics and set the invalid bit to true.  In any case, the type
7573 /// will be updated to reflect a well-formed type for the constructor and
7574 /// returned.
7575 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
7576                                           StorageClass &SC) {
7577   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7578 
7579   // C++ [class.ctor]p3:
7580   //   A constructor shall not be virtual (10.3) or static (9.4). A
7581   //   constructor can be invoked for a const, volatile or const
7582   //   volatile object. A constructor shall not be declared const,
7583   //   volatile, or const volatile (9.3.2).
7584   if (isVirtual) {
7585     if (!D.isInvalidType())
7586       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7587         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
7588         << SourceRange(D.getIdentifierLoc());
7589     D.setInvalidType();
7590   }
7591   if (SC == SC_Static) {
7592     if (!D.isInvalidType())
7593       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7594         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7595         << SourceRange(D.getIdentifierLoc());
7596     D.setInvalidType();
7597     SC = SC_None;
7598   }
7599 
7600   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7601     diagnoseIgnoredQualifiers(
7602         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
7603         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
7604         D.getDeclSpec().getRestrictSpecLoc(),
7605         D.getDeclSpec().getAtomicSpecLoc());
7606     D.setInvalidType();
7607   }
7608 
7609   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7610   if (FTI.TypeQuals != 0) {
7611     if (FTI.TypeQuals & Qualifiers::Const)
7612       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7613         << "const" << SourceRange(D.getIdentifierLoc());
7614     if (FTI.TypeQuals & Qualifiers::Volatile)
7615       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7616         << "volatile" << SourceRange(D.getIdentifierLoc());
7617     if (FTI.TypeQuals & Qualifiers::Restrict)
7618       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7619         << "restrict" << SourceRange(D.getIdentifierLoc());
7620     D.setInvalidType();
7621   }
7622 
7623   // C++0x [class.ctor]p4:
7624   //   A constructor shall not be declared with a ref-qualifier.
7625   if (FTI.hasRefQualifier()) {
7626     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
7627       << FTI.RefQualifierIsLValueRef
7628       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7629     D.setInvalidType();
7630   }
7631 
7632   // Rebuild the function type "R" without any type qualifiers (in
7633   // case any of the errors above fired) and with "void" as the
7634   // return type, since constructors don't have return types.
7635   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
7636   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
7637     return R;
7638 
7639   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
7640   EPI.TypeQuals = 0;
7641   EPI.RefQualifier = RQ_None;
7642 
7643   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
7644 }
7645 
7646 /// CheckConstructor - Checks a fully-formed constructor for
7647 /// well-formedness, issuing any diagnostics required. Returns true if
7648 /// the constructor declarator is invalid.
7649 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
7650   CXXRecordDecl *ClassDecl
7651     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
7652   if (!ClassDecl)
7653     return Constructor->setInvalidDecl();
7654 
7655   // C++ [class.copy]p3:
7656   //   A declaration of a constructor for a class X is ill-formed if
7657   //   its first parameter is of type (optionally cv-qualified) X and
7658   //   either there are no other parameters or else all other
7659   //   parameters have default arguments.
7660   if (!Constructor->isInvalidDecl() &&
7661       ((Constructor->getNumParams() == 1) ||
7662        (Constructor->getNumParams() > 1 &&
7663         Constructor->getParamDecl(1)->hasDefaultArg())) &&
7664       Constructor->getTemplateSpecializationKind()
7665                                               != TSK_ImplicitInstantiation) {
7666     QualType ParamType = Constructor->getParamDecl(0)->getType();
7667     QualType ClassTy = Context.getTagDeclType(ClassDecl);
7668     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
7669       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
7670       const char *ConstRef
7671         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
7672                                                         : " const &";
7673       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
7674         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
7675 
7676       // FIXME: Rather that making the constructor invalid, we should endeavor
7677       // to fix the type.
7678       Constructor->setInvalidDecl();
7679     }
7680   }
7681 }
7682 
7683 /// CheckDestructor - Checks a fully-formed destructor definition for
7684 /// well-formedness, issuing any diagnostics required.  Returns true
7685 /// on error.
7686 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
7687   CXXRecordDecl *RD = Destructor->getParent();
7688 
7689   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
7690     SourceLocation Loc;
7691 
7692     if (!Destructor->isImplicit())
7693       Loc = Destructor->getLocation();
7694     else
7695       Loc = RD->getLocation();
7696 
7697     // If we have a virtual destructor, look up the deallocation function
7698     if (FunctionDecl *OperatorDelete =
7699             FindDeallocationFunctionForDestructor(Loc, RD)) {
7700       MarkFunctionReferenced(Loc, OperatorDelete);
7701       Destructor->setOperatorDelete(OperatorDelete);
7702     }
7703   }
7704 
7705   return false;
7706 }
7707 
7708 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
7709 /// the well-formednes of the destructor declarator @p D with type @p
7710 /// R. If there are any errors in the declarator, this routine will
7711 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
7712 /// will be updated to reflect a well-formed type for the destructor and
7713 /// returned.
7714 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
7715                                          StorageClass& SC) {
7716   // C++ [class.dtor]p1:
7717   //   [...] A typedef-name that names a class is a class-name
7718   //   (7.1.3); however, a typedef-name that names a class shall not
7719   //   be used as the identifier in the declarator for a destructor
7720   //   declaration.
7721   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
7722   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
7723     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
7724       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
7725   else if (const TemplateSpecializationType *TST =
7726              DeclaratorType->getAs<TemplateSpecializationType>())
7727     if (TST->isTypeAlias())
7728       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
7729         << DeclaratorType << 1;
7730 
7731   // C++ [class.dtor]p2:
7732   //   A destructor is used to destroy objects of its class type. A
7733   //   destructor takes no parameters, and no return type can be
7734   //   specified for it (not even void). The address of a destructor
7735   //   shall not be taken. A destructor shall not be static. A
7736   //   destructor can be invoked for a const, volatile or const
7737   //   volatile object. A destructor shall not be declared const,
7738   //   volatile or const volatile (9.3.2).
7739   if (SC == SC_Static) {
7740     if (!D.isInvalidType())
7741       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
7742         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7743         << SourceRange(D.getIdentifierLoc())
7744         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7745 
7746     SC = SC_None;
7747   }
7748   if (!D.isInvalidType()) {
7749     // Destructors don't have return types, but the parser will
7750     // happily parse something like:
7751     //
7752     //   class X {
7753     //     float ~X();
7754     //   };
7755     //
7756     // The return type will be eliminated later.
7757     if (D.getDeclSpec().hasTypeSpecifier())
7758       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
7759         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7760         << SourceRange(D.getIdentifierLoc());
7761     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7762       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
7763                                 SourceLocation(),
7764                                 D.getDeclSpec().getConstSpecLoc(),
7765                                 D.getDeclSpec().getVolatileSpecLoc(),
7766                                 D.getDeclSpec().getRestrictSpecLoc(),
7767                                 D.getDeclSpec().getAtomicSpecLoc());
7768       D.setInvalidType();
7769     }
7770   }
7771 
7772   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7773   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
7774     if (FTI.TypeQuals & Qualifiers::Const)
7775       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7776         << "const" << SourceRange(D.getIdentifierLoc());
7777     if (FTI.TypeQuals & Qualifiers::Volatile)
7778       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7779         << "volatile" << SourceRange(D.getIdentifierLoc());
7780     if (FTI.TypeQuals & Qualifiers::Restrict)
7781       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7782         << "restrict" << SourceRange(D.getIdentifierLoc());
7783     D.setInvalidType();
7784   }
7785 
7786   // C++0x [class.dtor]p2:
7787   //   A destructor shall not be declared with a ref-qualifier.
7788   if (FTI.hasRefQualifier()) {
7789     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
7790       << FTI.RefQualifierIsLValueRef
7791       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7792     D.setInvalidType();
7793   }
7794 
7795   // Make sure we don't have any parameters.
7796   if (FTIHasNonVoidParameters(FTI)) {
7797     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
7798 
7799     // Delete the parameters.
7800     FTI.freeParams();
7801     D.setInvalidType();
7802   }
7803 
7804   // Make sure the destructor isn't variadic.
7805   if (FTI.isVariadic) {
7806     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
7807     D.setInvalidType();
7808   }
7809 
7810   // Rebuild the function type "R" without any type qualifiers or
7811   // parameters (in case any of the errors above fired) and with
7812   // "void" as the return type, since destructors don't have return
7813   // types.
7814   if (!D.isInvalidType())
7815     return R;
7816 
7817   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
7818   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
7819   EPI.Variadic = false;
7820   EPI.TypeQuals = 0;
7821   EPI.RefQualifier = RQ_None;
7822   return Context.getFunctionType(Context.VoidTy, None, EPI);
7823 }
7824 
7825 static void extendLeft(SourceRange &R, SourceRange Before) {
7826   if (Before.isInvalid())
7827     return;
7828   R.setBegin(Before.getBegin());
7829   if (R.getEnd().isInvalid())
7830     R.setEnd(Before.getEnd());
7831 }
7832 
7833 static void extendRight(SourceRange &R, SourceRange After) {
7834   if (After.isInvalid())
7835     return;
7836   if (R.getBegin().isInvalid())
7837     R.setBegin(After.getBegin());
7838   R.setEnd(After.getEnd());
7839 }
7840 
7841 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
7842 /// well-formednes of the conversion function declarator @p D with
7843 /// type @p R. If there are any errors in the declarator, this routine
7844 /// will emit diagnostics and return true. Otherwise, it will return
7845 /// false. Either way, the type @p R will be updated to reflect a
7846 /// well-formed type for the conversion operator.
7847 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
7848                                      StorageClass& SC) {
7849   // C++ [class.conv.fct]p1:
7850   //   Neither parameter types nor return type can be specified. The
7851   //   type of a conversion function (8.3.5) is "function taking no
7852   //   parameter returning conversion-type-id."
7853   if (SC == SC_Static) {
7854     if (!D.isInvalidType())
7855       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
7856         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7857         << D.getName().getSourceRange();
7858     D.setInvalidType();
7859     SC = SC_None;
7860   }
7861 
7862   TypeSourceInfo *ConvTSI = nullptr;
7863   QualType ConvType =
7864       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
7865 
7866   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
7867     // Conversion functions don't have return types, but the parser will
7868     // happily parse something like:
7869     //
7870     //   class X {
7871     //     float operator bool();
7872     //   };
7873     //
7874     // The return type will be changed later anyway.
7875     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
7876       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7877       << SourceRange(D.getIdentifierLoc());
7878     D.setInvalidType();
7879   }
7880 
7881   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
7882 
7883   // Make sure we don't have any parameters.
7884   if (Proto->getNumParams() > 0) {
7885     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
7886 
7887     // Delete the parameters.
7888     D.getFunctionTypeInfo().freeParams();
7889     D.setInvalidType();
7890   } else if (Proto->isVariadic()) {
7891     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
7892     D.setInvalidType();
7893   }
7894 
7895   // Diagnose "&operator bool()" and other such nonsense.  This
7896   // is actually a gcc extension which we don't support.
7897   if (Proto->getReturnType() != ConvType) {
7898     bool NeedsTypedef = false;
7899     SourceRange Before, After;
7900 
7901     // Walk the chunks and extract information on them for our diagnostic.
7902     bool PastFunctionChunk = false;
7903     for (auto &Chunk : D.type_objects()) {
7904       switch (Chunk.Kind) {
7905       case DeclaratorChunk::Function:
7906         if (!PastFunctionChunk) {
7907           if (Chunk.Fun.HasTrailingReturnType) {
7908             TypeSourceInfo *TRT = nullptr;
7909             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
7910             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
7911           }
7912           PastFunctionChunk = true;
7913           break;
7914         }
7915         // Fall through.
7916       case DeclaratorChunk::Array:
7917         NeedsTypedef = true;
7918         extendRight(After, Chunk.getSourceRange());
7919         break;
7920 
7921       case DeclaratorChunk::Pointer:
7922       case DeclaratorChunk::BlockPointer:
7923       case DeclaratorChunk::Reference:
7924       case DeclaratorChunk::MemberPointer:
7925       case DeclaratorChunk::Pipe:
7926         extendLeft(Before, Chunk.getSourceRange());
7927         break;
7928 
7929       case DeclaratorChunk::Paren:
7930         extendLeft(Before, Chunk.Loc);
7931         extendRight(After, Chunk.EndLoc);
7932         break;
7933       }
7934     }
7935 
7936     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
7937                          After.isValid()  ? After.getBegin() :
7938                                             D.getIdentifierLoc();
7939     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
7940     DB << Before << After;
7941 
7942     if (!NeedsTypedef) {
7943       DB << /*don't need a typedef*/0;
7944 
7945       // If we can provide a correct fix-it hint, do so.
7946       if (After.isInvalid() && ConvTSI) {
7947         SourceLocation InsertLoc =
7948             getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
7949         DB << FixItHint::CreateInsertion(InsertLoc, " ")
7950            << FixItHint::CreateInsertionFromRange(
7951                   InsertLoc, CharSourceRange::getTokenRange(Before))
7952            << FixItHint::CreateRemoval(Before);
7953       }
7954     } else if (!Proto->getReturnType()->isDependentType()) {
7955       DB << /*typedef*/1 << Proto->getReturnType();
7956     } else if (getLangOpts().CPlusPlus11) {
7957       DB << /*alias template*/2 << Proto->getReturnType();
7958     } else {
7959       DB << /*might not be fixable*/3;
7960     }
7961 
7962     // Recover by incorporating the other type chunks into the result type.
7963     // Note, this does *not* change the name of the function. This is compatible
7964     // with the GCC extension:
7965     //   struct S { &operator int(); } s;
7966     //   int &r = s.operator int(); // ok in GCC
7967     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
7968     ConvType = Proto->getReturnType();
7969   }
7970 
7971   // C++ [class.conv.fct]p4:
7972   //   The conversion-type-id shall not represent a function type nor
7973   //   an array type.
7974   if (ConvType->isArrayType()) {
7975     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
7976     ConvType = Context.getPointerType(ConvType);
7977     D.setInvalidType();
7978   } else if (ConvType->isFunctionType()) {
7979     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
7980     ConvType = Context.getPointerType(ConvType);
7981     D.setInvalidType();
7982   }
7983 
7984   // Rebuild the function type "R" without any parameters (in case any
7985   // of the errors above fired) and with the conversion type as the
7986   // return type.
7987   if (D.isInvalidType())
7988     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
7989 
7990   // C++0x explicit conversion operators.
7991   if (D.getDeclSpec().isExplicitSpecified())
7992     Diag(D.getDeclSpec().getExplicitSpecLoc(),
7993          getLangOpts().CPlusPlus11 ?
7994            diag::warn_cxx98_compat_explicit_conversion_functions :
7995            diag::ext_explicit_conversion_functions)
7996       << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
7997 }
7998 
7999 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8000 /// the declaration of the given C++ conversion function. This routine
8001 /// is responsible for recording the conversion function in the C++
8002 /// class, if possible.
8003 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
8004   assert(Conversion && "Expected to receive a conversion function declaration");
8005 
8006   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
8007 
8008   // Make sure we aren't redeclaring the conversion function.
8009   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
8010 
8011   // C++ [class.conv.fct]p1:
8012   //   [...] A conversion function is never used to convert a
8013   //   (possibly cv-qualified) object to the (possibly cv-qualified)
8014   //   same object type (or a reference to it), to a (possibly
8015   //   cv-qualified) base class of that type (or a reference to it),
8016   //   or to (possibly cv-qualified) void.
8017   // FIXME: Suppress this warning if the conversion function ends up being a
8018   // virtual function that overrides a virtual function in a base class.
8019   QualType ClassType
8020     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8021   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
8022     ConvType = ConvTypeRef->getPointeeType();
8023   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8024       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
8025     /* Suppress diagnostics for instantiations. */;
8026   else if (ConvType->isRecordType()) {
8027     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8028     if (ConvType == ClassType)
8029       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
8030         << ClassType;
8031     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
8032       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
8033         <<  ClassType << ConvType;
8034   } else if (ConvType->isVoidType()) {
8035     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
8036       << ClassType << ConvType;
8037   }
8038 
8039   if (FunctionTemplateDecl *ConversionTemplate
8040                                 = Conversion->getDescribedFunctionTemplate())
8041     return ConversionTemplate;
8042 
8043   return Conversion;
8044 }
8045 
8046 //===----------------------------------------------------------------------===//
8047 // Namespace Handling
8048 //===----------------------------------------------------------------------===//
8049 
8050 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
8051 /// reopened.
8052 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8053                                             SourceLocation Loc,
8054                                             IdentifierInfo *II, bool *IsInline,
8055                                             NamespaceDecl *PrevNS) {
8056   assert(*IsInline != PrevNS->isInline());
8057 
8058   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8059   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8060   // inline namespaces, with the intention of bringing names into namespace std.
8061   //
8062   // We support this just well enough to get that case working; this is not
8063   // sufficient to support reopening namespaces as inline in general.
8064   if (*IsInline && II && II->getName().startswith("__atomic") &&
8065       S.getSourceManager().isInSystemHeader(Loc)) {
8066     // Mark all prior declarations of the namespace as inline.
8067     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8068          NS = NS->getPreviousDecl())
8069       NS->setInline(*IsInline);
8070     // Patch up the lookup table for the containing namespace. This isn't really
8071     // correct, but it's good enough for this particular case.
8072     for (auto *I : PrevNS->decls())
8073       if (auto *ND = dyn_cast<NamedDecl>(I))
8074         PrevNS->getParent()->makeDeclVisibleInContext(ND);
8075     return;
8076   }
8077 
8078   if (PrevNS->isInline())
8079     // The user probably just forgot the 'inline', so suggest that it
8080     // be added back.
8081     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8082       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8083   else
8084     S.Diag(Loc, diag::err_inline_namespace_mismatch);
8085 
8086   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8087   *IsInline = PrevNS->isInline();
8088 }
8089 
8090 /// ActOnStartNamespaceDef - This is called at the start of a namespace
8091 /// definition.
8092 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
8093                                    SourceLocation InlineLoc,
8094                                    SourceLocation NamespaceLoc,
8095                                    SourceLocation IdentLoc,
8096                                    IdentifierInfo *II,
8097                                    SourceLocation LBrace,
8098                                    AttributeList *AttrList,
8099                                    UsingDirectiveDecl *&UD) {
8100   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8101   // For anonymous namespace, take the location of the left brace.
8102   SourceLocation Loc = II ? IdentLoc : LBrace;
8103   bool IsInline = InlineLoc.isValid();
8104   bool IsInvalid = false;
8105   bool IsStd = false;
8106   bool AddToKnown = false;
8107   Scope *DeclRegionScope = NamespcScope->getParent();
8108 
8109   NamespaceDecl *PrevNS = nullptr;
8110   if (II) {
8111     // C++ [namespace.def]p2:
8112     //   The identifier in an original-namespace-definition shall not
8113     //   have been previously defined in the declarative region in
8114     //   which the original-namespace-definition appears. The
8115     //   identifier in an original-namespace-definition is the name of
8116     //   the namespace. Subsequently in that declarative region, it is
8117     //   treated as an original-namespace-name.
8118     //
8119     // Since namespace names are unique in their scope, and we don't
8120     // look through using directives, just look for any ordinary names
8121     // as if by qualified name lookup.
8122     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, ForRedeclaration);
8123     LookupQualifiedName(R, CurContext->getRedeclContext());
8124     NamedDecl *PrevDecl =
8125         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
8126     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
8127 
8128     if (PrevNS) {
8129       // This is an extended namespace definition.
8130       if (IsInline != PrevNS->isInline())
8131         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8132                                         &IsInline, PrevNS);
8133     } else if (PrevDecl) {
8134       // This is an invalid name redefinition.
8135       Diag(Loc, diag::err_redefinition_different_kind)
8136         << II;
8137       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8138       IsInvalid = true;
8139       // Continue on to push Namespc as current DeclContext and return it.
8140     } else if (II->isStr("std") &&
8141                CurContext->getRedeclContext()->isTranslationUnit()) {
8142       // This is the first "real" definition of the namespace "std", so update
8143       // our cache of the "std" namespace to point at this definition.
8144       PrevNS = getStdNamespace();
8145       IsStd = true;
8146       AddToKnown = !IsInline;
8147     } else {
8148       // We've seen this namespace for the first time.
8149       AddToKnown = !IsInline;
8150     }
8151   } else {
8152     // Anonymous namespaces.
8153 
8154     // Determine whether the parent already has an anonymous namespace.
8155     DeclContext *Parent = CurContext->getRedeclContext();
8156     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8157       PrevNS = TU->getAnonymousNamespace();
8158     } else {
8159       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
8160       PrevNS = ND->getAnonymousNamespace();
8161     }
8162 
8163     if (PrevNS && IsInline != PrevNS->isInline())
8164       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8165                                       &IsInline, PrevNS);
8166   }
8167 
8168   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8169                                                  StartLoc, Loc, II, PrevNS);
8170   if (IsInvalid)
8171     Namespc->setInvalidDecl();
8172 
8173   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
8174 
8175   // FIXME: Should we be merging attributes?
8176   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
8177     PushNamespaceVisibilityAttr(Attr, Loc);
8178 
8179   if (IsStd)
8180     StdNamespace = Namespc;
8181   if (AddToKnown)
8182     KnownNamespaces[Namespc] = false;
8183 
8184   if (II) {
8185     PushOnScopeChains(Namespc, DeclRegionScope);
8186   } else {
8187     // Link the anonymous namespace into its parent.
8188     DeclContext *Parent = CurContext->getRedeclContext();
8189     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8190       TU->setAnonymousNamespace(Namespc);
8191     } else {
8192       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
8193     }
8194 
8195     CurContext->addDecl(Namespc);
8196 
8197     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
8198     //   behaves as if it were replaced by
8199     //     namespace unique { /* empty body */ }
8200     //     using namespace unique;
8201     //     namespace unique { namespace-body }
8202     //   where all occurrences of 'unique' in a translation unit are
8203     //   replaced by the same identifier and this identifier differs
8204     //   from all other identifiers in the entire program.
8205 
8206     // We just create the namespace with an empty name and then add an
8207     // implicit using declaration, just like the standard suggests.
8208     //
8209     // CodeGen enforces the "universally unique" aspect by giving all
8210     // declarations semantically contained within an anonymous
8211     // namespace internal linkage.
8212 
8213     if (!PrevNS) {
8214       UD = UsingDirectiveDecl::Create(Context, Parent,
8215                                       /* 'using' */ LBrace,
8216                                       /* 'namespace' */ SourceLocation(),
8217                                       /* qualifier */ NestedNameSpecifierLoc(),
8218                                       /* identifier */ SourceLocation(),
8219                                       Namespc,
8220                                       /* Ancestor */ Parent);
8221       UD->setImplicit();
8222       Parent->addDecl(UD);
8223     }
8224   }
8225 
8226   ActOnDocumentableDecl(Namespc);
8227 
8228   // Although we could have an invalid decl (i.e. the namespace name is a
8229   // redefinition), push it as current DeclContext and try to continue parsing.
8230   // FIXME: We should be able to push Namespc here, so that the each DeclContext
8231   // for the namespace has the declarations that showed up in that particular
8232   // namespace definition.
8233   PushDeclContext(NamespcScope, Namespc);
8234   return Namespc;
8235 }
8236 
8237 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
8238 /// is a namespace alias, returns the namespace it points to.
8239 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
8240   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
8241     return AD->getNamespace();
8242   return dyn_cast_or_null<NamespaceDecl>(D);
8243 }
8244 
8245 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
8246 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
8247 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
8248   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
8249   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
8250   Namespc->setRBraceLoc(RBrace);
8251   PopDeclContext();
8252   if (Namespc->hasAttr<VisibilityAttr>())
8253     PopPragmaVisibility(true, RBrace);
8254 }
8255 
8256 CXXRecordDecl *Sema::getStdBadAlloc() const {
8257   return cast_or_null<CXXRecordDecl>(
8258                                   StdBadAlloc.get(Context.getExternalSource()));
8259 }
8260 
8261 EnumDecl *Sema::getStdAlignValT() const {
8262   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
8263 }
8264 
8265 NamespaceDecl *Sema::getStdNamespace() const {
8266   return cast_or_null<NamespaceDecl>(
8267                                  StdNamespace.get(Context.getExternalSource()));
8268 }
8269 
8270 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
8271   if (!StdExperimentalNamespaceCache) {
8272     if (auto Std = getStdNamespace()) {
8273       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
8274                           SourceLocation(), LookupNamespaceName);
8275       if (!LookupQualifiedName(Result, Std) ||
8276           !(StdExperimentalNamespaceCache =
8277                 Result.getAsSingle<NamespaceDecl>()))
8278         Result.suppressDiagnostics();
8279     }
8280   }
8281   return StdExperimentalNamespaceCache;
8282 }
8283 
8284 /// \brief Retrieve the special "std" namespace, which may require us to
8285 /// implicitly define the namespace.
8286 NamespaceDecl *Sema::getOrCreateStdNamespace() {
8287   if (!StdNamespace) {
8288     // The "std" namespace has not yet been defined, so build one implicitly.
8289     StdNamespace = NamespaceDecl::Create(Context,
8290                                          Context.getTranslationUnitDecl(),
8291                                          /*Inline=*/false,
8292                                          SourceLocation(), SourceLocation(),
8293                                          &PP.getIdentifierTable().get("std"),
8294                                          /*PrevDecl=*/nullptr);
8295     getStdNamespace()->setImplicit(true);
8296   }
8297 
8298   return getStdNamespace();
8299 }
8300 
8301 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
8302   assert(getLangOpts().CPlusPlus &&
8303          "Looking for std::initializer_list outside of C++.");
8304 
8305   // We're looking for implicit instantiations of
8306   // template <typename E> class std::initializer_list.
8307 
8308   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
8309     return false;
8310 
8311   ClassTemplateDecl *Template = nullptr;
8312   const TemplateArgument *Arguments = nullptr;
8313 
8314   if (const RecordType *RT = Ty->getAs<RecordType>()) {
8315 
8316     ClassTemplateSpecializationDecl *Specialization =
8317         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
8318     if (!Specialization)
8319       return false;
8320 
8321     Template = Specialization->getSpecializedTemplate();
8322     Arguments = Specialization->getTemplateArgs().data();
8323   } else if (const TemplateSpecializationType *TST =
8324                  Ty->getAs<TemplateSpecializationType>()) {
8325     Template = dyn_cast_or_null<ClassTemplateDecl>(
8326         TST->getTemplateName().getAsTemplateDecl());
8327     Arguments = TST->getArgs();
8328   }
8329   if (!Template)
8330     return false;
8331 
8332   if (!StdInitializerList) {
8333     // Haven't recognized std::initializer_list yet, maybe this is it.
8334     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
8335     if (TemplateClass->getIdentifier() !=
8336             &PP.getIdentifierTable().get("initializer_list") ||
8337         !getStdNamespace()->InEnclosingNamespaceSetOf(
8338             TemplateClass->getDeclContext()))
8339       return false;
8340     // This is a template called std::initializer_list, but is it the right
8341     // template?
8342     TemplateParameterList *Params = Template->getTemplateParameters();
8343     if (Params->getMinRequiredArguments() != 1)
8344       return false;
8345     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
8346       return false;
8347 
8348     // It's the right template.
8349     StdInitializerList = Template;
8350   }
8351 
8352   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
8353     return false;
8354 
8355   // This is an instance of std::initializer_list. Find the argument type.
8356   if (Element)
8357     *Element = Arguments[0].getAsType();
8358   return true;
8359 }
8360 
8361 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
8362   NamespaceDecl *Std = S.getStdNamespace();
8363   if (!Std) {
8364     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
8365     return nullptr;
8366   }
8367 
8368   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
8369                       Loc, Sema::LookupOrdinaryName);
8370   if (!S.LookupQualifiedName(Result, Std)) {
8371     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
8372     return nullptr;
8373   }
8374   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
8375   if (!Template) {
8376     Result.suppressDiagnostics();
8377     // We found something weird. Complain about the first thing we found.
8378     NamedDecl *Found = *Result.begin();
8379     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
8380     return nullptr;
8381   }
8382 
8383   // We found some template called std::initializer_list. Now verify that it's
8384   // correct.
8385   TemplateParameterList *Params = Template->getTemplateParameters();
8386   if (Params->getMinRequiredArguments() != 1 ||
8387       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
8388     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
8389     return nullptr;
8390   }
8391 
8392   return Template;
8393 }
8394 
8395 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
8396   if (!StdInitializerList) {
8397     StdInitializerList = LookupStdInitializerList(*this, Loc);
8398     if (!StdInitializerList)
8399       return QualType();
8400   }
8401 
8402   TemplateArgumentListInfo Args(Loc, Loc);
8403   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
8404                                        Context.getTrivialTypeSourceInfo(Element,
8405                                                                         Loc)));
8406   return Context.getCanonicalType(
8407       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
8408 }
8409 
8410 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
8411   // C++ [dcl.init.list]p2:
8412   //   A constructor is an initializer-list constructor if its first parameter
8413   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
8414   //   std::initializer_list<E> for some type E, and either there are no other
8415   //   parameters or else all other parameters have default arguments.
8416   if (Ctor->getNumParams() < 1 ||
8417       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
8418     return false;
8419 
8420   QualType ArgType = Ctor->getParamDecl(0)->getType();
8421   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
8422     ArgType = RT->getPointeeType().getUnqualifiedType();
8423 
8424   return isStdInitializerList(ArgType, nullptr);
8425 }
8426 
8427 /// \brief Determine whether a using statement is in a context where it will be
8428 /// apply in all contexts.
8429 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
8430   switch (CurContext->getDeclKind()) {
8431     case Decl::TranslationUnit:
8432       return true;
8433     case Decl::LinkageSpec:
8434       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
8435     default:
8436       return false;
8437   }
8438 }
8439 
8440 namespace {
8441 
8442 // Callback to only accept typo corrections that are namespaces.
8443 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
8444 public:
8445   bool ValidateCandidate(const TypoCorrection &candidate) override {
8446     if (NamedDecl *ND = candidate.getCorrectionDecl())
8447       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
8448     return false;
8449   }
8450 };
8451 
8452 }
8453 
8454 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
8455                                        CXXScopeSpec &SS,
8456                                        SourceLocation IdentLoc,
8457                                        IdentifierInfo *Ident) {
8458   R.clear();
8459   if (TypoCorrection Corrected =
8460           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
8461                         llvm::make_unique<NamespaceValidatorCCC>(),
8462                         Sema::CTK_ErrorRecovery)) {
8463     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
8464       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
8465       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
8466                               Ident->getName().equals(CorrectedStr);
8467       S.diagnoseTypo(Corrected,
8468                      S.PDiag(diag::err_using_directive_member_suggest)
8469                        << Ident << DC << DroppedSpecifier << SS.getRange(),
8470                      S.PDiag(diag::note_namespace_defined_here));
8471     } else {
8472       S.diagnoseTypo(Corrected,
8473                      S.PDiag(diag::err_using_directive_suggest) << Ident,
8474                      S.PDiag(diag::note_namespace_defined_here));
8475     }
8476     R.addDecl(Corrected.getFoundDecl());
8477     return true;
8478   }
8479   return false;
8480 }
8481 
8482 Decl *Sema::ActOnUsingDirective(Scope *S,
8483                                           SourceLocation UsingLoc,
8484                                           SourceLocation NamespcLoc,
8485                                           CXXScopeSpec &SS,
8486                                           SourceLocation IdentLoc,
8487                                           IdentifierInfo *NamespcName,
8488                                           AttributeList *AttrList) {
8489   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
8490   assert(NamespcName && "Invalid NamespcName.");
8491   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
8492 
8493   // This can only happen along a recovery path.
8494   while (S->isTemplateParamScope())
8495     S = S->getParent();
8496   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
8497 
8498   UsingDirectiveDecl *UDir = nullptr;
8499   NestedNameSpecifier *Qualifier = nullptr;
8500   if (SS.isSet())
8501     Qualifier = SS.getScopeRep();
8502 
8503   // Lookup namespace name.
8504   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
8505   LookupParsedName(R, S, &SS);
8506   if (R.isAmbiguous())
8507     return nullptr;
8508 
8509   if (R.empty()) {
8510     R.clear();
8511     // Allow "using namespace std;" or "using namespace ::std;" even if
8512     // "std" hasn't been defined yet, for GCC compatibility.
8513     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
8514         NamespcName->isStr("std")) {
8515       Diag(IdentLoc, diag::ext_using_undefined_std);
8516       R.addDecl(getOrCreateStdNamespace());
8517       R.resolveKind();
8518     }
8519     // Otherwise, attempt typo correction.
8520     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
8521   }
8522 
8523   if (!R.empty()) {
8524     NamedDecl *Named = R.getRepresentativeDecl();
8525     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
8526     assert(NS && "expected namespace decl");
8527 
8528     // The use of a nested name specifier may trigger deprecation warnings.
8529     DiagnoseUseOfDecl(Named, IdentLoc);
8530 
8531     // C++ [namespace.udir]p1:
8532     //   A using-directive specifies that the names in the nominated
8533     //   namespace can be used in the scope in which the
8534     //   using-directive appears after the using-directive. During
8535     //   unqualified name lookup (3.4.1), the names appear as if they
8536     //   were declared in the nearest enclosing namespace which
8537     //   contains both the using-directive and the nominated
8538     //   namespace. [Note: in this context, "contains" means "contains
8539     //   directly or indirectly". ]
8540 
8541     // Find enclosing context containing both using-directive and
8542     // nominated namespace.
8543     DeclContext *CommonAncestor = cast<DeclContext>(NS);
8544     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
8545       CommonAncestor = CommonAncestor->getParent();
8546 
8547     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
8548                                       SS.getWithLocInContext(Context),
8549                                       IdentLoc, Named, CommonAncestor);
8550 
8551     if (IsUsingDirectiveInToplevelContext(CurContext) &&
8552         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
8553       Diag(IdentLoc, diag::warn_using_directive_in_header);
8554     }
8555 
8556     PushUsingDirective(S, UDir);
8557   } else {
8558     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
8559   }
8560 
8561   if (UDir)
8562     ProcessDeclAttributeList(S, UDir, AttrList);
8563 
8564   return UDir;
8565 }
8566 
8567 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
8568   // If the scope has an associated entity and the using directive is at
8569   // namespace or translation unit scope, add the UsingDirectiveDecl into
8570   // its lookup structure so qualified name lookup can find it.
8571   DeclContext *Ctx = S->getEntity();
8572   if (Ctx && !Ctx->isFunctionOrMethod())
8573     Ctx->addDecl(UDir);
8574   else
8575     // Otherwise, it is at block scope. The using-directives will affect lookup
8576     // only to the end of the scope.
8577     S->PushUsingDirective(UDir);
8578 }
8579 
8580 
8581 Decl *Sema::ActOnUsingDeclaration(Scope *S,
8582                                   AccessSpecifier AS,
8583                                   bool HasUsingKeyword,
8584                                   SourceLocation UsingLoc,
8585                                   CXXScopeSpec &SS,
8586                                   UnqualifiedId &Name,
8587                                   AttributeList *AttrList,
8588                                   bool HasTypenameKeyword,
8589                                   SourceLocation TypenameLoc) {
8590   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
8591 
8592   switch (Name.getKind()) {
8593   case UnqualifiedId::IK_ImplicitSelfParam:
8594   case UnqualifiedId::IK_Identifier:
8595   case UnqualifiedId::IK_OperatorFunctionId:
8596   case UnqualifiedId::IK_LiteralOperatorId:
8597   case UnqualifiedId::IK_ConversionFunctionId:
8598     break;
8599 
8600   case UnqualifiedId::IK_ConstructorName:
8601   case UnqualifiedId::IK_ConstructorTemplateId:
8602     // C++11 inheriting constructors.
8603     Diag(Name.getLocStart(),
8604          getLangOpts().CPlusPlus11 ?
8605            diag::warn_cxx98_compat_using_decl_constructor :
8606            diag::err_using_decl_constructor)
8607       << SS.getRange();
8608 
8609     if (getLangOpts().CPlusPlus11) break;
8610 
8611     return nullptr;
8612 
8613   case UnqualifiedId::IK_DestructorName:
8614     Diag(Name.getLocStart(), diag::err_using_decl_destructor)
8615       << SS.getRange();
8616     return nullptr;
8617 
8618   case UnqualifiedId::IK_TemplateId:
8619     Diag(Name.getLocStart(), diag::err_using_decl_template_id)
8620       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
8621     return nullptr;
8622   }
8623 
8624   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
8625   DeclarationName TargetName = TargetNameInfo.getName();
8626   if (!TargetName)
8627     return nullptr;
8628 
8629   // Warn about access declarations.
8630   if (!HasUsingKeyword) {
8631     Diag(Name.getLocStart(),
8632          getLangOpts().CPlusPlus11 ? diag::err_access_decl
8633                                    : diag::warn_access_decl_deprecated)
8634       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
8635   }
8636 
8637   if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
8638       DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
8639     return nullptr;
8640 
8641   NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
8642                                         TargetNameInfo, AttrList,
8643                                         /* IsInstantiation */ false,
8644                                         HasTypenameKeyword, TypenameLoc);
8645   if (UD)
8646     PushOnScopeChains(UD, S, /*AddToContext*/ false);
8647 
8648   return UD;
8649 }
8650 
8651 /// \brief Determine whether a using declaration considers the given
8652 /// declarations as "equivalent", e.g., if they are redeclarations of
8653 /// the same entity or are both typedefs of the same type.
8654 static bool
8655 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
8656   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
8657     return true;
8658 
8659   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
8660     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
8661       return Context.hasSameType(TD1->getUnderlyingType(),
8662                                  TD2->getUnderlyingType());
8663 
8664   return false;
8665 }
8666 
8667 
8668 /// Determines whether to create a using shadow decl for a particular
8669 /// decl, given the set of decls existing prior to this using lookup.
8670 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
8671                                 const LookupResult &Previous,
8672                                 UsingShadowDecl *&PrevShadow) {
8673   // Diagnose finding a decl which is not from a base class of the
8674   // current class.  We do this now because there are cases where this
8675   // function will silently decide not to build a shadow decl, which
8676   // will pre-empt further diagnostics.
8677   //
8678   // We don't need to do this in C++11 because we do the check once on
8679   // the qualifier.
8680   //
8681   // FIXME: diagnose the following if we care enough:
8682   //   struct A { int foo; };
8683   //   struct B : A { using A::foo; };
8684   //   template <class T> struct C : A {};
8685   //   template <class T> struct D : C<T> { using B::foo; } // <---
8686   // This is invalid (during instantiation) in C++03 because B::foo
8687   // resolves to the using decl in B, which is not a base class of D<T>.
8688   // We can't diagnose it immediately because C<T> is an unknown
8689   // specialization.  The UsingShadowDecl in D<T> then points directly
8690   // to A::foo, which will look well-formed when we instantiate.
8691   // The right solution is to not collapse the shadow-decl chain.
8692   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
8693     DeclContext *OrigDC = Orig->getDeclContext();
8694 
8695     // Handle enums and anonymous structs.
8696     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
8697     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
8698     while (OrigRec->isAnonymousStructOrUnion())
8699       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
8700 
8701     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
8702       if (OrigDC == CurContext) {
8703         Diag(Using->getLocation(),
8704              diag::err_using_decl_nested_name_specifier_is_current_class)
8705           << Using->getQualifierLoc().getSourceRange();
8706         Diag(Orig->getLocation(), diag::note_using_decl_target);
8707         return true;
8708       }
8709 
8710       Diag(Using->getQualifierLoc().getBeginLoc(),
8711            diag::err_using_decl_nested_name_specifier_is_not_base_class)
8712         << Using->getQualifier()
8713         << cast<CXXRecordDecl>(CurContext)
8714         << Using->getQualifierLoc().getSourceRange();
8715       Diag(Orig->getLocation(), diag::note_using_decl_target);
8716       return true;
8717     }
8718   }
8719 
8720   if (Previous.empty()) return false;
8721 
8722   NamedDecl *Target = Orig;
8723   if (isa<UsingShadowDecl>(Target))
8724     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
8725 
8726   // If the target happens to be one of the previous declarations, we
8727   // don't have a conflict.
8728   //
8729   // FIXME: but we might be increasing its access, in which case we
8730   // should redeclare it.
8731   NamedDecl *NonTag = nullptr, *Tag = nullptr;
8732   bool FoundEquivalentDecl = false;
8733   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8734          I != E; ++I) {
8735     NamedDecl *D = (*I)->getUnderlyingDecl();
8736     // We can have UsingDecls in our Previous results because we use the same
8737     // LookupResult for checking whether the UsingDecl itself is a valid
8738     // redeclaration.
8739     if (isa<UsingDecl>(D))
8740       continue;
8741 
8742     if (IsEquivalentForUsingDecl(Context, D, Target)) {
8743       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
8744         PrevShadow = Shadow;
8745       FoundEquivalentDecl = true;
8746     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
8747       // We don't conflict with an existing using shadow decl of an equivalent
8748       // declaration, but we're not a redeclaration of it.
8749       FoundEquivalentDecl = true;
8750     }
8751 
8752     if (isVisible(D))
8753       (isa<TagDecl>(D) ? Tag : NonTag) = D;
8754   }
8755 
8756   if (FoundEquivalentDecl)
8757     return false;
8758 
8759   if (FunctionDecl *FD = Target->getAsFunction()) {
8760     NamedDecl *OldDecl = nullptr;
8761     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
8762                           /*IsForUsingDecl*/ true)) {
8763     case Ovl_Overload:
8764       return false;
8765 
8766     case Ovl_NonFunction:
8767       Diag(Using->getLocation(), diag::err_using_decl_conflict);
8768       break;
8769 
8770     // We found a decl with the exact signature.
8771     case Ovl_Match:
8772       // If we're in a record, we want to hide the target, so we
8773       // return true (without a diagnostic) to tell the caller not to
8774       // build a shadow decl.
8775       if (CurContext->isRecord())
8776         return true;
8777 
8778       // If we're not in a record, this is an error.
8779       Diag(Using->getLocation(), diag::err_using_decl_conflict);
8780       break;
8781     }
8782 
8783     Diag(Target->getLocation(), diag::note_using_decl_target);
8784     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
8785     return true;
8786   }
8787 
8788   // Target is not a function.
8789 
8790   if (isa<TagDecl>(Target)) {
8791     // No conflict between a tag and a non-tag.
8792     if (!Tag) return false;
8793 
8794     Diag(Using->getLocation(), diag::err_using_decl_conflict);
8795     Diag(Target->getLocation(), diag::note_using_decl_target);
8796     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
8797     return true;
8798   }
8799 
8800   // No conflict between a tag and a non-tag.
8801   if (!NonTag) return false;
8802 
8803   Diag(Using->getLocation(), diag::err_using_decl_conflict);
8804   Diag(Target->getLocation(), diag::note_using_decl_target);
8805   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
8806   return true;
8807 }
8808 
8809 /// Determine whether a direct base class is a virtual base class.
8810 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
8811   if (!Derived->getNumVBases())
8812     return false;
8813   for (auto &B : Derived->bases())
8814     if (B.getType()->getAsCXXRecordDecl() == Base)
8815       return B.isVirtual();
8816   llvm_unreachable("not a direct base class");
8817 }
8818 
8819 /// Builds a shadow declaration corresponding to a 'using' declaration.
8820 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
8821                                             UsingDecl *UD,
8822                                             NamedDecl *Orig,
8823                                             UsingShadowDecl *PrevDecl) {
8824   // If we resolved to another shadow declaration, just coalesce them.
8825   NamedDecl *Target = Orig;
8826   if (isa<UsingShadowDecl>(Target)) {
8827     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
8828     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
8829   }
8830 
8831   NamedDecl *NonTemplateTarget = Target;
8832   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
8833     NonTemplateTarget = TargetTD->getTemplatedDecl();
8834 
8835   UsingShadowDecl *Shadow;
8836   if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
8837     bool IsVirtualBase =
8838         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
8839                             UD->getQualifier()->getAsRecordDecl());
8840     Shadow = ConstructorUsingShadowDecl::Create(
8841         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
8842   } else {
8843     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
8844                                      Target);
8845   }
8846   UD->addShadowDecl(Shadow);
8847 
8848   Shadow->setAccess(UD->getAccess());
8849   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
8850     Shadow->setInvalidDecl();
8851 
8852   Shadow->setPreviousDecl(PrevDecl);
8853 
8854   if (S)
8855     PushOnScopeChains(Shadow, S);
8856   else
8857     CurContext->addDecl(Shadow);
8858 
8859 
8860   return Shadow;
8861 }
8862 
8863 /// Hides a using shadow declaration.  This is required by the current
8864 /// using-decl implementation when a resolvable using declaration in a
8865 /// class is followed by a declaration which would hide or override
8866 /// one or more of the using decl's targets; for example:
8867 ///
8868 ///   struct Base { void foo(int); };
8869 ///   struct Derived : Base {
8870 ///     using Base::foo;
8871 ///     void foo(int);
8872 ///   };
8873 ///
8874 /// The governing language is C++03 [namespace.udecl]p12:
8875 ///
8876 ///   When a using-declaration brings names from a base class into a
8877 ///   derived class scope, member functions in the derived class
8878 ///   override and/or hide member functions with the same name and
8879 ///   parameter types in a base class (rather than conflicting).
8880 ///
8881 /// There are two ways to implement this:
8882 ///   (1) optimistically create shadow decls when they're not hidden
8883 ///       by existing declarations, or
8884 ///   (2) don't create any shadow decls (or at least don't make them
8885 ///       visible) until we've fully parsed/instantiated the class.
8886 /// The problem with (1) is that we might have to retroactively remove
8887 /// a shadow decl, which requires several O(n) operations because the
8888 /// decl structures are (very reasonably) not designed for removal.
8889 /// (2) avoids this but is very fiddly and phase-dependent.
8890 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
8891   if (Shadow->getDeclName().getNameKind() ==
8892         DeclarationName::CXXConversionFunctionName)
8893     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
8894 
8895   // Remove it from the DeclContext...
8896   Shadow->getDeclContext()->removeDecl(Shadow);
8897 
8898   // ...and the scope, if applicable...
8899   if (S) {
8900     S->RemoveDecl(Shadow);
8901     IdResolver.RemoveDecl(Shadow);
8902   }
8903 
8904   // ...and the using decl.
8905   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
8906 
8907   // TODO: complain somehow if Shadow was used.  It shouldn't
8908   // be possible for this to happen, because...?
8909 }
8910 
8911 /// Find the base specifier for a base class with the given type.
8912 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
8913                                                 QualType DesiredBase,
8914                                                 bool &AnyDependentBases) {
8915   // Check whether the named type is a direct base class.
8916   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
8917   for (auto &Base : Derived->bases()) {
8918     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
8919     if (CanonicalDesiredBase == BaseType)
8920       return &Base;
8921     if (BaseType->isDependentType())
8922       AnyDependentBases = true;
8923   }
8924   return nullptr;
8925 }
8926 
8927 namespace {
8928 class UsingValidatorCCC : public CorrectionCandidateCallback {
8929 public:
8930   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
8931                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
8932       : HasTypenameKeyword(HasTypenameKeyword),
8933         IsInstantiation(IsInstantiation), OldNNS(NNS),
8934         RequireMemberOf(RequireMemberOf) {}
8935 
8936   bool ValidateCandidate(const TypoCorrection &Candidate) override {
8937     NamedDecl *ND = Candidate.getCorrectionDecl();
8938 
8939     // Keywords are not valid here.
8940     if (!ND || isa<NamespaceDecl>(ND))
8941       return false;
8942 
8943     // Completely unqualified names are invalid for a 'using' declaration.
8944     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
8945       return false;
8946 
8947     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
8948     // reject.
8949 
8950     if (RequireMemberOf) {
8951       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
8952       if (FoundRecord && FoundRecord->isInjectedClassName()) {
8953         // No-one ever wants a using-declaration to name an injected-class-name
8954         // of a base class, unless they're declaring an inheriting constructor.
8955         ASTContext &Ctx = ND->getASTContext();
8956         if (!Ctx.getLangOpts().CPlusPlus11)
8957           return false;
8958         QualType FoundType = Ctx.getRecordType(FoundRecord);
8959 
8960         // Check that the injected-class-name is named as a member of its own
8961         // type; we don't want to suggest 'using Derived::Base;', since that
8962         // means something else.
8963         NestedNameSpecifier *Specifier =
8964             Candidate.WillReplaceSpecifier()
8965                 ? Candidate.getCorrectionSpecifier()
8966                 : OldNNS;
8967         if (!Specifier->getAsType() ||
8968             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
8969           return false;
8970 
8971         // Check that this inheriting constructor declaration actually names a
8972         // direct base class of the current class.
8973         bool AnyDependentBases = false;
8974         if (!findDirectBaseWithType(RequireMemberOf,
8975                                     Ctx.getRecordType(FoundRecord),
8976                                     AnyDependentBases) &&
8977             !AnyDependentBases)
8978           return false;
8979       } else {
8980         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
8981         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
8982           return false;
8983 
8984         // FIXME: Check that the base class member is accessible?
8985       }
8986     } else {
8987       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
8988       if (FoundRecord && FoundRecord->isInjectedClassName())
8989         return false;
8990     }
8991 
8992     if (isa<TypeDecl>(ND))
8993       return HasTypenameKeyword || !IsInstantiation;
8994 
8995     return !HasTypenameKeyword;
8996   }
8997 
8998 private:
8999   bool HasTypenameKeyword;
9000   bool IsInstantiation;
9001   NestedNameSpecifier *OldNNS;
9002   CXXRecordDecl *RequireMemberOf;
9003 };
9004 } // end anonymous namespace
9005 
9006 /// Builds a using declaration.
9007 ///
9008 /// \param IsInstantiation - Whether this call arises from an
9009 ///   instantiation of an unresolved using declaration.  We treat
9010 ///   the lookup differently for these declarations.
9011 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
9012                                        SourceLocation UsingLoc,
9013                                        CXXScopeSpec &SS,
9014                                        DeclarationNameInfo NameInfo,
9015                                        AttributeList *AttrList,
9016                                        bool IsInstantiation,
9017                                        bool HasTypenameKeyword,
9018                                        SourceLocation TypenameLoc) {
9019   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9020   SourceLocation IdentLoc = NameInfo.getLoc();
9021   assert(IdentLoc.isValid() && "Invalid TargetName location.");
9022 
9023   // FIXME: We ignore attributes for now.
9024 
9025   if (SS.isEmpty()) {
9026     Diag(IdentLoc, diag::err_using_requires_qualname);
9027     return nullptr;
9028   }
9029 
9030   // For an inheriting constructor declaration, the name of the using
9031   // declaration is the name of a constructor in this class, not in the
9032   // base class.
9033   DeclarationNameInfo UsingName = NameInfo;
9034   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9035     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9036       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9037           Context.getCanonicalType(Context.getRecordType(RD))));
9038 
9039   // Do the redeclaration lookup in the current scope.
9040   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
9041                         ForRedeclaration);
9042   Previous.setHideTags(false);
9043   if (S) {
9044     LookupName(Previous, S);
9045 
9046     // It is really dumb that we have to do this.
9047     LookupResult::Filter F = Previous.makeFilter();
9048     while (F.hasNext()) {
9049       NamedDecl *D = F.next();
9050       if (!isDeclInScope(D, CurContext, S))
9051         F.erase();
9052       // If we found a local extern declaration that's not ordinarily visible,
9053       // and this declaration is being added to a non-block scope, ignore it.
9054       // We're only checking for scope conflicts here, not also for violations
9055       // of the linkage rules.
9056       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
9057                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
9058         F.erase();
9059     }
9060     F.done();
9061   } else {
9062     assert(IsInstantiation && "no scope in non-instantiation");
9063     assert(CurContext->isRecord() && "scope not record in instantiation");
9064     LookupQualifiedName(Previous, CurContext);
9065   }
9066 
9067   // Check for invalid redeclarations.
9068   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
9069                                   SS, IdentLoc, Previous))
9070     return nullptr;
9071 
9072   // Check for bad qualifiers.
9073   if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
9074     return nullptr;
9075 
9076   DeclContext *LookupContext = computeDeclContext(SS);
9077   NamedDecl *D;
9078   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9079   if (!LookupContext) {
9080     if (HasTypenameKeyword) {
9081       // FIXME: not all declaration name kinds are legal here
9082       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
9083                                               UsingLoc, TypenameLoc,
9084                                               QualifierLoc,
9085                                               IdentLoc, NameInfo.getName());
9086     } else {
9087       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
9088                                            QualifierLoc, NameInfo);
9089     }
9090     D->setAccess(AS);
9091     CurContext->addDecl(D);
9092     return D;
9093   }
9094 
9095   auto Build = [&](bool Invalid) {
9096     UsingDecl *UD =
9097         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
9098                           UsingName, HasTypenameKeyword);
9099     UD->setAccess(AS);
9100     CurContext->addDecl(UD);
9101     UD->setInvalidDecl(Invalid);
9102     return UD;
9103   };
9104   auto BuildInvalid = [&]{ return Build(true); };
9105   auto BuildValid = [&]{ return Build(false); };
9106 
9107   if (RequireCompleteDeclContext(SS, LookupContext))
9108     return BuildInvalid();
9109 
9110   // Look up the target name.
9111   LookupResult R(*this, NameInfo, LookupOrdinaryName);
9112 
9113   // Unlike most lookups, we don't always want to hide tag
9114   // declarations: tag names are visible through the using declaration
9115   // even if hidden by ordinary names, *except* in a dependent context
9116   // where it's important for the sanity of two-phase lookup.
9117   if (!IsInstantiation)
9118     R.setHideTags(false);
9119 
9120   // For the purposes of this lookup, we have a base object type
9121   // equal to that of the current context.
9122   if (CurContext->isRecord()) {
9123     R.setBaseObjectType(
9124                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
9125   }
9126 
9127   LookupQualifiedName(R, LookupContext);
9128 
9129   // Try to correct typos if possible. If constructor name lookup finds no
9130   // results, that means the named class has no explicit constructors, and we
9131   // suppressed declaring implicit ones (probably because it's dependent or
9132   // invalid).
9133   if (R.empty() &&
9134       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
9135     if (TypoCorrection Corrected = CorrectTypo(
9136             R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
9137             llvm::make_unique<UsingValidatorCCC>(
9138                 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
9139                 dyn_cast<CXXRecordDecl>(CurContext)),
9140             CTK_ErrorRecovery)) {
9141       // We reject any correction for which ND would be NULL.
9142       NamedDecl *ND = Corrected.getCorrectionDecl();
9143 
9144       // We reject candidates where DroppedSpecifier == true, hence the
9145       // literal '0' below.
9146       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
9147                                 << NameInfo.getName() << LookupContext << 0
9148                                 << SS.getRange());
9149 
9150       // If we corrected to an inheriting constructor, handle it as one.
9151       auto *RD = dyn_cast<CXXRecordDecl>(ND);
9152       if (RD && RD->isInjectedClassName()) {
9153         // The parent of the injected class name is the class itself.
9154         RD = cast<CXXRecordDecl>(RD->getParent());
9155 
9156         // Fix up the information we'll use to build the using declaration.
9157         if (Corrected.WillReplaceSpecifier()) {
9158           NestedNameSpecifierLocBuilder Builder;
9159           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
9160                               QualifierLoc.getSourceRange());
9161           QualifierLoc = Builder.getWithLocInContext(Context);
9162         }
9163 
9164         // In this case, the name we introduce is the name of a derived class
9165         // constructor.
9166         auto *CurClass = cast<CXXRecordDecl>(CurContext);
9167         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9168             Context.getCanonicalType(Context.getRecordType(CurClass))));
9169         UsingName.setNamedTypeInfo(nullptr);
9170         for (auto *Ctor : LookupConstructors(RD))
9171           R.addDecl(Ctor);
9172         R.resolveKind();
9173       } else {
9174         // FIXME: Pick up all the declarations if we found an overloaded
9175         // function.
9176         UsingName.setName(ND->getDeclName());
9177         R.addDecl(ND);
9178       }
9179     } else {
9180       Diag(IdentLoc, diag::err_no_member)
9181         << NameInfo.getName() << LookupContext << SS.getRange();
9182       return BuildInvalid();
9183     }
9184   }
9185 
9186   if (R.isAmbiguous())
9187     return BuildInvalid();
9188 
9189   if (HasTypenameKeyword) {
9190     // If we asked for a typename and got a non-type decl, error out.
9191     if (!R.getAsSingle<TypeDecl>()) {
9192       Diag(IdentLoc, diag::err_using_typename_non_type);
9193       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9194         Diag((*I)->getUnderlyingDecl()->getLocation(),
9195              diag::note_using_decl_target);
9196       return BuildInvalid();
9197     }
9198   } else {
9199     // If we asked for a non-typename and we got a type, error out,
9200     // but only if this is an instantiation of an unresolved using
9201     // decl.  Otherwise just silently find the type name.
9202     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
9203       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
9204       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
9205       return BuildInvalid();
9206     }
9207   }
9208 
9209   // C++14 [namespace.udecl]p6:
9210   // A using-declaration shall not name a namespace.
9211   if (R.getAsSingle<NamespaceDecl>()) {
9212     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
9213       << SS.getRange();
9214     return BuildInvalid();
9215   }
9216 
9217   // C++14 [namespace.udecl]p7:
9218   // A using-declaration shall not name a scoped enumerator.
9219   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
9220     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
9221       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
9222         << SS.getRange();
9223       return BuildInvalid();
9224     }
9225   }
9226 
9227   UsingDecl *UD = BuildValid();
9228 
9229   // Some additional rules apply to inheriting constructors.
9230   if (UsingName.getName().getNameKind() ==
9231         DeclarationName::CXXConstructorName) {
9232     // Suppress access diagnostics; the access check is instead performed at the
9233     // point of use for an inheriting constructor.
9234     R.suppressDiagnostics();
9235     if (CheckInheritingConstructorUsingDecl(UD))
9236       return UD;
9237   }
9238 
9239   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
9240     UsingShadowDecl *PrevDecl = nullptr;
9241     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
9242       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
9243   }
9244 
9245   return UD;
9246 }
9247 
9248 /// Additional checks for a using declaration referring to a constructor name.
9249 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
9250   assert(!UD->hasTypename() && "expecting a constructor name");
9251 
9252   const Type *SourceType = UD->getQualifier()->getAsType();
9253   assert(SourceType &&
9254          "Using decl naming constructor doesn't have type in scope spec.");
9255   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
9256 
9257   // Check whether the named type is a direct base class.
9258   bool AnyDependentBases = false;
9259   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
9260                                       AnyDependentBases);
9261   if (!Base && !AnyDependentBases) {
9262     Diag(UD->getUsingLoc(),
9263          diag::err_using_decl_constructor_not_in_direct_base)
9264       << UD->getNameInfo().getSourceRange()
9265       << QualType(SourceType, 0) << TargetClass;
9266     UD->setInvalidDecl();
9267     return true;
9268   }
9269 
9270   if (Base)
9271     Base->setInheritConstructors();
9272 
9273   return false;
9274 }
9275 
9276 /// Checks that the given using declaration is not an invalid
9277 /// redeclaration.  Note that this is checking only for the using decl
9278 /// itself, not for any ill-formedness among the UsingShadowDecls.
9279 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
9280                                        bool HasTypenameKeyword,
9281                                        const CXXScopeSpec &SS,
9282                                        SourceLocation NameLoc,
9283                                        const LookupResult &Prev) {
9284   // C++03 [namespace.udecl]p8:
9285   // C++0x [namespace.udecl]p10:
9286   //   A using-declaration is a declaration and can therefore be used
9287   //   repeatedly where (and only where) multiple declarations are
9288   //   allowed.
9289   //
9290   // That's in non-member contexts.
9291   if (!CurContext->getRedeclContext()->isRecord())
9292     return false;
9293 
9294   NestedNameSpecifier *Qual = SS.getScopeRep();
9295 
9296   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
9297     NamedDecl *D = *I;
9298 
9299     bool DTypename;
9300     NestedNameSpecifier *DQual;
9301     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
9302       DTypename = UD->hasTypename();
9303       DQual = UD->getQualifier();
9304     } else if (UnresolvedUsingValueDecl *UD
9305                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
9306       DTypename = false;
9307       DQual = UD->getQualifier();
9308     } else if (UnresolvedUsingTypenameDecl *UD
9309                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
9310       DTypename = true;
9311       DQual = UD->getQualifier();
9312     } else continue;
9313 
9314     // using decls differ if one says 'typename' and the other doesn't.
9315     // FIXME: non-dependent using decls?
9316     if (HasTypenameKeyword != DTypename) continue;
9317 
9318     // using decls differ if they name different scopes (but note that
9319     // template instantiation can cause this check to trigger when it
9320     // didn't before instantiation).
9321     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
9322         Context.getCanonicalNestedNameSpecifier(DQual))
9323       continue;
9324 
9325     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
9326     Diag(D->getLocation(), diag::note_using_decl) << 1;
9327     return true;
9328   }
9329 
9330   return false;
9331 }
9332 
9333 
9334 /// Checks that the given nested-name qualifier used in a using decl
9335 /// in the current context is appropriately related to the current
9336 /// scope.  If an error is found, diagnoses it and returns true.
9337 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
9338                                    const CXXScopeSpec &SS,
9339                                    const DeclarationNameInfo &NameInfo,
9340                                    SourceLocation NameLoc) {
9341   DeclContext *NamedContext = computeDeclContext(SS);
9342 
9343   if (!CurContext->isRecord()) {
9344     // C++03 [namespace.udecl]p3:
9345     // C++0x [namespace.udecl]p8:
9346     //   A using-declaration for a class member shall be a member-declaration.
9347 
9348     // If we weren't able to compute a valid scope, it must be a
9349     // dependent class scope.
9350     if (!NamedContext || NamedContext->getRedeclContext()->isRecord()) {
9351       auto *RD = NamedContext
9352                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
9353                      : nullptr;
9354       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
9355         RD = nullptr;
9356 
9357       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
9358         << SS.getRange();
9359 
9360       // If we have a complete, non-dependent source type, try to suggest a
9361       // way to get the same effect.
9362       if (!RD)
9363         return true;
9364 
9365       // Find what this using-declaration was referring to.
9366       LookupResult R(*this, NameInfo, LookupOrdinaryName);
9367       R.setHideTags(false);
9368       R.suppressDiagnostics();
9369       LookupQualifiedName(R, RD);
9370 
9371       if (R.getAsSingle<TypeDecl>()) {
9372         if (getLangOpts().CPlusPlus11) {
9373           // Convert 'using X::Y;' to 'using Y = X::Y;'.
9374           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
9375             << 0 // alias declaration
9376             << FixItHint::CreateInsertion(SS.getBeginLoc(),
9377                                           NameInfo.getName().getAsString() +
9378                                               " = ");
9379         } else {
9380           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
9381           SourceLocation InsertLoc =
9382               getLocForEndOfToken(NameInfo.getLocEnd());
9383           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
9384             << 1 // typedef declaration
9385             << FixItHint::CreateReplacement(UsingLoc, "typedef")
9386             << FixItHint::CreateInsertion(
9387                    InsertLoc, " " + NameInfo.getName().getAsString());
9388         }
9389       } else if (R.getAsSingle<VarDecl>()) {
9390         // Don't provide a fixit outside C++11 mode; we don't want to suggest
9391         // repeating the type of the static data member here.
9392         FixItHint FixIt;
9393         if (getLangOpts().CPlusPlus11) {
9394           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
9395           FixIt = FixItHint::CreateReplacement(
9396               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
9397         }
9398 
9399         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
9400           << 2 // reference declaration
9401           << FixIt;
9402       } else if (R.getAsSingle<EnumConstantDecl>()) {
9403         // Don't provide a fixit outside C++11 mode; we don't want to suggest
9404         // repeating the type of the enumeration here, and we can't do so if
9405         // the type is anonymous.
9406         FixItHint FixIt;
9407         if (getLangOpts().CPlusPlus11) {
9408           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
9409           FixIt = FixItHint::CreateReplacement(
9410               UsingLoc, "constexpr auto " + NameInfo.getName().getAsString() + " = ");
9411         }
9412 
9413         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
9414           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
9415           << FixIt;
9416       }
9417       return true;
9418     }
9419 
9420     // Otherwise, everything is known to be fine.
9421     return false;
9422   }
9423 
9424   // The current scope is a record.
9425 
9426   // If the named context is dependent, we can't decide much.
9427   if (!NamedContext) {
9428     // FIXME: in C++0x, we can diagnose if we can prove that the
9429     // nested-name-specifier does not refer to a base class, which is
9430     // still possible in some cases.
9431 
9432     // Otherwise we have to conservatively report that things might be
9433     // okay.
9434     return false;
9435   }
9436 
9437   if (!NamedContext->isRecord()) {
9438     // Ideally this would point at the last name in the specifier,
9439     // but we don't have that level of source info.
9440     Diag(SS.getRange().getBegin(),
9441          diag::err_using_decl_nested_name_specifier_is_not_class)
9442       << SS.getScopeRep() << SS.getRange();
9443     return true;
9444   }
9445 
9446   if (!NamedContext->isDependentContext() &&
9447       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
9448     return true;
9449 
9450   if (getLangOpts().CPlusPlus11) {
9451     // C++11 [namespace.udecl]p3:
9452     //   In a using-declaration used as a member-declaration, the
9453     //   nested-name-specifier shall name a base class of the class
9454     //   being defined.
9455 
9456     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
9457                                  cast<CXXRecordDecl>(NamedContext))) {
9458       if (CurContext == NamedContext) {
9459         Diag(NameLoc,
9460              diag::err_using_decl_nested_name_specifier_is_current_class)
9461           << SS.getRange();
9462         return true;
9463       }
9464 
9465       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
9466         Diag(SS.getRange().getBegin(),
9467              diag::err_using_decl_nested_name_specifier_is_not_base_class)
9468           << SS.getScopeRep()
9469           << cast<CXXRecordDecl>(CurContext)
9470           << SS.getRange();
9471       }
9472       return true;
9473     }
9474 
9475     return false;
9476   }
9477 
9478   // C++03 [namespace.udecl]p4:
9479   //   A using-declaration used as a member-declaration shall refer
9480   //   to a member of a base class of the class being defined [etc.].
9481 
9482   // Salient point: SS doesn't have to name a base class as long as
9483   // lookup only finds members from base classes.  Therefore we can
9484   // diagnose here only if we can prove that that can't happen,
9485   // i.e. if the class hierarchies provably don't intersect.
9486 
9487   // TODO: it would be nice if "definitely valid" results were cached
9488   // in the UsingDecl and UsingShadowDecl so that these checks didn't
9489   // need to be repeated.
9490 
9491   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
9492   auto Collect = [&Bases](const CXXRecordDecl *Base) {
9493     Bases.insert(Base);
9494     return true;
9495   };
9496 
9497   // Collect all bases. Return false if we find a dependent base.
9498   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
9499     return false;
9500 
9501   // Returns true if the base is dependent or is one of the accumulated base
9502   // classes.
9503   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
9504     return !Bases.count(Base);
9505   };
9506 
9507   // Return false if the class has a dependent base or if it or one
9508   // of its bases is present in the base set of the current context.
9509   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
9510       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
9511     return false;
9512 
9513   Diag(SS.getRange().getBegin(),
9514        diag::err_using_decl_nested_name_specifier_is_not_base_class)
9515     << SS.getScopeRep()
9516     << cast<CXXRecordDecl>(CurContext)
9517     << SS.getRange();
9518 
9519   return true;
9520 }
9521 
9522 Decl *Sema::ActOnAliasDeclaration(Scope *S,
9523                                   AccessSpecifier AS,
9524                                   MultiTemplateParamsArg TemplateParamLists,
9525                                   SourceLocation UsingLoc,
9526                                   UnqualifiedId &Name,
9527                                   AttributeList *AttrList,
9528                                   TypeResult Type,
9529                                   Decl *DeclFromDeclSpec) {
9530   // Skip up to the relevant declaration scope.
9531   while (S->isTemplateParamScope())
9532     S = S->getParent();
9533   assert((S->getFlags() & Scope::DeclScope) &&
9534          "got alias-declaration outside of declaration scope");
9535 
9536   if (Type.isInvalid())
9537     return nullptr;
9538 
9539   bool Invalid = false;
9540   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
9541   TypeSourceInfo *TInfo = nullptr;
9542   GetTypeFromParser(Type.get(), &TInfo);
9543 
9544   if (DiagnoseClassNameShadow(CurContext, NameInfo))
9545     return nullptr;
9546 
9547   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
9548                                       UPPC_DeclarationType)) {
9549     Invalid = true;
9550     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9551                                              TInfo->getTypeLoc().getBeginLoc());
9552   }
9553 
9554   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
9555   LookupName(Previous, S);
9556 
9557   // Warn about shadowing the name of a template parameter.
9558   if (Previous.isSingleResult() &&
9559       Previous.getFoundDecl()->isTemplateParameter()) {
9560     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
9561     Previous.clear();
9562   }
9563 
9564   assert(Name.Kind == UnqualifiedId::IK_Identifier &&
9565          "name in alias declaration must be an identifier");
9566   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
9567                                                Name.StartLocation,
9568                                                Name.Identifier, TInfo);
9569 
9570   NewTD->setAccess(AS);
9571 
9572   if (Invalid)
9573     NewTD->setInvalidDecl();
9574 
9575   ProcessDeclAttributeList(S, NewTD, AttrList);
9576 
9577   CheckTypedefForVariablyModifiedType(S, NewTD);
9578   Invalid |= NewTD->isInvalidDecl();
9579 
9580   bool Redeclaration = false;
9581 
9582   NamedDecl *NewND;
9583   if (TemplateParamLists.size()) {
9584     TypeAliasTemplateDecl *OldDecl = nullptr;
9585     TemplateParameterList *OldTemplateParams = nullptr;
9586 
9587     if (TemplateParamLists.size() != 1) {
9588       Diag(UsingLoc, diag::err_alias_template_extra_headers)
9589         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
9590          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
9591     }
9592     TemplateParameterList *TemplateParams = TemplateParamLists[0];
9593 
9594     // Check that we can declare a template here.
9595     if (CheckTemplateDeclScope(S, TemplateParams))
9596       return nullptr;
9597 
9598     // Only consider previous declarations in the same scope.
9599     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
9600                          /*ExplicitInstantiationOrSpecialization*/false);
9601     if (!Previous.empty()) {
9602       Redeclaration = true;
9603 
9604       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
9605       if (!OldDecl && !Invalid) {
9606         Diag(UsingLoc, diag::err_redefinition_different_kind)
9607           << Name.Identifier;
9608 
9609         NamedDecl *OldD = Previous.getRepresentativeDecl();
9610         if (OldD->getLocation().isValid())
9611           Diag(OldD->getLocation(), diag::note_previous_definition);
9612 
9613         Invalid = true;
9614       }
9615 
9616       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
9617         if (TemplateParameterListsAreEqual(TemplateParams,
9618                                            OldDecl->getTemplateParameters(),
9619                                            /*Complain=*/true,
9620                                            TPL_TemplateMatch))
9621           OldTemplateParams = OldDecl->getTemplateParameters();
9622         else
9623           Invalid = true;
9624 
9625         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
9626         if (!Invalid &&
9627             !Context.hasSameType(OldTD->getUnderlyingType(),
9628                                  NewTD->getUnderlyingType())) {
9629           // FIXME: The C++0x standard does not clearly say this is ill-formed,
9630           // but we can't reasonably accept it.
9631           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
9632             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
9633           if (OldTD->getLocation().isValid())
9634             Diag(OldTD->getLocation(), diag::note_previous_definition);
9635           Invalid = true;
9636         }
9637       }
9638     }
9639 
9640     // Merge any previous default template arguments into our parameters,
9641     // and check the parameter list.
9642     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
9643                                    TPC_TypeAliasTemplate))
9644       return nullptr;
9645 
9646     TypeAliasTemplateDecl *NewDecl =
9647       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
9648                                     Name.Identifier, TemplateParams,
9649                                     NewTD);
9650     NewTD->setDescribedAliasTemplate(NewDecl);
9651 
9652     NewDecl->setAccess(AS);
9653 
9654     if (Invalid)
9655       NewDecl->setInvalidDecl();
9656     else if (OldDecl)
9657       NewDecl->setPreviousDecl(OldDecl);
9658 
9659     NewND = NewDecl;
9660   } else {
9661     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
9662       setTagNameForLinkagePurposes(TD, NewTD);
9663       handleTagNumbering(TD, S);
9664     }
9665     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
9666     NewND = NewTD;
9667   }
9668 
9669   PushOnScopeChains(NewND, S);
9670   ActOnDocumentableDecl(NewND);
9671   return NewND;
9672 }
9673 
9674 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
9675                                    SourceLocation AliasLoc,
9676                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
9677                                    SourceLocation IdentLoc,
9678                                    IdentifierInfo *Ident) {
9679 
9680   // Lookup the namespace name.
9681   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
9682   LookupParsedName(R, S, &SS);
9683 
9684   if (R.isAmbiguous())
9685     return nullptr;
9686 
9687   if (R.empty()) {
9688     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
9689       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
9690       return nullptr;
9691     }
9692   }
9693   assert(!R.isAmbiguous() && !R.empty());
9694   NamedDecl *ND = R.getRepresentativeDecl();
9695 
9696   // Check if we have a previous declaration with the same name.
9697   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
9698                      ForRedeclaration);
9699   LookupName(PrevR, S);
9700 
9701   // Check we're not shadowing a template parameter.
9702   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
9703     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
9704     PrevR.clear();
9705   }
9706 
9707   // Filter out any other lookup result from an enclosing scope.
9708   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
9709                        /*AllowInlineNamespace*/false);
9710 
9711   // Find the previous declaration and check that we can redeclare it.
9712   NamespaceAliasDecl *Prev = nullptr;
9713   if (PrevR.isSingleResult()) {
9714     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
9715     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
9716       // We already have an alias with the same name that points to the same
9717       // namespace; check that it matches.
9718       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
9719         Prev = AD;
9720       } else if (isVisible(PrevDecl)) {
9721         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
9722           << Alias;
9723         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
9724           << AD->getNamespace();
9725         return nullptr;
9726       }
9727     } else if (isVisible(PrevDecl)) {
9728       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
9729                             ? diag::err_redefinition
9730                             : diag::err_redefinition_different_kind;
9731       Diag(AliasLoc, DiagID) << Alias;
9732       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
9733       return nullptr;
9734     }
9735   }
9736 
9737   // The use of a nested name specifier may trigger deprecation warnings.
9738   DiagnoseUseOfDecl(ND, IdentLoc);
9739 
9740   NamespaceAliasDecl *AliasDecl =
9741     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
9742                                Alias, SS.getWithLocInContext(Context),
9743                                IdentLoc, ND);
9744   if (Prev)
9745     AliasDecl->setPreviousDecl(Prev);
9746 
9747   PushOnScopeChains(AliasDecl, S);
9748   return AliasDecl;
9749 }
9750 
9751 Sema::ImplicitExceptionSpecification
9752 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
9753                                                CXXMethodDecl *MD) {
9754   CXXRecordDecl *ClassDecl = MD->getParent();
9755 
9756   // C++ [except.spec]p14:
9757   //   An implicitly declared special member function (Clause 12) shall have an
9758   //   exception-specification. [...]
9759   ImplicitExceptionSpecification ExceptSpec(*this);
9760   if (ClassDecl->isInvalidDecl())
9761     return ExceptSpec;
9762 
9763   // Direct base-class constructors.
9764   for (const auto &B : ClassDecl->bases()) {
9765     if (B.isVirtual()) // Handled below.
9766       continue;
9767 
9768     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
9769       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
9770       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
9771       // If this is a deleted function, add it anyway. This might be conformant
9772       // with the standard. This might not. I'm not sure. It might not matter.
9773       if (Constructor)
9774         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
9775     }
9776   }
9777 
9778   // Virtual base-class constructors.
9779   for (const auto &B : ClassDecl->vbases()) {
9780     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
9781       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
9782       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
9783       // If this is a deleted function, add it anyway. This might be conformant
9784       // with the standard. This might not. I'm not sure. It might not matter.
9785       if (Constructor)
9786         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
9787     }
9788   }
9789 
9790   // Field constructors.
9791   for (const auto *F : ClassDecl->fields()) {
9792     if (F->hasInClassInitializer()) {
9793       if (Expr *E = F->getInClassInitializer())
9794         ExceptSpec.CalledExpr(E);
9795     } else if (const RecordType *RecordTy
9796               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
9797       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9798       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
9799       // If this is a deleted function, add it anyway. This might be conformant
9800       // with the standard. This might not. I'm not sure. It might not matter.
9801       // In particular, the problem is that this function never gets called. It
9802       // might just be ill-formed because this function attempts to refer to
9803       // a deleted function here.
9804       if (Constructor)
9805         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
9806     }
9807   }
9808 
9809   return ExceptSpec;
9810 }
9811 
9812 Sema::ImplicitExceptionSpecification
9813 Sema::ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
9814                                          CXXConstructorDecl *CD) {
9815   CXXRecordDecl *ClassDecl = CD->getParent();
9816 
9817   // C++ [except.spec]p14:
9818   //   An inheriting constructor [...] shall have an exception-specification. [...]
9819   ImplicitExceptionSpecification ExceptSpec(*this);
9820   if (ClassDecl->isInvalidDecl())
9821     return ExceptSpec;
9822 
9823   auto Inherited = CD->getInheritedConstructor();
9824   InheritedConstructorInfo ICI(*this, Loc, Inherited.getShadowDecl());
9825 
9826   // Direct and virtual base-class constructors.
9827   for (bool VBase : {false, true}) {
9828     for (CXXBaseSpecifier &B :
9829          VBase ? ClassDecl->vbases() : ClassDecl->bases()) {
9830       // Don't visit direct vbases twice.
9831       if (B.isVirtual() != VBase)
9832         continue;
9833 
9834       CXXRecordDecl *BaseClass = B.getType()->getAsCXXRecordDecl();
9835       if (!BaseClass)
9836         continue;
9837 
9838       CXXConstructorDecl *Constructor =
9839           ICI.findConstructorForBase(BaseClass, Inherited.getConstructor())
9840               .first;
9841       if (!Constructor)
9842         Constructor = LookupDefaultConstructor(BaseClass);
9843       if (Constructor)
9844         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
9845     }
9846   }
9847 
9848   // Field constructors.
9849   for (const auto *F : ClassDecl->fields()) {
9850     if (F->hasInClassInitializer()) {
9851       if (Expr *E = F->getInClassInitializer())
9852         ExceptSpec.CalledExpr(E);
9853     } else if (const RecordType *RecordTy
9854               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
9855       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9856       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
9857       if (Constructor)
9858         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
9859     }
9860   }
9861 
9862   return ExceptSpec;
9863 }
9864 
9865 namespace {
9866 /// RAII object to register a special member as being currently declared.
9867 struct DeclaringSpecialMember {
9868   Sema &S;
9869   Sema::SpecialMemberDecl D;
9870   Sema::ContextRAII SavedContext;
9871   bool WasAlreadyBeingDeclared;
9872 
9873   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
9874     : S(S), D(RD, CSM), SavedContext(S, RD) {
9875     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
9876     if (WasAlreadyBeingDeclared)
9877       // This almost never happens, but if it does, ensure that our cache
9878       // doesn't contain a stale result.
9879       S.SpecialMemberCache.clear();
9880 
9881     // FIXME: Register a note to be produced if we encounter an error while
9882     // declaring the special member.
9883   }
9884   ~DeclaringSpecialMember() {
9885     if (!WasAlreadyBeingDeclared)
9886       S.SpecialMembersBeingDeclared.erase(D);
9887   }
9888 
9889   /// \brief Are we already trying to declare this special member?
9890   bool isAlreadyBeingDeclared() const {
9891     return WasAlreadyBeingDeclared;
9892   }
9893 };
9894 }
9895 
9896 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
9897   // Look up any existing declarations, but don't trigger declaration of all
9898   // implicit special members with this name.
9899   DeclarationName Name = FD->getDeclName();
9900   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
9901                  ForRedeclaration);
9902   for (auto *D : FD->getParent()->lookup(Name))
9903     if (auto *Acceptable = R.getAcceptableDecl(D))
9904       R.addDecl(Acceptable);
9905   R.resolveKind();
9906   R.suppressDiagnostics();
9907 
9908   CheckFunctionDeclaration(S, FD, R, /*IsExplicitSpecialization*/false);
9909 }
9910 
9911 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
9912                                                      CXXRecordDecl *ClassDecl) {
9913   // C++ [class.ctor]p5:
9914   //   A default constructor for a class X is a constructor of class X
9915   //   that can be called without an argument. If there is no
9916   //   user-declared constructor for class X, a default constructor is
9917   //   implicitly declared. An implicitly-declared default constructor
9918   //   is an inline public member of its class.
9919   assert(ClassDecl->needsImplicitDefaultConstructor() &&
9920          "Should not build implicit default constructor!");
9921 
9922   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
9923   if (DSM.isAlreadyBeingDeclared())
9924     return nullptr;
9925 
9926   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9927                                                      CXXDefaultConstructor,
9928                                                      false);
9929 
9930   // Create the actual constructor declaration.
9931   CanQualType ClassType
9932     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
9933   SourceLocation ClassLoc = ClassDecl->getLocation();
9934   DeclarationName Name
9935     = Context.DeclarationNames.getCXXConstructorName(ClassType);
9936   DeclarationNameInfo NameInfo(Name, ClassLoc);
9937   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
9938       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
9939       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
9940       /*isImplicitlyDeclared=*/true, Constexpr);
9941   DefaultCon->setAccess(AS_public);
9942   DefaultCon->setDefaulted();
9943 
9944   if (getLangOpts().CUDA) {
9945     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
9946                                             DefaultCon,
9947                                             /* ConstRHS */ false,
9948                                             /* Diagnose */ false);
9949   }
9950 
9951   // Build an exception specification pointing back at this constructor.
9952   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
9953   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9954 
9955   // We don't need to use SpecialMemberIsTrivial here; triviality for default
9956   // constructors is easy to compute.
9957   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
9958 
9959   // Note that we have declared this constructor.
9960   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
9961 
9962   Scope *S = getScopeForContext(ClassDecl);
9963   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
9964 
9965   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
9966     SetDeclDeleted(DefaultCon, ClassLoc);
9967 
9968   if (S)
9969     PushOnScopeChains(DefaultCon, S, false);
9970   ClassDecl->addDecl(DefaultCon);
9971 
9972   return DefaultCon;
9973 }
9974 
9975 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
9976                                             CXXConstructorDecl *Constructor) {
9977   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
9978           !Constructor->doesThisDeclarationHaveABody() &&
9979           !Constructor->isDeleted()) &&
9980     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
9981 
9982   CXXRecordDecl *ClassDecl = Constructor->getParent();
9983   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
9984 
9985   SynthesizedFunctionScope Scope(*this, Constructor);
9986   DiagnosticErrorTrap Trap(Diags);
9987   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
9988       Trap.hasErrorOccurred()) {
9989     Diag(CurrentLocation, diag::note_member_synthesized_at)
9990       << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
9991     Constructor->setInvalidDecl();
9992     return;
9993   }
9994 
9995   // The exception specification is needed because we are defining the
9996   // function.
9997   ResolveExceptionSpec(CurrentLocation,
9998                        Constructor->getType()->castAs<FunctionProtoType>());
9999 
10000   SourceLocation Loc = Constructor->getLocEnd().isValid()
10001                            ? Constructor->getLocEnd()
10002                            : Constructor->getLocation();
10003   Constructor->setBody(new (Context) CompoundStmt(Loc));
10004 
10005   Constructor->markUsed(Context);
10006   MarkVTableUsed(CurrentLocation, ClassDecl);
10007 
10008   if (ASTMutationListener *L = getASTMutationListener()) {
10009     L->CompletedImplicitDefinition(Constructor);
10010   }
10011 
10012   DiagnoseUninitializedFields(*this, Constructor);
10013 }
10014 
10015 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
10016   // Perform any delayed checks on exception specifications.
10017   CheckDelayedMemberExceptionSpecs();
10018 }
10019 
10020 /// Find or create the fake constructor we synthesize to model constructing an
10021 /// object of a derived class via a constructor of a base class.
10022 CXXConstructorDecl *
10023 Sema::findInheritingConstructor(SourceLocation Loc,
10024                                 CXXConstructorDecl *BaseCtor,
10025                                 ConstructorUsingShadowDecl *Shadow) {
10026   CXXRecordDecl *Derived = Shadow->getParent();
10027   SourceLocation UsingLoc = Shadow->getLocation();
10028 
10029   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
10030   // For now we use the name of the base class constructor as a member of the
10031   // derived class to indicate a (fake) inherited constructor name.
10032   DeclarationName Name = BaseCtor->getDeclName();
10033 
10034   // Check to see if we already have a fake constructor for this inherited
10035   // constructor call.
10036   for (NamedDecl *Ctor : Derived->lookup(Name))
10037     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
10038                                ->getInheritedConstructor()
10039                                .getConstructor(),
10040                            BaseCtor))
10041       return cast<CXXConstructorDecl>(Ctor);
10042 
10043   DeclarationNameInfo NameInfo(Name, UsingLoc);
10044   TypeSourceInfo *TInfo =
10045       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
10046   FunctionProtoTypeLoc ProtoLoc =
10047       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
10048 
10049   // Check the inherited constructor is valid and find the list of base classes
10050   // from which it was inherited.
10051   InheritedConstructorInfo ICI(*this, Loc, Shadow);
10052 
10053   bool Constexpr =
10054       BaseCtor->isConstexpr() &&
10055       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
10056                                         false, BaseCtor, &ICI);
10057 
10058   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
10059       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
10060       BaseCtor->isExplicit(), /*Inline=*/true,
10061       /*ImplicitlyDeclared=*/true, Constexpr,
10062       InheritedConstructor(Shadow, BaseCtor));
10063   if (Shadow->isInvalidDecl())
10064     DerivedCtor->setInvalidDecl();
10065 
10066   // Build an unevaluated exception specification for this fake constructor.
10067   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
10068   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10069   EPI.ExceptionSpec.Type = EST_Unevaluated;
10070   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
10071   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
10072                                                FPT->getParamTypes(), EPI));
10073 
10074   // Build the parameter declarations.
10075   SmallVector<ParmVarDecl *, 16> ParamDecls;
10076   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
10077     TypeSourceInfo *TInfo =
10078         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
10079     ParmVarDecl *PD = ParmVarDecl::Create(
10080         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
10081         FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
10082     PD->setScopeInfo(0, I);
10083     PD->setImplicit();
10084     // Ensure attributes are propagated onto parameters (this matters for
10085     // format, pass_object_size, ...).
10086     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
10087     ParamDecls.push_back(PD);
10088     ProtoLoc.setParam(I, PD);
10089   }
10090 
10091   // Set up the new constructor.
10092   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
10093   DerivedCtor->setAccess(BaseCtor->getAccess());
10094   DerivedCtor->setParams(ParamDecls);
10095   Derived->addDecl(DerivedCtor);
10096 
10097   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
10098     SetDeclDeleted(DerivedCtor, UsingLoc);
10099 
10100   return DerivedCtor;
10101 }
10102 
10103 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
10104   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
10105                                Ctor->getInheritedConstructor().getShadowDecl());
10106   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
10107                             /*Diagnose*/true);
10108 }
10109 
10110 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
10111                                        CXXConstructorDecl *Constructor) {
10112   CXXRecordDecl *ClassDecl = Constructor->getParent();
10113   assert(Constructor->getInheritedConstructor() &&
10114          !Constructor->doesThisDeclarationHaveABody() &&
10115          !Constructor->isDeleted());
10116   if (Constructor->isInvalidDecl())
10117     return;
10118 
10119   ConstructorUsingShadowDecl *Shadow =
10120       Constructor->getInheritedConstructor().getShadowDecl();
10121   CXXConstructorDecl *InheritedCtor =
10122       Constructor->getInheritedConstructor().getConstructor();
10123 
10124   // [class.inhctor.init]p1:
10125   //   initialization proceeds as if a defaulted default constructor is used to
10126   //   initialize the D object and each base class subobject from which the
10127   //   constructor was inherited
10128 
10129   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
10130   CXXRecordDecl *RD = Shadow->getParent();
10131   SourceLocation InitLoc = Shadow->getLocation();
10132 
10133   // Initializations are performed "as if by a defaulted default constructor",
10134   // so enter the appropriate scope.
10135   SynthesizedFunctionScope Scope(*this, Constructor);
10136   DiagnosticErrorTrap Trap(Diags);
10137 
10138   // Build explicit initializers for all base classes from which the
10139   // constructor was inherited.
10140   SmallVector<CXXCtorInitializer*, 8> Inits;
10141   for (bool VBase : {false, true}) {
10142     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
10143       if (B.isVirtual() != VBase)
10144         continue;
10145 
10146       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
10147       if (!BaseRD)
10148         continue;
10149 
10150       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
10151       if (!BaseCtor.first)
10152         continue;
10153 
10154       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
10155       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
10156           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
10157 
10158       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
10159       Inits.push_back(new (Context) CXXCtorInitializer(
10160           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
10161           SourceLocation()));
10162     }
10163   }
10164 
10165   // We now proceed as if for a defaulted default constructor, with the relevant
10166   // initializers replaced.
10167 
10168   bool HadError = SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits);
10169   if (HadError || Trap.hasErrorOccurred()) {
10170     Diag(CurrentLocation, diag::note_inhctor_synthesized_at) << RD;
10171     Constructor->setInvalidDecl();
10172     return;
10173   }
10174 
10175   // The exception specification is needed because we are defining the
10176   // function.
10177   ResolveExceptionSpec(CurrentLocation,
10178                        Constructor->getType()->castAs<FunctionProtoType>());
10179 
10180   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
10181 
10182   Constructor->markUsed(Context);
10183   MarkVTableUsed(CurrentLocation, ClassDecl);
10184 
10185   if (ASTMutationListener *L = getASTMutationListener()) {
10186     L->CompletedImplicitDefinition(Constructor);
10187   }
10188 
10189   DiagnoseUninitializedFields(*this, Constructor);
10190 }
10191 
10192 Sema::ImplicitExceptionSpecification
10193 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
10194   CXXRecordDecl *ClassDecl = MD->getParent();
10195 
10196   // C++ [except.spec]p14:
10197   //   An implicitly declared special member function (Clause 12) shall have
10198   //   an exception-specification.
10199   ImplicitExceptionSpecification ExceptSpec(*this);
10200   if (ClassDecl->isInvalidDecl())
10201     return ExceptSpec;
10202 
10203   // Direct base-class destructors.
10204   for (const auto &B : ClassDecl->bases()) {
10205     if (B.isVirtual()) // Handled below.
10206       continue;
10207 
10208     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
10209       ExceptSpec.CalledDecl(B.getLocStart(),
10210                    LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
10211   }
10212 
10213   // Virtual base-class destructors.
10214   for (const auto &B : ClassDecl->vbases()) {
10215     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
10216       ExceptSpec.CalledDecl(B.getLocStart(),
10217                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
10218   }
10219 
10220   // Field destructors.
10221   for (const auto *F : ClassDecl->fields()) {
10222     if (const RecordType *RecordTy
10223         = Context.getBaseElementType(F->getType())->getAs<RecordType>())
10224       ExceptSpec.CalledDecl(F->getLocation(),
10225                   LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
10226   }
10227 
10228   return ExceptSpec;
10229 }
10230 
10231 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
10232   // C++ [class.dtor]p2:
10233   //   If a class has no user-declared destructor, a destructor is
10234   //   declared implicitly. An implicitly-declared destructor is an
10235   //   inline public member of its class.
10236   assert(ClassDecl->needsImplicitDestructor());
10237 
10238   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
10239   if (DSM.isAlreadyBeingDeclared())
10240     return nullptr;
10241 
10242   // Create the actual destructor declaration.
10243   CanQualType ClassType
10244     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10245   SourceLocation ClassLoc = ClassDecl->getLocation();
10246   DeclarationName Name
10247     = Context.DeclarationNames.getCXXDestructorName(ClassType);
10248   DeclarationNameInfo NameInfo(Name, ClassLoc);
10249   CXXDestructorDecl *Destructor
10250       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
10251                                   QualType(), nullptr, /*isInline=*/true,
10252                                   /*isImplicitlyDeclared=*/true);
10253   Destructor->setAccess(AS_public);
10254   Destructor->setDefaulted();
10255 
10256   if (getLangOpts().CUDA) {
10257     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
10258                                             Destructor,
10259                                             /* ConstRHS */ false,
10260                                             /* Diagnose */ false);
10261   }
10262 
10263   // Build an exception specification pointing back at this destructor.
10264   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
10265   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10266 
10267   // We don't need to use SpecialMemberIsTrivial here; triviality for
10268   // destructors is easy to compute.
10269   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
10270 
10271   // Note that we have declared this destructor.
10272   ++ASTContext::NumImplicitDestructorsDeclared;
10273 
10274   Scope *S = getScopeForContext(ClassDecl);
10275   CheckImplicitSpecialMemberDeclaration(S, Destructor);
10276 
10277   // We can't check whether an implicit destructor is deleted before we complete
10278   // the definition of the class, because its validity depends on the alignment
10279   // of the class. We'll check this from ActOnFields once the class is complete.
10280   if (ClassDecl->isCompleteDefinition() &&
10281       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
10282     SetDeclDeleted(Destructor, ClassLoc);
10283 
10284   // Introduce this destructor into its scope.
10285   if (S)
10286     PushOnScopeChains(Destructor, S, false);
10287   ClassDecl->addDecl(Destructor);
10288 
10289   return Destructor;
10290 }
10291 
10292 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
10293                                     CXXDestructorDecl *Destructor) {
10294   assert((Destructor->isDefaulted() &&
10295           !Destructor->doesThisDeclarationHaveABody() &&
10296           !Destructor->isDeleted()) &&
10297          "DefineImplicitDestructor - call it for implicit default dtor");
10298   CXXRecordDecl *ClassDecl = Destructor->getParent();
10299   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
10300 
10301   if (Destructor->isInvalidDecl())
10302     return;
10303 
10304   SynthesizedFunctionScope Scope(*this, Destructor);
10305 
10306   DiagnosticErrorTrap Trap(Diags);
10307   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
10308                                          Destructor->getParent());
10309 
10310   if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
10311     Diag(CurrentLocation, diag::note_member_synthesized_at)
10312       << CXXDestructor << Context.getTagDeclType(ClassDecl);
10313 
10314     Destructor->setInvalidDecl();
10315     return;
10316   }
10317 
10318   // The exception specification is needed because we are defining the
10319   // function.
10320   ResolveExceptionSpec(CurrentLocation,
10321                        Destructor->getType()->castAs<FunctionProtoType>());
10322 
10323   SourceLocation Loc = Destructor->getLocEnd().isValid()
10324                            ? Destructor->getLocEnd()
10325                            : Destructor->getLocation();
10326   Destructor->setBody(new (Context) CompoundStmt(Loc));
10327   Destructor->markUsed(Context);
10328   MarkVTableUsed(CurrentLocation, ClassDecl);
10329 
10330   if (ASTMutationListener *L = getASTMutationListener()) {
10331     L->CompletedImplicitDefinition(Destructor);
10332   }
10333 }
10334 
10335 /// \brief Perform any semantic analysis which needs to be delayed until all
10336 /// pending class member declarations have been parsed.
10337 void Sema::ActOnFinishCXXMemberDecls() {
10338   // If the context is an invalid C++ class, just suppress these checks.
10339   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
10340     if (Record->isInvalidDecl()) {
10341       DelayedDefaultedMemberExceptionSpecs.clear();
10342       DelayedExceptionSpecChecks.clear();
10343       return;
10344     }
10345   }
10346 }
10347 
10348 static void getDefaultArgExprsForConstructors(Sema &S, CXXRecordDecl *Class) {
10349   // Don't do anything for template patterns.
10350   if (Class->getDescribedClassTemplate())
10351     return;
10352 
10353   CallingConv ExpectedCallingConv = S.Context.getDefaultCallingConvention(
10354       /*IsVariadic=*/false, /*IsCXXMethod=*/true);
10355 
10356   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
10357   for (Decl *Member : Class->decls()) {
10358     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
10359     if (!CD) {
10360       // Recurse on nested classes.
10361       if (auto *NestedRD = dyn_cast<CXXRecordDecl>(Member))
10362         getDefaultArgExprsForConstructors(S, NestedRD);
10363       continue;
10364     } else if (!CD->isDefaultConstructor() || !CD->hasAttr<DLLExportAttr>()) {
10365       continue;
10366     }
10367 
10368     CallingConv ActualCallingConv =
10369         CD->getType()->getAs<FunctionProtoType>()->getCallConv();
10370 
10371     // Skip default constructors with typical calling conventions and no default
10372     // arguments.
10373     unsigned NumParams = CD->getNumParams();
10374     if (ExpectedCallingConv == ActualCallingConv && NumParams == 0)
10375       continue;
10376 
10377     if (LastExportedDefaultCtor) {
10378       S.Diag(LastExportedDefaultCtor->getLocation(),
10379              diag::err_attribute_dll_ambiguous_default_ctor) << Class;
10380       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
10381           << CD->getDeclName();
10382       return;
10383     }
10384     LastExportedDefaultCtor = CD;
10385 
10386     for (unsigned I = 0; I != NumParams; ++I) {
10387       // Skip any default arguments that we've already instantiated.
10388       if (S.Context.getDefaultArgExprForConstructor(CD, I))
10389         continue;
10390 
10391       Expr *DefaultArg = S.BuildCXXDefaultArgExpr(Class->getLocation(), CD,
10392                                                   CD->getParamDecl(I)).get();
10393       S.DiscardCleanupsInEvaluationContext();
10394       S.Context.addDefaultArgExprForConstructor(CD, I, DefaultArg);
10395     }
10396   }
10397 }
10398 
10399 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
10400   auto *RD = dyn_cast<CXXRecordDecl>(D);
10401 
10402   // Default constructors that are annotated with __declspec(dllexport) which
10403   // have default arguments or don't use the standard calling convention are
10404   // wrapped with a thunk called the default constructor closure.
10405   if (RD && Context.getTargetInfo().getCXXABI().isMicrosoft())
10406     getDefaultArgExprsForConstructors(*this, RD);
10407 
10408   referenceDLLExportedClassMethods();
10409 }
10410 
10411 void Sema::referenceDLLExportedClassMethods() {
10412   if (!DelayedDllExportClasses.empty()) {
10413     // Calling ReferenceDllExportedMethods might cause the current function to
10414     // be called again, so use a local copy of DelayedDllExportClasses.
10415     SmallVector<CXXRecordDecl *, 4> WorkList;
10416     std::swap(DelayedDllExportClasses, WorkList);
10417     for (CXXRecordDecl *Class : WorkList)
10418       ReferenceDllExportedMethods(*this, Class);
10419   }
10420 }
10421 
10422 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
10423                                          CXXDestructorDecl *Destructor) {
10424   assert(getLangOpts().CPlusPlus11 &&
10425          "adjusting dtor exception specs was introduced in c++11");
10426 
10427   // C++11 [class.dtor]p3:
10428   //   A declaration of a destructor that does not have an exception-
10429   //   specification is implicitly considered to have the same exception-
10430   //   specification as an implicit declaration.
10431   const FunctionProtoType *DtorType = Destructor->getType()->
10432                                         getAs<FunctionProtoType>();
10433   if (DtorType->hasExceptionSpec())
10434     return;
10435 
10436   // Replace the destructor's type, building off the existing one. Fortunately,
10437   // the only thing of interest in the destructor type is its extended info.
10438   // The return and arguments are fixed.
10439   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
10440   EPI.ExceptionSpec.Type = EST_Unevaluated;
10441   EPI.ExceptionSpec.SourceDecl = Destructor;
10442   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10443 
10444   // FIXME: If the destructor has a body that could throw, and the newly created
10445   // spec doesn't allow exceptions, we should emit a warning, because this
10446   // change in behavior can break conforming C++03 programs at runtime.
10447   // However, we don't have a body or an exception specification yet, so it
10448   // needs to be done somewhere else.
10449 }
10450 
10451 namespace {
10452 /// \brief An abstract base class for all helper classes used in building the
10453 //  copy/move operators. These classes serve as factory functions and help us
10454 //  avoid using the same Expr* in the AST twice.
10455 class ExprBuilder {
10456   ExprBuilder(const ExprBuilder&) = delete;
10457   ExprBuilder &operator=(const ExprBuilder&) = delete;
10458 
10459 protected:
10460   static Expr *assertNotNull(Expr *E) {
10461     assert(E && "Expression construction must not fail.");
10462     return E;
10463   }
10464 
10465 public:
10466   ExprBuilder() {}
10467   virtual ~ExprBuilder() {}
10468 
10469   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
10470 };
10471 
10472 class RefBuilder: public ExprBuilder {
10473   VarDecl *Var;
10474   QualType VarType;
10475 
10476 public:
10477   Expr *build(Sema &S, SourceLocation Loc) const override {
10478     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
10479   }
10480 
10481   RefBuilder(VarDecl *Var, QualType VarType)
10482       : Var(Var), VarType(VarType) {}
10483 };
10484 
10485 class ThisBuilder: public ExprBuilder {
10486 public:
10487   Expr *build(Sema &S, SourceLocation Loc) const override {
10488     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
10489   }
10490 };
10491 
10492 class CastBuilder: public ExprBuilder {
10493   const ExprBuilder &Builder;
10494   QualType Type;
10495   ExprValueKind Kind;
10496   const CXXCastPath &Path;
10497 
10498 public:
10499   Expr *build(Sema &S, SourceLocation Loc) const override {
10500     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
10501                                              CK_UncheckedDerivedToBase, Kind,
10502                                              &Path).get());
10503   }
10504 
10505   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
10506               const CXXCastPath &Path)
10507       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
10508 };
10509 
10510 class DerefBuilder: public ExprBuilder {
10511   const ExprBuilder &Builder;
10512 
10513 public:
10514   Expr *build(Sema &S, SourceLocation Loc) const override {
10515     return assertNotNull(
10516         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
10517   }
10518 
10519   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10520 };
10521 
10522 class MemberBuilder: public ExprBuilder {
10523   const ExprBuilder &Builder;
10524   QualType Type;
10525   CXXScopeSpec SS;
10526   bool IsArrow;
10527   LookupResult &MemberLookup;
10528 
10529 public:
10530   Expr *build(Sema &S, SourceLocation Loc) const override {
10531     return assertNotNull(S.BuildMemberReferenceExpr(
10532         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
10533         nullptr, MemberLookup, nullptr, nullptr).get());
10534   }
10535 
10536   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
10537                 LookupResult &MemberLookup)
10538       : Builder(Builder), Type(Type), IsArrow(IsArrow),
10539         MemberLookup(MemberLookup) {}
10540 };
10541 
10542 class MoveCastBuilder: public ExprBuilder {
10543   const ExprBuilder &Builder;
10544 
10545 public:
10546   Expr *build(Sema &S, SourceLocation Loc) const override {
10547     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
10548   }
10549 
10550   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10551 };
10552 
10553 class LvalueConvBuilder: public ExprBuilder {
10554   const ExprBuilder &Builder;
10555 
10556 public:
10557   Expr *build(Sema &S, SourceLocation Loc) const override {
10558     return assertNotNull(
10559         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
10560   }
10561 
10562   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10563 };
10564 
10565 class SubscriptBuilder: public ExprBuilder {
10566   const ExprBuilder &Base;
10567   const ExprBuilder &Index;
10568 
10569 public:
10570   Expr *build(Sema &S, SourceLocation Loc) const override {
10571     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
10572         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
10573   }
10574 
10575   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
10576       : Base(Base), Index(Index) {}
10577 };
10578 
10579 } // end anonymous namespace
10580 
10581 /// When generating a defaulted copy or move assignment operator, if a field
10582 /// should be copied with __builtin_memcpy rather than via explicit assignments,
10583 /// do so. This optimization only applies for arrays of scalars, and for arrays
10584 /// of class type where the selected copy/move-assignment operator is trivial.
10585 static StmtResult
10586 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
10587                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
10588   // Compute the size of the memory buffer to be copied.
10589   QualType SizeType = S.Context.getSizeType();
10590   llvm::APInt Size(S.Context.getTypeSize(SizeType),
10591                    S.Context.getTypeSizeInChars(T).getQuantity());
10592 
10593   // Take the address of the field references for "from" and "to". We
10594   // directly construct UnaryOperators here because semantic analysis
10595   // does not permit us to take the address of an xvalue.
10596   Expr *From = FromB.build(S, Loc);
10597   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
10598                          S.Context.getPointerType(From->getType()),
10599                          VK_RValue, OK_Ordinary, Loc);
10600   Expr *To = ToB.build(S, Loc);
10601   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
10602                        S.Context.getPointerType(To->getType()),
10603                        VK_RValue, OK_Ordinary, Loc);
10604 
10605   const Type *E = T->getBaseElementTypeUnsafe();
10606   bool NeedsCollectableMemCpy =
10607     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
10608 
10609   // Create a reference to the __builtin_objc_memmove_collectable function
10610   StringRef MemCpyName = NeedsCollectableMemCpy ?
10611     "__builtin_objc_memmove_collectable" :
10612     "__builtin_memcpy";
10613   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
10614                  Sema::LookupOrdinaryName);
10615   S.LookupName(R, S.TUScope, true);
10616 
10617   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
10618   if (!MemCpy)
10619     // Something went horribly wrong earlier, and we will have complained
10620     // about it.
10621     return StmtError();
10622 
10623   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
10624                                             VK_RValue, Loc, nullptr);
10625   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
10626 
10627   Expr *CallArgs[] = {
10628     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
10629   };
10630   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
10631                                     Loc, CallArgs, Loc);
10632 
10633   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
10634   return Call.getAs<Stmt>();
10635 }
10636 
10637 /// \brief Builds a statement that copies/moves the given entity from \p From to
10638 /// \c To.
10639 ///
10640 /// This routine is used to copy/move the members of a class with an
10641 /// implicitly-declared copy/move assignment operator. When the entities being
10642 /// copied are arrays, this routine builds for loops to copy them.
10643 ///
10644 /// \param S The Sema object used for type-checking.
10645 ///
10646 /// \param Loc The location where the implicit copy/move is being generated.
10647 ///
10648 /// \param T The type of the expressions being copied/moved. Both expressions
10649 /// must have this type.
10650 ///
10651 /// \param To The expression we are copying/moving to.
10652 ///
10653 /// \param From The expression we are copying/moving from.
10654 ///
10655 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
10656 /// Otherwise, it's a non-static member subobject.
10657 ///
10658 /// \param Copying Whether we're copying or moving.
10659 ///
10660 /// \param Depth Internal parameter recording the depth of the recursion.
10661 ///
10662 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
10663 /// if a memcpy should be used instead.
10664 static StmtResult
10665 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
10666                                  const ExprBuilder &To, const ExprBuilder &From,
10667                                  bool CopyingBaseSubobject, bool Copying,
10668                                  unsigned Depth = 0) {
10669   // C++11 [class.copy]p28:
10670   //   Each subobject is assigned in the manner appropriate to its type:
10671   //
10672   //     - if the subobject is of class type, as if by a call to operator= with
10673   //       the subobject as the object expression and the corresponding
10674   //       subobject of x as a single function argument (as if by explicit
10675   //       qualification; that is, ignoring any possible virtual overriding
10676   //       functions in more derived classes);
10677   //
10678   // C++03 [class.copy]p13:
10679   //     - if the subobject is of class type, the copy assignment operator for
10680   //       the class is used (as if by explicit qualification; that is,
10681   //       ignoring any possible virtual overriding functions in more derived
10682   //       classes);
10683   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
10684     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
10685 
10686     // Look for operator=.
10687     DeclarationName Name
10688       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10689     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
10690     S.LookupQualifiedName(OpLookup, ClassDecl, false);
10691 
10692     // Prior to C++11, filter out any result that isn't a copy/move-assignment
10693     // operator.
10694     if (!S.getLangOpts().CPlusPlus11) {
10695       LookupResult::Filter F = OpLookup.makeFilter();
10696       while (F.hasNext()) {
10697         NamedDecl *D = F.next();
10698         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
10699           if (Method->isCopyAssignmentOperator() ||
10700               (!Copying && Method->isMoveAssignmentOperator()))
10701             continue;
10702 
10703         F.erase();
10704       }
10705       F.done();
10706     }
10707 
10708     // Suppress the protected check (C++ [class.protected]) for each of the
10709     // assignment operators we found. This strange dance is required when
10710     // we're assigning via a base classes's copy-assignment operator. To
10711     // ensure that we're getting the right base class subobject (without
10712     // ambiguities), we need to cast "this" to that subobject type; to
10713     // ensure that we don't go through the virtual call mechanism, we need
10714     // to qualify the operator= name with the base class (see below). However,
10715     // this means that if the base class has a protected copy assignment
10716     // operator, the protected member access check will fail. So, we
10717     // rewrite "protected" access to "public" access in this case, since we
10718     // know by construction that we're calling from a derived class.
10719     if (CopyingBaseSubobject) {
10720       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
10721            L != LEnd; ++L) {
10722         if (L.getAccess() == AS_protected)
10723           L.setAccess(AS_public);
10724       }
10725     }
10726 
10727     // Create the nested-name-specifier that will be used to qualify the
10728     // reference to operator=; this is required to suppress the virtual
10729     // call mechanism.
10730     CXXScopeSpec SS;
10731     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
10732     SS.MakeTrivial(S.Context,
10733                    NestedNameSpecifier::Create(S.Context, nullptr, false,
10734                                                CanonicalT),
10735                    Loc);
10736 
10737     // Create the reference to operator=.
10738     ExprResult OpEqualRef
10739       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
10740                                    SS, /*TemplateKWLoc=*/SourceLocation(),
10741                                    /*FirstQualifierInScope=*/nullptr,
10742                                    OpLookup,
10743                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
10744                                    /*SuppressQualifierCheck=*/true);
10745     if (OpEqualRef.isInvalid())
10746       return StmtError();
10747 
10748     // Build the call to the assignment operator.
10749 
10750     Expr *FromInst = From.build(S, Loc);
10751     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
10752                                                   OpEqualRef.getAs<Expr>(),
10753                                                   Loc, FromInst, Loc);
10754     if (Call.isInvalid())
10755       return StmtError();
10756 
10757     // If we built a call to a trivial 'operator=' while copying an array,
10758     // bail out. We'll replace the whole shebang with a memcpy.
10759     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
10760     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
10761       return StmtResult((Stmt*)nullptr);
10762 
10763     // Convert to an expression-statement, and clean up any produced
10764     // temporaries.
10765     return S.ActOnExprStmt(Call);
10766   }
10767 
10768   //     - if the subobject is of scalar type, the built-in assignment
10769   //       operator is used.
10770   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
10771   if (!ArrayTy) {
10772     ExprResult Assignment = S.CreateBuiltinBinOp(
10773         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
10774     if (Assignment.isInvalid())
10775       return StmtError();
10776     return S.ActOnExprStmt(Assignment);
10777   }
10778 
10779   //     - if the subobject is an array, each element is assigned, in the
10780   //       manner appropriate to the element type;
10781 
10782   // Construct a loop over the array bounds, e.g.,
10783   //
10784   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
10785   //
10786   // that will copy each of the array elements.
10787   QualType SizeType = S.Context.getSizeType();
10788 
10789   // Create the iteration variable.
10790   IdentifierInfo *IterationVarName = nullptr;
10791   {
10792     SmallString<8> Str;
10793     llvm::raw_svector_ostream OS(Str);
10794     OS << "__i" << Depth;
10795     IterationVarName = &S.Context.Idents.get(OS.str());
10796   }
10797   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10798                                           IterationVarName, SizeType,
10799                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10800                                           SC_None);
10801 
10802   // Initialize the iteration variable to zero.
10803   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
10804   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
10805 
10806   // Creates a reference to the iteration variable.
10807   RefBuilder IterationVarRef(IterationVar, SizeType);
10808   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
10809 
10810   // Create the DeclStmt that holds the iteration variable.
10811   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
10812 
10813   // Subscript the "from" and "to" expressions with the iteration variable.
10814   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
10815   MoveCastBuilder FromIndexMove(FromIndexCopy);
10816   const ExprBuilder *FromIndex;
10817   if (Copying)
10818     FromIndex = &FromIndexCopy;
10819   else
10820     FromIndex = &FromIndexMove;
10821 
10822   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
10823 
10824   // Build the copy/move for an individual element of the array.
10825   StmtResult Copy =
10826     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
10827                                      ToIndex, *FromIndex, CopyingBaseSubobject,
10828                                      Copying, Depth + 1);
10829   // Bail out if copying fails or if we determined that we should use memcpy.
10830   if (Copy.isInvalid() || !Copy.get())
10831     return Copy;
10832 
10833   // Create the comparison against the array bound.
10834   llvm::APInt Upper
10835     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
10836   Expr *Comparison
10837     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
10838                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
10839                                      BO_NE, S.Context.BoolTy,
10840                                      VK_RValue, OK_Ordinary, Loc, false);
10841 
10842   // Create the pre-increment of the iteration variable.
10843   Expr *Increment
10844     = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
10845                                     SizeType, VK_LValue, OK_Ordinary, Loc);
10846 
10847   // Construct the loop that copies all elements of this array.
10848   return S.ActOnForStmt(
10849       Loc, Loc, InitStmt,
10850       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
10851       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
10852 }
10853 
10854 static StmtResult
10855 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
10856                       const ExprBuilder &To, const ExprBuilder &From,
10857                       bool CopyingBaseSubobject, bool Copying) {
10858   // Maybe we should use a memcpy?
10859   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
10860       T.isTriviallyCopyableType(S.Context))
10861     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
10862 
10863   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
10864                                                      CopyingBaseSubobject,
10865                                                      Copying, 0));
10866 
10867   // If we ended up picking a trivial assignment operator for an array of a
10868   // non-trivially-copyable class type, just emit a memcpy.
10869   if (!Result.isInvalid() && !Result.get())
10870     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
10871 
10872   return Result;
10873 }
10874 
10875 Sema::ImplicitExceptionSpecification
10876 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
10877   CXXRecordDecl *ClassDecl = MD->getParent();
10878 
10879   ImplicitExceptionSpecification ExceptSpec(*this);
10880   if (ClassDecl->isInvalidDecl())
10881     return ExceptSpec;
10882 
10883   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
10884   assert(T->getNumParams() == 1 && "not a copy assignment op");
10885   unsigned ArgQuals =
10886       T->getParamType(0).getNonReferenceType().getCVRQualifiers();
10887 
10888   // C++ [except.spec]p14:
10889   //   An implicitly declared special member function (Clause 12) shall have an
10890   //   exception-specification. [...]
10891 
10892   // It is unspecified whether or not an implicit copy assignment operator
10893   // attempts to deduplicate calls to assignment operators of virtual bases are
10894   // made. As such, this exception specification is effectively unspecified.
10895   // Based on a similar decision made for constness in C++0x, we're erring on
10896   // the side of assuming such calls to be made regardless of whether they
10897   // actually happen.
10898   for (const auto &Base : ClassDecl->bases()) {
10899     if (Base.isVirtual())
10900       continue;
10901 
10902     CXXRecordDecl *BaseClassDecl
10903       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10904     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
10905                                                             ArgQuals, false, 0))
10906       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
10907   }
10908 
10909   for (const auto &Base : ClassDecl->vbases()) {
10910     CXXRecordDecl *BaseClassDecl
10911       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10912     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
10913                                                             ArgQuals, false, 0))
10914       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
10915   }
10916 
10917   for (const auto *Field : ClassDecl->fields()) {
10918     QualType FieldType = Context.getBaseElementType(Field->getType());
10919     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10920       if (CXXMethodDecl *CopyAssign =
10921           LookupCopyingAssignment(FieldClassDecl,
10922                                   ArgQuals | FieldType.getCVRQualifiers(),
10923                                   false, 0))
10924         ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
10925     }
10926   }
10927 
10928   return ExceptSpec;
10929 }
10930 
10931 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
10932   // Note: The following rules are largely analoguous to the copy
10933   // constructor rules. Note that virtual bases are not taken into account
10934   // for determining the argument type of the operator. Note also that
10935   // operators taking an object instead of a reference are allowed.
10936   assert(ClassDecl->needsImplicitCopyAssignment());
10937 
10938   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
10939   if (DSM.isAlreadyBeingDeclared())
10940     return nullptr;
10941 
10942   QualType ArgType = Context.getTypeDeclType(ClassDecl);
10943   QualType RetType = Context.getLValueReferenceType(ArgType);
10944   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
10945   if (Const)
10946     ArgType = ArgType.withConst();
10947   ArgType = Context.getLValueReferenceType(ArgType);
10948 
10949   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10950                                                      CXXCopyAssignment,
10951                                                      Const);
10952 
10953   //   An implicitly-declared copy assignment operator is an inline public
10954   //   member of its class.
10955   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10956   SourceLocation ClassLoc = ClassDecl->getLocation();
10957   DeclarationNameInfo NameInfo(Name, ClassLoc);
10958   CXXMethodDecl *CopyAssignment =
10959       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
10960                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10961                             /*isInline=*/true, Constexpr, SourceLocation());
10962   CopyAssignment->setAccess(AS_public);
10963   CopyAssignment->setDefaulted();
10964   CopyAssignment->setImplicit();
10965 
10966   if (getLangOpts().CUDA) {
10967     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
10968                                             CopyAssignment,
10969                                             /* ConstRHS */ Const,
10970                                             /* Diagnose */ false);
10971   }
10972 
10973   // Build an exception specification pointing back at this member.
10974   FunctionProtoType::ExtProtoInfo EPI =
10975       getImplicitMethodEPI(*this, CopyAssignment);
10976   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
10977 
10978   // Add the parameter to the operator.
10979   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
10980                                                ClassLoc, ClassLoc,
10981                                                /*Id=*/nullptr, ArgType,
10982                                                /*TInfo=*/nullptr, SC_None,
10983                                                nullptr);
10984   CopyAssignment->setParams(FromParam);
10985 
10986   CopyAssignment->setTrivial(
10987     ClassDecl->needsOverloadResolutionForCopyAssignment()
10988       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
10989       : ClassDecl->hasTrivialCopyAssignment());
10990 
10991   // Note that we have added this copy-assignment operator.
10992   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
10993 
10994   Scope *S = getScopeForContext(ClassDecl);
10995   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
10996 
10997   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
10998     SetDeclDeleted(CopyAssignment, ClassLoc);
10999 
11000   if (S)
11001     PushOnScopeChains(CopyAssignment, S, false);
11002   ClassDecl->addDecl(CopyAssignment);
11003 
11004   return CopyAssignment;
11005 }
11006 
11007 /// Diagnose an implicit copy operation for a class which is odr-used, but
11008 /// which is deprecated because the class has a user-declared copy constructor,
11009 /// copy assignment operator, or destructor.
11010 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
11011                                             SourceLocation UseLoc) {
11012   assert(CopyOp->isImplicit());
11013 
11014   CXXRecordDecl *RD = CopyOp->getParent();
11015   CXXMethodDecl *UserDeclaredOperation = nullptr;
11016 
11017   // In Microsoft mode, assignment operations don't affect constructors and
11018   // vice versa.
11019   if (RD->hasUserDeclaredDestructor()) {
11020     UserDeclaredOperation = RD->getDestructor();
11021   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11022              RD->hasUserDeclaredCopyConstructor() &&
11023              !S.getLangOpts().MSVCCompat) {
11024     // Find any user-declared copy constructor.
11025     for (auto *I : RD->ctors()) {
11026       if (I->isCopyConstructor()) {
11027         UserDeclaredOperation = I;
11028         break;
11029       }
11030     }
11031     assert(UserDeclaredOperation);
11032   } else if (isa<CXXConstructorDecl>(CopyOp) &&
11033              RD->hasUserDeclaredCopyAssignment() &&
11034              !S.getLangOpts().MSVCCompat) {
11035     // Find any user-declared move assignment operator.
11036     for (auto *I : RD->methods()) {
11037       if (I->isCopyAssignmentOperator()) {
11038         UserDeclaredOperation = I;
11039         break;
11040       }
11041     }
11042     assert(UserDeclaredOperation);
11043   }
11044 
11045   if (UserDeclaredOperation) {
11046     S.Diag(UserDeclaredOperation->getLocation(),
11047          diag::warn_deprecated_copy_operation)
11048       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
11049       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
11050     S.Diag(UseLoc, diag::note_member_synthesized_at)
11051       << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
11052                                           : Sema::CXXCopyAssignment)
11053       << RD;
11054   }
11055 }
11056 
11057 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
11058                                         CXXMethodDecl *CopyAssignOperator) {
11059   assert((CopyAssignOperator->isDefaulted() &&
11060           CopyAssignOperator->isOverloadedOperator() &&
11061           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
11062           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
11063           !CopyAssignOperator->isDeleted()) &&
11064          "DefineImplicitCopyAssignment called for wrong function");
11065 
11066   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
11067 
11068   if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
11069     CopyAssignOperator->setInvalidDecl();
11070     return;
11071   }
11072 
11073   // C++11 [class.copy]p18:
11074   //   The [definition of an implicitly declared copy assignment operator] is
11075   //   deprecated if the class has a user-declared copy constructor or a
11076   //   user-declared destructor.
11077   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
11078     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
11079 
11080   CopyAssignOperator->markUsed(Context);
11081 
11082   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
11083   DiagnosticErrorTrap Trap(Diags);
11084 
11085   // C++0x [class.copy]p30:
11086   //   The implicitly-defined or explicitly-defaulted copy assignment operator
11087   //   for a non-union class X performs memberwise copy assignment of its
11088   //   subobjects. The direct base classes of X are assigned first, in the
11089   //   order of their declaration in the base-specifier-list, and then the
11090   //   immediate non-static data members of X are assigned, in the order in
11091   //   which they were declared in the class definition.
11092 
11093   // The statements that form the synthesized function body.
11094   SmallVector<Stmt*, 8> Statements;
11095 
11096   // The parameter for the "other" object, which we are copying from.
11097   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
11098   Qualifiers OtherQuals = Other->getType().getQualifiers();
11099   QualType OtherRefType = Other->getType();
11100   if (const LValueReferenceType *OtherRef
11101                                 = OtherRefType->getAs<LValueReferenceType>()) {
11102     OtherRefType = OtherRef->getPointeeType();
11103     OtherQuals = OtherRefType.getQualifiers();
11104   }
11105 
11106   // Our location for everything implicitly-generated.
11107   SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
11108                            ? CopyAssignOperator->getLocEnd()
11109                            : CopyAssignOperator->getLocation();
11110 
11111   // Builds a DeclRefExpr for the "other" object.
11112   RefBuilder OtherRef(Other, OtherRefType);
11113 
11114   // Builds the "this" pointer.
11115   ThisBuilder This;
11116 
11117   // Assign base classes.
11118   bool Invalid = false;
11119   for (auto &Base : ClassDecl->bases()) {
11120     // Form the assignment:
11121     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
11122     QualType BaseType = Base.getType().getUnqualifiedType();
11123     if (!BaseType->isRecordType()) {
11124       Invalid = true;
11125       continue;
11126     }
11127 
11128     CXXCastPath BasePath;
11129     BasePath.push_back(&Base);
11130 
11131     // Construct the "from" expression, which is an implicit cast to the
11132     // appropriately-qualified base type.
11133     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
11134                      VK_LValue, BasePath);
11135 
11136     // Dereference "this".
11137     DerefBuilder DerefThis(This);
11138     CastBuilder To(DerefThis,
11139                    Context.getCVRQualifiedType(
11140                        BaseType, CopyAssignOperator->getTypeQualifiers()),
11141                    VK_LValue, BasePath);
11142 
11143     // Build the copy.
11144     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
11145                                             To, From,
11146                                             /*CopyingBaseSubobject=*/true,
11147                                             /*Copying=*/true);
11148     if (Copy.isInvalid()) {
11149       Diag(CurrentLocation, diag::note_member_synthesized_at)
11150         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11151       CopyAssignOperator->setInvalidDecl();
11152       return;
11153     }
11154 
11155     // Success! Record the copy.
11156     Statements.push_back(Copy.getAs<Expr>());
11157   }
11158 
11159   // Assign non-static members.
11160   for (auto *Field : ClassDecl->fields()) {
11161     // FIXME: We should form some kind of AST representation for the implied
11162     // memcpy in a union copy operation.
11163     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
11164       continue;
11165 
11166     if (Field->isInvalidDecl()) {
11167       Invalid = true;
11168       continue;
11169     }
11170 
11171     // Check for members of reference type; we can't copy those.
11172     if (Field->getType()->isReferenceType()) {
11173       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11174         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11175       Diag(Field->getLocation(), diag::note_declared_at);
11176       Diag(CurrentLocation, diag::note_member_synthesized_at)
11177         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11178       Invalid = true;
11179       continue;
11180     }
11181 
11182     // Check for members of const-qualified, non-class type.
11183     QualType BaseType = Context.getBaseElementType(Field->getType());
11184     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11185       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11186         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11187       Diag(Field->getLocation(), diag::note_declared_at);
11188       Diag(CurrentLocation, diag::note_member_synthesized_at)
11189         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11190       Invalid = true;
11191       continue;
11192     }
11193 
11194     // Suppress assigning zero-width bitfields.
11195     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
11196       continue;
11197 
11198     QualType FieldType = Field->getType().getNonReferenceType();
11199     if (FieldType->isIncompleteArrayType()) {
11200       assert(ClassDecl->hasFlexibleArrayMember() &&
11201              "Incomplete array type is not valid");
11202       continue;
11203     }
11204 
11205     // Build references to the field in the object we're copying from and to.
11206     CXXScopeSpec SS; // Intentionally empty
11207     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11208                               LookupMemberName);
11209     MemberLookup.addDecl(Field);
11210     MemberLookup.resolveKind();
11211 
11212     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
11213 
11214     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
11215 
11216     // Build the copy of this field.
11217     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
11218                                             To, From,
11219                                             /*CopyingBaseSubobject=*/false,
11220                                             /*Copying=*/true);
11221     if (Copy.isInvalid()) {
11222       Diag(CurrentLocation, diag::note_member_synthesized_at)
11223         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11224       CopyAssignOperator->setInvalidDecl();
11225       return;
11226     }
11227 
11228     // Success! Record the copy.
11229     Statements.push_back(Copy.getAs<Stmt>());
11230   }
11231 
11232   if (!Invalid) {
11233     // Add a "return *this;"
11234     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
11235 
11236     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
11237     if (Return.isInvalid())
11238       Invalid = true;
11239     else {
11240       Statements.push_back(Return.getAs<Stmt>());
11241 
11242       if (Trap.hasErrorOccurred()) {
11243         Diag(CurrentLocation, diag::note_member_synthesized_at)
11244           << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11245         Invalid = true;
11246       }
11247     }
11248   }
11249 
11250   // The exception specification is needed because we are defining the
11251   // function.
11252   ResolveExceptionSpec(CurrentLocation,
11253                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
11254 
11255   if (Invalid) {
11256     CopyAssignOperator->setInvalidDecl();
11257     return;
11258   }
11259 
11260   StmtResult Body;
11261   {
11262     CompoundScopeRAII CompoundScope(*this);
11263     Body = ActOnCompoundStmt(Loc, Loc, Statements,
11264                              /*isStmtExpr=*/false);
11265     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11266   }
11267   CopyAssignOperator->setBody(Body.getAs<Stmt>());
11268 
11269   if (ASTMutationListener *L = getASTMutationListener()) {
11270     L->CompletedImplicitDefinition(CopyAssignOperator);
11271   }
11272 }
11273 
11274 Sema::ImplicitExceptionSpecification
11275 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
11276   CXXRecordDecl *ClassDecl = MD->getParent();
11277 
11278   ImplicitExceptionSpecification ExceptSpec(*this);
11279   if (ClassDecl->isInvalidDecl())
11280     return ExceptSpec;
11281 
11282   // C++0x [except.spec]p14:
11283   //   An implicitly declared special member function (Clause 12) shall have an
11284   //   exception-specification. [...]
11285 
11286   // It is unspecified whether or not an implicit move assignment operator
11287   // attempts to deduplicate calls to assignment operators of virtual bases are
11288   // made. As such, this exception specification is effectively unspecified.
11289   // Based on a similar decision made for constness in C++0x, we're erring on
11290   // the side of assuming such calls to be made regardless of whether they
11291   // actually happen.
11292   // Note that a move constructor is not implicitly declared when there are
11293   // virtual bases, but it can still be user-declared and explicitly defaulted.
11294   for (const auto &Base : ClassDecl->bases()) {
11295     if (Base.isVirtual())
11296       continue;
11297 
11298     CXXRecordDecl *BaseClassDecl
11299       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
11300     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
11301                                                            0, false, 0))
11302       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
11303   }
11304 
11305   for (const auto &Base : ClassDecl->vbases()) {
11306     CXXRecordDecl *BaseClassDecl
11307       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
11308     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
11309                                                            0, false, 0))
11310       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
11311   }
11312 
11313   for (const auto *Field : ClassDecl->fields()) {
11314     QualType FieldType = Context.getBaseElementType(Field->getType());
11315     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
11316       if (CXXMethodDecl *MoveAssign =
11317               LookupMovingAssignment(FieldClassDecl,
11318                                      FieldType.getCVRQualifiers(),
11319                                      false, 0))
11320         ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
11321     }
11322   }
11323 
11324   return ExceptSpec;
11325 }
11326 
11327 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
11328   assert(ClassDecl->needsImplicitMoveAssignment());
11329 
11330   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
11331   if (DSM.isAlreadyBeingDeclared())
11332     return nullptr;
11333 
11334   // Note: The following rules are largely analoguous to the move
11335   // constructor rules.
11336 
11337   QualType ArgType = Context.getTypeDeclType(ClassDecl);
11338   QualType RetType = Context.getLValueReferenceType(ArgType);
11339   ArgType = Context.getRValueReferenceType(ArgType);
11340 
11341   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11342                                                      CXXMoveAssignment,
11343                                                      false);
11344 
11345   //   An implicitly-declared move assignment operator is an inline public
11346   //   member of its class.
11347   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11348   SourceLocation ClassLoc = ClassDecl->getLocation();
11349   DeclarationNameInfo NameInfo(Name, ClassLoc);
11350   CXXMethodDecl *MoveAssignment =
11351       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11352                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11353                             /*isInline=*/true, Constexpr, SourceLocation());
11354   MoveAssignment->setAccess(AS_public);
11355   MoveAssignment->setDefaulted();
11356   MoveAssignment->setImplicit();
11357 
11358   if (getLangOpts().CUDA) {
11359     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
11360                                             MoveAssignment,
11361                                             /* ConstRHS */ false,
11362                                             /* Diagnose */ false);
11363   }
11364 
11365   // Build an exception specification pointing back at this member.
11366   FunctionProtoType::ExtProtoInfo EPI =
11367       getImplicitMethodEPI(*this, MoveAssignment);
11368   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
11369 
11370   // Add the parameter to the operator.
11371   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
11372                                                ClassLoc, ClassLoc,
11373                                                /*Id=*/nullptr, ArgType,
11374                                                /*TInfo=*/nullptr, SC_None,
11375                                                nullptr);
11376   MoveAssignment->setParams(FromParam);
11377 
11378   MoveAssignment->setTrivial(
11379     ClassDecl->needsOverloadResolutionForMoveAssignment()
11380       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
11381       : ClassDecl->hasTrivialMoveAssignment());
11382 
11383   // Note that we have added this copy-assignment operator.
11384   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
11385 
11386   Scope *S = getScopeForContext(ClassDecl);
11387   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
11388 
11389   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
11390     ClassDecl->setImplicitMoveAssignmentIsDeleted();
11391     SetDeclDeleted(MoveAssignment, ClassLoc);
11392   }
11393 
11394   if (S)
11395     PushOnScopeChains(MoveAssignment, S, false);
11396   ClassDecl->addDecl(MoveAssignment);
11397 
11398   return MoveAssignment;
11399 }
11400 
11401 /// Check if we're implicitly defining a move assignment operator for a class
11402 /// with virtual bases. Such a move assignment might move-assign the virtual
11403 /// base multiple times.
11404 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
11405                                                SourceLocation CurrentLocation) {
11406   assert(!Class->isDependentContext() && "should not define dependent move");
11407 
11408   // Only a virtual base could get implicitly move-assigned multiple times.
11409   // Only a non-trivial move assignment can observe this. We only want to
11410   // diagnose if we implicitly define an assignment operator that assigns
11411   // two base classes, both of which move-assign the same virtual base.
11412   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
11413       Class->getNumBases() < 2)
11414     return;
11415 
11416   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
11417   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
11418   VBaseMap VBases;
11419 
11420   for (auto &BI : Class->bases()) {
11421     Worklist.push_back(&BI);
11422     while (!Worklist.empty()) {
11423       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
11424       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
11425 
11426       // If the base has no non-trivial move assignment operators,
11427       // we don't care about moves from it.
11428       if (!Base->hasNonTrivialMoveAssignment())
11429         continue;
11430 
11431       // If there's nothing virtual here, skip it.
11432       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
11433         continue;
11434 
11435       // If we're not actually going to call a move assignment for this base,
11436       // or the selected move assignment is trivial, skip it.
11437       Sema::SpecialMemberOverloadResult *SMOR =
11438         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
11439                               /*ConstArg*/false, /*VolatileArg*/false,
11440                               /*RValueThis*/true, /*ConstThis*/false,
11441                               /*VolatileThis*/false);
11442       if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
11443           !SMOR->getMethod()->isMoveAssignmentOperator())
11444         continue;
11445 
11446       if (BaseSpec->isVirtual()) {
11447         // We're going to move-assign this virtual base, and its move
11448         // assignment operator is not trivial. If this can happen for
11449         // multiple distinct direct bases of Class, diagnose it. (If it
11450         // only happens in one base, we'll diagnose it when synthesizing
11451         // that base class's move assignment operator.)
11452         CXXBaseSpecifier *&Existing =
11453             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
11454                 .first->second;
11455         if (Existing && Existing != &BI) {
11456           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
11457             << Class << Base;
11458           S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
11459             << (Base->getCanonicalDecl() ==
11460                 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
11461             << Base << Existing->getType() << Existing->getSourceRange();
11462           S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
11463             << (Base->getCanonicalDecl() ==
11464                 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
11465             << Base << BI.getType() << BaseSpec->getSourceRange();
11466 
11467           // Only diagnose each vbase once.
11468           Existing = nullptr;
11469         }
11470       } else {
11471         // Only walk over bases that have defaulted move assignment operators.
11472         // We assume that any user-provided move assignment operator handles
11473         // the multiple-moves-of-vbase case itself somehow.
11474         if (!SMOR->getMethod()->isDefaulted())
11475           continue;
11476 
11477         // We're going to move the base classes of Base. Add them to the list.
11478         for (auto &BI : Base->bases())
11479           Worklist.push_back(&BI);
11480       }
11481     }
11482   }
11483 }
11484 
11485 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
11486                                         CXXMethodDecl *MoveAssignOperator) {
11487   assert((MoveAssignOperator->isDefaulted() &&
11488           MoveAssignOperator->isOverloadedOperator() &&
11489           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
11490           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
11491           !MoveAssignOperator->isDeleted()) &&
11492          "DefineImplicitMoveAssignment called for wrong function");
11493 
11494   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
11495 
11496   if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
11497     MoveAssignOperator->setInvalidDecl();
11498     return;
11499   }
11500 
11501   MoveAssignOperator->markUsed(Context);
11502 
11503   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
11504   DiagnosticErrorTrap Trap(Diags);
11505 
11506   // C++0x [class.copy]p28:
11507   //   The implicitly-defined or move assignment operator for a non-union class
11508   //   X performs memberwise move assignment of its subobjects. The direct base
11509   //   classes of X are assigned first, in the order of their declaration in the
11510   //   base-specifier-list, and then the immediate non-static data members of X
11511   //   are assigned, in the order in which they were declared in the class
11512   //   definition.
11513 
11514   // Issue a warning if our implicit move assignment operator will move
11515   // from a virtual base more than once.
11516   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
11517 
11518   // The statements that form the synthesized function body.
11519   SmallVector<Stmt*, 8> Statements;
11520 
11521   // The parameter for the "other" object, which we are move from.
11522   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
11523   QualType OtherRefType = Other->getType()->
11524       getAs<RValueReferenceType>()->getPointeeType();
11525   assert(!OtherRefType.getQualifiers() &&
11526          "Bad argument type of defaulted move assignment");
11527 
11528   // Our location for everything implicitly-generated.
11529   SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
11530                            ? MoveAssignOperator->getLocEnd()
11531                            : MoveAssignOperator->getLocation();
11532 
11533   // Builds a reference to the "other" object.
11534   RefBuilder OtherRef(Other, OtherRefType);
11535   // Cast to rvalue.
11536   MoveCastBuilder MoveOther(OtherRef);
11537 
11538   // Builds the "this" pointer.
11539   ThisBuilder This;
11540 
11541   // Assign base classes.
11542   bool Invalid = false;
11543   for (auto &Base : ClassDecl->bases()) {
11544     // C++11 [class.copy]p28:
11545     //   It is unspecified whether subobjects representing virtual base classes
11546     //   are assigned more than once by the implicitly-defined copy assignment
11547     //   operator.
11548     // FIXME: Do not assign to a vbase that will be assigned by some other base
11549     // class. For a move-assignment, this can result in the vbase being moved
11550     // multiple times.
11551 
11552     // Form the assignment:
11553     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
11554     QualType BaseType = Base.getType().getUnqualifiedType();
11555     if (!BaseType->isRecordType()) {
11556       Invalid = true;
11557       continue;
11558     }
11559 
11560     CXXCastPath BasePath;
11561     BasePath.push_back(&Base);
11562 
11563     // Construct the "from" expression, which is an implicit cast to the
11564     // appropriately-qualified base type.
11565     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
11566 
11567     // Dereference "this".
11568     DerefBuilder DerefThis(This);
11569 
11570     // Implicitly cast "this" to the appropriately-qualified base type.
11571     CastBuilder To(DerefThis,
11572                    Context.getCVRQualifiedType(
11573                        BaseType, MoveAssignOperator->getTypeQualifiers()),
11574                    VK_LValue, BasePath);
11575 
11576     // Build the move.
11577     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
11578                                             To, From,
11579                                             /*CopyingBaseSubobject=*/true,
11580                                             /*Copying=*/false);
11581     if (Move.isInvalid()) {
11582       Diag(CurrentLocation, diag::note_member_synthesized_at)
11583         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11584       MoveAssignOperator->setInvalidDecl();
11585       return;
11586     }
11587 
11588     // Success! Record the move.
11589     Statements.push_back(Move.getAs<Expr>());
11590   }
11591 
11592   // Assign non-static members.
11593   for (auto *Field : ClassDecl->fields()) {
11594     // FIXME: We should form some kind of AST representation for the implied
11595     // memcpy in a union copy operation.
11596     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
11597       continue;
11598 
11599     if (Field->isInvalidDecl()) {
11600       Invalid = true;
11601       continue;
11602     }
11603 
11604     // Check for members of reference type; we can't move those.
11605     if (Field->getType()->isReferenceType()) {
11606       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11607         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11608       Diag(Field->getLocation(), diag::note_declared_at);
11609       Diag(CurrentLocation, diag::note_member_synthesized_at)
11610         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11611       Invalid = true;
11612       continue;
11613     }
11614 
11615     // Check for members of const-qualified, non-class type.
11616     QualType BaseType = Context.getBaseElementType(Field->getType());
11617     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11618       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11619         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11620       Diag(Field->getLocation(), diag::note_declared_at);
11621       Diag(CurrentLocation, diag::note_member_synthesized_at)
11622         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11623       Invalid = true;
11624       continue;
11625     }
11626 
11627     // Suppress assigning zero-width bitfields.
11628     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
11629       continue;
11630 
11631     QualType FieldType = Field->getType().getNonReferenceType();
11632     if (FieldType->isIncompleteArrayType()) {
11633       assert(ClassDecl->hasFlexibleArrayMember() &&
11634              "Incomplete array type is not valid");
11635       continue;
11636     }
11637 
11638     // Build references to the field in the object we're copying from and to.
11639     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11640                               LookupMemberName);
11641     MemberLookup.addDecl(Field);
11642     MemberLookup.resolveKind();
11643     MemberBuilder From(MoveOther, OtherRefType,
11644                        /*IsArrow=*/false, MemberLookup);
11645     MemberBuilder To(This, getCurrentThisType(),
11646                      /*IsArrow=*/true, MemberLookup);
11647 
11648     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
11649         "Member reference with rvalue base must be rvalue except for reference "
11650         "members, which aren't allowed for move assignment.");
11651 
11652     // Build the move of this field.
11653     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
11654                                             To, From,
11655                                             /*CopyingBaseSubobject=*/false,
11656                                             /*Copying=*/false);
11657     if (Move.isInvalid()) {
11658       Diag(CurrentLocation, diag::note_member_synthesized_at)
11659         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11660       MoveAssignOperator->setInvalidDecl();
11661       return;
11662     }
11663 
11664     // Success! Record the copy.
11665     Statements.push_back(Move.getAs<Stmt>());
11666   }
11667 
11668   if (!Invalid) {
11669     // Add a "return *this;"
11670     ExprResult ThisObj =
11671         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
11672 
11673     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
11674     if (Return.isInvalid())
11675       Invalid = true;
11676     else {
11677       Statements.push_back(Return.getAs<Stmt>());
11678 
11679       if (Trap.hasErrorOccurred()) {
11680         Diag(CurrentLocation, diag::note_member_synthesized_at)
11681           << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11682         Invalid = true;
11683       }
11684     }
11685   }
11686 
11687   // The exception specification is needed because we are defining the
11688   // function.
11689   ResolveExceptionSpec(CurrentLocation,
11690                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
11691 
11692   if (Invalid) {
11693     MoveAssignOperator->setInvalidDecl();
11694     return;
11695   }
11696 
11697   StmtResult Body;
11698   {
11699     CompoundScopeRAII CompoundScope(*this);
11700     Body = ActOnCompoundStmt(Loc, Loc, Statements,
11701                              /*isStmtExpr=*/false);
11702     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11703   }
11704   MoveAssignOperator->setBody(Body.getAs<Stmt>());
11705 
11706   if (ASTMutationListener *L = getASTMutationListener()) {
11707     L->CompletedImplicitDefinition(MoveAssignOperator);
11708   }
11709 }
11710 
11711 Sema::ImplicitExceptionSpecification
11712 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
11713   CXXRecordDecl *ClassDecl = MD->getParent();
11714 
11715   ImplicitExceptionSpecification ExceptSpec(*this);
11716   if (ClassDecl->isInvalidDecl())
11717     return ExceptSpec;
11718 
11719   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
11720   assert(T->getNumParams() >= 1 && "not a copy ctor");
11721   unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
11722 
11723   // C++ [except.spec]p14:
11724   //   An implicitly declared special member function (Clause 12) shall have an
11725   //   exception-specification. [...]
11726   for (const auto &Base : ClassDecl->bases()) {
11727     // Virtual bases are handled below.
11728     if (Base.isVirtual())
11729       continue;
11730 
11731     CXXRecordDecl *BaseClassDecl
11732       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
11733     if (CXXConstructorDecl *CopyConstructor =
11734           LookupCopyingConstructor(BaseClassDecl, Quals))
11735       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
11736   }
11737   for (const auto &Base : ClassDecl->vbases()) {
11738     CXXRecordDecl *BaseClassDecl
11739       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
11740     if (CXXConstructorDecl *CopyConstructor =
11741           LookupCopyingConstructor(BaseClassDecl, Quals))
11742       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
11743   }
11744   for (const auto *Field : ClassDecl->fields()) {
11745     QualType FieldType = Context.getBaseElementType(Field->getType());
11746     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
11747       if (CXXConstructorDecl *CopyConstructor =
11748               LookupCopyingConstructor(FieldClassDecl,
11749                                        Quals | FieldType.getCVRQualifiers()))
11750       ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
11751     }
11752   }
11753 
11754   return ExceptSpec;
11755 }
11756 
11757 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
11758                                                     CXXRecordDecl *ClassDecl) {
11759   // C++ [class.copy]p4:
11760   //   If the class definition does not explicitly declare a copy
11761   //   constructor, one is declared implicitly.
11762   assert(ClassDecl->needsImplicitCopyConstructor());
11763 
11764   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
11765   if (DSM.isAlreadyBeingDeclared())
11766     return nullptr;
11767 
11768   QualType ClassType = Context.getTypeDeclType(ClassDecl);
11769   QualType ArgType = ClassType;
11770   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
11771   if (Const)
11772     ArgType = ArgType.withConst();
11773   ArgType = Context.getLValueReferenceType(ArgType);
11774 
11775   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11776                                                      CXXCopyConstructor,
11777                                                      Const);
11778 
11779   DeclarationName Name
11780     = Context.DeclarationNames.getCXXConstructorName(
11781                                            Context.getCanonicalType(ClassType));
11782   SourceLocation ClassLoc = ClassDecl->getLocation();
11783   DeclarationNameInfo NameInfo(Name, ClassLoc);
11784 
11785   //   An implicitly-declared copy constructor is an inline public
11786   //   member of its class.
11787   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
11788       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
11789       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
11790       Constexpr);
11791   CopyConstructor->setAccess(AS_public);
11792   CopyConstructor->setDefaulted();
11793 
11794   if (getLangOpts().CUDA) {
11795     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
11796                                             CopyConstructor,
11797                                             /* ConstRHS */ Const,
11798                                             /* Diagnose */ false);
11799   }
11800 
11801   // Build an exception specification pointing back at this member.
11802   FunctionProtoType::ExtProtoInfo EPI =
11803       getImplicitMethodEPI(*this, CopyConstructor);
11804   CopyConstructor->setType(
11805       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
11806 
11807   // Add the parameter to the constructor.
11808   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
11809                                                ClassLoc, ClassLoc,
11810                                                /*IdentifierInfo=*/nullptr,
11811                                                ArgType, /*TInfo=*/nullptr,
11812                                                SC_None, nullptr);
11813   CopyConstructor->setParams(FromParam);
11814 
11815   CopyConstructor->setTrivial(
11816     ClassDecl->needsOverloadResolutionForCopyConstructor()
11817       ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
11818       : ClassDecl->hasTrivialCopyConstructor());
11819 
11820   // Note that we have declared this constructor.
11821   ++ASTContext::NumImplicitCopyConstructorsDeclared;
11822 
11823   Scope *S = getScopeForContext(ClassDecl);
11824   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
11825 
11826   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
11827     SetDeclDeleted(CopyConstructor, ClassLoc);
11828 
11829   if (S)
11830     PushOnScopeChains(CopyConstructor, S, false);
11831   ClassDecl->addDecl(CopyConstructor);
11832 
11833   return CopyConstructor;
11834 }
11835 
11836 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
11837                                    CXXConstructorDecl *CopyConstructor) {
11838   assert((CopyConstructor->isDefaulted() &&
11839           CopyConstructor->isCopyConstructor() &&
11840           !CopyConstructor->doesThisDeclarationHaveABody() &&
11841           !CopyConstructor->isDeleted()) &&
11842          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
11843 
11844   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
11845   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
11846 
11847   // C++11 [class.copy]p7:
11848   //   The [definition of an implicitly declared copy constructor] is
11849   //   deprecated if the class has a user-declared copy assignment operator
11850   //   or a user-declared destructor.
11851   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
11852     diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
11853 
11854   SynthesizedFunctionScope Scope(*this, CopyConstructor);
11855   DiagnosticErrorTrap Trap(Diags);
11856 
11857   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
11858       Trap.hasErrorOccurred()) {
11859     Diag(CurrentLocation, diag::note_member_synthesized_at)
11860       << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
11861     CopyConstructor->setInvalidDecl();
11862   }  else {
11863     SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
11864                              ? CopyConstructor->getLocEnd()
11865                              : CopyConstructor->getLocation();
11866     Sema::CompoundScopeRAII CompoundScope(*this);
11867     CopyConstructor->setBody(
11868         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
11869   }
11870 
11871   // The exception specification is needed because we are defining the
11872   // function.
11873   ResolveExceptionSpec(CurrentLocation,
11874                        CopyConstructor->getType()->castAs<FunctionProtoType>());
11875 
11876   CopyConstructor->markUsed(Context);
11877   MarkVTableUsed(CurrentLocation, ClassDecl);
11878 
11879   if (ASTMutationListener *L = getASTMutationListener()) {
11880     L->CompletedImplicitDefinition(CopyConstructor);
11881   }
11882 }
11883 
11884 Sema::ImplicitExceptionSpecification
11885 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
11886   CXXRecordDecl *ClassDecl = MD->getParent();
11887 
11888   // C++ [except.spec]p14:
11889   //   An implicitly declared special member function (Clause 12) shall have an
11890   //   exception-specification. [...]
11891   ImplicitExceptionSpecification ExceptSpec(*this);
11892   if (ClassDecl->isInvalidDecl())
11893     return ExceptSpec;
11894 
11895   // Direct base-class constructors.
11896   for (const auto &B : ClassDecl->bases()) {
11897     if (B.isVirtual()) // Handled below.
11898       continue;
11899 
11900     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
11901       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
11902       CXXConstructorDecl *Constructor =
11903           LookupMovingConstructor(BaseClassDecl, 0);
11904       // If this is a deleted function, add it anyway. This might be conformant
11905       // with the standard. This might not. I'm not sure. It might not matter.
11906       if (Constructor)
11907         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
11908     }
11909   }
11910 
11911   // Virtual base-class constructors.
11912   for (const auto &B : ClassDecl->vbases()) {
11913     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
11914       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
11915       CXXConstructorDecl *Constructor =
11916           LookupMovingConstructor(BaseClassDecl, 0);
11917       // If this is a deleted function, add it anyway. This might be conformant
11918       // with the standard. This might not. I'm not sure. It might not matter.
11919       if (Constructor)
11920         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
11921     }
11922   }
11923 
11924   // Field constructors.
11925   for (const auto *F : ClassDecl->fields()) {
11926     QualType FieldType = Context.getBaseElementType(F->getType());
11927     if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
11928       CXXConstructorDecl *Constructor =
11929           LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
11930       // If this is a deleted function, add it anyway. This might be conformant
11931       // with the standard. This might not. I'm not sure. It might not matter.
11932       // In particular, the problem is that this function never gets called. It
11933       // might just be ill-formed because this function attempts to refer to
11934       // a deleted function here.
11935       if (Constructor)
11936         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
11937     }
11938   }
11939 
11940   return ExceptSpec;
11941 }
11942 
11943 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
11944                                                     CXXRecordDecl *ClassDecl) {
11945   assert(ClassDecl->needsImplicitMoveConstructor());
11946 
11947   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
11948   if (DSM.isAlreadyBeingDeclared())
11949     return nullptr;
11950 
11951   QualType ClassType = Context.getTypeDeclType(ClassDecl);
11952   QualType ArgType = Context.getRValueReferenceType(ClassType);
11953 
11954   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11955                                                      CXXMoveConstructor,
11956                                                      false);
11957 
11958   DeclarationName Name
11959     = Context.DeclarationNames.getCXXConstructorName(
11960                                            Context.getCanonicalType(ClassType));
11961   SourceLocation ClassLoc = ClassDecl->getLocation();
11962   DeclarationNameInfo NameInfo(Name, ClassLoc);
11963 
11964   // C++11 [class.copy]p11:
11965   //   An implicitly-declared copy/move constructor is an inline public
11966   //   member of its class.
11967   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
11968       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
11969       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
11970       Constexpr);
11971   MoveConstructor->setAccess(AS_public);
11972   MoveConstructor->setDefaulted();
11973 
11974   if (getLangOpts().CUDA) {
11975     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
11976                                             MoveConstructor,
11977                                             /* ConstRHS */ false,
11978                                             /* Diagnose */ false);
11979   }
11980 
11981   // Build an exception specification pointing back at this member.
11982   FunctionProtoType::ExtProtoInfo EPI =
11983       getImplicitMethodEPI(*this, MoveConstructor);
11984   MoveConstructor->setType(
11985       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
11986 
11987   // Add the parameter to the constructor.
11988   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
11989                                                ClassLoc, ClassLoc,
11990                                                /*IdentifierInfo=*/nullptr,
11991                                                ArgType, /*TInfo=*/nullptr,
11992                                                SC_None, nullptr);
11993   MoveConstructor->setParams(FromParam);
11994 
11995   MoveConstructor->setTrivial(
11996     ClassDecl->needsOverloadResolutionForMoveConstructor()
11997       ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
11998       : ClassDecl->hasTrivialMoveConstructor());
11999 
12000   // Note that we have declared this constructor.
12001   ++ASTContext::NumImplicitMoveConstructorsDeclared;
12002 
12003   Scope *S = getScopeForContext(ClassDecl);
12004   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12005 
12006   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
12007     ClassDecl->setImplicitMoveConstructorIsDeleted();
12008     SetDeclDeleted(MoveConstructor, ClassLoc);
12009   }
12010 
12011   if (S)
12012     PushOnScopeChains(MoveConstructor, S, false);
12013   ClassDecl->addDecl(MoveConstructor);
12014 
12015   return MoveConstructor;
12016 }
12017 
12018 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12019                                    CXXConstructorDecl *MoveConstructor) {
12020   assert((MoveConstructor->isDefaulted() &&
12021           MoveConstructor->isMoveConstructor() &&
12022           !MoveConstructor->doesThisDeclarationHaveABody() &&
12023           !MoveConstructor->isDeleted()) &&
12024          "DefineImplicitMoveConstructor - call it for implicit move ctor");
12025 
12026   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12027   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12028 
12029   SynthesizedFunctionScope Scope(*this, MoveConstructor);
12030   DiagnosticErrorTrap Trap(Diags);
12031 
12032   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
12033       Trap.hasErrorOccurred()) {
12034     Diag(CurrentLocation, diag::note_member_synthesized_at)
12035       << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
12036     MoveConstructor->setInvalidDecl();
12037   }  else {
12038     SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
12039                              ? MoveConstructor->getLocEnd()
12040                              : MoveConstructor->getLocation();
12041     Sema::CompoundScopeRAII CompoundScope(*this);
12042     MoveConstructor->setBody(ActOnCompoundStmt(
12043         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
12044   }
12045 
12046   // The exception specification is needed because we are defining the
12047   // function.
12048   ResolveExceptionSpec(CurrentLocation,
12049                        MoveConstructor->getType()->castAs<FunctionProtoType>());
12050 
12051   MoveConstructor->markUsed(Context);
12052   MarkVTableUsed(CurrentLocation, ClassDecl);
12053 
12054   if (ASTMutationListener *L = getASTMutationListener()) {
12055     L->CompletedImplicitDefinition(MoveConstructor);
12056   }
12057 }
12058 
12059 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
12060   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
12061 }
12062 
12063 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
12064                             SourceLocation CurrentLocation,
12065                             CXXConversionDecl *Conv) {
12066   CXXRecordDecl *Lambda = Conv->getParent();
12067   CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
12068   // If we are defining a specialization of a conversion to function-ptr
12069   // cache the deduced template arguments for this specialization
12070   // so that we can use them to retrieve the corresponding call-operator
12071   // and static-invoker.
12072   const TemplateArgumentList *DeducedTemplateArgs = nullptr;
12073 
12074   // Retrieve the corresponding call-operator specialization.
12075   if (Lambda->isGenericLambda()) {
12076     assert(Conv->isFunctionTemplateSpecialization());
12077     FunctionTemplateDecl *CallOpTemplate =
12078         CallOp->getDescribedFunctionTemplate();
12079     DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
12080     void *InsertPos = nullptr;
12081     FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
12082                                                 DeducedTemplateArgs->asArray(),
12083                                                 InsertPos);
12084     assert(CallOpSpec &&
12085           "Conversion operator must have a corresponding call operator");
12086     CallOp = cast<CXXMethodDecl>(CallOpSpec);
12087   }
12088   // Mark the call operator referenced (and add to pending instantiations
12089   // if necessary).
12090   // For both the conversion and static-invoker template specializations
12091   // we construct their body's in this function, so no need to add them
12092   // to the PendingInstantiations.
12093   MarkFunctionReferenced(CurrentLocation, CallOp);
12094 
12095   SynthesizedFunctionScope Scope(*this, Conv);
12096   DiagnosticErrorTrap Trap(Diags);
12097 
12098   // Retrieve the static invoker...
12099   CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
12100   // ... and get the corresponding specialization for a generic lambda.
12101   if (Lambda->isGenericLambda()) {
12102     assert(DeducedTemplateArgs &&
12103       "Must have deduced template arguments from Conversion Operator");
12104     FunctionTemplateDecl *InvokeTemplate =
12105                           Invoker->getDescribedFunctionTemplate();
12106     void *InsertPos = nullptr;
12107     FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
12108                                                 DeducedTemplateArgs->asArray(),
12109                                                 InsertPos);
12110     assert(InvokeSpec &&
12111       "Must have a corresponding static invoker specialization");
12112     Invoker = cast<CXXMethodDecl>(InvokeSpec);
12113   }
12114   // Construct the body of the conversion function { return __invoke; }.
12115   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
12116                                         VK_LValue, Conv->getLocation()).get();
12117    assert(FunctionRef && "Can't refer to __invoke function?");
12118    Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
12119    Conv->setBody(new (Context) CompoundStmt(Context, Return,
12120                                             Conv->getLocation(),
12121                                             Conv->getLocation()));
12122 
12123   Conv->markUsed(Context);
12124   Conv->setReferenced();
12125 
12126   // Fill in the __invoke function with a dummy implementation. IR generation
12127   // will fill in the actual details.
12128   Invoker->markUsed(Context);
12129   Invoker->setReferenced();
12130   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12131 
12132   if (ASTMutationListener *L = getASTMutationListener()) {
12133     L->CompletedImplicitDefinition(Conv);
12134     L->CompletedImplicitDefinition(Invoker);
12135    }
12136 }
12137 
12138 
12139 
12140 void Sema::DefineImplicitLambdaToBlockPointerConversion(
12141        SourceLocation CurrentLocation,
12142        CXXConversionDecl *Conv)
12143 {
12144   assert(!Conv->getParent()->isGenericLambda());
12145 
12146   Conv->markUsed(Context);
12147 
12148   SynthesizedFunctionScope Scope(*this, Conv);
12149   DiagnosticErrorTrap Trap(Diags);
12150 
12151   // Copy-initialize the lambda object as needed to capture it.
12152   Expr *This = ActOnCXXThis(CurrentLocation).get();
12153   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
12154 
12155   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12156                                                         Conv->getLocation(),
12157                                                         Conv, DerefThis);
12158 
12159   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12160   // behavior.  Note that only the general conversion function does this
12161   // (since it's unusable otherwise); in the case where we inline the
12162   // block literal, it has block literal lifetime semantics.
12163   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
12164     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12165                                           CK_CopyAndAutoreleaseBlockObject,
12166                                           BuildBlock.get(), nullptr, VK_RValue);
12167 
12168   if (BuildBlock.isInvalid()) {
12169     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12170     Conv->setInvalidDecl();
12171     return;
12172   }
12173 
12174   // Create the return statement that returns the block from the conversion
12175   // function.
12176   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
12177   if (Return.isInvalid()) {
12178     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12179     Conv->setInvalidDecl();
12180     return;
12181   }
12182 
12183   // Set the body of the conversion function.
12184   Stmt *ReturnS = Return.get();
12185   Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
12186                                            Conv->getLocation(),
12187                                            Conv->getLocation()));
12188 
12189   // We're done; notify the mutation listener, if any.
12190   if (ASTMutationListener *L = getASTMutationListener()) {
12191     L->CompletedImplicitDefinition(Conv);
12192   }
12193 }
12194 
12195 /// \brief Determine whether the given list arguments contains exactly one
12196 /// "real" (non-default) argument.
12197 static bool hasOneRealArgument(MultiExprArg Args) {
12198   switch (Args.size()) {
12199   case 0:
12200     return false;
12201 
12202   default:
12203     if (!Args[1]->isDefaultArgument())
12204       return false;
12205 
12206     // fall through
12207   case 1:
12208     return !Args[0]->isDefaultArgument();
12209   }
12210 
12211   return false;
12212 }
12213 
12214 ExprResult
12215 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12216                             NamedDecl *FoundDecl,
12217                             CXXConstructorDecl *Constructor,
12218                             MultiExprArg ExprArgs,
12219                             bool HadMultipleCandidates,
12220                             bool IsListInitialization,
12221                             bool IsStdInitListInitialization,
12222                             bool RequiresZeroInit,
12223                             unsigned ConstructKind,
12224                             SourceRange ParenRange) {
12225   bool Elidable = false;
12226 
12227   // C++0x [class.copy]p34:
12228   //   When certain criteria are met, an implementation is allowed to
12229   //   omit the copy/move construction of a class object, even if the
12230   //   copy/move constructor and/or destructor for the object have
12231   //   side effects. [...]
12232   //     - when a temporary class object that has not been bound to a
12233   //       reference (12.2) would be copied/moved to a class object
12234   //       with the same cv-unqualified type, the copy/move operation
12235   //       can be omitted by constructing the temporary object
12236   //       directly into the target of the omitted copy/move
12237   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
12238       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
12239     Expr *SubExpr = ExprArgs[0];
12240     Elidable = SubExpr->isTemporaryObject(
12241         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
12242   }
12243 
12244   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
12245                                FoundDecl, Constructor,
12246                                Elidable, ExprArgs, HadMultipleCandidates,
12247                                IsListInitialization,
12248                                IsStdInitListInitialization, RequiresZeroInit,
12249                                ConstructKind, ParenRange);
12250 }
12251 
12252 ExprResult
12253 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12254                             NamedDecl *FoundDecl,
12255                             CXXConstructorDecl *Constructor,
12256                             bool Elidable,
12257                             MultiExprArg ExprArgs,
12258                             bool HadMultipleCandidates,
12259                             bool IsListInitialization,
12260                             bool IsStdInitListInitialization,
12261                             bool RequiresZeroInit,
12262                             unsigned ConstructKind,
12263                             SourceRange ParenRange) {
12264   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
12265     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
12266     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
12267       return ExprError();
12268   }
12269 
12270   return BuildCXXConstructExpr(
12271       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
12272       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
12273       RequiresZeroInit, ConstructKind, ParenRange);
12274 }
12275 
12276 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
12277 /// including handling of its default argument expressions.
12278 ExprResult
12279 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12280                             CXXConstructorDecl *Constructor,
12281                             bool Elidable,
12282                             MultiExprArg ExprArgs,
12283                             bool HadMultipleCandidates,
12284                             bool IsListInitialization,
12285                             bool IsStdInitListInitialization,
12286                             bool RequiresZeroInit,
12287                             unsigned ConstructKind,
12288                             SourceRange ParenRange) {
12289   assert(declaresSameEntity(
12290              Constructor->getParent(),
12291              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
12292          "given constructor for wrong type");
12293   MarkFunctionReferenced(ConstructLoc, Constructor);
12294   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
12295     return ExprError();
12296 
12297   return CXXConstructExpr::Create(
12298       Context, DeclInitType, ConstructLoc, Constructor, Elidable,
12299       ExprArgs, HadMultipleCandidates, IsListInitialization,
12300       IsStdInitListInitialization, RequiresZeroInit,
12301       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
12302       ParenRange);
12303 }
12304 
12305 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
12306   assert(Field->hasInClassInitializer());
12307 
12308   // If we already have the in-class initializer nothing needs to be done.
12309   if (Field->getInClassInitializer())
12310     return CXXDefaultInitExpr::Create(Context, Loc, Field);
12311 
12312   // Maybe we haven't instantiated the in-class initializer. Go check the
12313   // pattern FieldDecl to see if it has one.
12314   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
12315 
12316   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
12317     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
12318     DeclContext::lookup_result Lookup =
12319         ClassPattern->lookup(Field->getDeclName());
12320 
12321     // Lookup can return at most two results: the pattern for the field, or the
12322     // injected class name of the parent record. No other member can have the
12323     // same name as the field.
12324     assert(!Lookup.empty() && Lookup.size() <= 2 &&
12325            "more than two lookup results for field name");
12326     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
12327     if (!Pattern) {
12328       assert(isa<CXXRecordDecl>(Lookup[0]) &&
12329              "cannot have other non-field member with same name");
12330       Pattern = cast<FieldDecl>(Lookup[1]);
12331     }
12332 
12333     if (InstantiateInClassInitializer(Loc, Field, Pattern,
12334                                       getTemplateInstantiationArgs(Field)))
12335       return ExprError();
12336     return CXXDefaultInitExpr::Create(Context, Loc, Field);
12337   }
12338 
12339   // DR1351:
12340   //   If the brace-or-equal-initializer of a non-static data member
12341   //   invokes a defaulted default constructor of its class or of an
12342   //   enclosing class in a potentially evaluated subexpression, the
12343   //   program is ill-formed.
12344   //
12345   // This resolution is unworkable: the exception specification of the
12346   // default constructor can be needed in an unevaluated context, in
12347   // particular, in the operand of a noexcept-expression, and we can be
12348   // unable to compute an exception specification for an enclosed class.
12349   //
12350   // Any attempt to resolve the exception specification of a defaulted default
12351   // constructor before the initializer is lexically complete will ultimately
12352   // come here at which point we can diagnose it.
12353   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
12354   if (OutermostClass == ParentRD) {
12355     Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
12356         << ParentRD << Field;
12357   } else {
12358     Diag(Field->getLocEnd(),
12359          diag::err_in_class_initializer_not_yet_parsed_outer_class)
12360         << ParentRD << OutermostClass << Field;
12361   }
12362 
12363   return ExprError();
12364 }
12365 
12366 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
12367   if (VD->isInvalidDecl()) return;
12368 
12369   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
12370   if (ClassDecl->isInvalidDecl()) return;
12371   if (ClassDecl->hasIrrelevantDestructor()) return;
12372   if (ClassDecl->isDependentContext()) return;
12373 
12374   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12375   MarkFunctionReferenced(VD->getLocation(), Destructor);
12376   CheckDestructorAccess(VD->getLocation(), Destructor,
12377                         PDiag(diag::err_access_dtor_var)
12378                         << VD->getDeclName()
12379                         << VD->getType());
12380   DiagnoseUseOfDecl(Destructor, VD->getLocation());
12381 
12382   if (Destructor->isTrivial()) return;
12383   if (!VD->hasGlobalStorage()) return;
12384 
12385   // Emit warning for non-trivial dtor in global scope (a real global,
12386   // class-static, function-static).
12387   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
12388 
12389   // TODO: this should be re-enabled for static locals by !CXAAtExit
12390   if (!VD->isStaticLocal())
12391     Diag(VD->getLocation(), diag::warn_global_destructor);
12392 }
12393 
12394 /// \brief Given a constructor and the set of arguments provided for the
12395 /// constructor, convert the arguments and add any required default arguments
12396 /// to form a proper call to this constructor.
12397 ///
12398 /// \returns true if an error occurred, false otherwise.
12399 bool
12400 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
12401                               MultiExprArg ArgsPtr,
12402                               SourceLocation Loc,
12403                               SmallVectorImpl<Expr*> &ConvertedArgs,
12404                               bool AllowExplicit,
12405                               bool IsListInitialization) {
12406   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
12407   unsigned NumArgs = ArgsPtr.size();
12408   Expr **Args = ArgsPtr.data();
12409 
12410   const FunctionProtoType *Proto
12411     = Constructor->getType()->getAs<FunctionProtoType>();
12412   assert(Proto && "Constructor without a prototype?");
12413   unsigned NumParams = Proto->getNumParams();
12414 
12415   // If too few arguments are available, we'll fill in the rest with defaults.
12416   if (NumArgs < NumParams)
12417     ConvertedArgs.reserve(NumParams);
12418   else
12419     ConvertedArgs.reserve(NumArgs);
12420 
12421   VariadicCallType CallType =
12422     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
12423   SmallVector<Expr *, 8> AllArgs;
12424   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
12425                                         Proto, 0,
12426                                         llvm::makeArrayRef(Args, NumArgs),
12427                                         AllArgs,
12428                                         CallType, AllowExplicit,
12429                                         IsListInitialization);
12430   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
12431 
12432   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
12433 
12434   CheckConstructorCall(Constructor,
12435                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
12436                        Proto, Loc);
12437 
12438   return Invalid;
12439 }
12440 
12441 static inline bool
12442 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
12443                                        const FunctionDecl *FnDecl) {
12444   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
12445   if (isa<NamespaceDecl>(DC)) {
12446     return SemaRef.Diag(FnDecl->getLocation(),
12447                         diag::err_operator_new_delete_declared_in_namespace)
12448       << FnDecl->getDeclName();
12449   }
12450 
12451   if (isa<TranslationUnitDecl>(DC) &&
12452       FnDecl->getStorageClass() == SC_Static) {
12453     return SemaRef.Diag(FnDecl->getLocation(),
12454                         diag::err_operator_new_delete_declared_static)
12455       << FnDecl->getDeclName();
12456   }
12457 
12458   return false;
12459 }
12460 
12461 static inline bool
12462 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
12463                             CanQualType ExpectedResultType,
12464                             CanQualType ExpectedFirstParamType,
12465                             unsigned DependentParamTypeDiag,
12466                             unsigned InvalidParamTypeDiag) {
12467   QualType ResultType =
12468       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
12469 
12470   // Check that the result type is not dependent.
12471   if (ResultType->isDependentType())
12472     return SemaRef.Diag(FnDecl->getLocation(),
12473                         diag::err_operator_new_delete_dependent_result_type)
12474     << FnDecl->getDeclName() << ExpectedResultType;
12475 
12476   // Check that the result type is what we expect.
12477   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
12478     return SemaRef.Diag(FnDecl->getLocation(),
12479                         diag::err_operator_new_delete_invalid_result_type)
12480     << FnDecl->getDeclName() << ExpectedResultType;
12481 
12482   // A function template must have at least 2 parameters.
12483   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
12484     return SemaRef.Diag(FnDecl->getLocation(),
12485                       diag::err_operator_new_delete_template_too_few_parameters)
12486         << FnDecl->getDeclName();
12487 
12488   // The function decl must have at least 1 parameter.
12489   if (FnDecl->getNumParams() == 0)
12490     return SemaRef.Diag(FnDecl->getLocation(),
12491                         diag::err_operator_new_delete_too_few_parameters)
12492       << FnDecl->getDeclName();
12493 
12494   // Check the first parameter type is not dependent.
12495   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
12496   if (FirstParamType->isDependentType())
12497     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
12498       << FnDecl->getDeclName() << ExpectedFirstParamType;
12499 
12500   // Check that the first parameter type is what we expect.
12501   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
12502       ExpectedFirstParamType)
12503     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
12504     << FnDecl->getDeclName() << ExpectedFirstParamType;
12505 
12506   return false;
12507 }
12508 
12509 static bool
12510 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
12511   // C++ [basic.stc.dynamic.allocation]p1:
12512   //   A program is ill-formed if an allocation function is declared in a
12513   //   namespace scope other than global scope or declared static in global
12514   //   scope.
12515   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12516     return true;
12517 
12518   CanQualType SizeTy =
12519     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
12520 
12521   // C++ [basic.stc.dynamic.allocation]p1:
12522   //  The return type shall be void*. The first parameter shall have type
12523   //  std::size_t.
12524   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
12525                                   SizeTy,
12526                                   diag::err_operator_new_dependent_param_type,
12527                                   diag::err_operator_new_param_type))
12528     return true;
12529 
12530   // C++ [basic.stc.dynamic.allocation]p1:
12531   //  The first parameter shall not have an associated default argument.
12532   if (FnDecl->getParamDecl(0)->hasDefaultArg())
12533     return SemaRef.Diag(FnDecl->getLocation(),
12534                         diag::err_operator_new_default_arg)
12535       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
12536 
12537   return false;
12538 }
12539 
12540 static bool
12541 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
12542   // C++ [basic.stc.dynamic.deallocation]p1:
12543   //   A program is ill-formed if deallocation functions are declared in a
12544   //   namespace scope other than global scope or declared static in global
12545   //   scope.
12546   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12547     return true;
12548 
12549   // C++ [basic.stc.dynamic.deallocation]p2:
12550   //   Each deallocation function shall return void and its first parameter
12551   //   shall be void*.
12552   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
12553                                   SemaRef.Context.VoidPtrTy,
12554                                  diag::err_operator_delete_dependent_param_type,
12555                                  diag::err_operator_delete_param_type))
12556     return true;
12557 
12558   return false;
12559 }
12560 
12561 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
12562 /// of this overloaded operator is well-formed. If so, returns false;
12563 /// otherwise, emits appropriate diagnostics and returns true.
12564 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
12565   assert(FnDecl && FnDecl->isOverloadedOperator() &&
12566          "Expected an overloaded operator declaration");
12567 
12568   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
12569 
12570   // C++ [over.oper]p5:
12571   //   The allocation and deallocation functions, operator new,
12572   //   operator new[], operator delete and operator delete[], are
12573   //   described completely in 3.7.3. The attributes and restrictions
12574   //   found in the rest of this subclause do not apply to them unless
12575   //   explicitly stated in 3.7.3.
12576   if (Op == OO_Delete || Op == OO_Array_Delete)
12577     return CheckOperatorDeleteDeclaration(*this, FnDecl);
12578 
12579   if (Op == OO_New || Op == OO_Array_New)
12580     return CheckOperatorNewDeclaration(*this, FnDecl);
12581 
12582   // C++ [over.oper]p6:
12583   //   An operator function shall either be a non-static member
12584   //   function or be a non-member function and have at least one
12585   //   parameter whose type is a class, a reference to a class, an
12586   //   enumeration, or a reference to an enumeration.
12587   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
12588     if (MethodDecl->isStatic())
12589       return Diag(FnDecl->getLocation(),
12590                   diag::err_operator_overload_static) << FnDecl->getDeclName();
12591   } else {
12592     bool ClassOrEnumParam = false;
12593     for (auto Param : FnDecl->parameters()) {
12594       QualType ParamType = Param->getType().getNonReferenceType();
12595       if (ParamType->isDependentType() || ParamType->isRecordType() ||
12596           ParamType->isEnumeralType()) {
12597         ClassOrEnumParam = true;
12598         break;
12599       }
12600     }
12601 
12602     if (!ClassOrEnumParam)
12603       return Diag(FnDecl->getLocation(),
12604                   diag::err_operator_overload_needs_class_or_enum)
12605         << FnDecl->getDeclName();
12606   }
12607 
12608   // C++ [over.oper]p8:
12609   //   An operator function cannot have default arguments (8.3.6),
12610   //   except where explicitly stated below.
12611   //
12612   // Only the function-call operator allows default arguments
12613   // (C++ [over.call]p1).
12614   if (Op != OO_Call) {
12615     for (auto Param : FnDecl->parameters()) {
12616       if (Param->hasDefaultArg())
12617         return Diag(Param->getLocation(),
12618                     diag::err_operator_overload_default_arg)
12619           << FnDecl->getDeclName() << Param->getDefaultArgRange();
12620     }
12621   }
12622 
12623   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
12624     { false, false, false }
12625 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
12626     , { Unary, Binary, MemberOnly }
12627 #include "clang/Basic/OperatorKinds.def"
12628   };
12629 
12630   bool CanBeUnaryOperator = OperatorUses[Op][0];
12631   bool CanBeBinaryOperator = OperatorUses[Op][1];
12632   bool MustBeMemberOperator = OperatorUses[Op][2];
12633 
12634   // C++ [over.oper]p8:
12635   //   [...] Operator functions cannot have more or fewer parameters
12636   //   than the number required for the corresponding operator, as
12637   //   described in the rest of this subclause.
12638   unsigned NumParams = FnDecl->getNumParams()
12639                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
12640   if (Op != OO_Call &&
12641       ((NumParams == 1 && !CanBeUnaryOperator) ||
12642        (NumParams == 2 && !CanBeBinaryOperator) ||
12643        (NumParams < 1) || (NumParams > 2))) {
12644     // We have the wrong number of parameters.
12645     unsigned ErrorKind;
12646     if (CanBeUnaryOperator && CanBeBinaryOperator) {
12647       ErrorKind = 2;  // 2 -> unary or binary.
12648     } else if (CanBeUnaryOperator) {
12649       ErrorKind = 0;  // 0 -> unary
12650     } else {
12651       assert(CanBeBinaryOperator &&
12652              "All non-call overloaded operators are unary or binary!");
12653       ErrorKind = 1;  // 1 -> binary
12654     }
12655 
12656     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
12657       << FnDecl->getDeclName() << NumParams << ErrorKind;
12658   }
12659 
12660   // Overloaded operators other than operator() cannot be variadic.
12661   if (Op != OO_Call &&
12662       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
12663     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
12664       << FnDecl->getDeclName();
12665   }
12666 
12667   // Some operators must be non-static member functions.
12668   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
12669     return Diag(FnDecl->getLocation(),
12670                 diag::err_operator_overload_must_be_member)
12671       << FnDecl->getDeclName();
12672   }
12673 
12674   // C++ [over.inc]p1:
12675   //   The user-defined function called operator++ implements the
12676   //   prefix and postfix ++ operator. If this function is a member
12677   //   function with no parameters, or a non-member function with one
12678   //   parameter of class or enumeration type, it defines the prefix
12679   //   increment operator ++ for objects of that type. If the function
12680   //   is a member function with one parameter (which shall be of type
12681   //   int) or a non-member function with two parameters (the second
12682   //   of which shall be of type int), it defines the postfix
12683   //   increment operator ++ for objects of that type.
12684   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
12685     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
12686     QualType ParamType = LastParam->getType();
12687 
12688     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
12689         !ParamType->isDependentType())
12690       return Diag(LastParam->getLocation(),
12691                   diag::err_operator_overload_post_incdec_must_be_int)
12692         << LastParam->getType() << (Op == OO_MinusMinus);
12693   }
12694 
12695   return false;
12696 }
12697 
12698 static bool
12699 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
12700                                           FunctionTemplateDecl *TpDecl) {
12701   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
12702 
12703   // Must have one or two template parameters.
12704   if (TemplateParams->size() == 1) {
12705     NonTypeTemplateParmDecl *PmDecl =
12706         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
12707 
12708     // The template parameter must be a char parameter pack.
12709     if (PmDecl && PmDecl->isTemplateParameterPack() &&
12710         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
12711       return false;
12712 
12713   } else if (TemplateParams->size() == 2) {
12714     TemplateTypeParmDecl *PmType =
12715         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
12716     NonTypeTemplateParmDecl *PmArgs =
12717         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
12718 
12719     // The second template parameter must be a parameter pack with the
12720     // first template parameter as its type.
12721     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
12722         PmArgs->isTemplateParameterPack()) {
12723       const TemplateTypeParmType *TArgs =
12724           PmArgs->getType()->getAs<TemplateTypeParmType>();
12725       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
12726           TArgs->getIndex() == PmType->getIndex()) {
12727         if (SemaRef.ActiveTemplateInstantiations.empty())
12728           SemaRef.Diag(TpDecl->getLocation(),
12729                        diag::ext_string_literal_operator_template);
12730         return false;
12731       }
12732     }
12733   }
12734 
12735   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
12736                diag::err_literal_operator_template)
12737       << TpDecl->getTemplateParameters()->getSourceRange();
12738   return true;
12739 }
12740 
12741 /// CheckLiteralOperatorDeclaration - Check whether the declaration
12742 /// of this literal operator function is well-formed. If so, returns
12743 /// false; otherwise, emits appropriate diagnostics and returns true.
12744 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
12745   if (isa<CXXMethodDecl>(FnDecl)) {
12746     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
12747       << FnDecl->getDeclName();
12748     return true;
12749   }
12750 
12751   if (FnDecl->isExternC()) {
12752     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
12753     return true;
12754   }
12755 
12756   // This might be the definition of a literal operator template.
12757   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
12758 
12759   // This might be a specialization of a literal operator template.
12760   if (!TpDecl)
12761     TpDecl = FnDecl->getPrimaryTemplate();
12762 
12763   // template <char...> type operator "" name() and
12764   // template <class T, T...> type operator "" name() are the only valid
12765   // template signatures, and the only valid signatures with no parameters.
12766   if (TpDecl) {
12767     if (FnDecl->param_size() != 0) {
12768       Diag(FnDecl->getLocation(),
12769            diag::err_literal_operator_template_with_params);
12770       return true;
12771     }
12772 
12773     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
12774       return true;
12775 
12776   } else if (FnDecl->param_size() == 1) {
12777     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
12778 
12779     QualType ParamType = Param->getType().getUnqualifiedType();
12780 
12781     // Only unsigned long long int, long double, any character type, and const
12782     // char * are allowed as the only parameters.
12783     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
12784         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
12785         Context.hasSameType(ParamType, Context.CharTy) ||
12786         Context.hasSameType(ParamType, Context.WideCharTy) ||
12787         Context.hasSameType(ParamType, Context.Char16Ty) ||
12788         Context.hasSameType(ParamType, Context.Char32Ty)) {
12789     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
12790       QualType InnerType = Ptr->getPointeeType();
12791 
12792       // Pointer parameter must be a const char *.
12793       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
12794                                 Context.CharTy) &&
12795             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
12796         Diag(Param->getSourceRange().getBegin(),
12797              diag::err_literal_operator_param)
12798             << ParamType << "'const char *'" << Param->getSourceRange();
12799         return true;
12800       }
12801 
12802     } else if (ParamType->isRealFloatingType()) {
12803       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
12804           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
12805       return true;
12806 
12807     } else if (ParamType->isIntegerType()) {
12808       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
12809           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
12810       return true;
12811 
12812     } else {
12813       Diag(Param->getSourceRange().getBegin(),
12814            diag::err_literal_operator_invalid_param)
12815           << ParamType << Param->getSourceRange();
12816       return true;
12817     }
12818 
12819   } else if (FnDecl->param_size() == 2) {
12820     FunctionDecl::param_iterator Param = FnDecl->param_begin();
12821 
12822     // First, verify that the first parameter is correct.
12823 
12824     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
12825 
12826     // Two parameter function must have a pointer to const as a
12827     // first parameter; let's strip those qualifiers.
12828     const PointerType *PT = FirstParamType->getAs<PointerType>();
12829 
12830     if (!PT) {
12831       Diag((*Param)->getSourceRange().getBegin(),
12832            diag::err_literal_operator_param)
12833           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12834       return true;
12835     }
12836 
12837     QualType PointeeType = PT->getPointeeType();
12838     // First parameter must be const
12839     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
12840       Diag((*Param)->getSourceRange().getBegin(),
12841            diag::err_literal_operator_param)
12842           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12843       return true;
12844     }
12845 
12846     QualType InnerType = PointeeType.getUnqualifiedType();
12847     // Only const char *, const wchar_t*, const char16_t*, and const char32_t*
12848     // are allowed as the first parameter to a two-parameter function
12849     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
12850           Context.hasSameType(InnerType, Context.WideCharTy) ||
12851           Context.hasSameType(InnerType, Context.Char16Ty) ||
12852           Context.hasSameType(InnerType, Context.Char32Ty))) {
12853       Diag((*Param)->getSourceRange().getBegin(),
12854            diag::err_literal_operator_param)
12855           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12856       return true;
12857     }
12858 
12859     // Move on to the second and final parameter.
12860     ++Param;
12861 
12862     // The second parameter must be a std::size_t.
12863     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
12864     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
12865       Diag((*Param)->getSourceRange().getBegin(),
12866            diag::err_literal_operator_param)
12867           << SecondParamType << Context.getSizeType()
12868           << (*Param)->getSourceRange();
12869       return true;
12870     }
12871   } else {
12872     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
12873     return true;
12874   }
12875 
12876   // Parameters are good.
12877 
12878   // A parameter-declaration-clause containing a default argument is not
12879   // equivalent to any of the permitted forms.
12880   for (auto Param : FnDecl->parameters()) {
12881     if (Param->hasDefaultArg()) {
12882       Diag(Param->getDefaultArgRange().getBegin(),
12883            diag::err_literal_operator_default_argument)
12884         << Param->getDefaultArgRange();
12885       break;
12886     }
12887   }
12888 
12889   StringRef LiteralName
12890     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
12891   if (LiteralName[0] != '_') {
12892     // C++11 [usrlit.suffix]p1:
12893     //   Literal suffix identifiers that do not start with an underscore
12894     //   are reserved for future standardization.
12895     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
12896       << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
12897   }
12898 
12899   return false;
12900 }
12901 
12902 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
12903 /// linkage specification, including the language and (if present)
12904 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
12905 /// language string literal. LBraceLoc, if valid, provides the location of
12906 /// the '{' brace. Otherwise, this linkage specification does not
12907 /// have any braces.
12908 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
12909                                            Expr *LangStr,
12910                                            SourceLocation LBraceLoc) {
12911   StringLiteral *Lit = cast<StringLiteral>(LangStr);
12912   if (!Lit->isAscii()) {
12913     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
12914       << LangStr->getSourceRange();
12915     return nullptr;
12916   }
12917 
12918   StringRef Lang = Lit->getString();
12919   LinkageSpecDecl::LanguageIDs Language;
12920   if (Lang == "C")
12921     Language = LinkageSpecDecl::lang_c;
12922   else if (Lang == "C++")
12923     Language = LinkageSpecDecl::lang_cxx;
12924   else {
12925     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
12926       << LangStr->getSourceRange();
12927     return nullptr;
12928   }
12929 
12930   // FIXME: Add all the various semantics of linkage specifications
12931 
12932   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
12933                                                LangStr->getExprLoc(), Language,
12934                                                LBraceLoc.isValid());
12935   CurContext->addDecl(D);
12936   PushDeclContext(S, D);
12937   return D;
12938 }
12939 
12940 /// ActOnFinishLinkageSpecification - Complete the definition of
12941 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
12942 /// valid, it's the position of the closing '}' brace in a linkage
12943 /// specification that uses braces.
12944 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
12945                                             Decl *LinkageSpec,
12946                                             SourceLocation RBraceLoc) {
12947   if (RBraceLoc.isValid()) {
12948     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
12949     LSDecl->setRBraceLoc(RBraceLoc);
12950   }
12951   PopDeclContext();
12952   return LinkageSpec;
12953 }
12954 
12955 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
12956                                   AttributeList *AttrList,
12957                                   SourceLocation SemiLoc) {
12958   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
12959   // Attribute declarations appertain to empty declaration so we handle
12960   // them here.
12961   if (AttrList)
12962     ProcessDeclAttributeList(S, ED, AttrList);
12963 
12964   CurContext->addDecl(ED);
12965   return ED;
12966 }
12967 
12968 /// \brief Perform semantic analysis for the variable declaration that
12969 /// occurs within a C++ catch clause, returning the newly-created
12970 /// variable.
12971 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
12972                                          TypeSourceInfo *TInfo,
12973                                          SourceLocation StartLoc,
12974                                          SourceLocation Loc,
12975                                          IdentifierInfo *Name) {
12976   bool Invalid = false;
12977   QualType ExDeclType = TInfo->getType();
12978 
12979   // Arrays and functions decay.
12980   if (ExDeclType->isArrayType())
12981     ExDeclType = Context.getArrayDecayedType(ExDeclType);
12982   else if (ExDeclType->isFunctionType())
12983     ExDeclType = Context.getPointerType(ExDeclType);
12984 
12985   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
12986   // The exception-declaration shall not denote a pointer or reference to an
12987   // incomplete type, other than [cv] void*.
12988   // N2844 forbids rvalue references.
12989   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
12990     Diag(Loc, diag::err_catch_rvalue_ref);
12991     Invalid = true;
12992   }
12993 
12994   if (ExDeclType->isVariablyModifiedType()) {
12995     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
12996     Invalid = true;
12997   }
12998 
12999   QualType BaseType = ExDeclType;
13000   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
13001   unsigned DK = diag::err_catch_incomplete;
13002   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
13003     BaseType = Ptr->getPointeeType();
13004     Mode = 1;
13005     DK = diag::err_catch_incomplete_ptr;
13006   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
13007     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
13008     BaseType = Ref->getPointeeType();
13009     Mode = 2;
13010     DK = diag::err_catch_incomplete_ref;
13011   }
13012   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
13013       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
13014     Invalid = true;
13015 
13016   if (!Invalid && !ExDeclType->isDependentType() &&
13017       RequireNonAbstractType(Loc, ExDeclType,
13018                              diag::err_abstract_type_in_decl,
13019                              AbstractVariableType))
13020     Invalid = true;
13021 
13022   // Only the non-fragile NeXT runtime currently supports C++ catches
13023   // of ObjC types, and no runtime supports catching ObjC types by value.
13024   if (!Invalid && getLangOpts().ObjC1) {
13025     QualType T = ExDeclType;
13026     if (const ReferenceType *RT = T->getAs<ReferenceType>())
13027       T = RT->getPointeeType();
13028 
13029     if (T->isObjCObjectType()) {
13030       Diag(Loc, diag::err_objc_object_catch);
13031       Invalid = true;
13032     } else if (T->isObjCObjectPointerType()) {
13033       // FIXME: should this be a test for macosx-fragile specifically?
13034       if (getLangOpts().ObjCRuntime.isFragile())
13035         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
13036     }
13037   }
13038 
13039   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
13040                                     ExDeclType, TInfo, SC_None);
13041   ExDecl->setExceptionVariable(true);
13042 
13043   // In ARC, infer 'retaining' for variables of retainable type.
13044   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
13045     Invalid = true;
13046 
13047   if (!Invalid && !ExDeclType->isDependentType()) {
13048     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
13049       // Insulate this from anything else we might currently be parsing.
13050       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
13051 
13052       // C++ [except.handle]p16:
13053       //   The object declared in an exception-declaration or, if the
13054       //   exception-declaration does not specify a name, a temporary (12.2) is
13055       //   copy-initialized (8.5) from the exception object. [...]
13056       //   The object is destroyed when the handler exits, after the destruction
13057       //   of any automatic objects initialized within the handler.
13058       //
13059       // We just pretend to initialize the object with itself, then make sure
13060       // it can be destroyed later.
13061       QualType initType = Context.getExceptionObjectType(ExDeclType);
13062 
13063       InitializedEntity entity =
13064         InitializedEntity::InitializeVariable(ExDecl);
13065       InitializationKind initKind =
13066         InitializationKind::CreateCopy(Loc, SourceLocation());
13067 
13068       Expr *opaqueValue =
13069         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
13070       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13071       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
13072       if (result.isInvalid())
13073         Invalid = true;
13074       else {
13075         // If the constructor used was non-trivial, set this as the
13076         // "initializer".
13077         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
13078         if (!construct->getConstructor()->isTrivial()) {
13079           Expr *init = MaybeCreateExprWithCleanups(construct);
13080           ExDecl->setInit(init);
13081         }
13082 
13083         // And make sure it's destructable.
13084         FinalizeVarWithDestructor(ExDecl, recordType);
13085       }
13086     }
13087   }
13088 
13089   if (Invalid)
13090     ExDecl->setInvalidDecl();
13091 
13092   return ExDecl;
13093 }
13094 
13095 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13096 /// handler.
13097 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
13098   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13099   bool Invalid = D.isInvalidType();
13100 
13101   // Check for unexpanded parameter packs.
13102   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13103                                       UPPC_ExceptionType)) {
13104     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13105                                              D.getIdentifierLoc());
13106     Invalid = true;
13107   }
13108 
13109   IdentifierInfo *II = D.getIdentifier();
13110   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
13111                                              LookupOrdinaryName,
13112                                              ForRedeclaration)) {
13113     // The scope should be freshly made just for us. There is just no way
13114     // it contains any previous declaration, except for function parameters in
13115     // a function-try-block's catch statement.
13116     assert(!S->isDeclScope(PrevDecl));
13117     if (isDeclInScope(PrevDecl, CurContext, S)) {
13118       Diag(D.getIdentifierLoc(), diag::err_redefinition)
13119         << D.getIdentifier();
13120       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13121       Invalid = true;
13122     } else if (PrevDecl->isTemplateParameter())
13123       // Maybe we will complain about the shadowed template parameter.
13124       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13125   }
13126 
13127   if (D.getCXXScopeSpec().isSet() && !Invalid) {
13128     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13129       << D.getCXXScopeSpec().getRange();
13130     Invalid = true;
13131   }
13132 
13133   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
13134                                               D.getLocStart(),
13135                                               D.getIdentifierLoc(),
13136                                               D.getIdentifier());
13137   if (Invalid)
13138     ExDecl->setInvalidDecl();
13139 
13140   // Add the exception declaration into this scope.
13141   if (II)
13142     PushOnScopeChains(ExDecl, S);
13143   else
13144     CurContext->addDecl(ExDecl);
13145 
13146   ProcessDeclAttributes(S, ExDecl, D);
13147   return ExDecl;
13148 }
13149 
13150 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13151                                          Expr *AssertExpr,
13152                                          Expr *AssertMessageExpr,
13153                                          SourceLocation RParenLoc) {
13154   StringLiteral *AssertMessage =
13155       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
13156 
13157   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
13158     return nullptr;
13159 
13160   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
13161                                       AssertMessage, RParenLoc, false);
13162 }
13163 
13164 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13165                                          Expr *AssertExpr,
13166                                          StringLiteral *AssertMessage,
13167                                          SourceLocation RParenLoc,
13168                                          bool Failed) {
13169   assert(AssertExpr != nullptr && "Expected non-null condition");
13170   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
13171       !Failed) {
13172     // In a static_assert-declaration, the constant-expression shall be a
13173     // constant expression that can be contextually converted to bool.
13174     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
13175     if (Converted.isInvalid())
13176       Failed = true;
13177 
13178     llvm::APSInt Cond;
13179     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
13180           diag::err_static_assert_expression_is_not_constant,
13181           /*AllowFold=*/false).isInvalid())
13182       Failed = true;
13183 
13184     if (!Failed && !Cond) {
13185       SmallString<256> MsgBuffer;
13186       llvm::raw_svector_ostream Msg(MsgBuffer);
13187       if (AssertMessage)
13188         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
13189       Diag(StaticAssertLoc, diag::err_static_assert_failed)
13190         << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
13191       Failed = true;
13192     }
13193   }
13194 
13195   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
13196                                         AssertExpr, AssertMessage, RParenLoc,
13197                                         Failed);
13198 
13199   CurContext->addDecl(Decl);
13200   return Decl;
13201 }
13202 
13203 /// \brief Perform semantic analysis of the given friend type declaration.
13204 ///
13205 /// \returns A friend declaration that.
13206 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
13207                                       SourceLocation FriendLoc,
13208                                       TypeSourceInfo *TSInfo) {
13209   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
13210 
13211   QualType T = TSInfo->getType();
13212   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
13213 
13214   // C++03 [class.friend]p2:
13215   //   An elaborated-type-specifier shall be used in a friend declaration
13216   //   for a class.*
13217   //
13218   //   * The class-key of the elaborated-type-specifier is required.
13219   if (!ActiveTemplateInstantiations.empty()) {
13220     // Do not complain about the form of friend template types during
13221     // template instantiation; we will already have complained when the
13222     // template was declared.
13223   } else {
13224     if (!T->isElaboratedTypeSpecifier()) {
13225       // If we evaluated the type to a record type, suggest putting
13226       // a tag in front.
13227       if (const RecordType *RT = T->getAs<RecordType>()) {
13228         RecordDecl *RD = RT->getDecl();
13229 
13230         SmallString<16> InsertionText(" ");
13231         InsertionText += RD->getKindName();
13232 
13233         Diag(TypeRange.getBegin(),
13234              getLangOpts().CPlusPlus11 ?
13235                diag::warn_cxx98_compat_unelaborated_friend_type :
13236                diag::ext_unelaborated_friend_type)
13237           << (unsigned) RD->getTagKind()
13238           << T
13239           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
13240                                         InsertionText);
13241       } else {
13242         Diag(FriendLoc,
13243              getLangOpts().CPlusPlus11 ?
13244                diag::warn_cxx98_compat_nonclass_type_friend :
13245                diag::ext_nonclass_type_friend)
13246           << T
13247           << TypeRange;
13248       }
13249     } else if (T->getAs<EnumType>()) {
13250       Diag(FriendLoc,
13251            getLangOpts().CPlusPlus11 ?
13252              diag::warn_cxx98_compat_enum_friend :
13253              diag::ext_enum_friend)
13254         << T
13255         << TypeRange;
13256     }
13257 
13258     // C++11 [class.friend]p3:
13259     //   A friend declaration that does not declare a function shall have one
13260     //   of the following forms:
13261     //     friend elaborated-type-specifier ;
13262     //     friend simple-type-specifier ;
13263     //     friend typename-specifier ;
13264     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
13265       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
13266   }
13267 
13268   //   If the type specifier in a friend declaration designates a (possibly
13269   //   cv-qualified) class type, that class is declared as a friend; otherwise,
13270   //   the friend declaration is ignored.
13271   return FriendDecl::Create(Context, CurContext,
13272                             TSInfo->getTypeLoc().getLocStart(), TSInfo,
13273                             FriendLoc);
13274 }
13275 
13276 /// Handle a friend tag declaration where the scope specifier was
13277 /// templated.
13278 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
13279                                     unsigned TagSpec, SourceLocation TagLoc,
13280                                     CXXScopeSpec &SS,
13281                                     IdentifierInfo *Name,
13282                                     SourceLocation NameLoc,
13283                                     AttributeList *Attr,
13284                                     MultiTemplateParamsArg TempParamLists) {
13285   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13286 
13287   bool isExplicitSpecialization = false;
13288   bool Invalid = false;
13289 
13290   if (TemplateParameterList *TemplateParams =
13291           MatchTemplateParametersToScopeSpecifier(
13292               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
13293               isExplicitSpecialization, Invalid)) {
13294     if (TemplateParams->size() > 0) {
13295       // This is a declaration of a class template.
13296       if (Invalid)
13297         return nullptr;
13298 
13299       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
13300                                 NameLoc, Attr, TemplateParams, AS_public,
13301                                 /*ModulePrivateLoc=*/SourceLocation(),
13302                                 FriendLoc, TempParamLists.size() - 1,
13303                                 TempParamLists.data()).get();
13304     } else {
13305       // The "template<>" header is extraneous.
13306       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13307         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13308       isExplicitSpecialization = true;
13309     }
13310   }
13311 
13312   if (Invalid) return nullptr;
13313 
13314   bool isAllExplicitSpecializations = true;
13315   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
13316     if (TempParamLists[I]->size()) {
13317       isAllExplicitSpecializations = false;
13318       break;
13319     }
13320   }
13321 
13322   // FIXME: don't ignore attributes.
13323 
13324   // If it's explicit specializations all the way down, just forget
13325   // about the template header and build an appropriate non-templated
13326   // friend.  TODO: for source fidelity, remember the headers.
13327   if (isAllExplicitSpecializations) {
13328     if (SS.isEmpty()) {
13329       bool Owned = false;
13330       bool IsDependent = false;
13331       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
13332                       Attr, AS_public,
13333                       /*ModulePrivateLoc=*/SourceLocation(),
13334                       MultiTemplateParamsArg(), Owned, IsDependent,
13335                       /*ScopedEnumKWLoc=*/SourceLocation(),
13336                       /*ScopedEnumUsesClassTag=*/false,
13337                       /*UnderlyingType=*/TypeResult(),
13338                       /*IsTypeSpecifier=*/false);
13339     }
13340 
13341     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
13342     ElaboratedTypeKeyword Keyword
13343       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13344     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
13345                                    *Name, NameLoc);
13346     if (T.isNull())
13347       return nullptr;
13348 
13349     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13350     if (isa<DependentNameType>(T)) {
13351       DependentNameTypeLoc TL =
13352           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
13353       TL.setElaboratedKeywordLoc(TagLoc);
13354       TL.setQualifierLoc(QualifierLoc);
13355       TL.setNameLoc(NameLoc);
13356     } else {
13357       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
13358       TL.setElaboratedKeywordLoc(TagLoc);
13359       TL.setQualifierLoc(QualifierLoc);
13360       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
13361     }
13362 
13363     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
13364                                             TSI, FriendLoc, TempParamLists);
13365     Friend->setAccess(AS_public);
13366     CurContext->addDecl(Friend);
13367     return Friend;
13368   }
13369 
13370   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
13371 
13372 
13373 
13374   // Handle the case of a templated-scope friend class.  e.g.
13375   //   template <class T> class A<T>::B;
13376   // FIXME: we don't support these right now.
13377   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
13378     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
13379   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13380   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
13381   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13382   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
13383   TL.setElaboratedKeywordLoc(TagLoc);
13384   TL.setQualifierLoc(SS.getWithLocInContext(Context));
13385   TL.setNameLoc(NameLoc);
13386 
13387   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
13388                                           TSI, FriendLoc, TempParamLists);
13389   Friend->setAccess(AS_public);
13390   Friend->setUnsupportedFriend(true);
13391   CurContext->addDecl(Friend);
13392   return Friend;
13393 }
13394 
13395 
13396 /// Handle a friend type declaration.  This works in tandem with
13397 /// ActOnTag.
13398 ///
13399 /// Notes on friend class templates:
13400 ///
13401 /// We generally treat friend class declarations as if they were
13402 /// declaring a class.  So, for example, the elaborated type specifier
13403 /// in a friend declaration is required to obey the restrictions of a
13404 /// class-head (i.e. no typedefs in the scope chain), template
13405 /// parameters are required to match up with simple template-ids, &c.
13406 /// However, unlike when declaring a template specialization, it's
13407 /// okay to refer to a template specialization without an empty
13408 /// template parameter declaration, e.g.
13409 ///   friend class A<T>::B<unsigned>;
13410 /// We permit this as a special case; if there are any template
13411 /// parameters present at all, require proper matching, i.e.
13412 ///   template <> template \<class T> friend class A<int>::B;
13413 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
13414                                 MultiTemplateParamsArg TempParams) {
13415   SourceLocation Loc = DS.getLocStart();
13416 
13417   assert(DS.isFriendSpecified());
13418   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13419 
13420   // Try to convert the decl specifier to a type.  This works for
13421   // friend templates because ActOnTag never produces a ClassTemplateDecl
13422   // for a TUK_Friend.
13423   Declarator TheDeclarator(DS, Declarator::MemberContext);
13424   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
13425   QualType T = TSI->getType();
13426   if (TheDeclarator.isInvalidType())
13427     return nullptr;
13428 
13429   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
13430     return nullptr;
13431 
13432   // This is definitely an error in C++98.  It's probably meant to
13433   // be forbidden in C++0x, too, but the specification is just
13434   // poorly written.
13435   //
13436   // The problem is with declarations like the following:
13437   //   template <T> friend A<T>::foo;
13438   // where deciding whether a class C is a friend or not now hinges
13439   // on whether there exists an instantiation of A that causes
13440   // 'foo' to equal C.  There are restrictions on class-heads
13441   // (which we declare (by fiat) elaborated friend declarations to
13442   // be) that makes this tractable.
13443   //
13444   // FIXME: handle "template <> friend class A<T>;", which
13445   // is possibly well-formed?  Who even knows?
13446   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
13447     Diag(Loc, diag::err_tagless_friend_type_template)
13448       << DS.getSourceRange();
13449     return nullptr;
13450   }
13451 
13452   // C++98 [class.friend]p1: A friend of a class is a function
13453   //   or class that is not a member of the class . . .
13454   // This is fixed in DR77, which just barely didn't make the C++03
13455   // deadline.  It's also a very silly restriction that seriously
13456   // affects inner classes and which nobody else seems to implement;
13457   // thus we never diagnose it, not even in -pedantic.
13458   //
13459   // But note that we could warn about it: it's always useless to
13460   // friend one of your own members (it's not, however, worthless to
13461   // friend a member of an arbitrary specialization of your template).
13462 
13463   Decl *D;
13464   if (!TempParams.empty())
13465     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
13466                                    TempParams,
13467                                    TSI,
13468                                    DS.getFriendSpecLoc());
13469   else
13470     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
13471 
13472   if (!D)
13473     return nullptr;
13474 
13475   D->setAccess(AS_public);
13476   CurContext->addDecl(D);
13477 
13478   return D;
13479 }
13480 
13481 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
13482                                         MultiTemplateParamsArg TemplateParams) {
13483   const DeclSpec &DS = D.getDeclSpec();
13484 
13485   assert(DS.isFriendSpecified());
13486   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13487 
13488   SourceLocation Loc = D.getIdentifierLoc();
13489   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13490 
13491   // C++ [class.friend]p1
13492   //   A friend of a class is a function or class....
13493   // Note that this sees through typedefs, which is intended.
13494   // It *doesn't* see through dependent types, which is correct
13495   // according to [temp.arg.type]p3:
13496   //   If a declaration acquires a function type through a
13497   //   type dependent on a template-parameter and this causes
13498   //   a declaration that does not use the syntactic form of a
13499   //   function declarator to have a function type, the program
13500   //   is ill-formed.
13501   if (!TInfo->getType()->isFunctionType()) {
13502     Diag(Loc, diag::err_unexpected_friend);
13503 
13504     // It might be worthwhile to try to recover by creating an
13505     // appropriate declaration.
13506     return nullptr;
13507   }
13508 
13509   // C++ [namespace.memdef]p3
13510   //  - If a friend declaration in a non-local class first declares a
13511   //    class or function, the friend class or function is a member
13512   //    of the innermost enclosing namespace.
13513   //  - The name of the friend is not found by simple name lookup
13514   //    until a matching declaration is provided in that namespace
13515   //    scope (either before or after the class declaration granting
13516   //    friendship).
13517   //  - If a friend function is called, its name may be found by the
13518   //    name lookup that considers functions from namespaces and
13519   //    classes associated with the types of the function arguments.
13520   //  - When looking for a prior declaration of a class or a function
13521   //    declared as a friend, scopes outside the innermost enclosing
13522   //    namespace scope are not considered.
13523 
13524   CXXScopeSpec &SS = D.getCXXScopeSpec();
13525   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
13526   DeclarationName Name = NameInfo.getName();
13527   assert(Name);
13528 
13529   // Check for unexpanded parameter packs.
13530   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
13531       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
13532       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
13533     return nullptr;
13534 
13535   // The context we found the declaration in, or in which we should
13536   // create the declaration.
13537   DeclContext *DC;
13538   Scope *DCScope = S;
13539   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13540                         ForRedeclaration);
13541 
13542   // There are five cases here.
13543   //   - There's no scope specifier and we're in a local class. Only look
13544   //     for functions declared in the immediately-enclosing block scope.
13545   // We recover from invalid scope qualifiers as if they just weren't there.
13546   FunctionDecl *FunctionContainingLocalClass = nullptr;
13547   if ((SS.isInvalid() || !SS.isSet()) &&
13548       (FunctionContainingLocalClass =
13549            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
13550     // C++11 [class.friend]p11:
13551     //   If a friend declaration appears in a local class and the name
13552     //   specified is an unqualified name, a prior declaration is
13553     //   looked up without considering scopes that are outside the
13554     //   innermost enclosing non-class scope. For a friend function
13555     //   declaration, if there is no prior declaration, the program is
13556     //   ill-formed.
13557 
13558     // Find the innermost enclosing non-class scope. This is the block
13559     // scope containing the local class definition (or for a nested class,
13560     // the outer local class).
13561     DCScope = S->getFnParent();
13562 
13563     // Look up the function name in the scope.
13564     Previous.clear(LookupLocalFriendName);
13565     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
13566 
13567     if (!Previous.empty()) {
13568       // All possible previous declarations must have the same context:
13569       // either they were declared at block scope or they are members of
13570       // one of the enclosing local classes.
13571       DC = Previous.getRepresentativeDecl()->getDeclContext();
13572     } else {
13573       // This is ill-formed, but provide the context that we would have
13574       // declared the function in, if we were permitted to, for error recovery.
13575       DC = FunctionContainingLocalClass;
13576     }
13577     adjustContextForLocalExternDecl(DC);
13578 
13579     // C++ [class.friend]p6:
13580     //   A function can be defined in a friend declaration of a class if and
13581     //   only if the class is a non-local class (9.8), the function name is
13582     //   unqualified, and the function has namespace scope.
13583     if (D.isFunctionDefinition()) {
13584       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
13585     }
13586 
13587   //   - There's no scope specifier, in which case we just go to the
13588   //     appropriate scope and look for a function or function template
13589   //     there as appropriate.
13590   } else if (SS.isInvalid() || !SS.isSet()) {
13591     // C++11 [namespace.memdef]p3:
13592     //   If the name in a friend declaration is neither qualified nor
13593     //   a template-id and the declaration is a function or an
13594     //   elaborated-type-specifier, the lookup to determine whether
13595     //   the entity has been previously declared shall not consider
13596     //   any scopes outside the innermost enclosing namespace.
13597     bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
13598 
13599     // Find the appropriate context according to the above.
13600     DC = CurContext;
13601 
13602     // Skip class contexts.  If someone can cite chapter and verse
13603     // for this behavior, that would be nice --- it's what GCC and
13604     // EDG do, and it seems like a reasonable intent, but the spec
13605     // really only says that checks for unqualified existing
13606     // declarations should stop at the nearest enclosing namespace,
13607     // not that they should only consider the nearest enclosing
13608     // namespace.
13609     while (DC->isRecord())
13610       DC = DC->getParent();
13611 
13612     DeclContext *LookupDC = DC;
13613     while (LookupDC->isTransparentContext())
13614       LookupDC = LookupDC->getParent();
13615 
13616     while (true) {
13617       LookupQualifiedName(Previous, LookupDC);
13618 
13619       if (!Previous.empty()) {
13620         DC = LookupDC;
13621         break;
13622       }
13623 
13624       if (isTemplateId) {
13625         if (isa<TranslationUnitDecl>(LookupDC)) break;
13626       } else {
13627         if (LookupDC->isFileContext()) break;
13628       }
13629       LookupDC = LookupDC->getParent();
13630     }
13631 
13632     DCScope = getScopeForDeclContext(S, DC);
13633 
13634   //   - There's a non-dependent scope specifier, in which case we
13635   //     compute it and do a previous lookup there for a function
13636   //     or function template.
13637   } else if (!SS.getScopeRep()->isDependent()) {
13638     DC = computeDeclContext(SS);
13639     if (!DC) return nullptr;
13640 
13641     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
13642 
13643     LookupQualifiedName(Previous, DC);
13644 
13645     // Ignore things found implicitly in the wrong scope.
13646     // TODO: better diagnostics for this case.  Suggesting the right
13647     // qualified scope would be nice...
13648     LookupResult::Filter F = Previous.makeFilter();
13649     while (F.hasNext()) {
13650       NamedDecl *D = F.next();
13651       if (!DC->InEnclosingNamespaceSetOf(
13652               D->getDeclContext()->getRedeclContext()))
13653         F.erase();
13654     }
13655     F.done();
13656 
13657     if (Previous.empty()) {
13658       D.setInvalidType();
13659       Diag(Loc, diag::err_qualified_friend_not_found)
13660           << Name << TInfo->getType();
13661       return nullptr;
13662     }
13663 
13664     // C++ [class.friend]p1: A friend of a class is a function or
13665     //   class that is not a member of the class . . .
13666     if (DC->Equals(CurContext))
13667       Diag(DS.getFriendSpecLoc(),
13668            getLangOpts().CPlusPlus11 ?
13669              diag::warn_cxx98_compat_friend_is_member :
13670              diag::err_friend_is_member);
13671 
13672     if (D.isFunctionDefinition()) {
13673       // C++ [class.friend]p6:
13674       //   A function can be defined in a friend declaration of a class if and
13675       //   only if the class is a non-local class (9.8), the function name is
13676       //   unqualified, and the function has namespace scope.
13677       SemaDiagnosticBuilder DB
13678         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
13679 
13680       DB << SS.getScopeRep();
13681       if (DC->isFileContext())
13682         DB << FixItHint::CreateRemoval(SS.getRange());
13683       SS.clear();
13684     }
13685 
13686   //   - There's a scope specifier that does not match any template
13687   //     parameter lists, in which case we use some arbitrary context,
13688   //     create a method or method template, and wait for instantiation.
13689   //   - There's a scope specifier that does match some template
13690   //     parameter lists, which we don't handle right now.
13691   } else {
13692     if (D.isFunctionDefinition()) {
13693       // C++ [class.friend]p6:
13694       //   A function can be defined in a friend declaration of a class if and
13695       //   only if the class is a non-local class (9.8), the function name is
13696       //   unqualified, and the function has namespace scope.
13697       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
13698         << SS.getScopeRep();
13699     }
13700 
13701     DC = CurContext;
13702     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
13703   }
13704 
13705   if (!DC->isRecord()) {
13706     int DiagArg = -1;
13707     switch (D.getName().getKind()) {
13708     case UnqualifiedId::IK_ConstructorTemplateId:
13709     case UnqualifiedId::IK_ConstructorName:
13710       DiagArg = 0;
13711       break;
13712     case UnqualifiedId::IK_DestructorName:
13713       DiagArg = 1;
13714       break;
13715     case UnqualifiedId::IK_ConversionFunctionId:
13716       DiagArg = 2;
13717       break;
13718     case UnqualifiedId::IK_Identifier:
13719     case UnqualifiedId::IK_ImplicitSelfParam:
13720     case UnqualifiedId::IK_LiteralOperatorId:
13721     case UnqualifiedId::IK_OperatorFunctionId:
13722     case UnqualifiedId::IK_TemplateId:
13723       break;
13724     }
13725     // This implies that it has to be an operator or function.
13726     if (DiagArg >= 0) {
13727       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
13728       return nullptr;
13729     }
13730   }
13731 
13732   // FIXME: This is an egregious hack to cope with cases where the scope stack
13733   // does not contain the declaration context, i.e., in an out-of-line
13734   // definition of a class.
13735   Scope FakeDCScope(S, Scope::DeclScope, Diags);
13736   if (!DCScope) {
13737     FakeDCScope.setEntity(DC);
13738     DCScope = &FakeDCScope;
13739   }
13740 
13741   bool AddToScope = true;
13742   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
13743                                           TemplateParams, AddToScope);
13744   if (!ND) return nullptr;
13745 
13746   assert(ND->getLexicalDeclContext() == CurContext);
13747 
13748   // If we performed typo correction, we might have added a scope specifier
13749   // and changed the decl context.
13750   DC = ND->getDeclContext();
13751 
13752   // Add the function declaration to the appropriate lookup tables,
13753   // adjusting the redeclarations list as necessary.  We don't
13754   // want to do this yet if the friending class is dependent.
13755   //
13756   // Also update the scope-based lookup if the target context's
13757   // lookup context is in lexical scope.
13758   if (!CurContext->isDependentContext()) {
13759     DC = DC->getRedeclContext();
13760     DC->makeDeclVisibleInContext(ND);
13761     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
13762       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
13763   }
13764 
13765   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
13766                                        D.getIdentifierLoc(), ND,
13767                                        DS.getFriendSpecLoc());
13768   FrD->setAccess(AS_public);
13769   CurContext->addDecl(FrD);
13770 
13771   if (ND->isInvalidDecl()) {
13772     FrD->setInvalidDecl();
13773   } else {
13774     if (DC->isRecord()) CheckFriendAccess(ND);
13775 
13776     FunctionDecl *FD;
13777     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
13778       FD = FTD->getTemplatedDecl();
13779     else
13780       FD = cast<FunctionDecl>(ND);
13781 
13782     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
13783     // default argument expression, that declaration shall be a definition
13784     // and shall be the only declaration of the function or function
13785     // template in the translation unit.
13786     if (functionDeclHasDefaultArgument(FD)) {
13787       // We can't look at FD->getPreviousDecl() because it may not have been set
13788       // if we're in a dependent context. If we get this far with a non-empty
13789       // Previous set, we must have a valid previous declaration of this
13790       // function.
13791       if (!Previous.empty()) {
13792         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
13793         Diag(Previous.getRepresentativeDecl()->getLocation(),
13794              diag::note_previous_declaration);
13795       } else if (!D.isFunctionDefinition())
13796         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
13797     }
13798 
13799     // Mark templated-scope function declarations as unsupported.
13800     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
13801       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
13802         << SS.getScopeRep() << SS.getRange()
13803         << cast<CXXRecordDecl>(CurContext);
13804       FrD->setUnsupportedFriend(true);
13805     }
13806   }
13807 
13808   return ND;
13809 }
13810 
13811 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
13812   AdjustDeclIfTemplate(Dcl);
13813 
13814   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
13815   if (!Fn) {
13816     Diag(DelLoc, diag::err_deleted_non_function);
13817     return;
13818   }
13819 
13820   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
13821     // Don't consider the implicit declaration we generate for explicit
13822     // specializations. FIXME: Do not generate these implicit declarations.
13823     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
13824          Prev->getPreviousDecl()) &&
13825         !Prev->isDefined()) {
13826       Diag(DelLoc, diag::err_deleted_decl_not_first);
13827       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
13828            Prev->isImplicit() ? diag::note_previous_implicit_declaration
13829                               : diag::note_previous_declaration);
13830     }
13831     // If the declaration wasn't the first, we delete the function anyway for
13832     // recovery.
13833     Fn = Fn->getCanonicalDecl();
13834   }
13835 
13836   // dllimport/dllexport cannot be deleted.
13837   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
13838     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
13839     Fn->setInvalidDecl();
13840   }
13841 
13842   if (Fn->isDeleted())
13843     return;
13844 
13845   // See if we're deleting a function which is already known to override a
13846   // non-deleted virtual function.
13847   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
13848     bool IssuedDiagnostic = false;
13849     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
13850                                         E = MD->end_overridden_methods();
13851          I != E; ++I) {
13852       if (!(*MD->begin_overridden_methods())->isDeleted()) {
13853         if (!IssuedDiagnostic) {
13854           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
13855           IssuedDiagnostic = true;
13856         }
13857         Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
13858       }
13859     }
13860   }
13861 
13862   // C++11 [basic.start.main]p3:
13863   //   A program that defines main as deleted [...] is ill-formed.
13864   if (Fn->isMain())
13865     Diag(DelLoc, diag::err_deleted_main);
13866 
13867   Fn->setDeletedAsWritten();
13868 }
13869 
13870 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
13871   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
13872 
13873   if (MD) {
13874     if (MD->getParent()->isDependentType()) {
13875       MD->setDefaulted();
13876       MD->setExplicitlyDefaulted();
13877       return;
13878     }
13879 
13880     CXXSpecialMember Member = getSpecialMember(MD);
13881     if (Member == CXXInvalid) {
13882       if (!MD->isInvalidDecl())
13883         Diag(DefaultLoc, diag::err_default_special_members);
13884       return;
13885     }
13886 
13887     MD->setDefaulted();
13888     MD->setExplicitlyDefaulted();
13889 
13890     // If this definition appears within the record, do the checking when
13891     // the record is complete.
13892     const FunctionDecl *Primary = MD;
13893     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
13894       // Ask the template instantiation pattern that actually had the
13895       // '= default' on it.
13896       Primary = Pattern;
13897 
13898     // If the method was defaulted on its first declaration, we will have
13899     // already performed the checking in CheckCompletedCXXClass. Such a
13900     // declaration doesn't trigger an implicit definition.
13901     if (Primary->getCanonicalDecl()->isDefaulted())
13902       return;
13903 
13904     CheckExplicitlyDefaultedSpecialMember(MD);
13905 
13906     if (!MD->isInvalidDecl())
13907       DefineImplicitSpecialMember(*this, MD, DefaultLoc);
13908   } else {
13909     Diag(DefaultLoc, diag::err_default_special_members);
13910   }
13911 }
13912 
13913 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
13914   for (Stmt *SubStmt : S->children()) {
13915     if (!SubStmt)
13916       continue;
13917     if (isa<ReturnStmt>(SubStmt))
13918       Self.Diag(SubStmt->getLocStart(),
13919            diag::err_return_in_constructor_handler);
13920     if (!isa<Expr>(SubStmt))
13921       SearchForReturnInStmt(Self, SubStmt);
13922   }
13923 }
13924 
13925 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
13926   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
13927     CXXCatchStmt *Handler = TryBlock->getHandler(I);
13928     SearchForReturnInStmt(*this, Handler);
13929   }
13930 }
13931 
13932 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
13933                                              const CXXMethodDecl *Old) {
13934   const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
13935   const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
13936 
13937   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
13938 
13939   // If the calling conventions match, everything is fine
13940   if (NewCC == OldCC)
13941     return false;
13942 
13943   // If the calling conventions mismatch because the new function is static,
13944   // suppress the calling convention mismatch error; the error about static
13945   // function override (err_static_overrides_virtual from
13946   // Sema::CheckFunctionDeclaration) is more clear.
13947   if (New->getStorageClass() == SC_Static)
13948     return false;
13949 
13950   Diag(New->getLocation(),
13951        diag::err_conflicting_overriding_cc_attributes)
13952     << New->getDeclName() << New->getType() << Old->getType();
13953   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
13954   return true;
13955 }
13956 
13957 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
13958                                              const CXXMethodDecl *Old) {
13959   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
13960   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
13961 
13962   if (Context.hasSameType(NewTy, OldTy) ||
13963       NewTy->isDependentType() || OldTy->isDependentType())
13964     return false;
13965 
13966   // Check if the return types are covariant
13967   QualType NewClassTy, OldClassTy;
13968 
13969   /// Both types must be pointers or references to classes.
13970   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
13971     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
13972       NewClassTy = NewPT->getPointeeType();
13973       OldClassTy = OldPT->getPointeeType();
13974     }
13975   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
13976     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
13977       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
13978         NewClassTy = NewRT->getPointeeType();
13979         OldClassTy = OldRT->getPointeeType();
13980       }
13981     }
13982   }
13983 
13984   // The return types aren't either both pointers or references to a class type.
13985   if (NewClassTy.isNull()) {
13986     Diag(New->getLocation(),
13987          diag::err_different_return_type_for_overriding_virtual_function)
13988         << New->getDeclName() << NewTy << OldTy
13989         << New->getReturnTypeSourceRange();
13990     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13991         << Old->getReturnTypeSourceRange();
13992 
13993     return true;
13994   }
13995 
13996   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
13997     // C++14 [class.virtual]p8:
13998     //   If the class type in the covariant return type of D::f differs from
13999     //   that of B::f, the class type in the return type of D::f shall be
14000     //   complete at the point of declaration of D::f or shall be the class
14001     //   type D.
14002     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14003       if (!RT->isBeingDefined() &&
14004           RequireCompleteType(New->getLocation(), NewClassTy,
14005                               diag::err_covariant_return_incomplete,
14006                               New->getDeclName()))
14007         return true;
14008     }
14009 
14010     // Check if the new class derives from the old class.
14011     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
14012       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14013           << New->getDeclName() << NewTy << OldTy
14014           << New->getReturnTypeSourceRange();
14015       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14016           << Old->getReturnTypeSourceRange();
14017       return true;
14018     }
14019 
14020     // Check if we the conversion from derived to base is valid.
14021     if (CheckDerivedToBaseConversion(
14022             NewClassTy, OldClassTy,
14023             diag::err_covariant_return_inaccessible_base,
14024             diag::err_covariant_return_ambiguous_derived_to_base_conv,
14025             New->getLocation(), New->getReturnTypeSourceRange(),
14026             New->getDeclName(), nullptr)) {
14027       // FIXME: this note won't trigger for delayed access control
14028       // diagnostics, and it's impossible to get an undelayed error
14029       // here from access control during the original parse because
14030       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
14031       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14032           << Old->getReturnTypeSourceRange();
14033       return true;
14034     }
14035   }
14036 
14037   // The qualifiers of the return types must be the same.
14038   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
14039     Diag(New->getLocation(),
14040          diag::err_covariant_return_type_different_qualifications)
14041         << New->getDeclName() << NewTy << OldTy
14042         << New->getReturnTypeSourceRange();
14043     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14044         << Old->getReturnTypeSourceRange();
14045     return true;
14046   }
14047 
14048 
14049   // The new class type must have the same or less qualifiers as the old type.
14050   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14051     Diag(New->getLocation(),
14052          diag::err_covariant_return_type_class_type_more_qualified)
14053         << New->getDeclName() << NewTy << OldTy
14054         << New->getReturnTypeSourceRange();
14055     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14056         << Old->getReturnTypeSourceRange();
14057     return true;
14058   }
14059 
14060   return false;
14061 }
14062 
14063 /// \brief Mark the given method pure.
14064 ///
14065 /// \param Method the method to be marked pure.
14066 ///
14067 /// \param InitRange the source range that covers the "0" initializer.
14068 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
14069   SourceLocation EndLoc = InitRange.getEnd();
14070   if (EndLoc.isValid())
14071     Method->setRangeEnd(EndLoc);
14072 
14073   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14074     Method->setPure();
14075     return false;
14076   }
14077 
14078   if (!Method->isInvalidDecl())
14079     Diag(Method->getLocation(), diag::err_non_virtual_pure)
14080       << Method->getDeclName() << InitRange;
14081   return true;
14082 }
14083 
14084 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
14085   if (D->getFriendObjectKind())
14086     Diag(D->getLocation(), diag::err_pure_friend);
14087   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14088     CheckPureMethod(M, ZeroLoc);
14089   else
14090     Diag(D->getLocation(), diag::err_illegal_initializer);
14091 }
14092 
14093 /// \brief Determine whether the given declaration is a static data member.
14094 static bool isStaticDataMember(const Decl *D) {
14095   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
14096     return Var->isStaticDataMember();
14097 
14098   return false;
14099 }
14100 
14101 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
14102 /// an initializer for the out-of-line declaration 'Dcl'.  The scope
14103 /// is a fresh scope pushed for just this purpose.
14104 ///
14105 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
14106 /// static data member of class X, names should be looked up in the scope of
14107 /// class X.
14108 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
14109   // If there is no declaration, there was an error parsing it.
14110   if (!D || D->isInvalidDecl())
14111     return;
14112 
14113   // We will always have a nested name specifier here, but this declaration
14114   // might not be out of line if the specifier names the current namespace:
14115   //   extern int n;
14116   //   int ::n = 0;
14117   if (D->isOutOfLine())
14118     EnterDeclaratorContext(S, D->getDeclContext());
14119 
14120   // If we are parsing the initializer for a static data member, push a
14121   // new expression evaluation context that is associated with this static
14122   // data member.
14123   if (isStaticDataMember(D))
14124     PushExpressionEvaluationContext(PotentiallyEvaluated, D);
14125 }
14126 
14127 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
14128 /// initializer for the out-of-line declaration 'D'.
14129 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
14130   // If there is no declaration, there was an error parsing it.
14131   if (!D || D->isInvalidDecl())
14132     return;
14133 
14134   if (isStaticDataMember(D))
14135     PopExpressionEvaluationContext();
14136 
14137   if (D->isOutOfLine())
14138     ExitDeclaratorContext(S);
14139 }
14140 
14141 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
14142 /// C++ if/switch/while/for statement.
14143 /// e.g: "if (int x = f()) {...}"
14144 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
14145   // C++ 6.4p2:
14146   // The declarator shall not specify a function or an array.
14147   // The type-specifier-seq shall not contain typedef and shall not declare a
14148   // new class or enumeration.
14149   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
14150          "Parser allowed 'typedef' as storage class of condition decl.");
14151 
14152   Decl *Dcl = ActOnDeclarator(S, D);
14153   if (!Dcl)
14154     return true;
14155 
14156   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
14157     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
14158       << D.getSourceRange();
14159     return true;
14160   }
14161 
14162   return Dcl;
14163 }
14164 
14165 void Sema::LoadExternalVTableUses() {
14166   if (!ExternalSource)
14167     return;
14168 
14169   SmallVector<ExternalVTableUse, 4> VTables;
14170   ExternalSource->ReadUsedVTables(VTables);
14171   SmallVector<VTableUse, 4> NewUses;
14172   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
14173     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
14174       = VTablesUsed.find(VTables[I].Record);
14175     // Even if a definition wasn't required before, it may be required now.
14176     if (Pos != VTablesUsed.end()) {
14177       if (!Pos->second && VTables[I].DefinitionRequired)
14178         Pos->second = true;
14179       continue;
14180     }
14181 
14182     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
14183     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
14184   }
14185 
14186   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
14187 }
14188 
14189 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
14190                           bool DefinitionRequired) {
14191   // Ignore any vtable uses in unevaluated operands or for classes that do
14192   // not have a vtable.
14193   if (!Class->isDynamicClass() || Class->isDependentContext() ||
14194       CurContext->isDependentContext() || isUnevaluatedContext())
14195     return;
14196 
14197   // Try to insert this class into the map.
14198   LoadExternalVTableUses();
14199   Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
14200   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
14201     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
14202   if (!Pos.second) {
14203     // If we already had an entry, check to see if we are promoting this vtable
14204     // to require a definition. If so, we need to reappend to the VTableUses
14205     // list, since we may have already processed the first entry.
14206     if (DefinitionRequired && !Pos.first->second) {
14207       Pos.first->second = true;
14208     } else {
14209       // Otherwise, we can early exit.
14210       return;
14211     }
14212   } else {
14213     // The Microsoft ABI requires that we perform the destructor body
14214     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
14215     // the deleting destructor is emitted with the vtable, not with the
14216     // destructor definition as in the Itanium ABI.
14217     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14218       CXXDestructorDecl *DD = Class->getDestructor();
14219       if (DD && DD->isVirtual() && !DD->isDeleted()) {
14220         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
14221           // If this is an out-of-line declaration, marking it referenced will
14222           // not do anything. Manually call CheckDestructor to look up operator
14223           // delete().
14224           ContextRAII SavedContext(*this, DD);
14225           CheckDestructor(DD);
14226         } else {
14227           MarkFunctionReferenced(Loc, Class->getDestructor());
14228         }
14229       }
14230     }
14231   }
14232 
14233   // Local classes need to have their virtual members marked
14234   // immediately. For all other classes, we mark their virtual members
14235   // at the end of the translation unit.
14236   if (Class->isLocalClass())
14237     MarkVirtualMembersReferenced(Loc, Class);
14238   else
14239     VTableUses.push_back(std::make_pair(Class, Loc));
14240 }
14241 
14242 bool Sema::DefineUsedVTables() {
14243   LoadExternalVTableUses();
14244   if (VTableUses.empty())
14245     return false;
14246 
14247   // Note: The VTableUses vector could grow as a result of marking
14248   // the members of a class as "used", so we check the size each
14249   // time through the loop and prefer indices (which are stable) to
14250   // iterators (which are not).
14251   bool DefinedAnything = false;
14252   for (unsigned I = 0; I != VTableUses.size(); ++I) {
14253     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
14254     if (!Class)
14255       continue;
14256 
14257     SourceLocation Loc = VTableUses[I].second;
14258 
14259     bool DefineVTable = true;
14260 
14261     // If this class has a key function, but that key function is
14262     // defined in another translation unit, we don't need to emit the
14263     // vtable even though we're using it.
14264     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
14265     if (KeyFunction && !KeyFunction->hasBody()) {
14266       // The key function is in another translation unit.
14267       DefineVTable = false;
14268       TemplateSpecializationKind TSK =
14269           KeyFunction->getTemplateSpecializationKind();
14270       assert(TSK != TSK_ExplicitInstantiationDefinition &&
14271              TSK != TSK_ImplicitInstantiation &&
14272              "Instantiations don't have key functions");
14273       (void)TSK;
14274     } else if (!KeyFunction) {
14275       // If we have a class with no key function that is the subject
14276       // of an explicit instantiation declaration, suppress the
14277       // vtable; it will live with the explicit instantiation
14278       // definition.
14279       bool IsExplicitInstantiationDeclaration
14280         = Class->getTemplateSpecializationKind()
14281                                       == TSK_ExplicitInstantiationDeclaration;
14282       for (auto R : Class->redecls()) {
14283         TemplateSpecializationKind TSK
14284           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
14285         if (TSK == TSK_ExplicitInstantiationDeclaration)
14286           IsExplicitInstantiationDeclaration = true;
14287         else if (TSK == TSK_ExplicitInstantiationDefinition) {
14288           IsExplicitInstantiationDeclaration = false;
14289           break;
14290         }
14291       }
14292 
14293       if (IsExplicitInstantiationDeclaration)
14294         DefineVTable = false;
14295     }
14296 
14297     // The exception specifications for all virtual members may be needed even
14298     // if we are not providing an authoritative form of the vtable in this TU.
14299     // We may choose to emit it available_externally anyway.
14300     if (!DefineVTable) {
14301       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
14302       continue;
14303     }
14304 
14305     // Mark all of the virtual members of this class as referenced, so
14306     // that we can build a vtable. Then, tell the AST consumer that a
14307     // vtable for this class is required.
14308     DefinedAnything = true;
14309     MarkVirtualMembersReferenced(Loc, Class);
14310     CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
14311     if (VTablesUsed[Canonical])
14312       Consumer.HandleVTable(Class);
14313 
14314     // Optionally warn if we're emitting a weak vtable.
14315     if (Class->isExternallyVisible() &&
14316         Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
14317       const FunctionDecl *KeyFunctionDef = nullptr;
14318       if (!KeyFunction ||
14319           (KeyFunction->hasBody(KeyFunctionDef) &&
14320            KeyFunctionDef->isInlined()))
14321         Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
14322              TSK_ExplicitInstantiationDefinition
14323              ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
14324           << Class;
14325     }
14326   }
14327   VTableUses.clear();
14328 
14329   return DefinedAnything;
14330 }
14331 
14332 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
14333                                                  const CXXRecordDecl *RD) {
14334   for (const auto *I : RD->methods())
14335     if (I->isVirtual() && !I->isPure())
14336       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
14337 }
14338 
14339 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
14340                                         const CXXRecordDecl *RD) {
14341   // Mark all functions which will appear in RD's vtable as used.
14342   CXXFinalOverriderMap FinalOverriders;
14343   RD->getFinalOverriders(FinalOverriders);
14344   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
14345                                             E = FinalOverriders.end();
14346        I != E; ++I) {
14347     for (OverridingMethods::const_iterator OI = I->second.begin(),
14348                                            OE = I->second.end();
14349          OI != OE; ++OI) {
14350       assert(OI->second.size() > 0 && "no final overrider");
14351       CXXMethodDecl *Overrider = OI->second.front().Method;
14352 
14353       // C++ [basic.def.odr]p2:
14354       //   [...] A virtual member function is used if it is not pure. [...]
14355       if (!Overrider->isPure())
14356         MarkFunctionReferenced(Loc, Overrider);
14357     }
14358   }
14359 
14360   // Only classes that have virtual bases need a VTT.
14361   if (RD->getNumVBases() == 0)
14362     return;
14363 
14364   for (const auto &I : RD->bases()) {
14365     const CXXRecordDecl *Base =
14366         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
14367     if (Base->getNumVBases() == 0)
14368       continue;
14369     MarkVirtualMembersReferenced(Loc, Base);
14370   }
14371 }
14372 
14373 /// SetIvarInitializers - This routine builds initialization ASTs for the
14374 /// Objective-C implementation whose ivars need be initialized.
14375 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
14376   if (!getLangOpts().CPlusPlus)
14377     return;
14378   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
14379     SmallVector<ObjCIvarDecl*, 8> ivars;
14380     CollectIvarsToConstructOrDestruct(OID, ivars);
14381     if (ivars.empty())
14382       return;
14383     SmallVector<CXXCtorInitializer*, 32> AllToInit;
14384     for (unsigned i = 0; i < ivars.size(); i++) {
14385       FieldDecl *Field = ivars[i];
14386       if (Field->isInvalidDecl())
14387         continue;
14388 
14389       CXXCtorInitializer *Member;
14390       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
14391       InitializationKind InitKind =
14392         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
14393 
14394       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
14395       ExprResult MemberInit =
14396         InitSeq.Perform(*this, InitEntity, InitKind, None);
14397       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
14398       // Note, MemberInit could actually come back empty if no initialization
14399       // is required (e.g., because it would call a trivial default constructor)
14400       if (!MemberInit.get() || MemberInit.isInvalid())
14401         continue;
14402 
14403       Member =
14404         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
14405                                          SourceLocation(),
14406                                          MemberInit.getAs<Expr>(),
14407                                          SourceLocation());
14408       AllToInit.push_back(Member);
14409 
14410       // Be sure that the destructor is accessible and is marked as referenced.
14411       if (const RecordType *RecordTy =
14412               Context.getBaseElementType(Field->getType())
14413                   ->getAs<RecordType>()) {
14414         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
14415         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
14416           MarkFunctionReferenced(Field->getLocation(), Destructor);
14417           CheckDestructorAccess(Field->getLocation(), Destructor,
14418                             PDiag(diag::err_access_dtor_ivar)
14419                               << Context.getBaseElementType(Field->getType()));
14420         }
14421       }
14422     }
14423     ObjCImplementation->setIvarInitializers(Context,
14424                                             AllToInit.data(), AllToInit.size());
14425   }
14426 }
14427 
14428 static
14429 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
14430                            llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
14431                            llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
14432                            llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
14433                            Sema &S) {
14434   if (Ctor->isInvalidDecl())
14435     return;
14436 
14437   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
14438 
14439   // Target may not be determinable yet, for instance if this is a dependent
14440   // call in an uninstantiated template.
14441   if (Target) {
14442     const FunctionDecl *FNTarget = nullptr;
14443     (void)Target->hasBody(FNTarget);
14444     Target = const_cast<CXXConstructorDecl*>(
14445       cast_or_null<CXXConstructorDecl>(FNTarget));
14446   }
14447 
14448   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
14449                      // Avoid dereferencing a null pointer here.
14450                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
14451 
14452   if (!Current.insert(Canonical).second)
14453     return;
14454 
14455   // We know that beyond here, we aren't chaining into a cycle.
14456   if (!Target || !Target->isDelegatingConstructor() ||
14457       Target->isInvalidDecl() || Valid.count(TCanonical)) {
14458     Valid.insert(Current.begin(), Current.end());
14459     Current.clear();
14460   // We've hit a cycle.
14461   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
14462              Current.count(TCanonical)) {
14463     // If we haven't diagnosed this cycle yet, do so now.
14464     if (!Invalid.count(TCanonical)) {
14465       S.Diag((*Ctor->init_begin())->getSourceLocation(),
14466              diag::warn_delegating_ctor_cycle)
14467         << Ctor;
14468 
14469       // Don't add a note for a function delegating directly to itself.
14470       if (TCanonical != Canonical)
14471         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
14472 
14473       CXXConstructorDecl *C = Target;
14474       while (C->getCanonicalDecl() != Canonical) {
14475         const FunctionDecl *FNTarget = nullptr;
14476         (void)C->getTargetConstructor()->hasBody(FNTarget);
14477         assert(FNTarget && "Ctor cycle through bodiless function");
14478 
14479         C = const_cast<CXXConstructorDecl*>(
14480           cast<CXXConstructorDecl>(FNTarget));
14481         S.Diag(C->getLocation(), diag::note_which_delegates_to);
14482       }
14483     }
14484 
14485     Invalid.insert(Current.begin(), Current.end());
14486     Current.clear();
14487   } else {
14488     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
14489   }
14490 }
14491 
14492 
14493 void Sema::CheckDelegatingCtorCycles() {
14494   llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
14495 
14496   for (DelegatingCtorDeclsType::iterator
14497          I = DelegatingCtorDecls.begin(ExternalSource),
14498          E = DelegatingCtorDecls.end();
14499        I != E; ++I)
14500     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
14501 
14502   for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
14503                                                          CE = Invalid.end();
14504        CI != CE; ++CI)
14505     (*CI)->setInvalidDecl();
14506 }
14507 
14508 namespace {
14509   /// \brief AST visitor that finds references to the 'this' expression.
14510   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
14511     Sema &S;
14512 
14513   public:
14514     explicit FindCXXThisExpr(Sema &S) : S(S) { }
14515 
14516     bool VisitCXXThisExpr(CXXThisExpr *E) {
14517       S.Diag(E->getLocation(), diag::err_this_static_member_func)
14518         << E->isImplicit();
14519       return false;
14520     }
14521   };
14522 }
14523 
14524 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
14525   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14526   if (!TSInfo)
14527     return false;
14528 
14529   TypeLoc TL = TSInfo->getTypeLoc();
14530   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
14531   if (!ProtoTL)
14532     return false;
14533 
14534   // C++11 [expr.prim.general]p3:
14535   //   [The expression this] shall not appear before the optional
14536   //   cv-qualifier-seq and it shall not appear within the declaration of a
14537   //   static member function (although its type and value category are defined
14538   //   within a static member function as they are within a non-static member
14539   //   function). [ Note: this is because declaration matching does not occur
14540   //  until the complete declarator is known. - end note ]
14541   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
14542   FindCXXThisExpr Finder(*this);
14543 
14544   // If the return type came after the cv-qualifier-seq, check it now.
14545   if (Proto->hasTrailingReturn() &&
14546       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
14547     return true;
14548 
14549   // Check the exception specification.
14550   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
14551     return true;
14552 
14553   return checkThisInStaticMemberFunctionAttributes(Method);
14554 }
14555 
14556 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
14557   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14558   if (!TSInfo)
14559     return false;
14560 
14561   TypeLoc TL = TSInfo->getTypeLoc();
14562   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
14563   if (!ProtoTL)
14564     return false;
14565 
14566   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
14567   FindCXXThisExpr Finder(*this);
14568 
14569   switch (Proto->getExceptionSpecType()) {
14570   case EST_Unparsed:
14571   case EST_Uninstantiated:
14572   case EST_Unevaluated:
14573   case EST_BasicNoexcept:
14574   case EST_DynamicNone:
14575   case EST_MSAny:
14576   case EST_None:
14577     break;
14578 
14579   case EST_ComputedNoexcept:
14580     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
14581       return true;
14582 
14583   case EST_Dynamic:
14584     for (const auto &E : Proto->exceptions()) {
14585       if (!Finder.TraverseType(E))
14586         return true;
14587     }
14588     break;
14589   }
14590 
14591   return false;
14592 }
14593 
14594 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
14595   FindCXXThisExpr Finder(*this);
14596 
14597   // Check attributes.
14598   for (const auto *A : Method->attrs()) {
14599     // FIXME: This should be emitted by tblgen.
14600     Expr *Arg = nullptr;
14601     ArrayRef<Expr *> Args;
14602     if (const auto *G = dyn_cast<GuardedByAttr>(A))
14603       Arg = G->getArg();
14604     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
14605       Arg = G->getArg();
14606     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
14607       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
14608     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
14609       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
14610     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
14611       Arg = ETLF->getSuccessValue();
14612       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
14613     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
14614       Arg = STLF->getSuccessValue();
14615       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
14616     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
14617       Arg = LR->getArg();
14618     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
14619       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
14620     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
14621       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
14622     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
14623       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
14624     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
14625       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
14626     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
14627       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
14628 
14629     if (Arg && !Finder.TraverseStmt(Arg))
14630       return true;
14631 
14632     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
14633       if (!Finder.TraverseStmt(Args[I]))
14634         return true;
14635     }
14636   }
14637 
14638   return false;
14639 }
14640 
14641 void Sema::checkExceptionSpecification(
14642     bool IsTopLevel, ExceptionSpecificationType EST,
14643     ArrayRef<ParsedType> DynamicExceptions,
14644     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
14645     SmallVectorImpl<QualType> &Exceptions,
14646     FunctionProtoType::ExceptionSpecInfo &ESI) {
14647   Exceptions.clear();
14648   ESI.Type = EST;
14649   if (EST == EST_Dynamic) {
14650     Exceptions.reserve(DynamicExceptions.size());
14651     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
14652       // FIXME: Preserve type source info.
14653       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
14654 
14655       if (IsTopLevel) {
14656         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
14657         collectUnexpandedParameterPacks(ET, Unexpanded);
14658         if (!Unexpanded.empty()) {
14659           DiagnoseUnexpandedParameterPacks(
14660               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
14661               Unexpanded);
14662           continue;
14663         }
14664       }
14665 
14666       // Check that the type is valid for an exception spec, and
14667       // drop it if not.
14668       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
14669         Exceptions.push_back(ET);
14670     }
14671     ESI.Exceptions = Exceptions;
14672     return;
14673   }
14674 
14675   if (EST == EST_ComputedNoexcept) {
14676     // If an error occurred, there's no expression here.
14677     if (NoexceptExpr) {
14678       assert((NoexceptExpr->isTypeDependent() ||
14679               NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
14680               Context.BoolTy) &&
14681              "Parser should have made sure that the expression is boolean");
14682       if (IsTopLevel && NoexceptExpr &&
14683           DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
14684         ESI.Type = EST_BasicNoexcept;
14685         return;
14686       }
14687 
14688       if (!NoexceptExpr->isValueDependent())
14689         NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
14690                          diag::err_noexcept_needs_constant_expression,
14691                          /*AllowFold*/ false).get();
14692       ESI.NoexceptExpr = NoexceptExpr;
14693     }
14694     return;
14695   }
14696 }
14697 
14698 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
14699              ExceptionSpecificationType EST,
14700              SourceRange SpecificationRange,
14701              ArrayRef<ParsedType> DynamicExceptions,
14702              ArrayRef<SourceRange> DynamicExceptionRanges,
14703              Expr *NoexceptExpr) {
14704   if (!MethodD)
14705     return;
14706 
14707   // Dig out the method we're referring to.
14708   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
14709     MethodD = FunTmpl->getTemplatedDecl();
14710 
14711   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
14712   if (!Method)
14713     return;
14714 
14715   // Check the exception specification.
14716   llvm::SmallVector<QualType, 4> Exceptions;
14717   FunctionProtoType::ExceptionSpecInfo ESI;
14718   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
14719                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
14720                               ESI);
14721 
14722   // Update the exception specification on the function type.
14723   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
14724 
14725   if (Method->isStatic())
14726     checkThisInStaticMemberFunctionExceptionSpec(Method);
14727 
14728   if (Method->isVirtual()) {
14729     // Check overrides, which we previously had to delay.
14730     for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
14731                                      OEnd = Method->end_overridden_methods();
14732          O != OEnd; ++O)
14733       CheckOverridingFunctionExceptionSpec(Method, *O);
14734   }
14735 }
14736 
14737 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
14738 ///
14739 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
14740                                        SourceLocation DeclStart,
14741                                        Declarator &D, Expr *BitWidth,
14742                                        InClassInitStyle InitStyle,
14743                                        AccessSpecifier AS,
14744                                        AttributeList *MSPropertyAttr) {
14745   IdentifierInfo *II = D.getIdentifier();
14746   if (!II) {
14747     Diag(DeclStart, diag::err_anonymous_property);
14748     return nullptr;
14749   }
14750   SourceLocation Loc = D.getIdentifierLoc();
14751 
14752   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14753   QualType T = TInfo->getType();
14754   if (getLangOpts().CPlusPlus) {
14755     CheckExtraCXXDefaultArguments(D);
14756 
14757     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14758                                         UPPC_DataMemberType)) {
14759       D.setInvalidType();
14760       T = Context.IntTy;
14761       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
14762     }
14763   }
14764 
14765   DiagnoseFunctionSpecifiers(D.getDeclSpec());
14766 
14767   if (D.getDeclSpec().isInlineSpecified())
14768     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14769         << getLangOpts().CPlusPlus1z;
14770   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
14771     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
14772          diag::err_invalid_thread)
14773       << DeclSpec::getSpecifierName(TSCS);
14774 
14775   // Check to see if this name was declared as a member previously
14776   NamedDecl *PrevDecl = nullptr;
14777   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
14778   LookupName(Previous, S);
14779   switch (Previous.getResultKind()) {
14780   case LookupResult::Found:
14781   case LookupResult::FoundUnresolvedValue:
14782     PrevDecl = Previous.getAsSingle<NamedDecl>();
14783     break;
14784 
14785   case LookupResult::FoundOverloaded:
14786     PrevDecl = Previous.getRepresentativeDecl();
14787     break;
14788 
14789   case LookupResult::NotFound:
14790   case LookupResult::NotFoundInCurrentInstantiation:
14791   case LookupResult::Ambiguous:
14792     break;
14793   }
14794 
14795   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14796     // Maybe we will complain about the shadowed template parameter.
14797     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14798     // Just pretend that we didn't see the previous declaration.
14799     PrevDecl = nullptr;
14800   }
14801 
14802   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
14803     PrevDecl = nullptr;
14804 
14805   SourceLocation TSSL = D.getLocStart();
14806   const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
14807   MSPropertyDecl *NewPD = MSPropertyDecl::Create(
14808       Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
14809   ProcessDeclAttributes(TUScope, NewPD, D);
14810   NewPD->setAccess(AS);
14811 
14812   if (NewPD->isInvalidDecl())
14813     Record->setInvalidDecl();
14814 
14815   if (D.getDeclSpec().isModulePrivateSpecified())
14816     NewPD->setModulePrivate();
14817 
14818   if (NewPD->isInvalidDecl() && PrevDecl) {
14819     // Don't introduce NewFD into scope; there's already something
14820     // with the same name in the same scope.
14821   } else if (II) {
14822     PushOnScopeChains(NewPD, S);
14823   } else
14824     Record->addDecl(NewPD);
14825 
14826   return NewPD;
14827 }
14828