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/Sema/SemaInternal.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/EvaluatedExprVisitor.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/RecordLayout.h"
24 #include "clang/AST/RecursiveASTVisitor.h"
25 #include "clang/AST/StmtVisitor.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "clang/AST/TypeOrdering.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/LiteralSupport.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "clang/Sema/CXXFieldCollector.h"
33 #include "clang/Sema/DeclSpec.h"
34 #include "clang/Sema/Initialization.h"
35 #include "clang/Sema/Lookup.h"
36 #include "clang/Sema/ParsedTemplate.h"
37 #include "clang/Sema/Scope.h"
38 #include "clang/Sema/ScopeInfo.h"
39 #include "clang/Sema/Template.h"
40 #include "llvm/ADT/STLExtras.h"
41 #include "llvm/ADT/SmallString.h"
42 #include <map>
43 #include <set>
44 
45 using namespace clang;
46 
47 //===----------------------------------------------------------------------===//
48 // CheckDefaultArgumentVisitor
49 //===----------------------------------------------------------------------===//
50 
51 namespace {
52   /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
53   /// the default argument of a parameter to determine whether it
54   /// contains any ill-formed subexpressions. For example, this will
55   /// diagnose the use of local variables or parameters within the
56   /// default argument expression.
57   class CheckDefaultArgumentVisitor
58     : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
59     Expr *DefaultArg;
60     Sema *S;
61 
62   public:
63     CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
64       : DefaultArg(defarg), S(s) {}
65 
66     bool VisitExpr(Expr *Node);
67     bool VisitDeclRefExpr(DeclRefExpr *DRE);
68     bool VisitCXXThisExpr(CXXThisExpr *ThisE);
69     bool VisitLambdaExpr(LambdaExpr *Lambda);
70     bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
71   };
72 
73   /// VisitExpr - Visit all of the children of this expression.
74   bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
75     bool IsInvalid = false;
76     for (Stmt *SubStmt : Node->children())
77       IsInvalid |= Visit(SubStmt);
78     return IsInvalid;
79   }
80 
81   /// VisitDeclRefExpr - Visit a reference to a declaration, to
82   /// determine whether this declaration can be used in the default
83   /// argument expression.
84   bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
85     NamedDecl *Decl = DRE->getDecl();
86     if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
87       // C++ [dcl.fct.default]p9
88       //   Default arguments are evaluated each time the function is
89       //   called. The order of evaluation of function arguments is
90       //   unspecified. Consequently, parameters of a function shall not
91       //   be used in default argument expressions, even if they are not
92       //   evaluated. Parameters of a function declared before a default
93       //   argument expression are in scope and can hide namespace and
94       //   class member names.
95       return S->Diag(DRE->getLocStart(),
96                      diag::err_param_default_argument_references_param)
97          << Param->getDeclName() << DefaultArg->getSourceRange();
98     } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
99       // C++ [dcl.fct.default]p7
100       //   Local variables shall not be used in default argument
101       //   expressions.
102       if (VDecl->isLocalVarDecl())
103         return S->Diag(DRE->getLocStart(),
104                        diag::err_param_default_argument_references_local)
105           << VDecl->getDeclName() << DefaultArg->getSourceRange();
106     }
107 
108     return false;
109   }
110 
111   /// VisitCXXThisExpr - Visit a C++ "this" expression.
112   bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
113     // C++ [dcl.fct.default]p8:
114     //   The keyword this shall not be used in a default argument of a
115     //   member function.
116     return S->Diag(ThisE->getLocStart(),
117                    diag::err_param_default_argument_references_this)
118                << ThisE->getSourceRange();
119   }
120 
121   bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
122     bool Invalid = false;
123     for (PseudoObjectExpr::semantics_iterator
124            i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
125       Expr *E = *i;
126 
127       // Look through bindings.
128       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
129         E = OVE->getSourceExpr();
130         assert(E && "pseudo-object binding without source expression?");
131       }
132 
133       Invalid |= Visit(E);
134     }
135     return Invalid;
136   }
137 
138   bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
139     // C++11 [expr.lambda.prim]p13:
140     //   A lambda-expression appearing in a default argument shall not
141     //   implicitly or explicitly capture any entity.
142     if (Lambda->capture_begin() == Lambda->capture_end())
143       return false;
144 
145     return S->Diag(Lambda->getLocStart(),
146                    diag::err_lambda_capture_default_arg);
147   }
148 }
149 
150 void
151 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
152                                                  const CXXMethodDecl *Method) {
153   // If we have an MSAny spec already, don't bother.
154   if (!Method || ComputedEST == EST_MSAny)
155     return;
156 
157   const FunctionProtoType *Proto
158     = Method->getType()->getAs<FunctionProtoType>();
159   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
160   if (!Proto)
161     return;
162 
163   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
164 
165   // If we have a throw-all spec at this point, ignore the function.
166   if (ComputedEST == EST_None)
167     return;
168 
169   switch(EST) {
170   // If this function can throw any exceptions, make a note of that.
171   case EST_MSAny:
172   case EST_None:
173     ClearExceptions();
174     ComputedEST = EST;
175     return;
176   // FIXME: If the call to this decl is using any of its default arguments, we
177   // need to search them for potentially-throwing calls.
178   // If this function has a basic noexcept, it doesn't affect the outcome.
179   case EST_BasicNoexcept:
180     return;
181   // If we're still at noexcept(true) and there's a nothrow() callee,
182   // change to that specification.
183   case EST_DynamicNone:
184     if (ComputedEST == EST_BasicNoexcept)
185       ComputedEST = EST_DynamicNone;
186     return;
187   // Check out noexcept specs.
188   case EST_ComputedNoexcept:
189   {
190     FunctionProtoType::NoexceptResult NR =
191         Proto->getNoexceptSpec(Self->Context);
192     assert(NR != FunctionProtoType::NR_NoNoexcept &&
193            "Must have noexcept result for EST_ComputedNoexcept.");
194     assert(NR != FunctionProtoType::NR_Dependent &&
195            "Should not generate implicit declarations for dependent cases, "
196            "and don't know how to handle them anyway.");
197     // noexcept(false) -> no spec on the new function
198     if (NR == FunctionProtoType::NR_Throw) {
199       ClearExceptions();
200       ComputedEST = EST_None;
201     }
202     // noexcept(true) won't change anything either.
203     return;
204   }
205   default:
206     break;
207   }
208   assert(EST == EST_Dynamic && "EST case not considered earlier.");
209   assert(ComputedEST != EST_None &&
210          "Shouldn't collect exceptions when throw-all is guaranteed.");
211   ComputedEST = EST_Dynamic;
212   // Record the exceptions in this function's exception specification.
213   for (const auto &E : Proto->exceptions())
214     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
215       Exceptions.push_back(E);
216 }
217 
218 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
219   if (!E || ComputedEST == EST_MSAny)
220     return;
221 
222   // FIXME:
223   //
224   // C++0x [except.spec]p14:
225   //   [An] implicit exception-specification specifies the type-id T if and
226   // only if T is allowed by the exception-specification of a function directly
227   // invoked by f's implicit definition; f shall allow all exceptions if any
228   // function it directly invokes allows all exceptions, and f shall allow no
229   // exceptions if every function it directly invokes allows no exceptions.
230   //
231   // Note in particular that if an implicit exception-specification is generated
232   // for a function containing a throw-expression, that specification can still
233   // be noexcept(true).
234   //
235   // Note also that 'directly invoked' is not defined in the standard, and there
236   // is no indication that we should only consider potentially-evaluated calls.
237   //
238   // Ultimately we should implement the intent of the standard: the exception
239   // specification should be the set of exceptions which can be thrown by the
240   // implicit definition. For now, we assume that any non-nothrow expression can
241   // throw any exception.
242 
243   if (Self->canThrow(E))
244     ComputedEST = EST_None;
245 }
246 
247 bool
248 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
249                               SourceLocation EqualLoc) {
250   if (RequireCompleteType(Param->getLocation(), Param->getType(),
251                           diag::err_typecheck_decl_incomplete_type)) {
252     Param->setInvalidDecl();
253     return true;
254   }
255 
256   // C++ [dcl.fct.default]p5
257   //   A default argument expression is implicitly converted (clause
258   //   4) to the parameter type. The default argument expression has
259   //   the same semantic constraints as the initializer expression in
260   //   a declaration of a variable of the parameter type, using the
261   //   copy-initialization semantics (8.5).
262   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
263                                                                     Param);
264   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
265                                                            EqualLoc);
266   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
267   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
268   if (Result.isInvalid())
269     return true;
270   Arg = Result.getAs<Expr>();
271 
272   CheckCompletedExpr(Arg, EqualLoc);
273   Arg = MaybeCreateExprWithCleanups(Arg);
274 
275   // Okay: add the default argument to the parameter
276   Param->setDefaultArg(Arg);
277 
278   // We have already instantiated this parameter; provide each of the
279   // instantiations with the uninstantiated default argument.
280   UnparsedDefaultArgInstantiationsMap::iterator InstPos
281     = UnparsedDefaultArgInstantiations.find(Param);
282   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
283     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
284       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
285 
286     // We're done tracking this parameter's instantiations.
287     UnparsedDefaultArgInstantiations.erase(InstPos);
288   }
289 
290   return false;
291 }
292 
293 /// ActOnParamDefaultArgument - Check whether the default argument
294 /// provided for a function parameter is well-formed. If so, attach it
295 /// to the parameter declaration.
296 void
297 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
298                                 Expr *DefaultArg) {
299   if (!param || !DefaultArg)
300     return;
301 
302   ParmVarDecl *Param = cast<ParmVarDecl>(param);
303   UnparsedDefaultArgLocs.erase(Param);
304 
305   // Default arguments are only permitted in C++
306   if (!getLangOpts().CPlusPlus) {
307     Diag(EqualLoc, diag::err_param_default_argument)
308       << DefaultArg->getSourceRange();
309     Param->setInvalidDecl();
310     return;
311   }
312 
313   // Check for unexpanded parameter packs.
314   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
315     Param->setInvalidDecl();
316     return;
317   }
318 
319   // C++11 [dcl.fct.default]p3
320   //   A default argument expression [...] shall not be specified for a
321   //   parameter pack.
322   if (Param->isParameterPack()) {
323     Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
324         << DefaultArg->getSourceRange();
325     return;
326   }
327 
328   // Check that the default argument is well-formed
329   CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
330   if (DefaultArgChecker.Visit(DefaultArg)) {
331     Param->setInvalidDecl();
332     return;
333   }
334 
335   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
336 }
337 
338 /// ActOnParamUnparsedDefaultArgument - We've seen a default
339 /// argument for a function parameter, but we can't parse it yet
340 /// because we're inside a class definition. Note that this default
341 /// argument will be parsed later.
342 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
343                                              SourceLocation EqualLoc,
344                                              SourceLocation ArgLoc) {
345   if (!param)
346     return;
347 
348   ParmVarDecl *Param = cast<ParmVarDecl>(param);
349   Param->setUnparsedDefaultArg();
350   UnparsedDefaultArgLocs[Param] = ArgLoc;
351 }
352 
353 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
354 /// the default argument for the parameter param failed.
355 void Sema::ActOnParamDefaultArgumentError(Decl *param,
356                                           SourceLocation EqualLoc) {
357   if (!param)
358     return;
359 
360   ParmVarDecl *Param = cast<ParmVarDecl>(param);
361   Param->setInvalidDecl();
362   UnparsedDefaultArgLocs.erase(Param);
363   Param->setDefaultArg(new(Context)
364                        OpaqueValueExpr(EqualLoc,
365                                        Param->getType().getNonReferenceType(),
366                                        VK_RValue));
367 }
368 
369 /// CheckExtraCXXDefaultArguments - Check for any extra default
370 /// arguments in the declarator, which is not a function declaration
371 /// or definition and therefore is not permitted to have default
372 /// arguments. This routine should be invoked for every declarator
373 /// that is not a function declaration or definition.
374 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
375   // C++ [dcl.fct.default]p3
376   //   A default argument expression shall be specified only in the
377   //   parameter-declaration-clause of a function declaration or in a
378   //   template-parameter (14.1). It shall not be specified for a
379   //   parameter pack. If it is specified in a
380   //   parameter-declaration-clause, it shall not occur within a
381   //   declarator or abstract-declarator of a parameter-declaration.
382   bool MightBeFunction = D.isFunctionDeclarationContext();
383   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
384     DeclaratorChunk &chunk = D.getTypeObject(i);
385     if (chunk.Kind == DeclaratorChunk::Function) {
386       if (MightBeFunction) {
387         // This is a function declaration. It can have default arguments, but
388         // keep looking in case its return type is a function type with default
389         // arguments.
390         MightBeFunction = false;
391         continue;
392       }
393       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
394            ++argIdx) {
395         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
396         if (Param->hasUnparsedDefaultArg()) {
397           CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
398           SourceRange SR;
399           if (Toks->size() > 1)
400             SR = SourceRange((*Toks)[1].getLocation(),
401                              Toks->back().getLocation());
402           else
403             SR = UnparsedDefaultArgLocs[Param];
404           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
405             << SR;
406           delete Toks;
407           chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
408         } else if (Param->getDefaultArg()) {
409           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
410             << Param->getDefaultArg()->getSourceRange();
411           Param->setDefaultArg(nullptr);
412         }
413       }
414     } else if (chunk.Kind != DeclaratorChunk::Paren) {
415       MightBeFunction = false;
416     }
417   }
418 }
419 
420 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
421   for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
422     const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
423     if (!PVD->hasDefaultArg())
424       return false;
425     if (!PVD->hasInheritedDefaultArg())
426       return true;
427   }
428   return false;
429 }
430 
431 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
432 /// function, once we already know that they have the same
433 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
434 /// error, false otherwise.
435 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
436                                 Scope *S) {
437   bool Invalid = false;
438 
439   // The declaration context corresponding to the scope is the semantic
440   // parent, unless this is a local function declaration, in which case
441   // it is that surrounding function.
442   DeclContext *ScopeDC = New->isLocalExternDecl()
443                              ? New->getLexicalDeclContext()
444                              : New->getDeclContext();
445 
446   // Find the previous declaration for the purpose of default arguments.
447   FunctionDecl *PrevForDefaultArgs = Old;
448   for (/**/; PrevForDefaultArgs;
449        // Don't bother looking back past the latest decl if this is a local
450        // extern declaration; nothing else could work.
451        PrevForDefaultArgs = New->isLocalExternDecl()
452                                 ? nullptr
453                                 : PrevForDefaultArgs->getPreviousDecl()) {
454     // Ignore hidden declarations.
455     if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
456       continue;
457 
458     if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
459         !New->isCXXClassMember()) {
460       // Ignore default arguments of old decl if they are not in
461       // the same scope and this is not an out-of-line definition of
462       // a member function.
463       continue;
464     }
465 
466     if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
467       // If only one of these is a local function declaration, then they are
468       // declared in different scopes, even though isDeclInScope may think
469       // they're in the same scope. (If both are local, the scope check is
470       // sufficent, and if neither is local, then they are in the same scope.)
471       continue;
472     }
473 
474     // We found our guy.
475     break;
476   }
477 
478   // C++ [dcl.fct.default]p4:
479   //   For non-template functions, default arguments can be added in
480   //   later declarations of a function in the same
481   //   scope. Declarations in different scopes have completely
482   //   distinct sets of default arguments. That is, declarations in
483   //   inner scopes do not acquire default arguments from
484   //   declarations in outer scopes, and vice versa. In a given
485   //   function declaration, all parameters subsequent to a
486   //   parameter with a default argument shall have default
487   //   arguments supplied in this or previous declarations. A
488   //   default argument shall not be redefined by a later
489   //   declaration (not even to the same value).
490   //
491   // C++ [dcl.fct.default]p6:
492   //   Except for member functions of class templates, the default arguments
493   //   in a member function definition that appears outside of the class
494   //   definition are added to the set of default arguments provided by the
495   //   member function declaration in the class definition.
496   for (unsigned p = 0, NumParams = PrevForDefaultArgs
497                                        ? PrevForDefaultArgs->getNumParams()
498                                        : 0;
499        p < NumParams; ++p) {
500     ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
501     ParmVarDecl *NewParam = New->getParamDecl(p);
502 
503     bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
504     bool NewParamHasDfl = NewParam->hasDefaultArg();
505 
506     if (OldParamHasDfl && NewParamHasDfl) {
507       unsigned DiagDefaultParamID =
508         diag::err_param_default_argument_redefinition;
509 
510       // MSVC accepts that default parameters be redefined for member functions
511       // of template class. The new default parameter's value is ignored.
512       Invalid = true;
513       if (getLangOpts().MicrosoftExt) {
514         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
515         if (MD && MD->getParent()->getDescribedClassTemplate()) {
516           // Merge the old default argument into the new parameter.
517           NewParam->setHasInheritedDefaultArg();
518           if (OldParam->hasUninstantiatedDefaultArg())
519             NewParam->setUninstantiatedDefaultArg(
520                                       OldParam->getUninstantiatedDefaultArg());
521           else
522             NewParam->setDefaultArg(OldParam->getInit());
523           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
524           Invalid = false;
525         }
526       }
527 
528       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
529       // hint here. Alternatively, we could walk the type-source information
530       // for NewParam to find the last source location in the type... but it
531       // isn't worth the effort right now. This is the kind of test case that
532       // is hard to get right:
533       //   int f(int);
534       //   void g(int (*fp)(int) = f);
535       //   void g(int (*fp)(int) = &f);
536       Diag(NewParam->getLocation(), DiagDefaultParamID)
537         << NewParam->getDefaultArgRange();
538 
539       // Look for the function declaration where the default argument was
540       // actually written, which may be a declaration prior to Old.
541       for (auto Older = PrevForDefaultArgs;
542            OldParam->hasInheritedDefaultArg(); /**/) {
543         Older = Older->getPreviousDecl();
544         OldParam = Older->getParamDecl(p);
545       }
546 
547       Diag(OldParam->getLocation(), diag::note_previous_definition)
548         << OldParam->getDefaultArgRange();
549     } else if (OldParamHasDfl) {
550       // Merge the old default argument into the new parameter.
551       // It's important to use getInit() here;  getDefaultArg()
552       // strips off any top-level ExprWithCleanups.
553       NewParam->setHasInheritedDefaultArg();
554       if (OldParam->hasUnparsedDefaultArg())
555         NewParam->setUnparsedDefaultArg();
556       else if (OldParam->hasUninstantiatedDefaultArg())
557         NewParam->setUninstantiatedDefaultArg(
558                                       OldParam->getUninstantiatedDefaultArg());
559       else
560         NewParam->setDefaultArg(OldParam->getInit());
561     } else if (NewParamHasDfl) {
562       if (New->getDescribedFunctionTemplate()) {
563         // Paragraph 4, quoted above, only applies to non-template functions.
564         Diag(NewParam->getLocation(),
565              diag::err_param_default_argument_template_redecl)
566           << NewParam->getDefaultArgRange();
567         Diag(PrevForDefaultArgs->getLocation(),
568              diag::note_template_prev_declaration)
569             << false;
570       } else if (New->getTemplateSpecializationKind()
571                    != TSK_ImplicitInstantiation &&
572                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
573         // C++ [temp.expr.spec]p21:
574         //   Default function arguments shall not be specified in a declaration
575         //   or a definition for one of the following explicit specializations:
576         //     - the explicit specialization of a function template;
577         //     - the explicit specialization of a member function template;
578         //     - the explicit specialization of a member function of a class
579         //       template where the class template specialization to which the
580         //       member function specialization belongs is implicitly
581         //       instantiated.
582         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
583           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
584           << New->getDeclName()
585           << NewParam->getDefaultArgRange();
586       } else if (New->getDeclContext()->isDependentContext()) {
587         // C++ [dcl.fct.default]p6 (DR217):
588         //   Default arguments for a member function of a class template shall
589         //   be specified on the initial declaration of the member function
590         //   within the class template.
591         //
592         // Reading the tea leaves a bit in DR217 and its reference to DR205
593         // leads me to the conclusion that one cannot add default function
594         // arguments for an out-of-line definition of a member function of a
595         // dependent type.
596         int WhichKind = 2;
597         if (CXXRecordDecl *Record
598               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
599           if (Record->getDescribedClassTemplate())
600             WhichKind = 0;
601           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
602             WhichKind = 1;
603           else
604             WhichKind = 2;
605         }
606 
607         Diag(NewParam->getLocation(),
608              diag::err_param_default_argument_member_template_redecl)
609           << WhichKind
610           << NewParam->getDefaultArgRange();
611       }
612     }
613   }
614 
615   // DR1344: If a default argument is added outside a class definition and that
616   // default argument makes the function a special member function, the program
617   // is ill-formed. This can only happen for constructors.
618   if (isa<CXXConstructorDecl>(New) &&
619       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
620     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
621                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
622     if (NewSM != OldSM) {
623       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
624       assert(NewParam->hasDefaultArg());
625       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
626         << NewParam->getDefaultArgRange() << NewSM;
627       Diag(Old->getLocation(), diag::note_previous_declaration);
628     }
629   }
630 
631   const FunctionDecl *Def;
632   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
633   // template has a constexpr specifier then all its declarations shall
634   // contain the constexpr specifier.
635   if (New->isConstexpr() != Old->isConstexpr()) {
636     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
637       << New << New->isConstexpr();
638     Diag(Old->getLocation(), diag::note_previous_declaration);
639     Invalid = true;
640   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
641              Old->isDefined(Def)) {
642     // C++11 [dcl.fcn.spec]p4:
643     //   If the definition of a function appears in a translation unit before its
644     //   first declaration as inline, the program is ill-formed.
645     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
646     Diag(Def->getLocation(), diag::note_previous_definition);
647     Invalid = true;
648   }
649 
650   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
651   // argument expression, that declaration shall be a definition and shall be
652   // the only declaration of the function or function template in the
653   // translation unit.
654   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
655       functionDeclHasDefaultArgument(Old)) {
656     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
657     Diag(Old->getLocation(), diag::note_previous_declaration);
658     Invalid = true;
659   }
660 
661   if (CheckEquivalentExceptionSpec(Old, New))
662     Invalid = true;
663 
664   return Invalid;
665 }
666 
667 /// \brief Merge the exception specifications of two variable declarations.
668 ///
669 /// This is called when there's a redeclaration of a VarDecl. The function
670 /// checks if the redeclaration might have an exception specification and
671 /// validates compatibility and merges the specs if necessary.
672 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
673   // Shortcut if exceptions are disabled.
674   if (!getLangOpts().CXXExceptions)
675     return;
676 
677   assert(Context.hasSameType(New->getType(), Old->getType()) &&
678          "Should only be called if types are otherwise the same.");
679 
680   QualType NewType = New->getType();
681   QualType OldType = Old->getType();
682 
683   // We're only interested in pointers and references to functions, as well
684   // as pointers to member functions.
685   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
686     NewType = R->getPointeeType();
687     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
688   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
689     NewType = P->getPointeeType();
690     OldType = OldType->getAs<PointerType>()->getPointeeType();
691   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
692     NewType = M->getPointeeType();
693     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
694   }
695 
696   if (!NewType->isFunctionProtoType())
697     return;
698 
699   // There's lots of special cases for functions. For function pointers, system
700   // libraries are hopefully not as broken so that we don't need these
701   // workarounds.
702   if (CheckEquivalentExceptionSpec(
703         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
704         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
705     New->setInvalidDecl();
706   }
707 }
708 
709 /// CheckCXXDefaultArguments - Verify that the default arguments for a
710 /// function declaration are well-formed according to C++
711 /// [dcl.fct.default].
712 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
713   unsigned NumParams = FD->getNumParams();
714   unsigned p;
715 
716   // Find first parameter with a default argument
717   for (p = 0; p < NumParams; ++p) {
718     ParmVarDecl *Param = FD->getParamDecl(p);
719     if (Param->hasDefaultArg())
720       break;
721   }
722 
723   // C++11 [dcl.fct.default]p4:
724   //   In a given function declaration, each parameter subsequent to a parameter
725   //   with a default argument shall have a default argument supplied in this or
726   //   a previous declaration or shall be a function parameter pack. A default
727   //   argument shall not be redefined by a later declaration (not even to the
728   //   same value).
729   unsigned LastMissingDefaultArg = 0;
730   for (; p < NumParams; ++p) {
731     ParmVarDecl *Param = FD->getParamDecl(p);
732     if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
733       if (Param->isInvalidDecl())
734         /* We already complained about this parameter. */;
735       else if (Param->getIdentifier())
736         Diag(Param->getLocation(),
737              diag::err_param_default_argument_missing_name)
738           << Param->getIdentifier();
739       else
740         Diag(Param->getLocation(),
741              diag::err_param_default_argument_missing);
742 
743       LastMissingDefaultArg = p;
744     }
745   }
746 
747   if (LastMissingDefaultArg > 0) {
748     // Some default arguments were missing. Clear out all of the
749     // default arguments up to (and including) the last missing
750     // default argument, so that we leave the function parameters
751     // in a semantically valid state.
752     for (p = 0; p <= LastMissingDefaultArg; ++p) {
753       ParmVarDecl *Param = FD->getParamDecl(p);
754       if (Param->hasDefaultArg()) {
755         Param->setDefaultArg(nullptr);
756       }
757     }
758   }
759 }
760 
761 // CheckConstexprParameterTypes - Check whether a function's parameter types
762 // are all literal types. If so, return true. If not, produce a suitable
763 // diagnostic and return false.
764 static bool CheckConstexprParameterTypes(Sema &SemaRef,
765                                          const FunctionDecl *FD) {
766   unsigned ArgIndex = 0;
767   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
768   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
769                                               e = FT->param_type_end();
770        i != e; ++i, ++ArgIndex) {
771     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
772     SourceLocation ParamLoc = PD->getLocation();
773     if (!(*i)->isDependentType() &&
774         SemaRef.RequireLiteralType(ParamLoc, *i,
775                                    diag::err_constexpr_non_literal_param,
776                                    ArgIndex+1, PD->getSourceRange(),
777                                    isa<CXXConstructorDecl>(FD)))
778       return false;
779   }
780   return true;
781 }
782 
783 /// \brief Get diagnostic %select index for tag kind for
784 /// record diagnostic message.
785 /// WARNING: Indexes apply to particular diagnostics only!
786 ///
787 /// \returns diagnostic %select index.
788 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
789   switch (Tag) {
790   case TTK_Struct: return 0;
791   case TTK_Interface: return 1;
792   case TTK_Class:  return 2;
793   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
794   }
795 }
796 
797 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
798 // the requirements of a constexpr function definition or a constexpr
799 // constructor definition. If so, return true. If not, produce appropriate
800 // diagnostics and return false.
801 //
802 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
803 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
804   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
805   if (MD && MD->isInstance()) {
806     // C++11 [dcl.constexpr]p4:
807     //  The definition of a constexpr constructor shall satisfy the following
808     //  constraints:
809     //  - the class shall not have any virtual base classes;
810     const CXXRecordDecl *RD = MD->getParent();
811     if (RD->getNumVBases()) {
812       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
813         << isa<CXXConstructorDecl>(NewFD)
814         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
815       for (const auto &I : RD->vbases())
816         Diag(I.getLocStart(),
817              diag::note_constexpr_virtual_base_here) << I.getSourceRange();
818       return false;
819     }
820   }
821 
822   if (!isa<CXXConstructorDecl>(NewFD)) {
823     // C++11 [dcl.constexpr]p3:
824     //  The definition of a constexpr function shall satisfy the following
825     //  constraints:
826     // - it shall not be virtual;
827     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
828     if (Method && Method->isVirtual()) {
829       Method = Method->getCanonicalDecl();
830       Diag(Method->getLocation(), diag::err_constexpr_virtual);
831 
832       // If it's not obvious why this function is virtual, find an overridden
833       // function which uses the 'virtual' keyword.
834       const CXXMethodDecl *WrittenVirtual = Method;
835       while (!WrittenVirtual->isVirtualAsWritten())
836         WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
837       if (WrittenVirtual != Method)
838         Diag(WrittenVirtual->getLocation(),
839              diag::note_overridden_virtual_function);
840       return false;
841     }
842 
843     // - its return type shall be a literal type;
844     QualType RT = NewFD->getReturnType();
845     if (!RT->isDependentType() &&
846         RequireLiteralType(NewFD->getLocation(), RT,
847                            diag::err_constexpr_non_literal_return))
848       return false;
849   }
850 
851   // - each of its parameter types shall be a literal type;
852   if (!CheckConstexprParameterTypes(*this, NewFD))
853     return false;
854 
855   return true;
856 }
857 
858 /// Check the given declaration statement is legal within a constexpr function
859 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
860 ///
861 /// \return true if the body is OK (maybe only as an extension), false if we
862 ///         have diagnosed a problem.
863 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
864                                    DeclStmt *DS, SourceLocation &Cxx1yLoc) {
865   // C++11 [dcl.constexpr]p3 and p4:
866   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
867   //  contain only
868   for (const auto *DclIt : DS->decls()) {
869     switch (DclIt->getKind()) {
870     case Decl::StaticAssert:
871     case Decl::Using:
872     case Decl::UsingShadow:
873     case Decl::UsingDirective:
874     case Decl::UnresolvedUsingTypename:
875     case Decl::UnresolvedUsingValue:
876       //   - static_assert-declarations
877       //   - using-declarations,
878       //   - using-directives,
879       continue;
880 
881     case Decl::Typedef:
882     case Decl::TypeAlias: {
883       //   - typedef declarations and alias-declarations that do not define
884       //     classes or enumerations,
885       const auto *TN = cast<TypedefNameDecl>(DclIt);
886       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
887         // Don't allow variably-modified types in constexpr functions.
888         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
889         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
890           << TL.getSourceRange() << TL.getType()
891           << isa<CXXConstructorDecl>(Dcl);
892         return false;
893       }
894       continue;
895     }
896 
897     case Decl::Enum:
898     case Decl::CXXRecord:
899       // C++1y allows types to be defined, not just declared.
900       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
901         SemaRef.Diag(DS->getLocStart(),
902                      SemaRef.getLangOpts().CPlusPlus14
903                        ? diag::warn_cxx11_compat_constexpr_type_definition
904                        : diag::ext_constexpr_type_definition)
905           << isa<CXXConstructorDecl>(Dcl);
906       continue;
907 
908     case Decl::EnumConstant:
909     case Decl::IndirectField:
910     case Decl::ParmVar:
911       // These can only appear with other declarations which are banned in
912       // C++11 and permitted in C++1y, so ignore them.
913       continue;
914 
915     case Decl::Var: {
916       // C++1y [dcl.constexpr]p3 allows anything except:
917       //   a definition of a variable of non-literal type or of static or
918       //   thread storage duration or for which no initialization is performed.
919       const auto *VD = cast<VarDecl>(DclIt);
920       if (VD->isThisDeclarationADefinition()) {
921         if (VD->isStaticLocal()) {
922           SemaRef.Diag(VD->getLocation(),
923                        diag::err_constexpr_local_var_static)
924             << isa<CXXConstructorDecl>(Dcl)
925             << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
926           return false;
927         }
928         if (!VD->getType()->isDependentType() &&
929             SemaRef.RequireLiteralType(
930               VD->getLocation(), VD->getType(),
931               diag::err_constexpr_local_var_non_literal_type,
932               isa<CXXConstructorDecl>(Dcl)))
933           return false;
934         if (!VD->getType()->isDependentType() &&
935             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
936           SemaRef.Diag(VD->getLocation(),
937                        diag::err_constexpr_local_var_no_init)
938             << isa<CXXConstructorDecl>(Dcl);
939           return false;
940         }
941       }
942       SemaRef.Diag(VD->getLocation(),
943                    SemaRef.getLangOpts().CPlusPlus14
944                     ? diag::warn_cxx11_compat_constexpr_local_var
945                     : diag::ext_constexpr_local_var)
946         << isa<CXXConstructorDecl>(Dcl);
947       continue;
948     }
949 
950     case Decl::NamespaceAlias:
951     case Decl::Function:
952       // These are disallowed in C++11 and permitted in C++1y. Allow them
953       // everywhere as an extension.
954       if (!Cxx1yLoc.isValid())
955         Cxx1yLoc = DS->getLocStart();
956       continue;
957 
958     default:
959       SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
960         << isa<CXXConstructorDecl>(Dcl);
961       return false;
962     }
963   }
964 
965   return true;
966 }
967 
968 /// Check that the given field is initialized within a constexpr constructor.
969 ///
970 /// \param Dcl The constexpr constructor being checked.
971 /// \param Field The field being checked. This may be a member of an anonymous
972 ///        struct or union nested within the class being checked.
973 /// \param Inits All declarations, including anonymous struct/union members and
974 ///        indirect members, for which any initialization was provided.
975 /// \param Diagnosed Set to true if an error is produced.
976 static void CheckConstexprCtorInitializer(Sema &SemaRef,
977                                           const FunctionDecl *Dcl,
978                                           FieldDecl *Field,
979                                           llvm::SmallSet<Decl*, 16> &Inits,
980                                           bool &Diagnosed) {
981   if (Field->isInvalidDecl())
982     return;
983 
984   if (Field->isUnnamedBitfield())
985     return;
986 
987   // Anonymous unions with no variant members and empty anonymous structs do not
988   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
989   // indirect fields don't need initializing.
990   if (Field->isAnonymousStructOrUnion() &&
991       (Field->getType()->isUnionType()
992            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
993            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
994     return;
995 
996   if (!Inits.count(Field)) {
997     if (!Diagnosed) {
998       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
999       Diagnosed = true;
1000     }
1001     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1002   } else if (Field->isAnonymousStructOrUnion()) {
1003     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1004     for (auto *I : RD->fields())
1005       // If an anonymous union contains an anonymous struct of which any member
1006       // is initialized, all members must be initialized.
1007       if (!RD->isUnion() || Inits.count(I))
1008         CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
1009   }
1010 }
1011 
1012 /// Check the provided statement is allowed in a constexpr function
1013 /// definition.
1014 static bool
1015 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1016                            SmallVectorImpl<SourceLocation> &ReturnStmts,
1017                            SourceLocation &Cxx1yLoc) {
1018   // - its function-body shall be [...] a compound-statement that contains only
1019   switch (S->getStmtClass()) {
1020   case Stmt::NullStmtClass:
1021     //   - null statements,
1022     return true;
1023 
1024   case Stmt::DeclStmtClass:
1025     //   - static_assert-declarations
1026     //   - using-declarations,
1027     //   - using-directives,
1028     //   - typedef declarations and alias-declarations that do not define
1029     //     classes or enumerations,
1030     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1031       return false;
1032     return true;
1033 
1034   case Stmt::ReturnStmtClass:
1035     //   - and exactly one return statement;
1036     if (isa<CXXConstructorDecl>(Dcl)) {
1037       // C++1y allows return statements in constexpr constructors.
1038       if (!Cxx1yLoc.isValid())
1039         Cxx1yLoc = S->getLocStart();
1040       return true;
1041     }
1042 
1043     ReturnStmts.push_back(S->getLocStart());
1044     return true;
1045 
1046   case Stmt::CompoundStmtClass: {
1047     // C++1y allows compound-statements.
1048     if (!Cxx1yLoc.isValid())
1049       Cxx1yLoc = S->getLocStart();
1050 
1051     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1052     for (auto *BodyIt : CompStmt->body()) {
1053       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1054                                       Cxx1yLoc))
1055         return false;
1056     }
1057     return true;
1058   }
1059 
1060   case Stmt::AttributedStmtClass:
1061     if (!Cxx1yLoc.isValid())
1062       Cxx1yLoc = S->getLocStart();
1063     return true;
1064 
1065   case Stmt::IfStmtClass: {
1066     // C++1y allows if-statements.
1067     if (!Cxx1yLoc.isValid())
1068       Cxx1yLoc = S->getLocStart();
1069 
1070     IfStmt *If = cast<IfStmt>(S);
1071     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1072                                     Cxx1yLoc))
1073       return false;
1074     if (If->getElse() &&
1075         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1076                                     Cxx1yLoc))
1077       return false;
1078     return true;
1079   }
1080 
1081   case Stmt::WhileStmtClass:
1082   case Stmt::DoStmtClass:
1083   case Stmt::ForStmtClass:
1084   case Stmt::CXXForRangeStmtClass:
1085   case Stmt::ContinueStmtClass:
1086     // C++1y allows all of these. We don't allow them as extensions in C++11,
1087     // because they don't make sense without variable mutation.
1088     if (!SemaRef.getLangOpts().CPlusPlus14)
1089       break;
1090     if (!Cxx1yLoc.isValid())
1091       Cxx1yLoc = S->getLocStart();
1092     for (Stmt *SubStmt : S->children())
1093       if (SubStmt &&
1094           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1095                                       Cxx1yLoc))
1096         return false;
1097     return true;
1098 
1099   case Stmt::SwitchStmtClass:
1100   case Stmt::CaseStmtClass:
1101   case Stmt::DefaultStmtClass:
1102   case Stmt::BreakStmtClass:
1103     // C++1y allows switch-statements, and since they don't need variable
1104     // mutation, we can reasonably allow them in C++11 as an extension.
1105     if (!Cxx1yLoc.isValid())
1106       Cxx1yLoc = S->getLocStart();
1107     for (Stmt *SubStmt : S->children())
1108       if (SubStmt &&
1109           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1110                                       Cxx1yLoc))
1111         return false;
1112     return true;
1113 
1114   default:
1115     if (!isa<Expr>(S))
1116       break;
1117 
1118     // C++1y allows expression-statements.
1119     if (!Cxx1yLoc.isValid())
1120       Cxx1yLoc = S->getLocStart();
1121     return true;
1122   }
1123 
1124   SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1125     << isa<CXXConstructorDecl>(Dcl);
1126   return false;
1127 }
1128 
1129 /// Check the body for the given constexpr function declaration only contains
1130 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1131 ///
1132 /// \return true if the body is OK, false if we have diagnosed a problem.
1133 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1134   if (isa<CXXTryStmt>(Body)) {
1135     // C++11 [dcl.constexpr]p3:
1136     //  The definition of a constexpr function shall satisfy the following
1137     //  constraints: [...]
1138     // - its function-body shall be = delete, = default, or a
1139     //   compound-statement
1140     //
1141     // C++11 [dcl.constexpr]p4:
1142     //  In the definition of a constexpr constructor, [...]
1143     // - its function-body shall not be a function-try-block;
1144     Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1145       << isa<CXXConstructorDecl>(Dcl);
1146     return false;
1147   }
1148 
1149   SmallVector<SourceLocation, 4> ReturnStmts;
1150 
1151   // - its function-body shall be [...] a compound-statement that contains only
1152   //   [... list of cases ...]
1153   CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1154   SourceLocation Cxx1yLoc;
1155   for (auto *BodyIt : CompBody->body()) {
1156     if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
1157       return false;
1158   }
1159 
1160   if (Cxx1yLoc.isValid())
1161     Diag(Cxx1yLoc,
1162          getLangOpts().CPlusPlus14
1163            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1164            : diag::ext_constexpr_body_invalid_stmt)
1165       << isa<CXXConstructorDecl>(Dcl);
1166 
1167   if (const CXXConstructorDecl *Constructor
1168         = dyn_cast<CXXConstructorDecl>(Dcl)) {
1169     const CXXRecordDecl *RD = Constructor->getParent();
1170     // DR1359:
1171     // - every non-variant non-static data member and base class sub-object
1172     //   shall be initialized;
1173     // DR1460:
1174     // - if the class is a union having variant members, exactly one of them
1175     //   shall be initialized;
1176     if (RD->isUnion()) {
1177       if (Constructor->getNumCtorInitializers() == 0 &&
1178           RD->hasVariantMembers()) {
1179         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1180         return false;
1181       }
1182     } else if (!Constructor->isDependentContext() &&
1183                !Constructor->isDelegatingConstructor()) {
1184       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1185 
1186       // Skip detailed checking if we have enough initializers, and we would
1187       // allow at most one initializer per member.
1188       bool AnyAnonStructUnionMembers = false;
1189       unsigned Fields = 0;
1190       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1191            E = RD->field_end(); I != E; ++I, ++Fields) {
1192         if (I->isAnonymousStructOrUnion()) {
1193           AnyAnonStructUnionMembers = true;
1194           break;
1195         }
1196       }
1197       // DR1460:
1198       // - if the class is a union-like class, but is not a union, for each of
1199       //   its anonymous union members having variant members, exactly one of
1200       //   them shall be initialized;
1201       if (AnyAnonStructUnionMembers ||
1202           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1203         // Check initialization of non-static data members. Base classes are
1204         // always initialized so do not need to be checked. Dependent bases
1205         // might not have initializers in the member initializer list.
1206         llvm::SmallSet<Decl*, 16> Inits;
1207         for (const auto *I: Constructor->inits()) {
1208           if (FieldDecl *FD = I->getMember())
1209             Inits.insert(FD);
1210           else if (IndirectFieldDecl *ID = I->getIndirectMember())
1211             Inits.insert(ID->chain_begin(), ID->chain_end());
1212         }
1213 
1214         bool Diagnosed = false;
1215         for (auto *I : RD->fields())
1216           CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
1217         if (Diagnosed)
1218           return false;
1219       }
1220     }
1221   } else {
1222     if (ReturnStmts.empty()) {
1223       // C++1y doesn't require constexpr functions to contain a 'return'
1224       // statement. We still do, unless the return type might be void, because
1225       // otherwise if there's no return statement, the function cannot
1226       // be used in a core constant expression.
1227       bool OK = getLangOpts().CPlusPlus14 &&
1228                 (Dcl->getReturnType()->isVoidType() ||
1229                  Dcl->getReturnType()->isDependentType());
1230       Diag(Dcl->getLocation(),
1231            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1232               : diag::err_constexpr_body_no_return);
1233       return OK;
1234     }
1235     if (ReturnStmts.size() > 1) {
1236       Diag(ReturnStmts.back(),
1237            getLangOpts().CPlusPlus14
1238              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1239              : diag::ext_constexpr_body_multiple_return);
1240       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1241         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
1242     }
1243   }
1244 
1245   // C++11 [dcl.constexpr]p5:
1246   //   if no function argument values exist such that the function invocation
1247   //   substitution would produce a constant expression, the program is
1248   //   ill-formed; no diagnostic required.
1249   // C++11 [dcl.constexpr]p3:
1250   //   - every constructor call and implicit conversion used in initializing the
1251   //     return value shall be one of those allowed in a constant expression.
1252   // C++11 [dcl.constexpr]p4:
1253   //   - every constructor involved in initializing non-static data members and
1254   //     base class sub-objects shall be a constexpr constructor.
1255   SmallVector<PartialDiagnosticAt, 8> Diags;
1256   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
1257     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
1258       << isa<CXXConstructorDecl>(Dcl);
1259     for (size_t I = 0, N = Diags.size(); I != N; ++I)
1260       Diag(Diags[I].first, Diags[I].second);
1261     // Don't return false here: we allow this for compatibility in
1262     // system headers.
1263   }
1264 
1265   return true;
1266 }
1267 
1268 /// isCurrentClassName - Determine whether the identifier II is the
1269 /// name of the class type currently being defined. In the case of
1270 /// nested classes, this will only return true if II is the name of
1271 /// the innermost class.
1272 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1273                               const CXXScopeSpec *SS) {
1274   assert(getLangOpts().CPlusPlus && "No class names in C!");
1275 
1276   CXXRecordDecl *CurDecl;
1277   if (SS && SS->isSet() && !SS->isInvalid()) {
1278     DeclContext *DC = computeDeclContext(*SS, true);
1279     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1280   } else
1281     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1282 
1283   if (CurDecl && CurDecl->getIdentifier())
1284     return &II == CurDecl->getIdentifier();
1285   return false;
1286 }
1287 
1288 /// \brief Determine whether the identifier II is a typo for the name of
1289 /// the class type currently being defined. If so, update it to the identifier
1290 /// that should have been used.
1291 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1292   assert(getLangOpts().CPlusPlus && "No class names in C!");
1293 
1294   if (!getLangOpts().SpellChecking)
1295     return false;
1296 
1297   CXXRecordDecl *CurDecl;
1298   if (SS && SS->isSet() && !SS->isInvalid()) {
1299     DeclContext *DC = computeDeclContext(*SS, true);
1300     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1301   } else
1302     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1303 
1304   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1305       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1306           < II->getLength()) {
1307     II = CurDecl->getIdentifier();
1308     return true;
1309   }
1310 
1311   return false;
1312 }
1313 
1314 /// \brief Determine whether the given class is a base class of the given
1315 /// class, including looking at dependent bases.
1316 static bool findCircularInheritance(const CXXRecordDecl *Class,
1317                                     const CXXRecordDecl *Current) {
1318   SmallVector<const CXXRecordDecl*, 8> Queue;
1319 
1320   Class = Class->getCanonicalDecl();
1321   while (true) {
1322     for (const auto &I : Current->bases()) {
1323       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
1324       if (!Base)
1325         continue;
1326 
1327       Base = Base->getDefinition();
1328       if (!Base)
1329         continue;
1330 
1331       if (Base->getCanonicalDecl() == Class)
1332         return true;
1333 
1334       Queue.push_back(Base);
1335     }
1336 
1337     if (Queue.empty())
1338       return false;
1339 
1340     Current = Queue.pop_back_val();
1341   }
1342 
1343   return false;
1344 }
1345 
1346 /// \brief Check the validity of a C++ base class specifier.
1347 ///
1348 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1349 /// and returns NULL otherwise.
1350 CXXBaseSpecifier *
1351 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1352                          SourceRange SpecifierRange,
1353                          bool Virtual, AccessSpecifier Access,
1354                          TypeSourceInfo *TInfo,
1355                          SourceLocation EllipsisLoc) {
1356   QualType BaseType = TInfo->getType();
1357 
1358   // C++ [class.union]p1:
1359   //   A union shall not have base classes.
1360   if (Class->isUnion()) {
1361     Diag(Class->getLocation(), diag::err_base_clause_on_union)
1362       << SpecifierRange;
1363     return nullptr;
1364   }
1365 
1366   if (EllipsisLoc.isValid() &&
1367       !TInfo->getType()->containsUnexpandedParameterPack()) {
1368     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1369       << TInfo->getTypeLoc().getSourceRange();
1370     EllipsisLoc = SourceLocation();
1371   }
1372 
1373   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1374 
1375   if (BaseType->isDependentType()) {
1376     // Make sure that we don't have circular inheritance among our dependent
1377     // bases. For non-dependent bases, the check for completeness below handles
1378     // this.
1379     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1380       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1381           ((BaseDecl = BaseDecl->getDefinition()) &&
1382            findCircularInheritance(Class, BaseDecl))) {
1383         Diag(BaseLoc, diag::err_circular_inheritance)
1384           << BaseType << Context.getTypeDeclType(Class);
1385 
1386         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1387           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1388             << BaseType;
1389 
1390         return nullptr;
1391       }
1392     }
1393 
1394     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1395                                           Class->getTagKind() == TTK_Class,
1396                                           Access, TInfo, EllipsisLoc);
1397   }
1398 
1399   // Base specifiers must be record types.
1400   if (!BaseType->isRecordType()) {
1401     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1402     return nullptr;
1403   }
1404 
1405   // C++ [class.union]p1:
1406   //   A union shall not be used as a base class.
1407   if (BaseType->isUnionType()) {
1408     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1409     return nullptr;
1410   }
1411 
1412   // For the MS ABI, propagate DLL attributes to base class templates.
1413   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1414     if (Attr *ClassAttr = getDLLAttr(Class)) {
1415       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1416               BaseType->getAsCXXRecordDecl())) {
1417         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
1418                                             BaseLoc);
1419       }
1420     }
1421   }
1422 
1423   // C++ [class.derived]p2:
1424   //   The class-name in a base-specifier shall not be an incompletely
1425   //   defined class.
1426   if (RequireCompleteType(BaseLoc, BaseType,
1427                           diag::err_incomplete_base_class, SpecifierRange)) {
1428     Class->setInvalidDecl();
1429     return nullptr;
1430   }
1431 
1432   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1433   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1434   assert(BaseDecl && "Record type has no declaration");
1435   BaseDecl = BaseDecl->getDefinition();
1436   assert(BaseDecl && "Base type is not incomplete, but has no definition");
1437   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1438   assert(CXXBaseDecl && "Base type is not a C++ type");
1439 
1440   // A class which contains a flexible array member is not suitable for use as a
1441   // base class:
1442   //   - If the layout determines that a base comes before another base,
1443   //     the flexible array member would index into the subsequent base.
1444   //   - If the layout determines that base comes before the derived class,
1445   //     the flexible array member would index into the derived class.
1446   if (CXXBaseDecl->hasFlexibleArrayMember()) {
1447     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1448       << CXXBaseDecl->getDeclName();
1449     return nullptr;
1450   }
1451 
1452   // C++ [class]p3:
1453   //   If a class is marked final and it appears as a base-type-specifier in
1454   //   base-clause, the program is ill-formed.
1455   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
1456     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1457       << CXXBaseDecl->getDeclName()
1458       << FA->isSpelledAsSealed();
1459     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
1460         << CXXBaseDecl->getDeclName() << FA->getRange();
1461     return nullptr;
1462   }
1463 
1464   if (BaseDecl->isInvalidDecl())
1465     Class->setInvalidDecl();
1466 
1467   // Create the base specifier.
1468   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1469                                         Class->getTagKind() == TTK_Class,
1470                                         Access, TInfo, EllipsisLoc);
1471 }
1472 
1473 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1474 /// one entry in the base class list of a class specifier, for
1475 /// example:
1476 ///    class foo : public bar, virtual private baz {
1477 /// 'public bar' and 'virtual private baz' are each base-specifiers.
1478 BaseResult
1479 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1480                          ParsedAttributes &Attributes,
1481                          bool Virtual, AccessSpecifier Access,
1482                          ParsedType basetype, SourceLocation BaseLoc,
1483                          SourceLocation EllipsisLoc) {
1484   if (!classdecl)
1485     return true;
1486 
1487   AdjustDeclIfTemplate(classdecl);
1488   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1489   if (!Class)
1490     return true;
1491 
1492   // We haven't yet attached the base specifiers.
1493   Class->setIsParsingBaseSpecifiers();
1494 
1495   // We do not support any C++11 attributes on base-specifiers yet.
1496   // Diagnose any attributes we see.
1497   if (!Attributes.empty()) {
1498     for (AttributeList *Attr = Attributes.getList(); Attr;
1499          Attr = Attr->getNext()) {
1500       if (Attr->isInvalid() ||
1501           Attr->getKind() == AttributeList::IgnoredAttribute)
1502         continue;
1503       Diag(Attr->getLoc(),
1504            Attr->getKind() == AttributeList::UnknownAttribute
1505              ? diag::warn_unknown_attribute_ignored
1506              : diag::err_base_specifier_attribute)
1507         << Attr->getName();
1508     }
1509   }
1510 
1511   TypeSourceInfo *TInfo = nullptr;
1512   GetTypeFromParser(basetype, &TInfo);
1513 
1514   if (EllipsisLoc.isInvalid() &&
1515       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1516                                       UPPC_BaseType))
1517     return true;
1518 
1519   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1520                                                       Virtual, Access, TInfo,
1521                                                       EllipsisLoc))
1522     return BaseSpec;
1523   else
1524     Class->setInvalidDecl();
1525 
1526   return true;
1527 }
1528 
1529 /// Use small set to collect indirect bases.  As this is only used
1530 /// locally, there's no need to abstract the small size parameter.
1531 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
1532 
1533 /// \brief Recursively add the bases of Type.  Don't add Type itself.
1534 static void
1535 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
1536                   const QualType &Type)
1537 {
1538   // Even though the incoming type is a base, it might not be
1539   // a class -- it could be a template parm, for instance.
1540   if (auto Rec = Type->getAs<RecordType>()) {
1541     auto Decl = Rec->getAsCXXRecordDecl();
1542 
1543     // Iterate over its bases.
1544     for (const auto &BaseSpec : Decl->bases()) {
1545       QualType Base = Context.getCanonicalType(BaseSpec.getType())
1546         .getUnqualifiedType();
1547       if (Set.insert(Base).second)
1548         // If we've not already seen it, recurse.
1549         NoteIndirectBases(Context, Set, Base);
1550     }
1551   }
1552 }
1553 
1554 /// \brief Performs the actual work of attaching the given base class
1555 /// specifiers to a C++ class.
1556 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1557                                 unsigned NumBases) {
1558  if (NumBases == 0)
1559     return false;
1560 
1561   // Used to keep track of which base types we have already seen, so
1562   // that we can properly diagnose redundant direct base types. Note
1563   // that the key is always the unqualified canonical type of the base
1564   // class.
1565   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1566 
1567   // Used to track indirect bases so we can see if a direct base is
1568   // ambiguous.
1569   IndirectBaseSet IndirectBaseTypes;
1570 
1571   // Copy non-redundant base specifiers into permanent storage.
1572   unsigned NumGoodBases = 0;
1573   bool Invalid = false;
1574   for (unsigned idx = 0; idx < NumBases; ++idx) {
1575     QualType NewBaseType
1576       = Context.getCanonicalType(Bases[idx]->getType());
1577     NewBaseType = NewBaseType.getLocalUnqualifiedType();
1578 
1579     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1580     if (KnownBase) {
1581       // C++ [class.mi]p3:
1582       //   A class shall not be specified as a direct base class of a
1583       //   derived class more than once.
1584       Diag(Bases[idx]->getLocStart(),
1585            diag::err_duplicate_base_class)
1586         << KnownBase->getType()
1587         << Bases[idx]->getSourceRange();
1588 
1589       // Delete the duplicate base class specifier; we're going to
1590       // overwrite its pointer later.
1591       Context.Deallocate(Bases[idx]);
1592 
1593       Invalid = true;
1594     } else {
1595       // Okay, add this new base class.
1596       KnownBase = Bases[idx];
1597       Bases[NumGoodBases++] = Bases[idx];
1598 
1599       // Note this base's direct & indirect bases, if there could be ambiguity.
1600       if (NumBases > 1)
1601         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
1602 
1603       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1604         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1605         if (Class->isInterface() &&
1606               (!RD->isInterface() ||
1607                KnownBase->getAccessSpecifier() != AS_public)) {
1608           // The Microsoft extension __interface does not permit bases that
1609           // are not themselves public interfaces.
1610           Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1611             << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1612             << RD->getSourceRange();
1613           Invalid = true;
1614         }
1615         if (RD->hasAttr<WeakAttr>())
1616           Class->addAttr(WeakAttr::CreateImplicit(Context));
1617       }
1618     }
1619   }
1620 
1621   // Attach the remaining base class specifiers to the derived class.
1622   Class->setBases(Bases, NumGoodBases);
1623 
1624   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
1625     // Check whether this direct base is inaccessible due to ambiguity.
1626     QualType BaseType = Bases[idx]->getType();
1627     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
1628       .getUnqualifiedType();
1629 
1630     if (IndirectBaseTypes.count(CanonicalBase)) {
1631       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1632                          /*DetectVirtual=*/true);
1633       bool found
1634         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
1635       assert(found);
1636       (void)found;
1637 
1638       if (Paths.isAmbiguous(CanonicalBase))
1639         Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
1640           << BaseType << getAmbiguousPathsDisplayString(Paths)
1641           << Bases[idx]->getSourceRange();
1642       else
1643         assert(Bases[idx]->isVirtual());
1644     }
1645 
1646     // Delete the base class specifier, since its data has been copied
1647     // into the CXXRecordDecl.
1648     Context.Deallocate(Bases[idx]);
1649   }
1650 
1651   return Invalid;
1652 }
1653 
1654 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
1655 /// class, after checking whether there are any duplicate base
1656 /// classes.
1657 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
1658                                unsigned NumBases) {
1659   if (!ClassDecl || !Bases || !NumBases)
1660     return;
1661 
1662   AdjustDeclIfTemplate(ClassDecl);
1663   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
1664 }
1665 
1666 /// \brief Determine whether the type \p Derived is a C++ class that is
1667 /// derived from the type \p Base.
1668 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1669   if (!getLangOpts().CPlusPlus)
1670     return false;
1671 
1672   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1673   if (!DerivedRD)
1674     return false;
1675 
1676   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1677   if (!BaseRD)
1678     return false;
1679 
1680   // If either the base or the derived type is invalid, don't try to
1681   // check whether one is derived from the other.
1682   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1683     return false;
1684 
1685   // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
1686   return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
1687 }
1688 
1689 /// \brief Determine whether the type \p Derived is a C++ class that is
1690 /// derived from the type \p Base.
1691 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1692   if (!getLangOpts().CPlusPlus)
1693     return false;
1694 
1695   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1696   if (!DerivedRD)
1697     return false;
1698 
1699   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1700   if (!BaseRD)
1701     return false;
1702 
1703   return DerivedRD->isDerivedFrom(BaseRD, Paths);
1704 }
1705 
1706 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1707                               CXXCastPath &BasePathArray) {
1708   assert(BasePathArray.empty() && "Base path array must be empty!");
1709   assert(Paths.isRecordingPaths() && "Must record paths!");
1710 
1711   const CXXBasePath &Path = Paths.front();
1712 
1713   // We first go backward and check if we have a virtual base.
1714   // FIXME: It would be better if CXXBasePath had the base specifier for
1715   // the nearest virtual base.
1716   unsigned Start = 0;
1717   for (unsigned I = Path.size(); I != 0; --I) {
1718     if (Path[I - 1].Base->isVirtual()) {
1719       Start = I - 1;
1720       break;
1721     }
1722   }
1723 
1724   // Now add all bases.
1725   for (unsigned I = Start, E = Path.size(); I != E; ++I)
1726     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1727 }
1728 
1729 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1730 /// conversion (where Derived and Base are class types) is
1731 /// well-formed, meaning that the conversion is unambiguous (and
1732 /// that all of the base classes are accessible). Returns true
1733 /// and emits a diagnostic if the code is ill-formed, returns false
1734 /// otherwise. Loc is the location where this routine should point to
1735 /// if there is an error, and Range is the source range to highlight
1736 /// if there is an error.
1737 bool
1738 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1739                                    unsigned InaccessibleBaseID,
1740                                    unsigned AmbigiousBaseConvID,
1741                                    SourceLocation Loc, SourceRange Range,
1742                                    DeclarationName Name,
1743                                    CXXCastPath *BasePath) {
1744   // First, determine whether the path from Derived to Base is
1745   // ambiguous. This is slightly more expensive than checking whether
1746   // the Derived to Base conversion exists, because here we need to
1747   // explore multiple paths to determine if there is an ambiguity.
1748   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1749                      /*DetectVirtual=*/false);
1750   bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1751   assert(DerivationOkay &&
1752          "Can only be used with a derived-to-base conversion");
1753   (void)DerivationOkay;
1754 
1755   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1756     if (InaccessibleBaseID) {
1757       // Check that the base class can be accessed.
1758       switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1759                                    InaccessibleBaseID)) {
1760         case AR_inaccessible:
1761           return true;
1762         case AR_accessible:
1763         case AR_dependent:
1764         case AR_delayed:
1765           break;
1766       }
1767     }
1768 
1769     // Build a base path if necessary.
1770     if (BasePath)
1771       BuildBasePathArray(Paths, *BasePath);
1772     return false;
1773   }
1774 
1775   if (AmbigiousBaseConvID) {
1776     // We know that the derived-to-base conversion is ambiguous, and
1777     // we're going to produce a diagnostic. Perform the derived-to-base
1778     // search just one more time to compute all of the possible paths so
1779     // that we can print them out. This is more expensive than any of
1780     // the previous derived-to-base checks we've done, but at this point
1781     // performance isn't as much of an issue.
1782     Paths.clear();
1783     Paths.setRecordingPaths(true);
1784     bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1785     assert(StillOkay && "Can only be used with a derived-to-base conversion");
1786     (void)StillOkay;
1787 
1788     // Build up a textual representation of the ambiguous paths, e.g.,
1789     // D -> B -> A, that will be used to illustrate the ambiguous
1790     // conversions in the diagnostic. We only print one of the paths
1791     // to each base class subobject.
1792     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1793 
1794     Diag(Loc, AmbigiousBaseConvID)
1795     << Derived << Base << PathDisplayStr << Range << Name;
1796   }
1797   return true;
1798 }
1799 
1800 bool
1801 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1802                                    SourceLocation Loc, SourceRange Range,
1803                                    CXXCastPath *BasePath,
1804                                    bool IgnoreAccess) {
1805   return CheckDerivedToBaseConversion(Derived, Base,
1806                                       IgnoreAccess ? 0
1807                                        : diag::err_upcast_to_inaccessible_base,
1808                                       diag::err_ambiguous_derived_to_base_conv,
1809                                       Loc, Range, DeclarationName(),
1810                                       BasePath);
1811 }
1812 
1813 
1814 /// @brief Builds a string representing ambiguous paths from a
1815 /// specific derived class to different subobjects of the same base
1816 /// class.
1817 ///
1818 /// This function builds a string that can be used in error messages
1819 /// to show the different paths that one can take through the
1820 /// inheritance hierarchy to go from the derived class to different
1821 /// subobjects of a base class. The result looks something like this:
1822 /// @code
1823 /// struct D -> struct B -> struct A
1824 /// struct D -> struct C -> struct A
1825 /// @endcode
1826 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1827   std::string PathDisplayStr;
1828   std::set<unsigned> DisplayedPaths;
1829   for (CXXBasePaths::paths_iterator Path = Paths.begin();
1830        Path != Paths.end(); ++Path) {
1831     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1832       // We haven't displayed a path to this particular base
1833       // class subobject yet.
1834       PathDisplayStr += "\n    ";
1835       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1836       for (CXXBasePath::const_iterator Element = Path->begin();
1837            Element != Path->end(); ++Element)
1838         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1839     }
1840   }
1841 
1842   return PathDisplayStr;
1843 }
1844 
1845 //===----------------------------------------------------------------------===//
1846 // C++ class member Handling
1847 //===----------------------------------------------------------------------===//
1848 
1849 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1850 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1851                                 SourceLocation ASLoc,
1852                                 SourceLocation ColonLoc,
1853                                 AttributeList *Attrs) {
1854   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1855   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1856                                                   ASLoc, ColonLoc);
1857   CurContext->addHiddenDecl(ASDecl);
1858   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1859 }
1860 
1861 /// CheckOverrideControl - Check C++11 override control semantics.
1862 void Sema::CheckOverrideControl(NamedDecl *D) {
1863   if (D->isInvalidDecl())
1864     return;
1865 
1866   // We only care about "override" and "final" declarations.
1867   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1868     return;
1869 
1870   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1871 
1872   // We can't check dependent instance methods.
1873   if (MD && MD->isInstance() &&
1874       (MD->getParent()->hasAnyDependentBases() ||
1875        MD->getType()->isDependentType()))
1876     return;
1877 
1878   if (MD && !MD->isVirtual()) {
1879     // If we have a non-virtual method, check if if hides a virtual method.
1880     // (In that case, it's most likely the method has the wrong type.)
1881     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1882     FindHiddenVirtualMethods(MD, OverloadedMethods);
1883 
1884     if (!OverloadedMethods.empty()) {
1885       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1886         Diag(OA->getLocation(),
1887              diag::override_keyword_hides_virtual_member_function)
1888           << "override" << (OverloadedMethods.size() > 1);
1889       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1890         Diag(FA->getLocation(),
1891              diag::override_keyword_hides_virtual_member_function)
1892           << (FA->isSpelledAsSealed() ? "sealed" : "final")
1893           << (OverloadedMethods.size() > 1);
1894       }
1895       NoteHiddenVirtualMethods(MD, OverloadedMethods);
1896       MD->setInvalidDecl();
1897       return;
1898     }
1899     // Fall through into the general case diagnostic.
1900     // FIXME: We might want to attempt typo correction here.
1901   }
1902 
1903   if (!MD || !MD->isVirtual()) {
1904     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1905       Diag(OA->getLocation(),
1906            diag::override_keyword_only_allowed_on_virtual_member_functions)
1907         << "override" << FixItHint::CreateRemoval(OA->getLocation());
1908       D->dropAttr<OverrideAttr>();
1909     }
1910     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1911       Diag(FA->getLocation(),
1912            diag::override_keyword_only_allowed_on_virtual_member_functions)
1913         << (FA->isSpelledAsSealed() ? "sealed" : "final")
1914         << FixItHint::CreateRemoval(FA->getLocation());
1915       D->dropAttr<FinalAttr>();
1916     }
1917     return;
1918   }
1919 
1920   // C++11 [class.virtual]p5:
1921   //   If a function is marked with the virt-specifier override and
1922   //   does not override a member function of a base class, the program is
1923   //   ill-formed.
1924   bool HasOverriddenMethods =
1925     MD->begin_overridden_methods() != MD->end_overridden_methods();
1926   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1927     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1928       << MD->getDeclName();
1929 }
1930 
1931 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
1932   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
1933     return;
1934   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1935   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
1936       isa<CXXDestructorDecl>(MD))
1937     return;
1938 
1939   SourceLocation Loc = MD->getLocation();
1940   SourceLocation SpellingLoc = Loc;
1941   if (getSourceManager().isMacroArgExpansion(Loc))
1942     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
1943   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
1944   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
1945       return;
1946 
1947   if (MD->size_overridden_methods() > 0) {
1948     Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
1949       << MD->getDeclName();
1950     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
1951     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
1952   }
1953 }
1954 
1955 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1956 /// function overrides a virtual member function marked 'final', according to
1957 /// C++11 [class.virtual]p4.
1958 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1959                                                   const CXXMethodDecl *Old) {
1960   FinalAttr *FA = Old->getAttr<FinalAttr>();
1961   if (!FA)
1962     return false;
1963 
1964   Diag(New->getLocation(), diag::err_final_function_overridden)
1965     << New->getDeclName()
1966     << FA->isSpelledAsSealed();
1967   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1968   return true;
1969 }
1970 
1971 static bool InitializationHasSideEffects(const FieldDecl &FD) {
1972   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1973   // FIXME: Destruction of ObjC lifetime types has side-effects.
1974   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1975     return !RD->isCompleteDefinition() ||
1976            !RD->hasTrivialDefaultConstructor() ||
1977            !RD->hasTrivialDestructor();
1978   return false;
1979 }
1980 
1981 static AttributeList *getMSPropertyAttr(AttributeList *list) {
1982   for (AttributeList *it = list; it != nullptr; it = it->getNext())
1983     if (it->isDeclspecPropertyAttribute())
1984       return it;
1985   return nullptr;
1986 }
1987 
1988 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1989 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1990 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
1991 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1992 /// present (but parsing it has been deferred).
1993 NamedDecl *
1994 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1995                                MultiTemplateParamsArg TemplateParameterLists,
1996                                Expr *BW, const VirtSpecifiers &VS,
1997                                InClassInitStyle InitStyle) {
1998   const DeclSpec &DS = D.getDeclSpec();
1999   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2000   DeclarationName Name = NameInfo.getName();
2001   SourceLocation Loc = NameInfo.getLoc();
2002 
2003   // For anonymous bitfields, the location should point to the type.
2004   if (Loc.isInvalid())
2005     Loc = D.getLocStart();
2006 
2007   Expr *BitWidth = static_cast<Expr*>(BW);
2008 
2009   assert(isa<CXXRecordDecl>(CurContext));
2010   assert(!DS.isFriendSpecified());
2011 
2012   bool isFunc = D.isDeclarationOfFunction();
2013 
2014   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2015     // The Microsoft extension __interface only permits public member functions
2016     // and prohibits constructors, destructors, operators, non-public member
2017     // functions, static methods and data members.
2018     unsigned InvalidDecl;
2019     bool ShowDeclName = true;
2020     if (!isFunc)
2021       InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
2022     else if (AS != AS_public)
2023       InvalidDecl = 2;
2024     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2025       InvalidDecl = 3;
2026     else switch (Name.getNameKind()) {
2027       case DeclarationName::CXXConstructorName:
2028         InvalidDecl = 4;
2029         ShowDeclName = false;
2030         break;
2031 
2032       case DeclarationName::CXXDestructorName:
2033         InvalidDecl = 5;
2034         ShowDeclName = false;
2035         break;
2036 
2037       case DeclarationName::CXXOperatorName:
2038       case DeclarationName::CXXConversionFunctionName:
2039         InvalidDecl = 6;
2040         break;
2041 
2042       default:
2043         InvalidDecl = 0;
2044         break;
2045     }
2046 
2047     if (InvalidDecl) {
2048       if (ShowDeclName)
2049         Diag(Loc, diag::err_invalid_member_in_interface)
2050           << (InvalidDecl-1) << Name;
2051       else
2052         Diag(Loc, diag::err_invalid_member_in_interface)
2053           << (InvalidDecl-1) << "";
2054       return nullptr;
2055     }
2056   }
2057 
2058   // C++ 9.2p6: A member shall not be declared to have automatic storage
2059   // duration (auto, register) or with the extern storage-class-specifier.
2060   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2061   // data members and cannot be applied to names declared const or static,
2062   // and cannot be applied to reference members.
2063   switch (DS.getStorageClassSpec()) {
2064   case DeclSpec::SCS_unspecified:
2065   case DeclSpec::SCS_typedef:
2066   case DeclSpec::SCS_static:
2067     break;
2068   case DeclSpec::SCS_mutable:
2069     if (isFunc) {
2070       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2071 
2072       // FIXME: It would be nicer if the keyword was ignored only for this
2073       // declarator. Otherwise we could get follow-up errors.
2074       D.getMutableDeclSpec().ClearStorageClassSpecs();
2075     }
2076     break;
2077   default:
2078     Diag(DS.getStorageClassSpecLoc(),
2079          diag::err_storageclass_invalid_for_member);
2080     D.getMutableDeclSpec().ClearStorageClassSpecs();
2081     break;
2082   }
2083 
2084   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2085                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
2086                       !isFunc);
2087 
2088   if (DS.isConstexprSpecified() && isInstField) {
2089     SemaDiagnosticBuilder B =
2090         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2091     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2092     if (InitStyle == ICIS_NoInit) {
2093       B << 0 << 0;
2094       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2095         B << FixItHint::CreateRemoval(ConstexprLoc);
2096       else {
2097         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2098         D.getMutableDeclSpec().ClearConstexprSpec();
2099         const char *PrevSpec;
2100         unsigned DiagID;
2101         bool Failed = D.getMutableDeclSpec().SetTypeQual(
2102             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2103         (void)Failed;
2104         assert(!Failed && "Making a constexpr member const shouldn't fail");
2105       }
2106     } else {
2107       B << 1;
2108       const char *PrevSpec;
2109       unsigned DiagID;
2110       if (D.getMutableDeclSpec().SetStorageClassSpec(
2111           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2112           Context.getPrintingPolicy())) {
2113         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
2114                "This is the only DeclSpec that should fail to be applied");
2115         B << 1;
2116       } else {
2117         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2118         isInstField = false;
2119       }
2120     }
2121   }
2122 
2123   NamedDecl *Member;
2124   if (isInstField) {
2125     CXXScopeSpec &SS = D.getCXXScopeSpec();
2126 
2127     // Data members must have identifiers for names.
2128     if (!Name.isIdentifier()) {
2129       Diag(Loc, diag::err_bad_variable_name)
2130         << Name;
2131       return nullptr;
2132     }
2133 
2134     IdentifierInfo *II = Name.getAsIdentifierInfo();
2135 
2136     // Member field could not be with "template" keyword.
2137     // So TemplateParameterLists should be empty in this case.
2138     if (TemplateParameterLists.size()) {
2139       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
2140       if (TemplateParams->size()) {
2141         // There is no such thing as a member field template.
2142         Diag(D.getIdentifierLoc(), diag::err_template_member)
2143             << II
2144             << SourceRange(TemplateParams->getTemplateLoc(),
2145                 TemplateParams->getRAngleLoc());
2146       } else {
2147         // There is an extraneous 'template<>' for this member.
2148         Diag(TemplateParams->getTemplateLoc(),
2149             diag::err_template_member_noparams)
2150             << II
2151             << SourceRange(TemplateParams->getTemplateLoc(),
2152                 TemplateParams->getRAngleLoc());
2153       }
2154       return nullptr;
2155     }
2156 
2157     if (SS.isSet() && !SS.isInvalid()) {
2158       // The user provided a superfluous scope specifier inside a class
2159       // definition:
2160       //
2161       // class X {
2162       //   int X::member;
2163       // };
2164       if (DeclContext *DC = computeDeclContext(SS, false))
2165         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
2166       else
2167         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2168           << Name << SS.getRange();
2169 
2170       SS.clear();
2171     }
2172 
2173     AttributeList *MSPropertyAttr =
2174       getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
2175     if (MSPropertyAttr) {
2176       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2177                                 BitWidth, InitStyle, AS, MSPropertyAttr);
2178       if (!Member)
2179         return nullptr;
2180       isInstField = false;
2181     } else {
2182       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2183                                 BitWidth, InitStyle, AS);
2184       assert(Member && "HandleField never returns null");
2185     }
2186   } else {
2187     Member = HandleDeclarator(S, D, TemplateParameterLists);
2188     if (!Member)
2189       return nullptr;
2190 
2191     // Non-instance-fields can't have a bitfield.
2192     if (BitWidth) {
2193       if (Member->isInvalidDecl()) {
2194         // don't emit another diagnostic.
2195       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
2196         // C++ 9.6p3: A bit-field shall not be a static member.
2197         // "static member 'A' cannot be a bit-field"
2198         Diag(Loc, diag::err_static_not_bitfield)
2199           << Name << BitWidth->getSourceRange();
2200       } else if (isa<TypedefDecl>(Member)) {
2201         // "typedef member 'x' cannot be a bit-field"
2202         Diag(Loc, diag::err_typedef_not_bitfield)
2203           << Name << BitWidth->getSourceRange();
2204       } else {
2205         // A function typedef ("typedef int f(); f a;").
2206         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2207         Diag(Loc, diag::err_not_integral_type_bitfield)
2208           << Name << cast<ValueDecl>(Member)->getType()
2209           << BitWidth->getSourceRange();
2210       }
2211 
2212       BitWidth = nullptr;
2213       Member->setInvalidDecl();
2214     }
2215 
2216     Member->setAccess(AS);
2217 
2218     // If we have declared a member function template or static data member
2219     // template, set the access of the templated declaration as well.
2220     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2221       FunTmpl->getTemplatedDecl()->setAccess(AS);
2222     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2223       VarTmpl->getTemplatedDecl()->setAccess(AS);
2224   }
2225 
2226   if (VS.isOverrideSpecified())
2227     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
2228   if (VS.isFinalSpecified())
2229     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2230                                             VS.isFinalSpelledSealed()));
2231 
2232   if (VS.getLastLocation().isValid()) {
2233     // Update the end location of a method that has a virt-specifiers.
2234     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2235       MD->setRangeEnd(VS.getLastLocation());
2236   }
2237 
2238   CheckOverrideControl(Member);
2239 
2240   assert((Name || isInstField) && "No identifier for non-field ?");
2241 
2242   if (isInstField) {
2243     FieldDecl *FD = cast<FieldDecl>(Member);
2244     FieldCollector->Add(FD);
2245 
2246     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
2247       // Remember all explicit private FieldDecls that have a name, no side
2248       // effects and are not part of a dependent type declaration.
2249       if (!FD->isImplicit() && FD->getDeclName() &&
2250           FD->getAccess() == AS_private &&
2251           !FD->hasAttr<UnusedAttr>() &&
2252           !FD->getParent()->isDependentContext() &&
2253           !InitializationHasSideEffects(*FD))
2254         UnusedPrivateFields.insert(FD);
2255     }
2256   }
2257 
2258   return Member;
2259 }
2260 
2261 namespace {
2262   class UninitializedFieldVisitor
2263       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2264     Sema &S;
2265     // List of Decls to generate a warning on.  Also remove Decls that become
2266     // initialized.
2267     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
2268     // List of base classes of the record.  Classes are removed after their
2269     // initializers.
2270     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
2271     // Vector of decls to be removed from the Decl set prior to visiting the
2272     // nodes.  These Decls may have been initialized in the prior initializer.
2273     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
2274     // If non-null, add a note to the warning pointing back to the constructor.
2275     const CXXConstructorDecl *Constructor;
2276     // Variables to hold state when processing an initializer list.  When
2277     // InitList is true, special case initialization of FieldDecls matching
2278     // InitListFieldDecl.
2279     bool InitList;
2280     FieldDecl *InitListFieldDecl;
2281     llvm::SmallVector<unsigned, 4> InitFieldIndex;
2282 
2283   public:
2284     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2285     UninitializedFieldVisitor(Sema &S,
2286                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
2287                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
2288       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
2289         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
2290 
2291     // Returns true if the use of ME is not an uninitialized use.
2292     bool IsInitListMemberExprInitialized(MemberExpr *ME,
2293                                          bool CheckReferenceOnly) {
2294       llvm::SmallVector<FieldDecl*, 4> Fields;
2295       bool ReferenceField = false;
2296       while (ME) {
2297         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
2298         if (!FD)
2299           return false;
2300         Fields.push_back(FD);
2301         if (FD->getType()->isReferenceType())
2302           ReferenceField = true;
2303         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
2304       }
2305 
2306       // Binding a reference to an unintialized field is not an
2307       // uninitialized use.
2308       if (CheckReferenceOnly && !ReferenceField)
2309         return true;
2310 
2311       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
2312       // Discard the first field since it is the field decl that is being
2313       // initialized.
2314       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
2315         UsedFieldIndex.push_back((*I)->getFieldIndex());
2316       }
2317 
2318       for (auto UsedIter = UsedFieldIndex.begin(),
2319                 UsedEnd = UsedFieldIndex.end(),
2320                 OrigIter = InitFieldIndex.begin(),
2321                 OrigEnd = InitFieldIndex.end();
2322            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
2323         if (*UsedIter < *OrigIter)
2324           return true;
2325         if (*UsedIter > *OrigIter)
2326           break;
2327       }
2328 
2329       return false;
2330     }
2331 
2332     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
2333                           bool AddressOf) {
2334       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2335         return;
2336 
2337       // FieldME is the inner-most MemberExpr that is not an anonymous struct
2338       // or union.
2339       MemberExpr *FieldME = ME;
2340 
2341       bool AllPODFields = FieldME->getType().isPODType(S.Context);
2342 
2343       Expr *Base = ME;
2344       while (MemberExpr *SubME =
2345                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
2346 
2347         if (isa<VarDecl>(SubME->getMemberDecl()))
2348           return;
2349 
2350         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
2351           if (!FD->isAnonymousStructOrUnion())
2352             FieldME = SubME;
2353 
2354         if (!FieldME->getType().isPODType(S.Context))
2355           AllPODFields = false;
2356 
2357         Base = SubME->getBase();
2358       }
2359 
2360       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
2361         return;
2362 
2363       if (AddressOf && AllPODFields)
2364         return;
2365 
2366       ValueDecl* FoundVD = FieldME->getMemberDecl();
2367 
2368       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
2369         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
2370           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
2371         }
2372 
2373         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
2374           QualType T = BaseCast->getType();
2375           if (T->isPointerType() &&
2376               BaseClasses.count(T->getPointeeType())) {
2377             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
2378                 << T->getPointeeType() << FoundVD;
2379           }
2380         }
2381       }
2382 
2383       if (!Decls.count(FoundVD))
2384         return;
2385 
2386       const bool IsReference = FoundVD->getType()->isReferenceType();
2387 
2388       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
2389         // Special checking for initializer lists.
2390         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
2391           return;
2392         }
2393       } else {
2394         // Prevent double warnings on use of unbounded references.
2395         if (CheckReferenceOnly && !IsReference)
2396           return;
2397       }
2398 
2399       unsigned diag = IsReference
2400           ? diag::warn_reference_field_is_uninit
2401           : diag::warn_field_is_uninit;
2402       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2403       if (Constructor)
2404         S.Diag(Constructor->getLocation(),
2405                diag::note_uninit_in_this_constructor)
2406           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2407 
2408     }
2409 
2410     void HandleValue(Expr *E, bool AddressOf) {
2411       E = E->IgnoreParens();
2412 
2413       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2414         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
2415                          AddressOf /*AddressOf*/);
2416         return;
2417       }
2418 
2419       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2420         Visit(CO->getCond());
2421         HandleValue(CO->getTrueExpr(), AddressOf);
2422         HandleValue(CO->getFalseExpr(), AddressOf);
2423         return;
2424       }
2425 
2426       if (BinaryConditionalOperator *BCO =
2427               dyn_cast<BinaryConditionalOperator>(E)) {
2428         Visit(BCO->getCond());
2429         HandleValue(BCO->getFalseExpr(), AddressOf);
2430         return;
2431       }
2432 
2433       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
2434         HandleValue(OVE->getSourceExpr(), AddressOf);
2435         return;
2436       }
2437 
2438       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2439         switch (BO->getOpcode()) {
2440         default:
2441           break;
2442         case(BO_PtrMemD):
2443         case(BO_PtrMemI):
2444           HandleValue(BO->getLHS(), AddressOf);
2445           Visit(BO->getRHS());
2446           return;
2447         case(BO_Comma):
2448           Visit(BO->getLHS());
2449           HandleValue(BO->getRHS(), AddressOf);
2450           return;
2451         }
2452       }
2453 
2454       Visit(E);
2455     }
2456 
2457     void CheckInitListExpr(InitListExpr *ILE) {
2458       InitFieldIndex.push_back(0);
2459       for (auto Child : ILE->children()) {
2460         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
2461           CheckInitListExpr(SubList);
2462         } else {
2463           Visit(Child);
2464         }
2465         ++InitFieldIndex.back();
2466       }
2467       InitFieldIndex.pop_back();
2468     }
2469 
2470     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
2471                           FieldDecl *Field, const Type *BaseClass) {
2472       // Remove Decls that may have been initialized in the previous
2473       // initializer.
2474       for (ValueDecl* VD : DeclsToRemove)
2475         Decls.erase(VD);
2476       DeclsToRemove.clear();
2477 
2478       Constructor = FieldConstructor;
2479       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
2480 
2481       if (ILE && Field) {
2482         InitList = true;
2483         InitListFieldDecl = Field;
2484         InitFieldIndex.clear();
2485         CheckInitListExpr(ILE);
2486       } else {
2487         InitList = false;
2488         Visit(E);
2489       }
2490 
2491       if (Field)
2492         Decls.erase(Field);
2493       if (BaseClass)
2494         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
2495     }
2496 
2497     void VisitMemberExpr(MemberExpr *ME) {
2498       // All uses of unbounded reference fields will warn.
2499       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
2500     }
2501 
2502     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2503       if (E->getCastKind() == CK_LValueToRValue) {
2504         HandleValue(E->getSubExpr(), false /*AddressOf*/);
2505         return;
2506       }
2507 
2508       Inherited::VisitImplicitCastExpr(E);
2509     }
2510 
2511     void VisitCXXConstructExpr(CXXConstructExpr *E) {
2512       if (E->getConstructor()->isCopyConstructor()) {
2513         Expr *ArgExpr = E->getArg(0);
2514         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
2515           if (ILE->getNumInits() == 1)
2516             ArgExpr = ILE->getInit(0);
2517         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
2518           if (ICE->getCastKind() == CK_NoOp)
2519             ArgExpr = ICE->getSubExpr();
2520         HandleValue(ArgExpr, false /*AddressOf*/);
2521         return;
2522       }
2523       Inherited::VisitCXXConstructExpr(E);
2524     }
2525 
2526     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2527       Expr *Callee = E->getCallee();
2528       if (isa<MemberExpr>(Callee)) {
2529         HandleValue(Callee, false /*AddressOf*/);
2530         for (auto Arg : E->arguments())
2531           Visit(Arg);
2532         return;
2533       }
2534 
2535       Inherited::VisitCXXMemberCallExpr(E);
2536     }
2537 
2538     void VisitCallExpr(CallExpr *E) {
2539       // Treat std::move as a use.
2540       if (E->getNumArgs() == 1) {
2541         if (FunctionDecl *FD = E->getDirectCallee()) {
2542           if (FD->isInStdNamespace() && FD->getIdentifier() &&
2543               FD->getIdentifier()->isStr("move")) {
2544             HandleValue(E->getArg(0), false /*AddressOf*/);
2545             return;
2546           }
2547         }
2548       }
2549 
2550       Inherited::VisitCallExpr(E);
2551     }
2552 
2553     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
2554       Expr *Callee = E->getCallee();
2555 
2556       if (isa<UnresolvedLookupExpr>(Callee))
2557         return Inherited::VisitCXXOperatorCallExpr(E);
2558 
2559       Visit(Callee);
2560       for (auto Arg : E->arguments())
2561         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
2562     }
2563 
2564     void VisitBinaryOperator(BinaryOperator *E) {
2565       // If a field assignment is detected, remove the field from the
2566       // uninitiailized field set.
2567       if (E->getOpcode() == BO_Assign)
2568         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2569           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2570             if (!FD->getType()->isReferenceType())
2571               DeclsToRemove.push_back(FD);
2572 
2573       if (E->isCompoundAssignmentOp()) {
2574         HandleValue(E->getLHS(), false /*AddressOf*/);
2575         Visit(E->getRHS());
2576         return;
2577       }
2578 
2579       Inherited::VisitBinaryOperator(E);
2580     }
2581 
2582     void VisitUnaryOperator(UnaryOperator *E) {
2583       if (E->isIncrementDecrementOp()) {
2584         HandleValue(E->getSubExpr(), false /*AddressOf*/);
2585         return;
2586       }
2587       if (E->getOpcode() == UO_AddrOf) {
2588         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
2589           HandleValue(ME->getBase(), true /*AddressOf*/);
2590           return;
2591         }
2592       }
2593 
2594       Inherited::VisitUnaryOperator(E);
2595     }
2596   };
2597 
2598   // Diagnose value-uses of fields to initialize themselves, e.g.
2599   //   foo(foo)
2600   // where foo is not also a parameter to the constructor.
2601   // Also diagnose across field uninitialized use such as
2602   //   x(y), y(x)
2603   // TODO: implement -Wuninitialized and fold this into that framework.
2604   static void DiagnoseUninitializedFields(
2605       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2606 
2607     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
2608                                            Constructor->getLocation())) {
2609       return;
2610     }
2611 
2612     if (Constructor->isInvalidDecl())
2613       return;
2614 
2615     const CXXRecordDecl *RD = Constructor->getParent();
2616 
2617     if (RD->getDescribedClassTemplate())
2618       return;
2619 
2620     // Holds fields that are uninitialized.
2621     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2622 
2623     // At the beginning, all fields are uninitialized.
2624     for (auto *I : RD->decls()) {
2625       if (auto *FD = dyn_cast<FieldDecl>(I)) {
2626         UninitializedFields.insert(FD);
2627       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
2628         UninitializedFields.insert(IFD->getAnonField());
2629       }
2630     }
2631 
2632     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
2633     for (auto I : RD->bases())
2634       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
2635 
2636     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
2637       return;
2638 
2639     UninitializedFieldVisitor UninitializedChecker(SemaRef,
2640                                                    UninitializedFields,
2641                                                    UninitializedBaseClasses);
2642 
2643     for (const auto *FieldInit : Constructor->inits()) {
2644       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
2645         break;
2646 
2647       Expr *InitExpr = FieldInit->getInit();
2648       if (!InitExpr)
2649         continue;
2650 
2651       if (CXXDefaultInitExpr *Default =
2652               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
2653         InitExpr = Default->getExpr();
2654         if (!InitExpr)
2655           continue;
2656         // In class initializers will point to the constructor.
2657         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
2658                                               FieldInit->getAnyMember(),
2659                                               FieldInit->getBaseClass());
2660       } else {
2661         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
2662                                               FieldInit->getAnyMember(),
2663                                               FieldInit->getBaseClass());
2664       }
2665     }
2666   }
2667 } // namespace
2668 
2669 /// \brief Enter a new C++ default initializer scope. After calling this, the
2670 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2671 /// parsing or instantiating the initializer failed.
2672 void Sema::ActOnStartCXXInClassMemberInitializer() {
2673   // Create a synthetic function scope to represent the call to the constructor
2674   // that notionally surrounds a use of this initializer.
2675   PushFunctionScope();
2676 }
2677 
2678 /// \brief This is invoked after parsing an in-class initializer for a
2679 /// non-static C++ class member, and after instantiating an in-class initializer
2680 /// in a class template. Such actions are deferred until the class is complete.
2681 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2682                                                   SourceLocation InitLoc,
2683                                                   Expr *InitExpr) {
2684   // Pop the notional constructor scope we created earlier.
2685   PopFunctionScopeInfo(nullptr, D);
2686 
2687   FieldDecl *FD = dyn_cast<FieldDecl>(D);
2688   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
2689          "must set init style when field is created");
2690 
2691   if (!InitExpr) {
2692     D->setInvalidDecl();
2693     if (FD)
2694       FD->removeInClassInitializer();
2695     return;
2696   }
2697 
2698   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2699     FD->setInvalidDecl();
2700     FD->removeInClassInitializer();
2701     return;
2702   }
2703 
2704   ExprResult Init = InitExpr;
2705   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
2706     InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
2707     InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
2708         ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
2709         : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
2710     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2711     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
2712     if (Init.isInvalid()) {
2713       FD->setInvalidDecl();
2714       return;
2715     }
2716   }
2717 
2718   // C++11 [class.base.init]p7:
2719   //   The initialization of each base and member constitutes a
2720   //   full-expression.
2721   Init = ActOnFinishFullExpr(Init.get(), InitLoc);
2722   if (Init.isInvalid()) {
2723     FD->setInvalidDecl();
2724     return;
2725   }
2726 
2727   InitExpr = Init.get();
2728 
2729   FD->setInClassInitializer(InitExpr);
2730 }
2731 
2732 /// \brief Find the direct and/or virtual base specifiers that
2733 /// correspond to the given base type, for use in base initialization
2734 /// within a constructor.
2735 static bool FindBaseInitializer(Sema &SemaRef,
2736                                 CXXRecordDecl *ClassDecl,
2737                                 QualType BaseType,
2738                                 const CXXBaseSpecifier *&DirectBaseSpec,
2739                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
2740   // First, check for a direct base class.
2741   DirectBaseSpec = nullptr;
2742   for (const auto &Base : ClassDecl->bases()) {
2743     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
2744       // We found a direct base of this type. That's what we're
2745       // initializing.
2746       DirectBaseSpec = &Base;
2747       break;
2748     }
2749   }
2750 
2751   // Check for a virtual base class.
2752   // FIXME: We might be able to short-circuit this if we know in advance that
2753   // there are no virtual bases.
2754   VirtualBaseSpec = nullptr;
2755   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2756     // We haven't found a base yet; search the class hierarchy for a
2757     // virtual base class.
2758     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2759                        /*DetectVirtual=*/false);
2760     if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2761                               BaseType, Paths)) {
2762       for (CXXBasePaths::paths_iterator Path = Paths.begin();
2763            Path != Paths.end(); ++Path) {
2764         if (Path->back().Base->isVirtual()) {
2765           VirtualBaseSpec = Path->back().Base;
2766           break;
2767         }
2768       }
2769     }
2770   }
2771 
2772   return DirectBaseSpec || VirtualBaseSpec;
2773 }
2774 
2775 /// \brief Handle a C++ member initializer using braced-init-list syntax.
2776 MemInitResult
2777 Sema::ActOnMemInitializer(Decl *ConstructorD,
2778                           Scope *S,
2779                           CXXScopeSpec &SS,
2780                           IdentifierInfo *MemberOrBase,
2781                           ParsedType TemplateTypeTy,
2782                           const DeclSpec &DS,
2783                           SourceLocation IdLoc,
2784                           Expr *InitList,
2785                           SourceLocation EllipsisLoc) {
2786   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2787                              DS, IdLoc, InitList,
2788                              EllipsisLoc);
2789 }
2790 
2791 /// \brief Handle a C++ member initializer using parentheses syntax.
2792 MemInitResult
2793 Sema::ActOnMemInitializer(Decl *ConstructorD,
2794                           Scope *S,
2795                           CXXScopeSpec &SS,
2796                           IdentifierInfo *MemberOrBase,
2797                           ParsedType TemplateTypeTy,
2798                           const DeclSpec &DS,
2799                           SourceLocation IdLoc,
2800                           SourceLocation LParenLoc,
2801                           ArrayRef<Expr *> Args,
2802                           SourceLocation RParenLoc,
2803                           SourceLocation EllipsisLoc) {
2804   Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2805                                            Args, RParenLoc);
2806   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2807                              DS, IdLoc, List, EllipsisLoc);
2808 }
2809 
2810 namespace {
2811 
2812 // Callback to only accept typo corrections that can be a valid C++ member
2813 // intializer: either a non-static field member or a base class.
2814 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2815 public:
2816   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2817       : ClassDecl(ClassDecl) {}
2818 
2819   bool ValidateCandidate(const TypoCorrection &candidate) override {
2820     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2821       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2822         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2823       return isa<TypeDecl>(ND);
2824     }
2825     return false;
2826   }
2827 
2828 private:
2829   CXXRecordDecl *ClassDecl;
2830 };
2831 
2832 }
2833 
2834 /// \brief Handle a C++ member initializer.
2835 MemInitResult
2836 Sema::BuildMemInitializer(Decl *ConstructorD,
2837                           Scope *S,
2838                           CXXScopeSpec &SS,
2839                           IdentifierInfo *MemberOrBase,
2840                           ParsedType TemplateTypeTy,
2841                           const DeclSpec &DS,
2842                           SourceLocation IdLoc,
2843                           Expr *Init,
2844                           SourceLocation EllipsisLoc) {
2845   ExprResult Res = CorrectDelayedTyposInExpr(Init);
2846   if (!Res.isUsable())
2847     return true;
2848   Init = Res.get();
2849 
2850   if (!ConstructorD)
2851     return true;
2852 
2853   AdjustDeclIfTemplate(ConstructorD);
2854 
2855   CXXConstructorDecl *Constructor
2856     = dyn_cast<CXXConstructorDecl>(ConstructorD);
2857   if (!Constructor) {
2858     // The user wrote a constructor initializer on a function that is
2859     // not a C++ constructor. Ignore the error for now, because we may
2860     // have more member initializers coming; we'll diagnose it just
2861     // once in ActOnMemInitializers.
2862     return true;
2863   }
2864 
2865   CXXRecordDecl *ClassDecl = Constructor->getParent();
2866 
2867   // C++ [class.base.init]p2:
2868   //   Names in a mem-initializer-id are looked up in the scope of the
2869   //   constructor's class and, if not found in that scope, are looked
2870   //   up in the scope containing the constructor's definition.
2871   //   [Note: if the constructor's class contains a member with the
2872   //   same name as a direct or virtual base class of the class, a
2873   //   mem-initializer-id naming the member or base class and composed
2874   //   of a single identifier refers to the class member. A
2875   //   mem-initializer-id for the hidden base class may be specified
2876   //   using a qualified name. ]
2877   if (!SS.getScopeRep() && !TemplateTypeTy) {
2878     // Look for a member, first.
2879     DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
2880     if (!Result.empty()) {
2881       ValueDecl *Member;
2882       if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2883           (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
2884         if (EllipsisLoc.isValid())
2885           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
2886             << MemberOrBase
2887             << SourceRange(IdLoc, Init->getSourceRange().getEnd());
2888 
2889         return BuildMemberInitializer(Member, Init, IdLoc);
2890       }
2891     }
2892   }
2893   // It didn't name a member, so see if it names a class.
2894   QualType BaseType;
2895   TypeSourceInfo *TInfo = nullptr;
2896 
2897   if (TemplateTypeTy) {
2898     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
2899   } else if (DS.getTypeSpecType() == TST_decltype) {
2900     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
2901   } else {
2902     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2903     LookupParsedName(R, S, &SS);
2904 
2905     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2906     if (!TyD) {
2907       if (R.isAmbiguous()) return true;
2908 
2909       // We don't want access-control diagnostics here.
2910       R.suppressDiagnostics();
2911 
2912       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2913         bool NotUnknownSpecialization = false;
2914         DeclContext *DC = computeDeclContext(SS, false);
2915         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2916           NotUnknownSpecialization = !Record->hasAnyDependentBases();
2917 
2918         if (!NotUnknownSpecialization) {
2919           // When the scope specifier can refer to a member of an unknown
2920           // specialization, we take it as a type name.
2921           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2922                                        SS.getWithLocInContext(Context),
2923                                        *MemberOrBase, IdLoc);
2924           if (BaseType.isNull())
2925             return true;
2926 
2927           R.clear();
2928           R.setLookupName(MemberOrBase);
2929         }
2930       }
2931 
2932       // If no results were found, try to correct typos.
2933       TypoCorrection Corr;
2934       if (R.empty() && BaseType.isNull() &&
2935           (Corr = CorrectTypo(
2936                R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2937                llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
2938                CTK_ErrorRecovery, ClassDecl))) {
2939         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
2940           // We have found a non-static data member with a similar
2941           // name to what was typed; complain and initialize that
2942           // member.
2943           diagnoseTypo(Corr,
2944                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
2945                          << MemberOrBase << true);
2946           return BuildMemberInitializer(Member, Init, IdLoc);
2947         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
2948           const CXXBaseSpecifier *DirectBaseSpec;
2949           const CXXBaseSpecifier *VirtualBaseSpec;
2950           if (FindBaseInitializer(*this, ClassDecl,
2951                                   Context.getTypeDeclType(Type),
2952                                   DirectBaseSpec, VirtualBaseSpec)) {
2953             // We have found a direct or virtual base class with a
2954             // similar name to what was typed; complain and initialize
2955             // that base class.
2956             diagnoseTypo(Corr,
2957                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
2958                            << MemberOrBase << false,
2959                          PDiag() /*Suppress note, we provide our own.*/);
2960 
2961             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2962                                                               : VirtualBaseSpec;
2963             Diag(BaseSpec->getLocStart(),
2964                  diag::note_base_class_specified_here)
2965               << BaseSpec->getType()
2966               << BaseSpec->getSourceRange();
2967 
2968             TyD = Type;
2969           }
2970         }
2971       }
2972 
2973       if (!TyD && BaseType.isNull()) {
2974         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
2975           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
2976         return true;
2977       }
2978     }
2979 
2980     if (BaseType.isNull()) {
2981       BaseType = Context.getTypeDeclType(TyD);
2982       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
2983       if (SS.isSet())
2984         // FIXME: preserve source range information
2985         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2986                                              BaseType);
2987     }
2988   }
2989 
2990   if (!TInfo)
2991     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
2992 
2993   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
2994 }
2995 
2996 /// Checks a member initializer expression for cases where reference (or
2997 /// pointer) members are bound to by-value parameters (or their addresses).
2998 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2999                                                Expr *Init,
3000                                                SourceLocation IdLoc) {
3001   QualType MemberTy = Member->getType();
3002 
3003   // We only handle pointers and references currently.
3004   // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3005   if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3006     return;
3007 
3008   const bool IsPointer = MemberTy->isPointerType();
3009   if (IsPointer) {
3010     if (const UnaryOperator *Op
3011           = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3012       // The only case we're worried about with pointers requires taking the
3013       // address.
3014       if (Op->getOpcode() != UO_AddrOf)
3015         return;
3016 
3017       Init = Op->getSubExpr();
3018     } else {
3019       // We only handle address-of expression initializers for pointers.
3020       return;
3021     }
3022   }
3023 
3024   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
3025     // We only warn when referring to a non-reference parameter declaration.
3026     const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3027     if (!Parameter || Parameter->getType()->isReferenceType())
3028       return;
3029 
3030     S.Diag(Init->getExprLoc(),
3031            IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3032                      : diag::warn_bind_ref_member_to_parameter)
3033       << Member << Parameter << Init->getSourceRange();
3034   } else {
3035     // Other initializers are fine.
3036     return;
3037   }
3038 
3039   S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3040     << (unsigned)IsPointer;
3041 }
3042 
3043 MemInitResult
3044 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3045                              SourceLocation IdLoc) {
3046   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3047   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3048   assert((DirectMember || IndirectMember) &&
3049          "Member must be a FieldDecl or IndirectFieldDecl");
3050 
3051   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3052     return true;
3053 
3054   if (Member->isInvalidDecl())
3055     return true;
3056 
3057   MultiExprArg Args;
3058   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3059     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3060   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3061     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
3062   } else {
3063     // Template instantiation doesn't reconstruct ParenListExprs for us.
3064     Args = Init;
3065   }
3066 
3067   SourceRange InitRange = Init->getSourceRange();
3068 
3069   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
3070     // Can't check initialization for a member of dependent type or when
3071     // any of the arguments are type-dependent expressions.
3072     DiscardCleanupsInEvaluationContext();
3073   } else {
3074     bool InitList = false;
3075     if (isa<InitListExpr>(Init)) {
3076       InitList = true;
3077       Args = Init;
3078     }
3079 
3080     // Initialize the member.
3081     InitializedEntity MemberEntity =
3082       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3083                    : InitializedEntity::InitializeMember(IndirectMember,
3084                                                          nullptr);
3085     InitializationKind Kind =
3086       InitList ? InitializationKind::CreateDirectList(IdLoc)
3087                : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3088                                                   InitRange.getEnd());
3089 
3090     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
3091     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3092                                             nullptr);
3093     if (MemberInit.isInvalid())
3094       return true;
3095 
3096     CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3097 
3098     // C++11 [class.base.init]p7:
3099     //   The initialization of each base and member constitutes a
3100     //   full-expression.
3101     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
3102     if (MemberInit.isInvalid())
3103       return true;
3104 
3105     Init = MemberInit.get();
3106   }
3107 
3108   if (DirectMember) {
3109     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3110                                             InitRange.getBegin(), Init,
3111                                             InitRange.getEnd());
3112   } else {
3113     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3114                                             InitRange.getBegin(), Init,
3115                                             InitRange.getEnd());
3116   }
3117 }
3118 
3119 MemInitResult
3120 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
3121                                  CXXRecordDecl *ClassDecl) {
3122   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
3123   if (!LangOpts.CPlusPlus11)
3124     return Diag(NameLoc, diag::err_delegating_ctor)
3125       << TInfo->getTypeLoc().getLocalSourceRange();
3126   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
3127 
3128   bool InitList = true;
3129   MultiExprArg Args = Init;
3130   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3131     InitList = false;
3132     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3133   }
3134 
3135   SourceRange InitRange = Init->getSourceRange();
3136   // Initialize the object.
3137   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3138                                      QualType(ClassDecl->getTypeForDecl(), 0));
3139   InitializationKind Kind =
3140     InitList ? InitializationKind::CreateDirectList(NameLoc)
3141              : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3142                                                 InitRange.getEnd());
3143   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
3144   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
3145                                               Args, nullptr);
3146   if (DelegationInit.isInvalid())
3147     return true;
3148 
3149   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3150          "Delegating constructor with no target?");
3151 
3152   // C++11 [class.base.init]p7:
3153   //   The initialization of each base and member constitutes a
3154   //   full-expression.
3155   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
3156                                        InitRange.getBegin());
3157   if (DelegationInit.isInvalid())
3158     return true;
3159 
3160   // If we are in a dependent context, template instantiation will
3161   // perform this type-checking again. Just save the arguments that we
3162   // received in a ParenListExpr.
3163   // FIXME: This isn't quite ideal, since our ASTs don't capture all
3164   // of the information that we have about the base
3165   // initializer. However, deconstructing the ASTs is a dicey process,
3166   // and this approach is far more likely to get the corner cases right.
3167   if (CurContext->isDependentContext())
3168     DelegationInit = Init;
3169 
3170   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
3171                                           DelegationInit.getAs<Expr>(),
3172                                           InitRange.getEnd());
3173 }
3174 
3175 MemInitResult
3176 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
3177                            Expr *Init, CXXRecordDecl *ClassDecl,
3178                            SourceLocation EllipsisLoc) {
3179   SourceLocation BaseLoc
3180     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
3181 
3182   if (!BaseType->isDependentType() && !BaseType->isRecordType())
3183     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
3184              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3185 
3186   // C++ [class.base.init]p2:
3187   //   [...] Unless the mem-initializer-id names a nonstatic data
3188   //   member of the constructor's class or a direct or virtual base
3189   //   of that class, the mem-initializer is ill-formed. A
3190   //   mem-initializer-list can initialize a base class using any
3191   //   name that denotes that base class type.
3192   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
3193 
3194   SourceRange InitRange = Init->getSourceRange();
3195   if (EllipsisLoc.isValid()) {
3196     // This is a pack expansion.
3197     if (!BaseType->containsUnexpandedParameterPack())  {
3198       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
3199         << SourceRange(BaseLoc, InitRange.getEnd());
3200 
3201       EllipsisLoc = SourceLocation();
3202     }
3203   } else {
3204     // Check for any unexpanded parameter packs.
3205     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
3206       return true;
3207 
3208     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3209       return true;
3210   }
3211 
3212   // Check for direct and virtual base classes.
3213   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
3214   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
3215   if (!Dependent) {
3216     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
3217                                        BaseType))
3218       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
3219 
3220     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
3221                         VirtualBaseSpec);
3222 
3223     // C++ [base.class.init]p2:
3224     // Unless the mem-initializer-id names a nonstatic data member of the
3225     // constructor's class or a direct or virtual base of that class, the
3226     // mem-initializer is ill-formed.
3227     if (!DirectBaseSpec && !VirtualBaseSpec) {
3228       // If the class has any dependent bases, then it's possible that
3229       // one of those types will resolve to the same type as
3230       // BaseType. Therefore, just treat this as a dependent base
3231       // class initialization.  FIXME: Should we try to check the
3232       // initialization anyway? It seems odd.
3233       if (ClassDecl->hasAnyDependentBases())
3234         Dependent = true;
3235       else
3236         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
3237           << BaseType << Context.getTypeDeclType(ClassDecl)
3238           << BaseTInfo->getTypeLoc().getLocalSourceRange();
3239     }
3240   }
3241 
3242   if (Dependent) {
3243     DiscardCleanupsInEvaluationContext();
3244 
3245     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3246                                             /*IsVirtual=*/false,
3247                                             InitRange.getBegin(), Init,
3248                                             InitRange.getEnd(), EllipsisLoc);
3249   }
3250 
3251   // C++ [base.class.init]p2:
3252   //   If a mem-initializer-id is ambiguous because it designates both
3253   //   a direct non-virtual base class and an inherited virtual base
3254   //   class, the mem-initializer is ill-formed.
3255   if (DirectBaseSpec && VirtualBaseSpec)
3256     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
3257       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3258 
3259   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
3260   if (!BaseSpec)
3261     BaseSpec = VirtualBaseSpec;
3262 
3263   // Initialize the base.
3264   bool InitList = true;
3265   MultiExprArg Args = Init;
3266   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3267     InitList = false;
3268     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3269   }
3270 
3271   InitializedEntity BaseEntity =
3272     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
3273   InitializationKind Kind =
3274     InitList ? InitializationKind::CreateDirectList(BaseLoc)
3275              : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
3276                                                 InitRange.getEnd());
3277   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
3278   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
3279   if (BaseInit.isInvalid())
3280     return true;
3281 
3282   // C++11 [class.base.init]p7:
3283   //   The initialization of each base and member constitutes a
3284   //   full-expression.
3285   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
3286   if (BaseInit.isInvalid())
3287     return true;
3288 
3289   // If we are in a dependent context, template instantiation will
3290   // perform this type-checking again. Just save the arguments that we
3291   // received in a ParenListExpr.
3292   // FIXME: This isn't quite ideal, since our ASTs don't capture all
3293   // of the information that we have about the base
3294   // initializer. However, deconstructing the ASTs is a dicey process,
3295   // and this approach is far more likely to get the corner cases right.
3296   if (CurContext->isDependentContext())
3297     BaseInit = Init;
3298 
3299   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3300                                           BaseSpec->isVirtual(),
3301                                           InitRange.getBegin(),
3302                                           BaseInit.getAs<Expr>(),
3303                                           InitRange.getEnd(), EllipsisLoc);
3304 }
3305 
3306 // Create a static_cast\<T&&>(expr).
3307 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
3308   if (T.isNull()) T = E->getType();
3309   QualType TargetType = SemaRef.BuildReferenceType(
3310       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
3311   SourceLocation ExprLoc = E->getLocStart();
3312   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
3313       TargetType, ExprLoc);
3314 
3315   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
3316                                    SourceRange(ExprLoc, ExprLoc),
3317                                    E->getSourceRange()).get();
3318 }
3319 
3320 /// ImplicitInitializerKind - How an implicit base or member initializer should
3321 /// initialize its base or member.
3322 enum ImplicitInitializerKind {
3323   IIK_Default,
3324   IIK_Copy,
3325   IIK_Move,
3326   IIK_Inherit
3327 };
3328 
3329 static bool
3330 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3331                              ImplicitInitializerKind ImplicitInitKind,
3332                              CXXBaseSpecifier *BaseSpec,
3333                              bool IsInheritedVirtualBase,
3334                              CXXCtorInitializer *&CXXBaseInit) {
3335   InitializedEntity InitEntity
3336     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3337                                         IsInheritedVirtualBase);
3338 
3339   ExprResult BaseInit;
3340 
3341   switch (ImplicitInitKind) {
3342   case IIK_Inherit: {
3343     const CXXRecordDecl *Inherited =
3344         Constructor->getInheritedConstructor()->getParent();
3345     const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3346     if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3347       // C++11 [class.inhctor]p8:
3348       //   Each expression in the expression-list is of the form
3349       //   static_cast<T&&>(p), where p is the name of the corresponding
3350       //   constructor parameter and T is the declared type of p.
3351       SmallVector<Expr*, 16> Args;
3352       for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3353         ParmVarDecl *PD = Constructor->getParamDecl(I);
3354         ExprResult ArgExpr =
3355             SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3356                                      VK_LValue, SourceLocation());
3357         if (ArgExpr.isInvalid())
3358           return true;
3359         Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
3360       }
3361 
3362       InitializationKind InitKind = InitializationKind::CreateDirect(
3363           Constructor->getLocation(), SourceLocation(), SourceLocation());
3364       InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
3365       BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3366       break;
3367     }
3368   }
3369   // Fall through.
3370   case IIK_Default: {
3371     InitializationKind InitKind
3372       = InitializationKind::CreateDefault(Constructor->getLocation());
3373     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3374     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3375     break;
3376   }
3377 
3378   case IIK_Move:
3379   case IIK_Copy: {
3380     bool Moving = ImplicitInitKind == IIK_Move;
3381     ParmVarDecl *Param = Constructor->getParamDecl(0);
3382     QualType ParamType = Param->getType().getNonReferenceType();
3383 
3384     Expr *CopyCtorArg =
3385       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3386                           SourceLocation(), Param, false,
3387                           Constructor->getLocation(), ParamType,
3388                           VK_LValue, nullptr);
3389 
3390     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3391 
3392     // Cast to the base class to avoid ambiguities.
3393     QualType ArgTy =
3394       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3395                                        ParamType.getQualifiers());
3396 
3397     if (Moving) {
3398       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3399     }
3400 
3401     CXXCastPath BasePath;
3402     BasePath.push_back(BaseSpec);
3403     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3404                                             CK_UncheckedDerivedToBase,
3405                                             Moving ? VK_XValue : VK_LValue,
3406                                             &BasePath).get();
3407 
3408     InitializationKind InitKind
3409       = InitializationKind::CreateDirect(Constructor->getLocation(),
3410                                          SourceLocation(), SourceLocation());
3411     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3412     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
3413     break;
3414   }
3415   }
3416 
3417   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
3418   if (BaseInit.isInvalid())
3419     return true;
3420 
3421   CXXBaseInit =
3422     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3423                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3424                                                         SourceLocation()),
3425                                              BaseSpec->isVirtual(),
3426                                              SourceLocation(),
3427                                              BaseInit.getAs<Expr>(),
3428                                              SourceLocation(),
3429                                              SourceLocation());
3430 
3431   return false;
3432 }
3433 
3434 static bool RefersToRValueRef(Expr *MemRef) {
3435   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3436   return Referenced->getType()->isRValueReferenceType();
3437 }
3438 
3439 static bool
3440 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3441                                ImplicitInitializerKind ImplicitInitKind,
3442                                FieldDecl *Field, IndirectFieldDecl *Indirect,
3443                                CXXCtorInitializer *&CXXMemberInit) {
3444   if (Field->isInvalidDecl())
3445     return true;
3446 
3447   SourceLocation Loc = Constructor->getLocation();
3448 
3449   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3450     bool Moving = ImplicitInitKind == IIK_Move;
3451     ParmVarDecl *Param = Constructor->getParamDecl(0);
3452     QualType ParamType = Param->getType().getNonReferenceType();
3453 
3454     // Suppress copying zero-width bitfields.
3455     if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3456       return false;
3457 
3458     Expr *MemberExprBase =
3459       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3460                           SourceLocation(), Param, false,
3461                           Loc, ParamType, VK_LValue, nullptr);
3462 
3463     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3464 
3465     if (Moving) {
3466       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3467     }
3468 
3469     // Build a reference to this field within the parameter.
3470     CXXScopeSpec SS;
3471     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3472                               Sema::LookupMemberName);
3473     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3474                                   : cast<ValueDecl>(Field), AS_public);
3475     MemberLookup.resolveKind();
3476     ExprResult CtorArg
3477       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
3478                                          ParamType, Loc,
3479                                          /*IsArrow=*/false,
3480                                          SS,
3481                                          /*TemplateKWLoc=*/SourceLocation(),
3482                                          /*FirstQualifierInScope=*/nullptr,
3483                                          MemberLookup,
3484                                          /*TemplateArgs=*/nullptr);
3485     if (CtorArg.isInvalid())
3486       return true;
3487 
3488     // C++11 [class.copy]p15:
3489     //   - if a member m has rvalue reference type T&&, it is direct-initialized
3490     //     with static_cast<T&&>(x.m);
3491     if (RefersToRValueRef(CtorArg.get())) {
3492       CtorArg = CastForMoving(SemaRef, CtorArg.get());
3493     }
3494 
3495     // When the field we are copying is an array, create index variables for
3496     // each dimension of the array. We use these index variables to subscript
3497     // the source array, and other clients (e.g., CodeGen) will perform the
3498     // necessary iteration with these index variables.
3499     SmallVector<VarDecl *, 4> IndexVariables;
3500     QualType BaseType = Field->getType();
3501     QualType SizeType = SemaRef.Context.getSizeType();
3502     bool InitializingArray = false;
3503     while (const ConstantArrayType *Array
3504                           = SemaRef.Context.getAsConstantArrayType(BaseType)) {
3505       InitializingArray = true;
3506       // Create the iteration variable for this array index.
3507       IdentifierInfo *IterationVarName = nullptr;
3508       {
3509         SmallString<8> Str;
3510         llvm::raw_svector_ostream OS(Str);
3511         OS << "__i" << IndexVariables.size();
3512         IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3513       }
3514       VarDecl *IterationVar
3515         = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
3516                           IterationVarName, SizeType,
3517                         SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
3518                           SC_None);
3519       IndexVariables.push_back(IterationVar);
3520 
3521       // Create a reference to the iteration variable.
3522       ExprResult IterationVarRef
3523         = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
3524       assert(!IterationVarRef.isInvalid() &&
3525              "Reference to invented variable cannot fail!");
3526       IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
3527       assert(!IterationVarRef.isInvalid() &&
3528              "Conversion of invented variable cannot fail!");
3529 
3530       // Subscript the array with this iteration variable.
3531       CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3532                                                         IterationVarRef.get(),
3533                                                         Loc);
3534       if (CtorArg.isInvalid())
3535         return true;
3536 
3537       BaseType = Array->getElementType();
3538     }
3539 
3540     // The array subscript expression is an lvalue, which is wrong for moving.
3541     if (Moving && InitializingArray)
3542       CtorArg = CastForMoving(SemaRef, CtorArg.get());
3543 
3544     // Construct the entity that we will be initializing. For an array, this
3545     // will be first element in the array, which may require several levels
3546     // of array-subscript entities.
3547     SmallVector<InitializedEntity, 4> Entities;
3548     Entities.reserve(1 + IndexVariables.size());
3549     if (Indirect)
3550       Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3551     else
3552       Entities.push_back(InitializedEntity::InitializeMember(Field));
3553     for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3554       Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3555                                                               0,
3556                                                               Entities.back()));
3557 
3558     // Direct-initialize to use the copy constructor.
3559     InitializationKind InitKind =
3560       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3561 
3562     Expr *CtorArgE = CtorArg.getAs<Expr>();
3563     InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
3564                                    CtorArgE);
3565 
3566     ExprResult MemberInit
3567       = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
3568                         MultiExprArg(&CtorArgE, 1));
3569     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3570     if (MemberInit.isInvalid())
3571       return true;
3572 
3573     if (Indirect) {
3574       assert(IndexVariables.size() == 0 &&
3575              "Indirect field improperly initialized");
3576       CXXMemberInit
3577         = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3578                                                    Loc, Loc,
3579                                                    MemberInit.getAs<Expr>(),
3580                                                    Loc);
3581     } else
3582       CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3583                                                  Loc, MemberInit.getAs<Expr>(),
3584                                                  Loc,
3585                                                  IndexVariables.data(),
3586                                                  IndexVariables.size());
3587     return false;
3588   }
3589 
3590   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3591          "Unhandled implicit init kind!");
3592 
3593   QualType FieldBaseElementType =
3594     SemaRef.Context.getBaseElementType(Field->getType());
3595 
3596   if (FieldBaseElementType->isRecordType()) {
3597     InitializedEntity InitEntity
3598       = Indirect? InitializedEntity::InitializeMember(Indirect)
3599                 : InitializedEntity::InitializeMember(Field);
3600     InitializationKind InitKind =
3601       InitializationKind::CreateDefault(Loc);
3602 
3603     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3604     ExprResult MemberInit =
3605       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3606 
3607     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3608     if (MemberInit.isInvalid())
3609       return true;
3610 
3611     if (Indirect)
3612       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3613                                                                Indirect, Loc,
3614                                                                Loc,
3615                                                                MemberInit.get(),
3616                                                                Loc);
3617     else
3618       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3619                                                                Field, Loc, Loc,
3620                                                                MemberInit.get(),
3621                                                                Loc);
3622     return false;
3623   }
3624 
3625   if (!Field->getParent()->isUnion()) {
3626     if (FieldBaseElementType->isReferenceType()) {
3627       SemaRef.Diag(Constructor->getLocation(),
3628                    diag::err_uninitialized_member_in_ctor)
3629       << (int)Constructor->isImplicit()
3630       << SemaRef.Context.getTagDeclType(Constructor->getParent())
3631       << 0 << Field->getDeclName();
3632       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3633       return true;
3634     }
3635 
3636     if (FieldBaseElementType.isConstQualified()) {
3637       SemaRef.Diag(Constructor->getLocation(),
3638                    diag::err_uninitialized_member_in_ctor)
3639       << (int)Constructor->isImplicit()
3640       << SemaRef.Context.getTagDeclType(Constructor->getParent())
3641       << 1 << Field->getDeclName();
3642       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3643       return true;
3644     }
3645   }
3646 
3647   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
3648       FieldBaseElementType->isObjCRetainableType() &&
3649       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3650       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
3651     // ARC:
3652     //   Default-initialize Objective-C pointers to NULL.
3653     CXXMemberInit
3654       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3655                                                  Loc, Loc,
3656                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3657                                                  Loc);
3658     return false;
3659   }
3660 
3661   // Nothing to initialize.
3662   CXXMemberInit = nullptr;
3663   return false;
3664 }
3665 
3666 namespace {
3667 struct BaseAndFieldInfo {
3668   Sema &S;
3669   CXXConstructorDecl *Ctor;
3670   bool AnyErrorsInInits;
3671   ImplicitInitializerKind IIK;
3672   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
3673   SmallVector<CXXCtorInitializer*, 8> AllToInit;
3674   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
3675 
3676   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3677     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
3678     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3679     if (Generated && Ctor->isCopyConstructor())
3680       IIK = IIK_Copy;
3681     else if (Generated && Ctor->isMoveConstructor())
3682       IIK = IIK_Move;
3683     else if (Ctor->getInheritedConstructor())
3684       IIK = IIK_Inherit;
3685     else
3686       IIK = IIK_Default;
3687   }
3688 
3689   bool isImplicitCopyOrMove() const {
3690     switch (IIK) {
3691     case IIK_Copy:
3692     case IIK_Move:
3693       return true;
3694 
3695     case IIK_Default:
3696     case IIK_Inherit:
3697       return false;
3698     }
3699 
3700     llvm_unreachable("Invalid ImplicitInitializerKind!");
3701   }
3702 
3703   bool addFieldInitializer(CXXCtorInitializer *Init) {
3704     AllToInit.push_back(Init);
3705 
3706     // Check whether this initializer makes the field "used".
3707     if (Init->getInit()->HasSideEffects(S.Context))
3708       S.UnusedPrivateFields.remove(Init->getAnyMember());
3709 
3710     return false;
3711   }
3712 
3713   bool isInactiveUnionMember(FieldDecl *Field) {
3714     RecordDecl *Record = Field->getParent();
3715     if (!Record->isUnion())
3716       return false;
3717 
3718     if (FieldDecl *Active =
3719             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
3720       return Active != Field->getCanonicalDecl();
3721 
3722     // In an implicit copy or move constructor, ignore any in-class initializer.
3723     if (isImplicitCopyOrMove())
3724       return true;
3725 
3726     // If there's no explicit initialization, the field is active only if it
3727     // has an in-class initializer...
3728     if (Field->hasInClassInitializer())
3729       return false;
3730     // ... or it's an anonymous struct or union whose class has an in-class
3731     // initializer.
3732     if (!Field->isAnonymousStructOrUnion())
3733       return true;
3734     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3735     return !FieldRD->hasInClassInitializer();
3736   }
3737 
3738   /// \brief Determine whether the given field is, or is within, a union member
3739   /// that is inactive (because there was an initializer given for a different
3740   /// member of the union, or because the union was not initialized at all).
3741   bool isWithinInactiveUnionMember(FieldDecl *Field,
3742                                    IndirectFieldDecl *Indirect) {
3743     if (!Indirect)
3744       return isInactiveUnionMember(Field);
3745 
3746     for (auto *C : Indirect->chain()) {
3747       FieldDecl *Field = dyn_cast<FieldDecl>(C);
3748       if (Field && isInactiveUnionMember(Field))
3749         return true;
3750     }
3751     return false;
3752   }
3753 };
3754 }
3755 
3756 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
3757 /// array type.
3758 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3759   if (T->isIncompleteArrayType())
3760     return true;
3761 
3762   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3763     if (!ArrayT->getSize())
3764       return true;
3765 
3766     T = ArrayT->getElementType();
3767   }
3768 
3769   return false;
3770 }
3771 
3772 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
3773                                     FieldDecl *Field,
3774                                     IndirectFieldDecl *Indirect = nullptr) {
3775   if (Field->isInvalidDecl())
3776     return false;
3777 
3778   // Overwhelmingly common case: we have a direct initializer for this field.
3779   if (CXXCtorInitializer *Init =
3780           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
3781     return Info.addFieldInitializer(Init);
3782 
3783   // C++11 [class.base.init]p8:
3784   //   if the entity is a non-static data member that has a
3785   //   brace-or-equal-initializer and either
3786   //   -- the constructor's class is a union and no other variant member of that
3787   //      union is designated by a mem-initializer-id or
3788   //   -- the constructor's class is not a union, and, if the entity is a member
3789   //      of an anonymous union, no other member of that union is designated by
3790   //      a mem-initializer-id,
3791   //   the entity is initialized as specified in [dcl.init].
3792   //
3793   // We also apply the same rules to handle anonymous structs within anonymous
3794   // unions.
3795   if (Info.isWithinInactiveUnionMember(Field, Indirect))
3796     return false;
3797 
3798   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
3799     ExprResult DIE =
3800         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
3801     if (DIE.isInvalid())
3802       return true;
3803     CXXCtorInitializer *Init;
3804     if (Indirect)
3805       Init = new (SemaRef.Context)
3806           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
3807                              SourceLocation(), DIE.get(), SourceLocation());
3808     else
3809       Init = new (SemaRef.Context)
3810           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
3811                              SourceLocation(), DIE.get(), SourceLocation());
3812     return Info.addFieldInitializer(Init);
3813   }
3814 
3815   // Don't initialize incomplete or zero-length arrays.
3816   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3817     return false;
3818 
3819   // Don't try to build an implicit initializer if there were semantic
3820   // errors in any of the initializers (and therefore we might be
3821   // missing some that the user actually wrote).
3822   if (Info.AnyErrorsInInits)
3823     return false;
3824 
3825   CXXCtorInitializer *Init = nullptr;
3826   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3827                                      Indirect, Init))
3828     return true;
3829 
3830   if (!Init)
3831     return false;
3832 
3833   return Info.addFieldInitializer(Init);
3834 }
3835 
3836 bool
3837 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3838                                CXXCtorInitializer *Initializer) {
3839   assert(Initializer->isDelegatingInitializer());
3840   Constructor->setNumCtorInitializers(1);
3841   CXXCtorInitializer **initializer =
3842     new (Context) CXXCtorInitializer*[1];
3843   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3844   Constructor->setCtorInitializers(initializer);
3845 
3846   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
3847     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
3848     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3849   }
3850 
3851   DelegatingCtorDecls.push_back(Constructor);
3852 
3853   DiagnoseUninitializedFields(*this, Constructor);
3854 
3855   return false;
3856 }
3857 
3858 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3859                                ArrayRef<CXXCtorInitializer *> Initializers) {
3860   if (Constructor->isDependentContext()) {
3861     // Just store the initializers as written, they will be checked during
3862     // instantiation.
3863     if (!Initializers.empty()) {
3864       Constructor->setNumCtorInitializers(Initializers.size());
3865       CXXCtorInitializer **baseOrMemberInitializers =
3866         new (Context) CXXCtorInitializer*[Initializers.size()];
3867       memcpy(baseOrMemberInitializers, Initializers.data(),
3868              Initializers.size() * sizeof(CXXCtorInitializer*));
3869       Constructor->setCtorInitializers(baseOrMemberInitializers);
3870     }
3871 
3872     // Let template instantiation know whether we had errors.
3873     if (AnyErrors)
3874       Constructor->setInvalidDecl();
3875 
3876     return false;
3877   }
3878 
3879   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
3880 
3881   // We need to build the initializer AST according to order of construction
3882   // and not what user specified in the Initializers list.
3883   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
3884   if (!ClassDecl)
3885     return true;
3886 
3887   bool HadError = false;
3888 
3889   for (unsigned i = 0; i < Initializers.size(); i++) {
3890     CXXCtorInitializer *Member = Initializers[i];
3891 
3892     if (Member->isBaseInitializer())
3893       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
3894     else {
3895       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
3896 
3897       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
3898         for (auto *C : F->chain()) {
3899           FieldDecl *FD = dyn_cast<FieldDecl>(C);
3900           if (FD && FD->getParent()->isUnion())
3901             Info.ActiveUnionMember.insert(std::make_pair(
3902                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3903         }
3904       } else if (FieldDecl *FD = Member->getMember()) {
3905         if (FD->getParent()->isUnion())
3906           Info.ActiveUnionMember.insert(std::make_pair(
3907               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3908       }
3909     }
3910   }
3911 
3912   // Keep track of the direct virtual bases.
3913   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3914   for (auto &I : ClassDecl->bases()) {
3915     if (I.isVirtual())
3916       DirectVBases.insert(&I);
3917   }
3918 
3919   // Push virtual bases before others.
3920   for (auto &VBase : ClassDecl->vbases()) {
3921     if (CXXCtorInitializer *Value
3922         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
3923       // [class.base.init]p7, per DR257:
3924       //   A mem-initializer where the mem-initializer-id names a virtual base
3925       //   class is ignored during execution of a constructor of any class that
3926       //   is not the most derived class.
3927       if (ClassDecl->isAbstract()) {
3928         // FIXME: Provide a fixit to remove the base specifier. This requires
3929         // tracking the location of the associated comma for a base specifier.
3930         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3931           << VBase.getType() << ClassDecl;
3932         DiagnoseAbstractType(ClassDecl);
3933       }
3934 
3935       Info.AllToInit.push_back(Value);
3936     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3937       // [class.base.init]p8, per DR257:
3938       //   If a given [...] base class is not named by a mem-initializer-id
3939       //   [...] and the entity is not a virtual base class of an abstract
3940       //   class, then [...] the entity is default-initialized.
3941       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
3942       CXXCtorInitializer *CXXBaseInit;
3943       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3944                                        &VBase, IsInheritedVirtualBase,
3945                                        CXXBaseInit)) {
3946         HadError = true;
3947         continue;
3948       }
3949 
3950       Info.AllToInit.push_back(CXXBaseInit);
3951     }
3952   }
3953 
3954   // Non-virtual bases.
3955   for (auto &Base : ClassDecl->bases()) {
3956     // Virtuals are in the virtual base list and already constructed.
3957     if (Base.isVirtual())
3958       continue;
3959 
3960     if (CXXCtorInitializer *Value
3961           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
3962       Info.AllToInit.push_back(Value);
3963     } else if (!AnyErrors) {
3964       CXXCtorInitializer *CXXBaseInit;
3965       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3966                                        &Base, /*IsInheritedVirtualBase=*/false,
3967                                        CXXBaseInit)) {
3968         HadError = true;
3969         continue;
3970       }
3971 
3972       Info.AllToInit.push_back(CXXBaseInit);
3973     }
3974   }
3975 
3976   // Fields.
3977   for (auto *Mem : ClassDecl->decls()) {
3978     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
3979       // C++ [class.bit]p2:
3980       //   A declaration for a bit-field that omits the identifier declares an
3981       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
3982       //   initialized.
3983       if (F->isUnnamedBitfield())
3984         continue;
3985 
3986       // If we're not generating the implicit copy/move constructor, then we'll
3987       // handle anonymous struct/union fields based on their individual
3988       // indirect fields.
3989       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
3990         continue;
3991 
3992       if (CollectFieldInitializer(*this, Info, F))
3993         HadError = true;
3994       continue;
3995     }
3996 
3997     // Beyond this point, we only consider default initialization.
3998     if (Info.isImplicitCopyOrMove())
3999       continue;
4000 
4001     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4002       if (F->getType()->isIncompleteArrayType()) {
4003         assert(ClassDecl->hasFlexibleArrayMember() &&
4004                "Incomplete array type is not valid");
4005         continue;
4006       }
4007 
4008       // Initialize each field of an anonymous struct individually.
4009       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4010         HadError = true;
4011 
4012       continue;
4013     }
4014   }
4015 
4016   unsigned NumInitializers = Info.AllToInit.size();
4017   if (NumInitializers > 0) {
4018     Constructor->setNumCtorInitializers(NumInitializers);
4019     CXXCtorInitializer **baseOrMemberInitializers =
4020       new (Context) CXXCtorInitializer*[NumInitializers];
4021     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4022            NumInitializers * sizeof(CXXCtorInitializer*));
4023     Constructor->setCtorInitializers(baseOrMemberInitializers);
4024 
4025     // Constructors implicitly reference the base and member
4026     // destructors.
4027     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4028                                            Constructor->getParent());
4029   }
4030 
4031   return HadError;
4032 }
4033 
4034 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4035   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4036     const RecordDecl *RD = RT->getDecl();
4037     if (RD->isAnonymousStructOrUnion()) {
4038       for (auto *Field : RD->fields())
4039         PopulateKeysForFields(Field, IdealInits);
4040       return;
4041     }
4042   }
4043   IdealInits.push_back(Field->getCanonicalDecl());
4044 }
4045 
4046 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4047   return Context.getCanonicalType(BaseType).getTypePtr();
4048 }
4049 
4050 static const void *GetKeyForMember(ASTContext &Context,
4051                                    CXXCtorInitializer *Member) {
4052   if (!Member->isAnyMemberInitializer())
4053     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4054 
4055   return Member->getAnyMember()->getCanonicalDecl();
4056 }
4057 
4058 static void DiagnoseBaseOrMemInitializerOrder(
4059     Sema &SemaRef, const CXXConstructorDecl *Constructor,
4060     ArrayRef<CXXCtorInitializer *> Inits) {
4061   if (Constructor->getDeclContext()->isDependentContext())
4062     return;
4063 
4064   // Don't check initializers order unless the warning is enabled at the
4065   // location of at least one initializer.
4066   bool ShouldCheckOrder = false;
4067   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4068     CXXCtorInitializer *Init = Inits[InitIndex];
4069     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4070                                  Init->getSourceLocation())) {
4071       ShouldCheckOrder = true;
4072       break;
4073     }
4074   }
4075   if (!ShouldCheckOrder)
4076     return;
4077 
4078   // Build the list of bases and members in the order that they'll
4079   // actually be initialized.  The explicit initializers should be in
4080   // this same order but may be missing things.
4081   SmallVector<const void*, 32> IdealInitKeys;
4082 
4083   const CXXRecordDecl *ClassDecl = Constructor->getParent();
4084 
4085   // 1. Virtual bases.
4086   for (const auto &VBase : ClassDecl->vbases())
4087     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4088 
4089   // 2. Non-virtual bases.
4090   for (const auto &Base : ClassDecl->bases()) {
4091     if (Base.isVirtual())
4092       continue;
4093     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4094   }
4095 
4096   // 3. Direct fields.
4097   for (auto *Field : ClassDecl->fields()) {
4098     if (Field->isUnnamedBitfield())
4099       continue;
4100 
4101     PopulateKeysForFields(Field, IdealInitKeys);
4102   }
4103 
4104   unsigned NumIdealInits = IdealInitKeys.size();
4105   unsigned IdealIndex = 0;
4106 
4107   CXXCtorInitializer *PrevInit = nullptr;
4108   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4109     CXXCtorInitializer *Init = Inits[InitIndex];
4110     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4111 
4112     // Scan forward to try to find this initializer in the idealized
4113     // initializers list.
4114     for (; IdealIndex != NumIdealInits; ++IdealIndex)
4115       if (InitKey == IdealInitKeys[IdealIndex])
4116         break;
4117 
4118     // If we didn't find this initializer, it must be because we
4119     // scanned past it on a previous iteration.  That can only
4120     // happen if we're out of order;  emit a warning.
4121     if (IdealIndex == NumIdealInits && PrevInit) {
4122       Sema::SemaDiagnosticBuilder D =
4123         SemaRef.Diag(PrevInit->getSourceLocation(),
4124                      diag::warn_initializer_out_of_order);
4125 
4126       if (PrevInit->isAnyMemberInitializer())
4127         D << 0 << PrevInit->getAnyMember()->getDeclName();
4128       else
4129         D << 1 << PrevInit->getTypeSourceInfo()->getType();
4130 
4131       if (Init->isAnyMemberInitializer())
4132         D << 0 << Init->getAnyMember()->getDeclName();
4133       else
4134         D << 1 << Init->getTypeSourceInfo()->getType();
4135 
4136       // Move back to the initializer's location in the ideal list.
4137       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4138         if (InitKey == IdealInitKeys[IdealIndex])
4139           break;
4140 
4141       assert(IdealIndex != NumIdealInits &&
4142              "initializer not found in initializer list");
4143     }
4144 
4145     PrevInit = Init;
4146   }
4147 }
4148 
4149 namespace {
4150 bool CheckRedundantInit(Sema &S,
4151                         CXXCtorInitializer *Init,
4152                         CXXCtorInitializer *&PrevInit) {
4153   if (!PrevInit) {
4154     PrevInit = Init;
4155     return false;
4156   }
4157 
4158   if (FieldDecl *Field = Init->getAnyMember())
4159     S.Diag(Init->getSourceLocation(),
4160            diag::err_multiple_mem_initialization)
4161       << Field->getDeclName()
4162       << Init->getSourceRange();
4163   else {
4164     const Type *BaseClass = Init->getBaseClass();
4165     assert(BaseClass && "neither field nor base");
4166     S.Diag(Init->getSourceLocation(),
4167            diag::err_multiple_base_initialization)
4168       << QualType(BaseClass, 0)
4169       << Init->getSourceRange();
4170   }
4171   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4172     << 0 << PrevInit->getSourceRange();
4173 
4174   return true;
4175 }
4176 
4177 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
4178 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4179 
4180 bool CheckRedundantUnionInit(Sema &S,
4181                              CXXCtorInitializer *Init,
4182                              RedundantUnionMap &Unions) {
4183   FieldDecl *Field = Init->getAnyMember();
4184   RecordDecl *Parent = Field->getParent();
4185   NamedDecl *Child = Field;
4186 
4187   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
4188     if (Parent->isUnion()) {
4189       UnionEntry &En = Unions[Parent];
4190       if (En.first && En.first != Child) {
4191         S.Diag(Init->getSourceLocation(),
4192                diag::err_multiple_mem_union_initialization)
4193           << Field->getDeclName()
4194           << Init->getSourceRange();
4195         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4196           << 0 << En.second->getSourceRange();
4197         return true;
4198       }
4199       if (!En.first) {
4200         En.first = Child;
4201         En.second = Init;
4202       }
4203       if (!Parent->isAnonymousStructOrUnion())
4204         return false;
4205     }
4206 
4207     Child = Parent;
4208     Parent = cast<RecordDecl>(Parent->getDeclContext());
4209   }
4210 
4211   return false;
4212 }
4213 }
4214 
4215 /// ActOnMemInitializers - Handle the member initializers for a constructor.
4216 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
4217                                 SourceLocation ColonLoc,
4218                                 ArrayRef<CXXCtorInitializer*> MemInits,
4219                                 bool AnyErrors) {
4220   if (!ConstructorDecl)
4221     return;
4222 
4223   AdjustDeclIfTemplate(ConstructorDecl);
4224 
4225   CXXConstructorDecl *Constructor
4226     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
4227 
4228   if (!Constructor) {
4229     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4230     return;
4231   }
4232 
4233   // Mapping for the duplicate initializers check.
4234   // For member initializers, this is keyed with a FieldDecl*.
4235   // For base initializers, this is keyed with a Type*.
4236   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
4237 
4238   // Mapping for the inconsistent anonymous-union initializers check.
4239   RedundantUnionMap MemberUnions;
4240 
4241   bool HadError = false;
4242   for (unsigned i = 0; i < MemInits.size(); i++) {
4243     CXXCtorInitializer *Init = MemInits[i];
4244 
4245     // Set the source order index.
4246     Init->setSourceOrder(i);
4247 
4248     if (Init->isAnyMemberInitializer()) {
4249       const void *Key = GetKeyForMember(Context, Init);
4250       if (CheckRedundantInit(*this, Init, Members[Key]) ||
4251           CheckRedundantUnionInit(*this, Init, MemberUnions))
4252         HadError = true;
4253     } else if (Init->isBaseInitializer()) {
4254       const void *Key = GetKeyForMember(Context, Init);
4255       if (CheckRedundantInit(*this, Init, Members[Key]))
4256         HadError = true;
4257     } else {
4258       assert(Init->isDelegatingInitializer());
4259       // This must be the only initializer
4260       if (MemInits.size() != 1) {
4261         Diag(Init->getSourceLocation(),
4262              diag::err_delegating_initializer_alone)
4263           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
4264         // We will treat this as being the only initializer.
4265       }
4266       SetDelegatingInitializer(Constructor, MemInits[i]);
4267       // Return immediately as the initializer is set.
4268       return;
4269     }
4270   }
4271 
4272   if (HadError)
4273     return;
4274 
4275   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
4276 
4277   SetCtorInitializers(Constructor, AnyErrors, MemInits);
4278 
4279   DiagnoseUninitializedFields(*this, Constructor);
4280 }
4281 
4282 void
4283 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
4284                                              CXXRecordDecl *ClassDecl) {
4285   // Ignore dependent contexts. Also ignore unions, since their members never
4286   // have destructors implicitly called.
4287   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
4288     return;
4289 
4290   // FIXME: all the access-control diagnostics are positioned on the
4291   // field/base declaration.  That's probably good; that said, the
4292   // user might reasonably want to know why the destructor is being
4293   // emitted, and we currently don't say.
4294 
4295   // Non-static data members.
4296   for (auto *Field : ClassDecl->fields()) {
4297     if (Field->isInvalidDecl())
4298       continue;
4299 
4300     // Don't destroy incomplete or zero-length arrays.
4301     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
4302       continue;
4303 
4304     QualType FieldType = Context.getBaseElementType(Field->getType());
4305 
4306     const RecordType* RT = FieldType->getAs<RecordType>();
4307     if (!RT)
4308       continue;
4309 
4310     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4311     if (FieldClassDecl->isInvalidDecl())
4312       continue;
4313     if (FieldClassDecl->hasIrrelevantDestructor())
4314       continue;
4315     // The destructor for an implicit anonymous union member is never invoked.
4316     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4317       continue;
4318 
4319     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
4320     assert(Dtor && "No dtor found for FieldClassDecl!");
4321     CheckDestructorAccess(Field->getLocation(), Dtor,
4322                           PDiag(diag::err_access_dtor_field)
4323                             << Field->getDeclName()
4324                             << FieldType);
4325 
4326     MarkFunctionReferenced(Location, Dtor);
4327     DiagnoseUseOfDecl(Dtor, Location);
4328   }
4329 
4330   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4331 
4332   // Bases.
4333   for (const auto &Base : ClassDecl->bases()) {
4334     // Bases are always records in a well-formed non-dependent class.
4335     const RecordType *RT = Base.getType()->getAs<RecordType>();
4336 
4337     // Remember direct virtual bases.
4338     if (Base.isVirtual())
4339       DirectVirtualBases.insert(RT);
4340 
4341     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4342     // If our base class is invalid, we probably can't get its dtor anyway.
4343     if (BaseClassDecl->isInvalidDecl())
4344       continue;
4345     if (BaseClassDecl->hasIrrelevantDestructor())
4346       continue;
4347 
4348     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4349     assert(Dtor && "No dtor found for BaseClassDecl!");
4350 
4351     // FIXME: caret should be on the start of the class name
4352     CheckDestructorAccess(Base.getLocStart(), Dtor,
4353                           PDiag(diag::err_access_dtor_base)
4354                             << Base.getType()
4355                             << Base.getSourceRange(),
4356                           Context.getTypeDeclType(ClassDecl));
4357 
4358     MarkFunctionReferenced(Location, Dtor);
4359     DiagnoseUseOfDecl(Dtor, Location);
4360   }
4361 
4362   // Virtual bases.
4363   for (const auto &VBase : ClassDecl->vbases()) {
4364     // Bases are always records in a well-formed non-dependent class.
4365     const RecordType *RT = VBase.getType()->castAs<RecordType>();
4366 
4367     // Ignore direct virtual bases.
4368     if (DirectVirtualBases.count(RT))
4369       continue;
4370 
4371     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4372     // If our base class is invalid, we probably can't get its dtor anyway.
4373     if (BaseClassDecl->isInvalidDecl())
4374       continue;
4375     if (BaseClassDecl->hasIrrelevantDestructor())
4376       continue;
4377 
4378     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4379     assert(Dtor && "No dtor found for BaseClassDecl!");
4380     if (CheckDestructorAccess(
4381             ClassDecl->getLocation(), Dtor,
4382             PDiag(diag::err_access_dtor_vbase)
4383                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
4384             Context.getTypeDeclType(ClassDecl)) ==
4385         AR_accessible) {
4386       CheckDerivedToBaseConversion(
4387           Context.getTypeDeclType(ClassDecl), VBase.getType(),
4388           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4389           SourceRange(), DeclarationName(), nullptr);
4390     }
4391 
4392     MarkFunctionReferenced(Location, Dtor);
4393     DiagnoseUseOfDecl(Dtor, Location);
4394   }
4395 }
4396 
4397 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
4398   if (!CDtorDecl)
4399     return;
4400 
4401   if (CXXConstructorDecl *Constructor
4402       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
4403     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
4404     DiagnoseUninitializedFields(*this, Constructor);
4405   }
4406 }
4407 
4408 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4409                                   unsigned DiagID, AbstractDiagSelID SelID) {
4410   class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4411     unsigned DiagID;
4412     AbstractDiagSelID SelID;
4413 
4414   public:
4415     NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4416       : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
4417 
4418     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
4419       if (Suppressed) return;
4420       if (SelID == -1)
4421         S.Diag(Loc, DiagID) << T;
4422       else
4423         S.Diag(Loc, DiagID) << SelID << T;
4424     }
4425   } Diagnoser(DiagID, SelID);
4426 
4427   return RequireNonAbstractType(Loc, T, Diagnoser);
4428 }
4429 
4430 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4431                                   TypeDiagnoser &Diagnoser) {
4432   if (!getLangOpts().CPlusPlus)
4433     return false;
4434 
4435   if (const ArrayType *AT = Context.getAsArrayType(T))
4436     return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4437 
4438   if (const PointerType *PT = T->getAs<PointerType>()) {
4439     // Find the innermost pointer type.
4440     while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
4441       PT = T;
4442 
4443     if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
4444       return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4445   }
4446 
4447   const RecordType *RT = T->getAs<RecordType>();
4448   if (!RT)
4449     return false;
4450 
4451   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4452 
4453   // We can't answer whether something is abstract until it has a
4454   // definition.  If it's currently being defined, we'll walk back
4455   // over all the declarations when we have a full definition.
4456   const CXXRecordDecl *Def = RD->getDefinition();
4457   if (!Def || Def->isBeingDefined())
4458     return false;
4459 
4460   if (!RD->isAbstract())
4461     return false;
4462 
4463   Diagnoser.diagnose(*this, Loc, T);
4464   DiagnoseAbstractType(RD);
4465 
4466   return true;
4467 }
4468 
4469 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4470   // Check if we've already emitted the list of pure virtual functions
4471   // for this class.
4472   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
4473     return;
4474 
4475   // If the diagnostic is suppressed, don't emit the notes. We're only
4476   // going to emit them once, so try to attach them to a diagnostic we're
4477   // actually going to show.
4478   if (Diags.isLastDiagnosticIgnored())
4479     return;
4480 
4481   CXXFinalOverriderMap FinalOverriders;
4482   RD->getFinalOverriders(FinalOverriders);
4483 
4484   // Keep a set of seen pure methods so we won't diagnose the same method
4485   // more than once.
4486   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4487 
4488   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4489                                    MEnd = FinalOverriders.end();
4490        M != MEnd;
4491        ++M) {
4492     for (OverridingMethods::iterator SO = M->second.begin(),
4493                                   SOEnd = M->second.end();
4494          SO != SOEnd; ++SO) {
4495       // C++ [class.abstract]p4:
4496       //   A class is abstract if it contains or inherits at least one
4497       //   pure virtual function for which the final overrider is pure
4498       //   virtual.
4499 
4500       //
4501       if (SO->second.size() != 1)
4502         continue;
4503 
4504       if (!SO->second.front().Method->isPure())
4505         continue;
4506 
4507       if (!SeenPureMethods.insert(SO->second.front().Method).second)
4508         continue;
4509 
4510       Diag(SO->second.front().Method->getLocation(),
4511            diag::note_pure_virtual_function)
4512         << SO->second.front().Method->getDeclName() << RD->getDeclName();
4513     }
4514   }
4515 
4516   if (!PureVirtualClassDiagSet)
4517     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4518   PureVirtualClassDiagSet->insert(RD);
4519 }
4520 
4521 namespace {
4522 struct AbstractUsageInfo {
4523   Sema &S;
4524   CXXRecordDecl *Record;
4525   CanQualType AbstractType;
4526   bool Invalid;
4527 
4528   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4529     : S(S), Record(Record),
4530       AbstractType(S.Context.getCanonicalType(
4531                    S.Context.getTypeDeclType(Record))),
4532       Invalid(false) {}
4533 
4534   void DiagnoseAbstractType() {
4535     if (Invalid) return;
4536     S.DiagnoseAbstractType(Record);
4537     Invalid = true;
4538   }
4539 
4540   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4541 };
4542 
4543 struct CheckAbstractUsage {
4544   AbstractUsageInfo &Info;
4545   const NamedDecl *Ctx;
4546 
4547   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4548     : Info(Info), Ctx(Ctx) {}
4549 
4550   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4551     switch (TL.getTypeLocClass()) {
4552 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4553 #define TYPELOC(CLASS, PARENT) \
4554     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
4555 #include "clang/AST/TypeLocNodes.def"
4556     }
4557   }
4558 
4559   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4560     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
4561     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4562       if (!TL.getParam(I))
4563         continue;
4564 
4565       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
4566       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
4567     }
4568   }
4569 
4570   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4571     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4572   }
4573 
4574   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4575     // Visit the type parameters from a permissive context.
4576     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4577       TemplateArgumentLoc TAL = TL.getArgLoc(I);
4578       if (TAL.getArgument().getKind() == TemplateArgument::Type)
4579         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4580           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4581       // TODO: other template argument types?
4582     }
4583   }
4584 
4585   // Visit pointee types from a permissive context.
4586 #define CheckPolymorphic(Type) \
4587   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4588     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4589   }
4590   CheckPolymorphic(PointerTypeLoc)
4591   CheckPolymorphic(ReferenceTypeLoc)
4592   CheckPolymorphic(MemberPointerTypeLoc)
4593   CheckPolymorphic(BlockPointerTypeLoc)
4594   CheckPolymorphic(AtomicTypeLoc)
4595 
4596   /// Handle all the types we haven't given a more specific
4597   /// implementation for above.
4598   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4599     // Every other kind of type that we haven't called out already
4600     // that has an inner type is either (1) sugar or (2) contains that
4601     // inner type in some way as a subobject.
4602     if (TypeLoc Next = TL.getNextTypeLoc())
4603       return Visit(Next, Sel);
4604 
4605     // If there's no inner type and we're in a permissive context,
4606     // don't diagnose.
4607     if (Sel == Sema::AbstractNone) return;
4608 
4609     // Check whether the type matches the abstract type.
4610     QualType T = TL.getType();
4611     if (T->isArrayType()) {
4612       Sel = Sema::AbstractArrayType;
4613       T = Info.S.Context.getBaseElementType(T);
4614     }
4615     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4616     if (CT != Info.AbstractType) return;
4617 
4618     // It matched; do some magic.
4619     if (Sel == Sema::AbstractArrayType) {
4620       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4621         << T << TL.getSourceRange();
4622     } else {
4623       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4624         << Sel << T << TL.getSourceRange();
4625     }
4626     Info.DiagnoseAbstractType();
4627   }
4628 };
4629 
4630 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4631                                   Sema::AbstractDiagSelID Sel) {
4632   CheckAbstractUsage(*this, D).Visit(TL, Sel);
4633 }
4634 
4635 }
4636 
4637 /// Check for invalid uses of an abstract type in a method declaration.
4638 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4639                                     CXXMethodDecl *MD) {
4640   // No need to do the check on definitions, which require that
4641   // the return/param types be complete.
4642   if (MD->doesThisDeclarationHaveABody())
4643     return;
4644 
4645   // For safety's sake, just ignore it if we don't have type source
4646   // information.  This should never happen for non-implicit methods,
4647   // but...
4648   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4649     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4650 }
4651 
4652 /// Check for invalid uses of an abstract type within a class definition.
4653 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4654                                     CXXRecordDecl *RD) {
4655   for (auto *D : RD->decls()) {
4656     if (D->isImplicit()) continue;
4657 
4658     // Methods and method templates.
4659     if (isa<CXXMethodDecl>(D)) {
4660       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4661     } else if (isa<FunctionTemplateDecl>(D)) {
4662       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4663       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4664 
4665     // Fields and static variables.
4666     } else if (isa<FieldDecl>(D)) {
4667       FieldDecl *FD = cast<FieldDecl>(D);
4668       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4669         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4670     } else if (isa<VarDecl>(D)) {
4671       VarDecl *VD = cast<VarDecl>(D);
4672       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4673         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4674 
4675     // Nested classes and class templates.
4676     } else if (isa<CXXRecordDecl>(D)) {
4677       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4678     } else if (isa<ClassTemplateDecl>(D)) {
4679       CheckAbstractClassUsage(Info,
4680                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4681     }
4682   }
4683 }
4684 
4685 /// \brief Check class-level dllimport/dllexport attribute.
4686 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
4687   Attr *ClassAttr = getDLLAttr(Class);
4688 
4689   // MSVC inherits DLL attributes to partial class template specializations.
4690   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
4691     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
4692       if (Attr *TemplateAttr =
4693               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
4694         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
4695         A->setInherited(true);
4696         ClassAttr = A;
4697       }
4698     }
4699   }
4700 
4701   if (!ClassAttr)
4702     return;
4703 
4704   if (!Class->isExternallyVisible()) {
4705     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
4706         << Class << ClassAttr;
4707     return;
4708   }
4709 
4710   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4711       !ClassAttr->isInherited()) {
4712     // Diagnose dll attributes on members of class with dll attribute.
4713     for (Decl *Member : Class->decls()) {
4714       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
4715         continue;
4716       InheritableAttr *MemberAttr = getDLLAttr(Member);
4717       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
4718         continue;
4719 
4720       Diag(MemberAttr->getLocation(),
4721              diag::err_attribute_dll_member_of_dll_class)
4722           << MemberAttr << ClassAttr;
4723       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
4724       Member->setInvalidDecl();
4725     }
4726   }
4727 
4728   if (Class->getDescribedClassTemplate())
4729     // Don't inherit dll attribute until the template is instantiated.
4730     return;
4731 
4732   // The class is either imported or exported.
4733   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4734   const bool ClassImported = !ClassExported;
4735 
4736   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
4737 
4738   // Ignore explicit dllexport on explicit class template instantiation declarations.
4739   if (ClassExported && !ClassAttr->isInherited() &&
4740       TSK == TSK_ExplicitInstantiationDeclaration) {
4741     Class->dropAttr<DLLExportAttr>();
4742     return;
4743   }
4744 
4745   // Force declaration of implicit members so they can inherit the attribute.
4746   ForceDeclarationOfImplicitMembers(Class);
4747 
4748   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4749   // seem to be true in practice?
4750 
4751   for (Decl *Member : Class->decls()) {
4752     VarDecl *VD = dyn_cast<VarDecl>(Member);
4753     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4754 
4755     // Only methods and static fields inherit the attributes.
4756     if (!VD && !MD)
4757       continue;
4758 
4759     if (MD) {
4760       // Don't process deleted methods.
4761       if (MD->isDeleted())
4762         continue;
4763 
4764       if (MD->isInlined()) {
4765         // MinGW does not import or export inline methods.
4766         if (!Context.getTargetInfo().getCXXABI().isMicrosoft())
4767           continue;
4768 
4769         // MSVC versions before 2015 don't export the move assignment operators,
4770         // so don't attempt to import them if we have a definition.
4771         if (ClassImported && MD->isMoveAssignmentOperator() &&
4772             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
4773           continue;
4774       }
4775     }
4776 
4777     if (!cast<NamedDecl>(Member)->isExternallyVisible())
4778       continue;
4779 
4780     if (!getDLLAttr(Member)) {
4781       auto *NewAttr =
4782           cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
4783       NewAttr->setInherited(true);
4784       Member->addAttr(NewAttr);
4785     }
4786 
4787     if (MD && ClassExported) {
4788       if (TSK == TSK_ExplicitInstantiationDeclaration)
4789         // Don't go any further if this is just an explicit instantiation
4790         // declaration.
4791         continue;
4792 
4793       if (MD->isUserProvided()) {
4794         // Instantiate non-default class member functions ...
4795 
4796         // .. except for certain kinds of template specializations.
4797         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
4798           continue;
4799 
4800         MarkFunctionReferenced(Class->getLocation(), MD);
4801 
4802         // The function will be passed to the consumer when its definition is
4803         // encountered.
4804       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4805                  MD->isCopyAssignmentOperator() ||
4806                  MD->isMoveAssignmentOperator()) {
4807         // Synthesize and instantiate non-trivial implicit methods, explicitly
4808         // defaulted methods, and the copy and move assignment operators. The
4809         // latter are exported even if they are trivial, because the address of
4810         // an operator can be taken and should compare equal accross libraries.
4811         DiagnosticErrorTrap Trap(Diags);
4812         MarkFunctionReferenced(Class->getLocation(), MD);
4813         if (Trap.hasErrorOccurred()) {
4814           Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
4815               << Class->getName() << !getLangOpts().CPlusPlus11;
4816           break;
4817         }
4818 
4819         // There is no later point when we will see the definition of this
4820         // function, so pass it to the consumer now.
4821         Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
4822       }
4823     }
4824   }
4825 }
4826 
4827 /// \brief Perform propagation of DLL attributes from a derived class to a
4828 /// templated base class for MS compatibility.
4829 void Sema::propagateDLLAttrToBaseClassTemplate(
4830     CXXRecordDecl *Class, Attr *ClassAttr,
4831     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
4832   if (getDLLAttr(
4833           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
4834     // If the base class template has a DLL attribute, don't try to change it.
4835     return;
4836   }
4837 
4838   auto TSK = BaseTemplateSpec->getSpecializationKind();
4839   if (!getDLLAttr(BaseTemplateSpec) &&
4840       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
4841        TSK == TSK_ImplicitInstantiation)) {
4842     // The template hasn't been instantiated yet (or it has, but only as an
4843     // explicit instantiation declaration or implicit instantiation, which means
4844     // we haven't codegenned any members yet), so propagate the attribute.
4845     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
4846     NewAttr->setInherited(true);
4847     BaseTemplateSpec->addAttr(NewAttr);
4848 
4849     // If the template is already instantiated, checkDLLAttributeRedeclaration()
4850     // needs to be run again to work see the new attribute. Otherwise this will
4851     // get run whenever the template is instantiated.
4852     if (TSK != TSK_Undeclared)
4853       checkClassLevelDLLAttribute(BaseTemplateSpec);
4854 
4855     return;
4856   }
4857 
4858   if (getDLLAttr(BaseTemplateSpec)) {
4859     // The template has already been specialized or instantiated with an
4860     // attribute, explicitly or through propagation. We should not try to change
4861     // it.
4862     return;
4863   }
4864 
4865   // The template was previously instantiated or explicitly specialized without
4866   // a dll attribute, It's too late for us to add an attribute, so warn that
4867   // this is unsupported.
4868   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
4869       << BaseTemplateSpec->isExplicitSpecialization();
4870   Diag(ClassAttr->getLocation(), diag::note_attribute);
4871   if (BaseTemplateSpec->isExplicitSpecialization()) {
4872     Diag(BaseTemplateSpec->getLocation(),
4873            diag::note_template_class_explicit_specialization_was_here)
4874         << BaseTemplateSpec;
4875   } else {
4876     Diag(BaseTemplateSpec->getPointOfInstantiation(),
4877            diag::note_template_class_instantiation_was_here)
4878         << BaseTemplateSpec;
4879   }
4880 }
4881 
4882 /// \brief Perform semantic checks on a class definition that has been
4883 /// completing, introducing implicitly-declared members, checking for
4884 /// abstract types, etc.
4885 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
4886   if (!Record)
4887     return;
4888 
4889   if (Record->isAbstract() && !Record->isInvalidDecl()) {
4890     AbstractUsageInfo Info(*this, Record);
4891     CheckAbstractClassUsage(Info, Record);
4892   }
4893 
4894   // If this is not an aggregate type and has no user-declared constructor,
4895   // complain about any non-static data members of reference or const scalar
4896   // type, since they will never get initializers.
4897   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
4898       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4899       !Record->isLambda()) {
4900     bool Complained = false;
4901     for (const auto *F : Record->fields()) {
4902       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
4903         continue;
4904 
4905       if (F->getType()->isReferenceType() ||
4906           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
4907         if (!Complained) {
4908           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4909             << Record->getTagKind() << Record;
4910           Complained = true;
4911         }
4912 
4913         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4914           << F->getType()->isReferenceType()
4915           << F->getDeclName();
4916       }
4917     }
4918   }
4919 
4920   if (Record->getIdentifier()) {
4921     // C++ [class.mem]p13:
4922     //   If T is the name of a class, then each of the following shall have a
4923     //   name different from T:
4924     //     - every member of every anonymous union that is a member of class T.
4925     //
4926     // C++ [class.mem]p14:
4927     //   In addition, if class T has a user-declared constructor (12.1), every
4928     //   non-static data member of class T shall have a name different from T.
4929     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4930     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4931          ++I) {
4932       NamedDecl *D = *I;
4933       if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4934           isa<IndirectFieldDecl>(D)) {
4935         Diag(D->getLocation(), diag::err_member_name_of_class)
4936           << D->getDeclName();
4937         break;
4938       }
4939     }
4940   }
4941 
4942   // Warn if the class has virtual methods but non-virtual public destructor.
4943   if (Record->isPolymorphic() && !Record->isDependentType()) {
4944     CXXDestructorDecl *dtor = Record->getDestructor();
4945     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4946         !Record->hasAttr<FinalAttr>())
4947       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4948            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4949   }
4950 
4951   if (Record->isAbstract()) {
4952     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4953       Diag(Record->getLocation(), diag::warn_abstract_final_class)
4954         << FA->isSpelledAsSealed();
4955       DiagnoseAbstractType(Record);
4956     }
4957   }
4958 
4959   bool HasMethodWithOverrideControl = false,
4960        HasOverridingMethodWithoutOverrideControl = false;
4961   if (!Record->isDependentType()) {
4962     for (auto *M : Record->methods()) {
4963       // See if a method overloads virtual methods in a base
4964       // class without overriding any.
4965       if (!M->isStatic())
4966         DiagnoseHiddenVirtualMethods(M);
4967       if (M->hasAttr<OverrideAttr>())
4968         HasMethodWithOverrideControl = true;
4969       else if (M->size_overridden_methods() > 0)
4970         HasOverridingMethodWithoutOverrideControl = true;
4971       // Check whether the explicitly-defaulted special members are valid.
4972       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4973         CheckExplicitlyDefaultedSpecialMember(M);
4974 
4975       // For an explicitly defaulted or deleted special member, we defer
4976       // determining triviality until the class is complete. That time is now!
4977       if (!M->isImplicit() && !M->isUserProvided()) {
4978         CXXSpecialMember CSM = getSpecialMember(M);
4979         if (CSM != CXXInvalid) {
4980           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
4981 
4982           // Inform the class that we've finished declaring this member.
4983           Record->finishedDefaultedOrDeletedMember(M);
4984         }
4985       }
4986     }
4987   }
4988 
4989   if (HasMethodWithOverrideControl &&
4990       HasOverridingMethodWithoutOverrideControl) {
4991     // At least one method has the 'override' control declared.
4992     // Diagnose all other overridden methods which do not have 'override' specified on them.
4993     for (auto *M : Record->methods())
4994       DiagnoseAbsenceOfOverrideControl(M);
4995   }
4996 
4997   // ms_struct is a request to use the same ABI rules as MSVC.  Check
4998   // whether this class uses any C++ features that are implemented
4999   // completely differently in MSVC, and if so, emit a diagnostic.
5000   // That diagnostic defaults to an error, but we allow projects to
5001   // map it down to a warning (or ignore it).  It's a fairly common
5002   // practice among users of the ms_struct pragma to mass-annotate
5003   // headers, sweeping up a bunch of types that the project doesn't
5004   // really rely on MSVC-compatible layout for.  We must therefore
5005   // support "ms_struct except for C++ stuff" as a secondary ABI.
5006   if (Record->isMsStruct(Context) &&
5007       (Record->isPolymorphic() || Record->getNumBases())) {
5008     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
5009   }
5010 
5011   // Declare inheriting constructors. We do this eagerly here because:
5012   // - The standard requires an eager diagnostic for conflicting inheriting
5013   //   constructors from different classes.
5014   // - The lazy declaration of the other implicit constructors is so as to not
5015   //   waste space and performance on classes that are not meant to be
5016   //   instantiated (e.g. meta-functions). This doesn't apply to classes that
5017   //   have inheriting constructors.
5018   DeclareInheritingConstructors(Record);
5019 
5020   checkClassLevelDLLAttribute(Record);
5021 }
5022 
5023 /// Look up the special member function that would be called by a special
5024 /// member function for a subobject of class type.
5025 ///
5026 /// \param Class The class type of the subobject.
5027 /// \param CSM The kind of special member function.
5028 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
5029 /// \param ConstRHS True if this is a copy operation with a const object
5030 ///        on its RHS, that is, if the argument to the outer special member
5031 ///        function is 'const' and this is not a field marked 'mutable'.
5032 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
5033     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
5034     unsigned FieldQuals, bool ConstRHS) {
5035   unsigned LHSQuals = 0;
5036   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
5037     LHSQuals = FieldQuals;
5038 
5039   unsigned RHSQuals = FieldQuals;
5040   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
5041     RHSQuals = 0;
5042   else if (ConstRHS)
5043     RHSQuals |= Qualifiers::Const;
5044 
5045   return S.LookupSpecialMember(Class, CSM,
5046                                RHSQuals & Qualifiers::Const,
5047                                RHSQuals & Qualifiers::Volatile,
5048                                false,
5049                                LHSQuals & Qualifiers::Const,
5050                                LHSQuals & Qualifiers::Volatile);
5051 }
5052 
5053 /// Is the special member function which would be selected to perform the
5054 /// specified operation on the specified class type a constexpr constructor?
5055 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5056                                      Sema::CXXSpecialMember CSM,
5057                                      unsigned Quals, bool ConstRHS) {
5058   Sema::SpecialMemberOverloadResult *SMOR =
5059       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
5060   if (!SMOR || !SMOR->getMethod())
5061     // A constructor we wouldn't select can't be "involved in initializing"
5062     // anything.
5063     return true;
5064   return SMOR->getMethod()->isConstexpr();
5065 }
5066 
5067 /// Determine whether the specified special member function would be constexpr
5068 /// if it were implicitly defined.
5069 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5070                                               Sema::CXXSpecialMember CSM,
5071                                               bool ConstArg) {
5072   if (!S.getLangOpts().CPlusPlus11)
5073     return false;
5074 
5075   // C++11 [dcl.constexpr]p4:
5076   // In the definition of a constexpr constructor [...]
5077   bool Ctor = true;
5078   switch (CSM) {
5079   case Sema::CXXDefaultConstructor:
5080     // Since default constructor lookup is essentially trivial (and cannot
5081     // involve, for instance, template instantiation), we compute whether a
5082     // defaulted default constructor is constexpr directly within CXXRecordDecl.
5083     //
5084     // This is important for performance; we need to know whether the default
5085     // constructor is constexpr to determine whether the type is a literal type.
5086     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
5087 
5088   case Sema::CXXCopyConstructor:
5089   case Sema::CXXMoveConstructor:
5090     // For copy or move constructors, we need to perform overload resolution.
5091     break;
5092 
5093   case Sema::CXXCopyAssignment:
5094   case Sema::CXXMoveAssignment:
5095     if (!S.getLangOpts().CPlusPlus14)
5096       return false;
5097     // In C++1y, we need to perform overload resolution.
5098     Ctor = false;
5099     break;
5100 
5101   case Sema::CXXDestructor:
5102   case Sema::CXXInvalid:
5103     return false;
5104   }
5105 
5106   //   -- if the class is a non-empty union, or for each non-empty anonymous
5107   //      union member of a non-union class, exactly one non-static data member
5108   //      shall be initialized; [DR1359]
5109   //
5110   // If we squint, this is guaranteed, since exactly one non-static data member
5111   // will be initialized (if the constructor isn't deleted), we just don't know
5112   // which one.
5113   if (Ctor && ClassDecl->isUnion())
5114     return true;
5115 
5116   //   -- the class shall not have any virtual base classes;
5117   if (Ctor && ClassDecl->getNumVBases())
5118     return false;
5119 
5120   // C++1y [class.copy]p26:
5121   //   -- [the class] is a literal type, and
5122   if (!Ctor && !ClassDecl->isLiteral())
5123     return false;
5124 
5125   //   -- every constructor involved in initializing [...] base class
5126   //      sub-objects shall be a constexpr constructor;
5127   //   -- the assignment operator selected to copy/move each direct base
5128   //      class is a constexpr function, and
5129   for (const auto &B : ClassDecl->bases()) {
5130     const RecordType *BaseType = B.getType()->getAs<RecordType>();
5131     if (!BaseType) continue;
5132 
5133     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
5134     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
5135       return false;
5136   }
5137 
5138   //   -- every constructor involved in initializing non-static data members
5139   //      [...] shall be a constexpr constructor;
5140   //   -- every non-static data member and base class sub-object shall be
5141   //      initialized
5142   //   -- for each non-static data member of X that is of class type (or array
5143   //      thereof), the assignment operator selected to copy/move that member is
5144   //      a constexpr function
5145   for (const auto *F : ClassDecl->fields()) {
5146     if (F->isInvalidDecl())
5147       continue;
5148     QualType BaseType = S.Context.getBaseElementType(F->getType());
5149     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
5150       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5151       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
5152                                     BaseType.getCVRQualifiers(),
5153                                     ConstArg && !F->isMutable()))
5154         return false;
5155     }
5156   }
5157 
5158   // All OK, it's constexpr!
5159   return true;
5160 }
5161 
5162 static Sema::ImplicitExceptionSpecification
5163 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
5164   switch (S.getSpecialMember(MD)) {
5165   case Sema::CXXDefaultConstructor:
5166     return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
5167   case Sema::CXXCopyConstructor:
5168     return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
5169   case Sema::CXXCopyAssignment:
5170     return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
5171   case Sema::CXXMoveConstructor:
5172     return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
5173   case Sema::CXXMoveAssignment:
5174     return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
5175   case Sema::CXXDestructor:
5176     return S.ComputeDefaultedDtorExceptionSpec(MD);
5177   case Sema::CXXInvalid:
5178     break;
5179   }
5180   assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
5181          "only special members have implicit exception specs");
5182   return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
5183 }
5184 
5185 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
5186                                                             CXXMethodDecl *MD) {
5187   FunctionProtoType::ExtProtoInfo EPI;
5188 
5189   // Build an exception specification pointing back at this member.
5190   EPI.ExceptionSpec.Type = EST_Unevaluated;
5191   EPI.ExceptionSpec.SourceDecl = MD;
5192 
5193   // Set the calling convention to the default for C++ instance methods.
5194   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
5195       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5196                                             /*IsCXXMethod=*/true));
5197   return EPI;
5198 }
5199 
5200 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
5201   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
5202   if (FPT->getExceptionSpecType() != EST_Unevaluated)
5203     return;
5204 
5205   // Evaluate the exception specification.
5206   auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
5207 
5208   // Update the type of the special member to use it.
5209   UpdateExceptionSpec(MD, ESI);
5210 
5211   // A user-provided destructor can be defined outside the class. When that
5212   // happens, be sure to update the exception specification on both
5213   // declarations.
5214   const FunctionProtoType *CanonicalFPT =
5215     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
5216   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
5217     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
5218 }
5219 
5220 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
5221   CXXRecordDecl *RD = MD->getParent();
5222   CXXSpecialMember CSM = getSpecialMember(MD);
5223 
5224   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
5225          "not an explicitly-defaulted special member");
5226 
5227   // Whether this was the first-declared instance of the constructor.
5228   // This affects whether we implicitly add an exception spec and constexpr.
5229   bool First = MD == MD->getCanonicalDecl();
5230 
5231   bool HadError = false;
5232 
5233   // C++11 [dcl.fct.def.default]p1:
5234   //   A function that is explicitly defaulted shall
5235   //     -- be a special member function (checked elsewhere),
5236   //     -- have the same type (except for ref-qualifiers, and except that a
5237   //        copy operation can take a non-const reference) as an implicit
5238   //        declaration, and
5239   //     -- not have default arguments.
5240   unsigned ExpectedParams = 1;
5241   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
5242     ExpectedParams = 0;
5243   if (MD->getNumParams() != ExpectedParams) {
5244     // This also checks for default arguments: a copy or move constructor with a
5245     // default argument is classified as a default constructor, and assignment
5246     // operations and destructors can't have default arguments.
5247     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
5248       << CSM << MD->getSourceRange();
5249     HadError = true;
5250   } else if (MD->isVariadic()) {
5251     Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
5252       << CSM << MD->getSourceRange();
5253     HadError = true;
5254   }
5255 
5256   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
5257 
5258   bool CanHaveConstParam = false;
5259   if (CSM == CXXCopyConstructor)
5260     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
5261   else if (CSM == CXXCopyAssignment)
5262     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
5263 
5264   QualType ReturnType = Context.VoidTy;
5265   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
5266     // Check for return type matching.
5267     ReturnType = Type->getReturnType();
5268     QualType ExpectedReturnType =
5269         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
5270     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
5271       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
5272         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
5273       HadError = true;
5274     }
5275 
5276     // A defaulted special member cannot have cv-qualifiers.
5277     if (Type->getTypeQuals()) {
5278       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
5279         << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
5280       HadError = true;
5281     }
5282   }
5283 
5284   // Check for parameter type matching.
5285   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
5286   bool HasConstParam = false;
5287   if (ExpectedParams && ArgType->isReferenceType()) {
5288     // Argument must be reference to possibly-const T.
5289     QualType ReferentType = ArgType->getPointeeType();
5290     HasConstParam = ReferentType.isConstQualified();
5291 
5292     if (ReferentType.isVolatileQualified()) {
5293       Diag(MD->getLocation(),
5294            diag::err_defaulted_special_member_volatile_param) << CSM;
5295       HadError = true;
5296     }
5297 
5298     if (HasConstParam && !CanHaveConstParam) {
5299       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
5300         Diag(MD->getLocation(),
5301              diag::err_defaulted_special_member_copy_const_param)
5302           << (CSM == CXXCopyAssignment);
5303         // FIXME: Explain why this special member can't be const.
5304       } else {
5305         Diag(MD->getLocation(),
5306              diag::err_defaulted_special_member_move_const_param)
5307           << (CSM == CXXMoveAssignment);
5308       }
5309       HadError = true;
5310     }
5311   } else if (ExpectedParams) {
5312     // A copy assignment operator can take its argument by value, but a
5313     // defaulted one cannot.
5314     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
5315     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
5316     HadError = true;
5317   }
5318 
5319   // C++11 [dcl.fct.def.default]p2:
5320   //   An explicitly-defaulted function may be declared constexpr only if it
5321   //   would have been implicitly declared as constexpr,
5322   // Do not apply this rule to members of class templates, since core issue 1358
5323   // makes such functions always instantiate to constexpr functions. For
5324   // functions which cannot be constexpr (for non-constructors in C++11 and for
5325   // destructors in C++1y), this is checked elsewhere.
5326   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
5327                                                      HasConstParam);
5328   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
5329                                  : isa<CXXConstructorDecl>(MD)) &&
5330       MD->isConstexpr() && !Constexpr &&
5331       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
5332     Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
5333     // FIXME: Explain why the special member can't be constexpr.
5334     HadError = true;
5335   }
5336 
5337   //   and may have an explicit exception-specification only if it is compatible
5338   //   with the exception-specification on the implicit declaration.
5339   if (Type->hasExceptionSpec()) {
5340     // Delay the check if this is the first declaration of the special member,
5341     // since we may not have parsed some necessary in-class initializers yet.
5342     if (First) {
5343       // If the exception specification needs to be instantiated, do so now,
5344       // before we clobber it with an EST_Unevaluated specification below.
5345       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
5346         InstantiateExceptionSpec(MD->getLocStart(), MD);
5347         Type = MD->getType()->getAs<FunctionProtoType>();
5348       }
5349       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
5350     } else
5351       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
5352   }
5353 
5354   //   If a function is explicitly defaulted on its first declaration,
5355   if (First) {
5356     //  -- it is implicitly considered to be constexpr if the implicit
5357     //     definition would be,
5358     MD->setConstexpr(Constexpr);
5359 
5360     //  -- it is implicitly considered to have the same exception-specification
5361     //     as if it had been implicitly declared,
5362     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
5363     EPI.ExceptionSpec.Type = EST_Unevaluated;
5364     EPI.ExceptionSpec.SourceDecl = MD;
5365     MD->setType(Context.getFunctionType(ReturnType,
5366                                         llvm::makeArrayRef(&ArgType,
5367                                                            ExpectedParams),
5368                                         EPI));
5369   }
5370 
5371   if (ShouldDeleteSpecialMember(MD, CSM)) {
5372     if (First) {
5373       SetDeclDeleted(MD, MD->getLocation());
5374     } else {
5375       // C++11 [dcl.fct.def.default]p4:
5376       //   [For a] user-provided explicitly-defaulted function [...] if such a
5377       //   function is implicitly defined as deleted, the program is ill-formed.
5378       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
5379       ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
5380       HadError = true;
5381     }
5382   }
5383 
5384   if (HadError)
5385     MD->setInvalidDecl();
5386 }
5387 
5388 /// Check whether the exception specification provided for an
5389 /// explicitly-defaulted special member matches the exception specification
5390 /// that would have been generated for an implicit special member, per
5391 /// C++11 [dcl.fct.def.default]p2.
5392 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
5393     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
5394   // If the exception specification was explicitly specified but hadn't been
5395   // parsed when the method was defaulted, grab it now.
5396   if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
5397     SpecifiedType =
5398         MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
5399 
5400   // Compute the implicit exception specification.
5401   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5402                                                        /*IsCXXMethod=*/true);
5403   FunctionProtoType::ExtProtoInfo EPI(CC);
5404   EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
5405                           .getExceptionSpec();
5406   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
5407     Context.getFunctionType(Context.VoidTy, None, EPI));
5408 
5409   // Ensure that it matches.
5410   CheckEquivalentExceptionSpec(
5411     PDiag(diag::err_incorrect_defaulted_exception_spec)
5412       << getSpecialMember(MD), PDiag(),
5413     ImplicitType, SourceLocation(),
5414     SpecifiedType, MD->getLocation());
5415 }
5416 
5417 void Sema::CheckDelayedMemberExceptionSpecs() {
5418   decltype(DelayedExceptionSpecChecks) Checks;
5419   decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
5420 
5421   std::swap(Checks, DelayedExceptionSpecChecks);
5422   std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
5423 
5424   // Perform any deferred checking of exception specifications for virtual
5425   // destructors.
5426   for (auto &Check : Checks)
5427     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
5428 
5429   // Check that any explicitly-defaulted methods have exception specifications
5430   // compatible with their implicit exception specifications.
5431   for (auto &Spec : Specs)
5432     CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
5433 }
5434 
5435 namespace {
5436 struct SpecialMemberDeletionInfo {
5437   Sema &S;
5438   CXXMethodDecl *MD;
5439   Sema::CXXSpecialMember CSM;
5440   bool Diagnose;
5441 
5442   // Properties of the special member, computed for convenience.
5443   bool IsConstructor, IsAssignment, IsMove, ConstArg;
5444   SourceLocation Loc;
5445 
5446   bool AllFieldsAreConst;
5447 
5448   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
5449                             Sema::CXXSpecialMember CSM, bool Diagnose)
5450     : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
5451       IsConstructor(false), IsAssignment(false), IsMove(false),
5452       ConstArg(false), Loc(MD->getLocation()),
5453       AllFieldsAreConst(true) {
5454     switch (CSM) {
5455       case Sema::CXXDefaultConstructor:
5456       case Sema::CXXCopyConstructor:
5457         IsConstructor = true;
5458         break;
5459       case Sema::CXXMoveConstructor:
5460         IsConstructor = true;
5461         IsMove = true;
5462         break;
5463       case Sema::CXXCopyAssignment:
5464         IsAssignment = true;
5465         break;
5466       case Sema::CXXMoveAssignment:
5467         IsAssignment = true;
5468         IsMove = true;
5469         break;
5470       case Sema::CXXDestructor:
5471         break;
5472       case Sema::CXXInvalid:
5473         llvm_unreachable("invalid special member kind");
5474     }
5475 
5476     if (MD->getNumParams()) {
5477       if (const ReferenceType *RT =
5478               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5479         ConstArg = RT->getPointeeType().isConstQualified();
5480     }
5481   }
5482 
5483   bool inUnion() const { return MD->getParent()->isUnion(); }
5484 
5485   /// Look up the corresponding special member in the given class.
5486   Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
5487                                               unsigned Quals, bool IsMutable) {
5488     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5489                                        ConstArg && !IsMutable);
5490   }
5491 
5492   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
5493 
5494   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
5495   bool shouldDeleteForField(FieldDecl *FD);
5496   bool shouldDeleteForAllConstMembers();
5497 
5498   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5499                                      unsigned Quals);
5500   bool shouldDeleteForSubobjectCall(Subobject Subobj,
5501                                     Sema::SpecialMemberOverloadResult *SMOR,
5502                                     bool IsDtorCallInCtor);
5503 
5504   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
5505 };
5506 }
5507 
5508 /// Is the given special member inaccessible when used on the given
5509 /// sub-object.
5510 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5511                                              CXXMethodDecl *target) {
5512   /// If we're operating on a base class, the object type is the
5513   /// type of this special member.
5514   QualType objectTy;
5515   AccessSpecifier access = target->getAccess();
5516   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5517     objectTy = S.Context.getTypeDeclType(MD->getParent());
5518     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5519 
5520   // If we're operating on a field, the object type is the type of the field.
5521   } else {
5522     objectTy = S.Context.getTypeDeclType(target->getParent());
5523   }
5524 
5525   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5526 }
5527 
5528 /// Check whether we should delete a special member due to the implicit
5529 /// definition containing a call to a special member of a subobject.
5530 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5531     Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5532     bool IsDtorCallInCtor) {
5533   CXXMethodDecl *Decl = SMOR->getMethod();
5534   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5535 
5536   int DiagKind = -1;
5537 
5538   if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5539     DiagKind = !Decl ? 0 : 1;
5540   else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5541     DiagKind = 2;
5542   else if (!isAccessible(Subobj, Decl))
5543     DiagKind = 3;
5544   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5545            !Decl->isTrivial()) {
5546     // A member of a union must have a trivial corresponding special member.
5547     // As a weird special case, a destructor call from a union's constructor
5548     // must be accessible and non-deleted, but need not be trivial. Such a
5549     // destructor is never actually called, but is semantically checked as
5550     // if it were.
5551     DiagKind = 4;
5552   }
5553 
5554   if (DiagKind == -1)
5555     return false;
5556 
5557   if (Diagnose) {
5558     if (Field) {
5559       S.Diag(Field->getLocation(),
5560              diag::note_deleted_special_member_class_subobject)
5561         << CSM << MD->getParent() << /*IsField*/true
5562         << Field << DiagKind << IsDtorCallInCtor;
5563     } else {
5564       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5565       S.Diag(Base->getLocStart(),
5566              diag::note_deleted_special_member_class_subobject)
5567         << CSM << MD->getParent() << /*IsField*/false
5568         << Base->getType() << DiagKind << IsDtorCallInCtor;
5569     }
5570 
5571     if (DiagKind == 1)
5572       S.NoteDeletedFunction(Decl);
5573     // FIXME: Explain inaccessibility if DiagKind == 3.
5574   }
5575 
5576   return true;
5577 }
5578 
5579 /// Check whether we should delete a special member function due to having a
5580 /// direct or virtual base class or non-static data member of class type M.
5581 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
5582     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
5583   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5584   bool IsMutable = Field && Field->isMutable();
5585 
5586   // C++11 [class.ctor]p5:
5587   // -- any direct or virtual base class, or non-static data member with no
5588   //    brace-or-equal-initializer, has class type M (or array thereof) and
5589   //    either M has no default constructor or overload resolution as applied
5590   //    to M's default constructor results in an ambiguity or in a function
5591   //    that is deleted or inaccessible
5592   // C++11 [class.copy]p11, C++11 [class.copy]p23:
5593   // -- a direct or virtual base class B that cannot be copied/moved because
5594   //    overload resolution, as applied to B's corresponding special member,
5595   //    results in an ambiguity or a function that is deleted or inaccessible
5596   //    from the defaulted special member
5597   // C++11 [class.dtor]p5:
5598   // -- any direct or virtual base class [...] has a type with a destructor
5599   //    that is deleted or inaccessible
5600   if (!(CSM == Sema::CXXDefaultConstructor &&
5601         Field && Field->hasInClassInitializer()) &&
5602       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5603                                    false))
5604     return true;
5605 
5606   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5607   // -- any direct or virtual base class or non-static data member has a
5608   //    type with a destructor that is deleted or inaccessible
5609   if (IsConstructor) {
5610     Sema::SpecialMemberOverloadResult *SMOR =
5611         S.LookupSpecialMember(Class, Sema::CXXDestructor,
5612                               false, false, false, false, false);
5613     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5614       return true;
5615   }
5616 
5617   return false;
5618 }
5619 
5620 /// Check whether we should delete a special member function due to the class
5621 /// having a particular direct or virtual base class.
5622 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
5623   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
5624   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
5625 }
5626 
5627 /// Check whether we should delete a special member function due to the class
5628 /// having a particular non-static data member.
5629 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5630   QualType FieldType = S.Context.getBaseElementType(FD->getType());
5631   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5632 
5633   if (CSM == Sema::CXXDefaultConstructor) {
5634     // For a default constructor, all references must be initialized in-class
5635     // and, if a union, it must have a non-const member.
5636     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5637       if (Diagnose)
5638         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5639           << MD->getParent() << FD << FieldType << /*Reference*/0;
5640       return true;
5641     }
5642     // C++11 [class.ctor]p5: any non-variant non-static data member of
5643     // const-qualified type (or array thereof) with no
5644     // brace-or-equal-initializer does not have a user-provided default
5645     // constructor.
5646     if (!inUnion() && FieldType.isConstQualified() &&
5647         !FD->hasInClassInitializer() &&
5648         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5649       if (Diagnose)
5650         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5651           << MD->getParent() << FD << FD->getType() << /*Const*/1;
5652       return true;
5653     }
5654 
5655     if (inUnion() && !FieldType.isConstQualified())
5656       AllFieldsAreConst = false;
5657   } else if (CSM == Sema::CXXCopyConstructor) {
5658     // For a copy constructor, data members must not be of rvalue reference
5659     // type.
5660     if (FieldType->isRValueReferenceType()) {
5661       if (Diagnose)
5662         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5663           << MD->getParent() << FD << FieldType;
5664       return true;
5665     }
5666   } else if (IsAssignment) {
5667     // For an assignment operator, data members must not be of reference type.
5668     if (FieldType->isReferenceType()) {
5669       if (Diagnose)
5670         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5671           << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
5672       return true;
5673     }
5674     if (!FieldRecord && FieldType.isConstQualified()) {
5675       // C++11 [class.copy]p23:
5676       // -- a non-static data member of const non-class type (or array thereof)
5677       if (Diagnose)
5678         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5679           << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
5680       return true;
5681     }
5682   }
5683 
5684   if (FieldRecord) {
5685     // Some additional restrictions exist on the variant members.
5686     if (!inUnion() && FieldRecord->isUnion() &&
5687         FieldRecord->isAnonymousStructOrUnion()) {
5688       bool AllVariantFieldsAreConst = true;
5689 
5690       // FIXME: Handle anonymous unions declared within anonymous unions.
5691       for (auto *UI : FieldRecord->fields()) {
5692         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
5693 
5694         if (!UnionFieldType.isConstQualified())
5695           AllVariantFieldsAreConst = false;
5696 
5697         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5698         if (UnionFieldRecord &&
5699             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
5700                                           UnionFieldType.getCVRQualifiers()))
5701           return true;
5702       }
5703 
5704       // At least one member in each anonymous union must be non-const
5705       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
5706           !FieldRecord->field_empty()) {
5707         if (Diagnose)
5708           S.Diag(FieldRecord->getLocation(),
5709                  diag::note_deleted_default_ctor_all_const)
5710             << MD->getParent() << /*anonymous union*/1;
5711         return true;
5712       }
5713 
5714       // Don't check the implicit member of the anonymous union type.
5715       // This is technically non-conformant, but sanity demands it.
5716       return false;
5717     }
5718 
5719     if (shouldDeleteForClassSubobject(FieldRecord, FD,
5720                                       FieldType.getCVRQualifiers()))
5721       return true;
5722   }
5723 
5724   return false;
5725 }
5726 
5727 /// C++11 [class.ctor] p5:
5728 ///   A defaulted default constructor for a class X is defined as deleted if
5729 /// X is a union and all of its variant members are of const-qualified type.
5730 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
5731   // This is a silly definition, because it gives an empty union a deleted
5732   // default constructor. Don't do that.
5733   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5734       !MD->getParent()->field_empty()) {
5735     if (Diagnose)
5736       S.Diag(MD->getParent()->getLocation(),
5737              diag::note_deleted_default_ctor_all_const)
5738         << MD->getParent() << /*not anonymous union*/0;
5739     return true;
5740   }
5741   return false;
5742 }
5743 
5744 /// Determine whether a defaulted special member function should be defined as
5745 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5746 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
5747 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5748                                      bool Diagnose) {
5749   if (MD->isInvalidDecl())
5750     return false;
5751   CXXRecordDecl *RD = MD->getParent();
5752   assert(!RD->isDependentType() && "do deletion after instantiation");
5753   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
5754     return false;
5755 
5756   // C++11 [expr.lambda.prim]p19:
5757   //   The closure type associated with a lambda-expression has a
5758   //   deleted (8.4.3) default constructor and a deleted copy
5759   //   assignment operator.
5760   if (RD->isLambda() &&
5761       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5762     if (Diagnose)
5763       Diag(RD->getLocation(), diag::note_lambda_decl);
5764     return true;
5765   }
5766 
5767   // For an anonymous struct or union, the copy and assignment special members
5768   // will never be used, so skip the check. For an anonymous union declared at
5769   // namespace scope, the constructor and destructor are used.
5770   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5771       RD->isAnonymousStructOrUnion())
5772     return false;
5773 
5774   // C++11 [class.copy]p7, p18:
5775   //   If the class definition declares a move constructor or move assignment
5776   //   operator, an implicitly declared copy constructor or copy assignment
5777   //   operator is defined as deleted.
5778   if (MD->isImplicit() &&
5779       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5780     CXXMethodDecl *UserDeclaredMove = nullptr;
5781 
5782     // In Microsoft mode, a user-declared move only causes the deletion of the
5783     // corresponding copy operation, not both copy operations.
5784     if (RD->hasUserDeclaredMoveConstructor() &&
5785         (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
5786       if (!Diagnose) return true;
5787 
5788       // Find any user-declared move constructor.
5789       for (auto *I : RD->ctors()) {
5790         if (I->isMoveConstructor()) {
5791           UserDeclaredMove = I;
5792           break;
5793         }
5794       }
5795       assert(UserDeclaredMove);
5796     } else if (RD->hasUserDeclaredMoveAssignment() &&
5797                (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
5798       if (!Diagnose) return true;
5799 
5800       // Find any user-declared move assignment operator.
5801       for (auto *I : RD->methods()) {
5802         if (I->isMoveAssignmentOperator()) {
5803           UserDeclaredMove = I;
5804           break;
5805         }
5806       }
5807       assert(UserDeclaredMove);
5808     }
5809 
5810     if (UserDeclaredMove) {
5811       Diag(UserDeclaredMove->getLocation(),
5812            diag::note_deleted_copy_user_declared_move)
5813         << (CSM == CXXCopyAssignment) << RD
5814         << UserDeclaredMove->isMoveAssignmentOperator();
5815       return true;
5816     }
5817   }
5818 
5819   // Do access control from the special member function
5820   ContextRAII MethodContext(*this, MD);
5821 
5822   // C++11 [class.dtor]p5:
5823   // -- for a virtual destructor, lookup of the non-array deallocation function
5824   //    results in an ambiguity or in a function that is deleted or inaccessible
5825   if (CSM == CXXDestructor && MD->isVirtual()) {
5826     FunctionDecl *OperatorDelete = nullptr;
5827     DeclarationName Name =
5828       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5829     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
5830                                  OperatorDelete, false)) {
5831       if (Diagnose)
5832         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
5833       return true;
5834     }
5835   }
5836 
5837   SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
5838 
5839   for (auto &BI : RD->bases())
5840     if (!BI.isVirtual() &&
5841         SMI.shouldDeleteForBase(&BI))
5842       return true;
5843 
5844   // Per DR1611, do not consider virtual bases of constructors of abstract
5845   // classes, since we are not going to construct them.
5846   if (!RD->isAbstract() || !SMI.IsConstructor) {
5847     for (auto &BI : RD->vbases())
5848       if (SMI.shouldDeleteForBase(&BI))
5849         return true;
5850   }
5851 
5852   for (auto *FI : RD->fields())
5853     if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
5854         SMI.shouldDeleteForField(FI))
5855       return true;
5856 
5857   if (SMI.shouldDeleteForAllConstMembers())
5858     return true;
5859 
5860   if (getLangOpts().CUDA) {
5861     // We should delete the special member in CUDA mode if target inference
5862     // failed.
5863     return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
5864                                                    Diagnose);
5865   }
5866 
5867   return false;
5868 }
5869 
5870 /// Perform lookup for a special member of the specified kind, and determine
5871 /// whether it is trivial. If the triviality can be determined without the
5872 /// lookup, skip it. This is intended for use when determining whether a
5873 /// special member of a containing object is trivial, and thus does not ever
5874 /// perform overload resolution for default constructors.
5875 ///
5876 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5877 /// member that was most likely to be intended to be trivial, if any.
5878 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5879                                      Sema::CXXSpecialMember CSM, unsigned Quals,
5880                                      bool ConstRHS, CXXMethodDecl **Selected) {
5881   if (Selected)
5882     *Selected = nullptr;
5883 
5884   switch (CSM) {
5885   case Sema::CXXInvalid:
5886     llvm_unreachable("not a special member");
5887 
5888   case Sema::CXXDefaultConstructor:
5889     // C++11 [class.ctor]p5:
5890     //   A default constructor is trivial if:
5891     //    - all the [direct subobjects] have trivial default constructors
5892     //
5893     // Note, no overload resolution is performed in this case.
5894     if (RD->hasTrivialDefaultConstructor())
5895       return true;
5896 
5897     if (Selected) {
5898       // If there's a default constructor which could have been trivial, dig it
5899       // out. Otherwise, if there's any user-provided default constructor, point
5900       // to that as an example of why there's not a trivial one.
5901       CXXConstructorDecl *DefCtor = nullptr;
5902       if (RD->needsImplicitDefaultConstructor())
5903         S.DeclareImplicitDefaultConstructor(RD);
5904       for (auto *CI : RD->ctors()) {
5905         if (!CI->isDefaultConstructor())
5906           continue;
5907         DefCtor = CI;
5908         if (!DefCtor->isUserProvided())
5909           break;
5910       }
5911 
5912       *Selected = DefCtor;
5913     }
5914 
5915     return false;
5916 
5917   case Sema::CXXDestructor:
5918     // C++11 [class.dtor]p5:
5919     //   A destructor is trivial if:
5920     //    - all the direct [subobjects] have trivial destructors
5921     if (RD->hasTrivialDestructor())
5922       return true;
5923 
5924     if (Selected) {
5925       if (RD->needsImplicitDestructor())
5926         S.DeclareImplicitDestructor(RD);
5927       *Selected = RD->getDestructor();
5928     }
5929 
5930     return false;
5931 
5932   case Sema::CXXCopyConstructor:
5933     // C++11 [class.copy]p12:
5934     //   A copy constructor is trivial if:
5935     //    - the constructor selected to copy each direct [subobject] is trivial
5936     if (RD->hasTrivialCopyConstructor()) {
5937       if (Quals == Qualifiers::Const)
5938         // We must either select the trivial copy constructor or reach an
5939         // ambiguity; no need to actually perform overload resolution.
5940         return true;
5941     } else if (!Selected) {
5942       return false;
5943     }
5944     // In C++98, we are not supposed to perform overload resolution here, but we
5945     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5946     // cases like B as having a non-trivial copy constructor:
5947     //   struct A { template<typename T> A(T&); };
5948     //   struct B { mutable A a; };
5949     goto NeedOverloadResolution;
5950 
5951   case Sema::CXXCopyAssignment:
5952     // C++11 [class.copy]p25:
5953     //   A copy assignment operator is trivial if:
5954     //    - the assignment operator selected to copy each direct [subobject] is
5955     //      trivial
5956     if (RD->hasTrivialCopyAssignment()) {
5957       if (Quals == Qualifiers::Const)
5958         return true;
5959     } else if (!Selected) {
5960       return false;
5961     }
5962     // In C++98, we are not supposed to perform overload resolution here, but we
5963     // treat that as a language defect.
5964     goto NeedOverloadResolution;
5965 
5966   case Sema::CXXMoveConstructor:
5967   case Sema::CXXMoveAssignment:
5968   NeedOverloadResolution:
5969     Sema::SpecialMemberOverloadResult *SMOR =
5970         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
5971 
5972     // The standard doesn't describe how to behave if the lookup is ambiguous.
5973     // We treat it as not making the member non-trivial, just like the standard
5974     // mandates for the default constructor. This should rarely matter, because
5975     // the member will also be deleted.
5976     if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5977       return true;
5978 
5979     if (!SMOR->getMethod()) {
5980       assert(SMOR->getKind() ==
5981              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5982       return false;
5983     }
5984 
5985     // We deliberately don't check if we found a deleted special member. We're
5986     // not supposed to!
5987     if (Selected)
5988       *Selected = SMOR->getMethod();
5989     return SMOR->getMethod()->isTrivial();
5990   }
5991 
5992   llvm_unreachable("unknown special method kind");
5993 }
5994 
5995 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
5996   for (auto *CI : RD->ctors())
5997     if (!CI->isImplicit())
5998       return CI;
5999 
6000   // Look for constructor templates.
6001   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
6002   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
6003     if (CXXConstructorDecl *CD =
6004           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
6005       return CD;
6006   }
6007 
6008   return nullptr;
6009 }
6010 
6011 /// The kind of subobject we are checking for triviality. The values of this
6012 /// enumeration are used in diagnostics.
6013 enum TrivialSubobjectKind {
6014   /// The subobject is a base class.
6015   TSK_BaseClass,
6016   /// The subobject is a non-static data member.
6017   TSK_Field,
6018   /// The object is actually the complete object.
6019   TSK_CompleteObject
6020 };
6021 
6022 /// Check whether the special member selected for a given type would be trivial.
6023 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
6024                                       QualType SubType, bool ConstRHS,
6025                                       Sema::CXXSpecialMember CSM,
6026                                       TrivialSubobjectKind Kind,
6027                                       bool Diagnose) {
6028   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
6029   if (!SubRD)
6030     return true;
6031 
6032   CXXMethodDecl *Selected;
6033   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
6034                                ConstRHS, Diagnose ? &Selected : nullptr))
6035     return true;
6036 
6037   if (Diagnose) {
6038     if (ConstRHS)
6039       SubType.addConst();
6040 
6041     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
6042       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
6043         << Kind << SubType.getUnqualifiedType();
6044       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
6045         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
6046     } else if (!Selected)
6047       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
6048         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
6049     else if (Selected->isUserProvided()) {
6050       if (Kind == TSK_CompleteObject)
6051         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
6052           << Kind << SubType.getUnqualifiedType() << CSM;
6053       else {
6054         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
6055           << Kind << SubType.getUnqualifiedType() << CSM;
6056         S.Diag(Selected->getLocation(), diag::note_declared_at);
6057       }
6058     } else {
6059       if (Kind != TSK_CompleteObject)
6060         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
6061           << Kind << SubType.getUnqualifiedType() << CSM;
6062 
6063       // Explain why the defaulted or deleted special member isn't trivial.
6064       S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
6065     }
6066   }
6067 
6068   return false;
6069 }
6070 
6071 /// Check whether the members of a class type allow a special member to be
6072 /// trivial.
6073 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
6074                                      Sema::CXXSpecialMember CSM,
6075                                      bool ConstArg, bool Diagnose) {
6076   for (const auto *FI : RD->fields()) {
6077     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
6078       continue;
6079 
6080     QualType FieldType = S.Context.getBaseElementType(FI->getType());
6081 
6082     // Pretend anonymous struct or union members are members of this class.
6083     if (FI->isAnonymousStructOrUnion()) {
6084       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
6085                                     CSM, ConstArg, Diagnose))
6086         return false;
6087       continue;
6088     }
6089 
6090     // C++11 [class.ctor]p5:
6091     //   A default constructor is trivial if [...]
6092     //    -- no non-static data member of its class has a
6093     //       brace-or-equal-initializer
6094     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
6095       if (Diagnose)
6096         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
6097       return false;
6098     }
6099 
6100     // Objective C ARC 4.3.5:
6101     //   [...] nontrivally ownership-qualified types are [...] not trivially
6102     //   default constructible, copy constructible, move constructible, copy
6103     //   assignable, move assignable, or destructible [...]
6104     if (S.getLangOpts().ObjCAutoRefCount &&
6105         FieldType.hasNonTrivialObjCLifetime()) {
6106       if (Diagnose)
6107         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
6108           << RD << FieldType.getObjCLifetime();
6109       return false;
6110     }
6111 
6112     bool ConstRHS = ConstArg && !FI->isMutable();
6113     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
6114                                    CSM, TSK_Field, Diagnose))
6115       return false;
6116   }
6117 
6118   return true;
6119 }
6120 
6121 /// Diagnose why the specified class does not have a trivial special member of
6122 /// the given kind.
6123 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
6124   QualType Ty = Context.getRecordType(RD);
6125 
6126   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
6127   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
6128                             TSK_CompleteObject, /*Diagnose*/true);
6129 }
6130 
6131 /// Determine whether a defaulted or deleted special member function is trivial,
6132 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6133 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
6134 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
6135                                   bool Diagnose) {
6136   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
6137 
6138   CXXRecordDecl *RD = MD->getParent();
6139 
6140   bool ConstArg = false;
6141 
6142   // C++11 [class.copy]p12, p25: [DR1593]
6143   //   A [special member] is trivial if [...] its parameter-type-list is
6144   //   equivalent to the parameter-type-list of an implicit declaration [...]
6145   switch (CSM) {
6146   case CXXDefaultConstructor:
6147   case CXXDestructor:
6148     // Trivial default constructors and destructors cannot have parameters.
6149     break;
6150 
6151   case CXXCopyConstructor:
6152   case CXXCopyAssignment: {
6153     // Trivial copy operations always have const, non-volatile parameter types.
6154     ConstArg = true;
6155     const ParmVarDecl *Param0 = MD->getParamDecl(0);
6156     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
6157     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
6158       if (Diagnose)
6159         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6160           << Param0->getSourceRange() << Param0->getType()
6161           << Context.getLValueReferenceType(
6162                Context.getRecordType(RD).withConst());
6163       return false;
6164     }
6165     break;
6166   }
6167 
6168   case CXXMoveConstructor:
6169   case CXXMoveAssignment: {
6170     // Trivial move operations always have non-cv-qualified parameters.
6171     const ParmVarDecl *Param0 = MD->getParamDecl(0);
6172     const RValueReferenceType *RT =
6173       Param0->getType()->getAs<RValueReferenceType>();
6174     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
6175       if (Diagnose)
6176         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6177           << Param0->getSourceRange() << Param0->getType()
6178           << Context.getRValueReferenceType(Context.getRecordType(RD));
6179       return false;
6180     }
6181     break;
6182   }
6183 
6184   case CXXInvalid:
6185     llvm_unreachable("not a special member");
6186   }
6187 
6188   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
6189     if (Diagnose)
6190       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
6191            diag::note_nontrivial_default_arg)
6192         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
6193     return false;
6194   }
6195   if (MD->isVariadic()) {
6196     if (Diagnose)
6197       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
6198     return false;
6199   }
6200 
6201   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6202   //   A copy/move [constructor or assignment operator] is trivial if
6203   //    -- the [member] selected to copy/move each direct base class subobject
6204   //       is trivial
6205   //
6206   // C++11 [class.copy]p12, C++11 [class.copy]p25:
6207   //   A [default constructor or destructor] is trivial if
6208   //    -- all the direct base classes have trivial [default constructors or
6209   //       destructors]
6210   for (const auto &BI : RD->bases())
6211     if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
6212                                    ConstArg, CSM, TSK_BaseClass, Diagnose))
6213       return false;
6214 
6215   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6216   //   A copy/move [constructor or assignment operator] for a class X is
6217   //   trivial if
6218   //    -- for each non-static data member of X that is of class type (or array
6219   //       thereof), the constructor selected to copy/move that member is
6220   //       trivial
6221   //
6222   // C++11 [class.copy]p12, C++11 [class.copy]p25:
6223   //   A [default constructor or destructor] is trivial if
6224   //    -- for all of the non-static data members of its class that are of class
6225   //       type (or array thereof), each such class has a trivial [default
6226   //       constructor or destructor]
6227   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
6228     return false;
6229 
6230   // C++11 [class.dtor]p5:
6231   //   A destructor is trivial if [...]
6232   //    -- the destructor is not virtual
6233   if (CSM == CXXDestructor && MD->isVirtual()) {
6234     if (Diagnose)
6235       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
6236     return false;
6237   }
6238 
6239   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
6240   //   A [special member] for class X is trivial if [...]
6241   //    -- class X has no virtual functions and no virtual base classes
6242   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
6243     if (!Diagnose)
6244       return false;
6245 
6246     if (RD->getNumVBases()) {
6247       // Check for virtual bases. We already know that the corresponding
6248       // member in all bases is trivial, so vbases must all be direct.
6249       CXXBaseSpecifier &BS = *RD->vbases_begin();
6250       assert(BS.isVirtual());
6251       Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
6252       return false;
6253     }
6254 
6255     // Must have a virtual method.
6256     for (const auto *MI : RD->methods()) {
6257       if (MI->isVirtual()) {
6258         SourceLocation MLoc = MI->getLocStart();
6259         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
6260         return false;
6261       }
6262     }
6263 
6264     llvm_unreachable("dynamic class with no vbases and no virtual functions");
6265   }
6266 
6267   // Looks like it's trivial!
6268   return true;
6269 }
6270 
6271 /// \brief Data used with FindHiddenVirtualMethod
6272 namespace {
6273   struct FindHiddenVirtualMethodData {
6274     Sema *S;
6275     CXXMethodDecl *Method;
6276     llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
6277     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6278   };
6279 }
6280 
6281 /// \brief Check whether any most overriden method from MD in Methods
6282 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
6283                   const llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
6284   if (MD->size_overridden_methods() == 0)
6285     return Methods.count(MD->getCanonicalDecl());
6286   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6287                                       E = MD->end_overridden_methods();
6288        I != E; ++I)
6289     if (CheckMostOverridenMethods(*I, Methods))
6290       return true;
6291   return false;
6292 }
6293 
6294 /// \brief Member lookup function that determines whether a given C++
6295 /// method overloads virtual methods in a base class without overriding any,
6296 /// to be used with CXXRecordDecl::lookupInBases().
6297 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
6298                                     CXXBasePath &Path,
6299                                     void *UserData) {
6300   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
6301 
6302   FindHiddenVirtualMethodData &Data
6303     = *static_cast<FindHiddenVirtualMethodData*>(UserData);
6304 
6305   DeclarationName Name = Data.Method->getDeclName();
6306   assert(Name.getNameKind() == DeclarationName::Identifier);
6307 
6308   bool foundSameNameMethod = false;
6309   SmallVector<CXXMethodDecl *, 8> overloadedMethods;
6310   for (Path.Decls = BaseRecord->lookup(Name);
6311        !Path.Decls.empty();
6312        Path.Decls = Path.Decls.slice(1)) {
6313     NamedDecl *D = Path.Decls.front();
6314     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6315       MD = MD->getCanonicalDecl();
6316       foundSameNameMethod = true;
6317       // Interested only in hidden virtual methods.
6318       if (!MD->isVirtual())
6319         continue;
6320       // If the method we are checking overrides a method from its base
6321       // don't warn about the other overloaded methods. Clang deviates from GCC
6322       // by only diagnosing overloads of inherited virtual functions that do not
6323       // override any other virtual functions in the base. GCC's
6324       // -Woverloaded-virtual diagnoses any derived function hiding a virtual
6325       // function from a base class. These cases may be better served by a
6326       // warning (not specific to virtual functions) on call sites when the call
6327       // would select a different function from the base class, were it visible.
6328       // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
6329       if (!Data.S->IsOverload(Data.Method, MD, false))
6330         return true;
6331       // Collect the overload only if its hidden.
6332       if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
6333         overloadedMethods.push_back(MD);
6334     }
6335   }
6336 
6337   if (foundSameNameMethod)
6338     Data.OverloadedMethods.append(overloadedMethods.begin(),
6339                                    overloadedMethods.end());
6340   return foundSameNameMethod;
6341 }
6342 
6343 /// \brief Add the most overriden methods from MD to Methods
6344 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
6345                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
6346   if (MD->size_overridden_methods() == 0)
6347     Methods.insert(MD->getCanonicalDecl());
6348   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6349                                       E = MD->end_overridden_methods();
6350        I != E; ++I)
6351     AddMostOverridenMethods(*I, Methods);
6352 }
6353 
6354 /// \brief Check if a method overloads virtual methods in a base class without
6355 /// overriding any.
6356 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
6357                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6358   if (!MD->getDeclName().isIdentifier())
6359     return;
6360 
6361   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
6362                      /*bool RecordPaths=*/false,
6363                      /*bool DetectVirtual=*/false);
6364   FindHiddenVirtualMethodData Data;
6365   Data.Method = MD;
6366   Data.S = this;
6367 
6368   // Keep the base methods that were overriden or introduced in the subclass
6369   // by 'using' in a set. A base method not in this set is hidden.
6370   CXXRecordDecl *DC = MD->getParent();
6371   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
6372   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
6373     NamedDecl *ND = *I;
6374     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
6375       ND = shad->getTargetDecl();
6376     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6377       AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
6378   }
6379 
6380   if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
6381     OverloadedMethods = Data.OverloadedMethods;
6382 }
6383 
6384 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6385                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6386   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
6387     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
6388     PartialDiagnostic PD = PDiag(
6389          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
6390     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
6391     Diag(overloadedMD->getLocation(), PD);
6392   }
6393 }
6394 
6395 /// \brief Diagnose methods which overload virtual methods in a base class
6396 /// without overriding any.
6397 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
6398   if (MD->isInvalidDecl())
6399     return;
6400 
6401   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
6402     return;
6403 
6404   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6405   FindHiddenVirtualMethods(MD, OverloadedMethods);
6406   if (!OverloadedMethods.empty()) {
6407     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
6408       << MD << (OverloadedMethods.size() > 1);
6409 
6410     NoteHiddenVirtualMethods(MD, OverloadedMethods);
6411   }
6412 }
6413 
6414 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
6415                                              Decl *TagDecl,
6416                                              SourceLocation LBrac,
6417                                              SourceLocation RBrac,
6418                                              AttributeList *AttrList) {
6419   if (!TagDecl)
6420     return;
6421 
6422   AdjustDeclIfTemplate(TagDecl);
6423 
6424   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6425     if (l->getKind() != AttributeList::AT_Visibility)
6426       continue;
6427     l->setInvalid();
6428     Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
6429       l->getName();
6430   }
6431 
6432   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
6433               // strict aliasing violation!
6434               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
6435               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
6436 
6437   CheckCompletedCXXClass(
6438                         dyn_cast_or_null<CXXRecordDecl>(TagDecl));
6439 }
6440 
6441 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6442 /// special functions, such as the default constructor, copy
6443 /// constructor, or destructor, to the given C++ class (C++
6444 /// [special]p1).  This routine can only be executed just before the
6445 /// definition of the class is complete.
6446 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
6447   if (!ClassDecl->hasUserDeclaredConstructor())
6448     ++ASTContext::NumImplicitDefaultConstructors;
6449 
6450   if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
6451     ++ASTContext::NumImplicitCopyConstructors;
6452 
6453     // If the properties or semantics of the copy constructor couldn't be
6454     // determined while the class was being declared, force a declaration
6455     // of it now.
6456     if (ClassDecl->needsOverloadResolutionForCopyConstructor())
6457       DeclareImplicitCopyConstructor(ClassDecl);
6458   }
6459 
6460   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
6461     ++ASTContext::NumImplicitMoveConstructors;
6462 
6463     if (ClassDecl->needsOverloadResolutionForMoveConstructor())
6464       DeclareImplicitMoveConstructor(ClassDecl);
6465   }
6466 
6467   if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6468     ++ASTContext::NumImplicitCopyAssignmentOperators;
6469 
6470     // If we have a dynamic class, then the copy assignment operator may be
6471     // virtual, so we have to declare it immediately. This ensures that, e.g.,
6472     // it shows up in the right place in the vtable and that we diagnose
6473     // problems with the implicit exception specification.
6474     if (ClassDecl->isDynamicClass() ||
6475         ClassDecl->needsOverloadResolutionForCopyAssignment())
6476       DeclareImplicitCopyAssignment(ClassDecl);
6477   }
6478 
6479   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
6480     ++ASTContext::NumImplicitMoveAssignmentOperators;
6481 
6482     // Likewise for the move assignment operator.
6483     if (ClassDecl->isDynamicClass() ||
6484         ClassDecl->needsOverloadResolutionForMoveAssignment())
6485       DeclareImplicitMoveAssignment(ClassDecl);
6486   }
6487 
6488   if (!ClassDecl->hasUserDeclaredDestructor()) {
6489     ++ASTContext::NumImplicitDestructors;
6490 
6491     // If we have a dynamic class, then the destructor may be virtual, so we
6492     // have to declare the destructor immediately. This ensures that, e.g., it
6493     // shows up in the right place in the vtable and that we diagnose problems
6494     // with the implicit exception specification.
6495     if (ClassDecl->isDynamicClass() ||
6496         ClassDecl->needsOverloadResolutionForDestructor())
6497       DeclareImplicitDestructor(ClassDecl);
6498   }
6499 }
6500 
6501 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
6502   if (!D)
6503     return 0;
6504 
6505   // The order of template parameters is not important here. All names
6506   // get added to the same scope.
6507   SmallVector<TemplateParameterList *, 4> ParameterLists;
6508 
6509   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6510     D = TD->getTemplatedDecl();
6511 
6512   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6513     ParameterLists.push_back(PSD->getTemplateParameters());
6514 
6515   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6516     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6517       ParameterLists.push_back(DD->getTemplateParameterList(i));
6518 
6519     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6520       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6521         ParameterLists.push_back(FTD->getTemplateParameters());
6522     }
6523   }
6524 
6525   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6526     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6527       ParameterLists.push_back(TD->getTemplateParameterList(i));
6528 
6529     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6530       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6531         ParameterLists.push_back(CTD->getTemplateParameters());
6532     }
6533   }
6534 
6535   unsigned Count = 0;
6536   for (TemplateParameterList *Params : ParameterLists) {
6537     if (Params->size() > 0)
6538       // Ignore explicit specializations; they don't contribute to the template
6539       // depth.
6540       ++Count;
6541     for (NamedDecl *Param : *Params) {
6542       if (Param->getDeclName()) {
6543         S->AddDecl(Param);
6544         IdResolver.AddDecl(Param);
6545       }
6546     }
6547   }
6548 
6549   return Count;
6550 }
6551 
6552 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6553   if (!RecordD) return;
6554   AdjustDeclIfTemplate(RecordD);
6555   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
6556   PushDeclContext(S, Record);
6557 }
6558 
6559 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6560   if (!RecordD) return;
6561   PopDeclContext();
6562 }
6563 
6564 /// This is used to implement the constant expression evaluation part of the
6565 /// attribute enable_if extension. There is nothing in standard C++ which would
6566 /// require reentering parameters.
6567 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6568   if (!Param)
6569     return;
6570 
6571   S->AddDecl(Param);
6572   if (Param->getDeclName())
6573     IdResolver.AddDecl(Param);
6574 }
6575 
6576 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
6577 /// parsing a top-level (non-nested) C++ class, and we are now
6578 /// parsing those parts of the given Method declaration that could
6579 /// not be parsed earlier (C++ [class.mem]p2), such as default
6580 /// arguments. This action should enter the scope of the given
6581 /// Method declaration as if we had just parsed the qualified method
6582 /// name. However, it should not bring the parameters into scope;
6583 /// that will be performed by ActOnDelayedCXXMethodParameter.
6584 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6585 }
6586 
6587 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
6588 /// C++ method declaration. We're (re-)introducing the given
6589 /// function parameter into scope for use in parsing later parts of
6590 /// the method declaration. For example, we could see an
6591 /// ActOnParamDefaultArgument event for this parameter.
6592 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
6593   if (!ParamD)
6594     return;
6595 
6596   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
6597 
6598   // If this parameter has an unparsed default argument, clear it out
6599   // to make way for the parsed default argument.
6600   if (Param->hasUnparsedDefaultArg())
6601     Param->setDefaultArg(nullptr);
6602 
6603   S->AddDecl(Param);
6604   if (Param->getDeclName())
6605     IdResolver.AddDecl(Param);
6606 }
6607 
6608 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6609 /// processing the delayed method declaration for Method. The method
6610 /// declaration is now considered finished. There may be a separate
6611 /// ActOnStartOfFunctionDef action later (not necessarily
6612 /// immediately!) for this method, if it was also defined inside the
6613 /// class body.
6614 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6615   if (!MethodD)
6616     return;
6617 
6618   AdjustDeclIfTemplate(MethodD);
6619 
6620   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
6621 
6622   // Now that we have our default arguments, check the constructor
6623   // again. It could produce additional diagnostics or affect whether
6624   // the class has implicitly-declared destructors, among other
6625   // things.
6626   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6627     CheckConstructor(Constructor);
6628 
6629   // Check the default arguments, which we may have added.
6630   if (!Method->isInvalidDecl())
6631     CheckCXXDefaultArguments(Method);
6632 }
6633 
6634 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
6635 /// the well-formedness of the constructor declarator @p D with type @p
6636 /// R. If there are any errors in the declarator, this routine will
6637 /// emit diagnostics and set the invalid bit to true.  In any case, the type
6638 /// will be updated to reflect a well-formed type for the constructor and
6639 /// returned.
6640 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
6641                                           StorageClass &SC) {
6642   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6643 
6644   // C++ [class.ctor]p3:
6645   //   A constructor shall not be virtual (10.3) or static (9.4). A
6646   //   constructor can be invoked for a const, volatile or const
6647   //   volatile object. A constructor shall not be declared const,
6648   //   volatile, or const volatile (9.3.2).
6649   if (isVirtual) {
6650     if (!D.isInvalidType())
6651       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6652         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6653         << SourceRange(D.getIdentifierLoc());
6654     D.setInvalidType();
6655   }
6656   if (SC == SC_Static) {
6657     if (!D.isInvalidType())
6658       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6659         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6660         << SourceRange(D.getIdentifierLoc());
6661     D.setInvalidType();
6662     SC = SC_None;
6663   }
6664 
6665   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6666     diagnoseIgnoredQualifiers(
6667         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
6668         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
6669         D.getDeclSpec().getRestrictSpecLoc(),
6670         D.getDeclSpec().getAtomicSpecLoc());
6671     D.setInvalidType();
6672   }
6673 
6674   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6675   if (FTI.TypeQuals != 0) {
6676     if (FTI.TypeQuals & Qualifiers::Const)
6677       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6678         << "const" << SourceRange(D.getIdentifierLoc());
6679     if (FTI.TypeQuals & Qualifiers::Volatile)
6680       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6681         << "volatile" << SourceRange(D.getIdentifierLoc());
6682     if (FTI.TypeQuals & Qualifiers::Restrict)
6683       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6684         << "restrict" << SourceRange(D.getIdentifierLoc());
6685     D.setInvalidType();
6686   }
6687 
6688   // C++0x [class.ctor]p4:
6689   //   A constructor shall not be declared with a ref-qualifier.
6690   if (FTI.hasRefQualifier()) {
6691     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6692       << FTI.RefQualifierIsLValueRef
6693       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6694     D.setInvalidType();
6695   }
6696 
6697   // Rebuild the function type "R" without any type qualifiers (in
6698   // case any of the errors above fired) and with "void" as the
6699   // return type, since constructors don't have return types.
6700   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6701   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
6702     return R;
6703 
6704   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6705   EPI.TypeQuals = 0;
6706   EPI.RefQualifier = RQ_None;
6707 
6708   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
6709 }
6710 
6711 /// CheckConstructor - Checks a fully-formed constructor for
6712 /// well-formedness, issuing any diagnostics required. Returns true if
6713 /// the constructor declarator is invalid.
6714 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
6715   CXXRecordDecl *ClassDecl
6716     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6717   if (!ClassDecl)
6718     return Constructor->setInvalidDecl();
6719 
6720   // C++ [class.copy]p3:
6721   //   A declaration of a constructor for a class X is ill-formed if
6722   //   its first parameter is of type (optionally cv-qualified) X and
6723   //   either there are no other parameters or else all other
6724   //   parameters have default arguments.
6725   if (!Constructor->isInvalidDecl() &&
6726       ((Constructor->getNumParams() == 1) ||
6727        (Constructor->getNumParams() > 1 &&
6728         Constructor->getParamDecl(1)->hasDefaultArg())) &&
6729       Constructor->getTemplateSpecializationKind()
6730                                               != TSK_ImplicitInstantiation) {
6731     QualType ParamType = Constructor->getParamDecl(0)->getType();
6732     QualType ClassTy = Context.getTagDeclType(ClassDecl);
6733     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
6734       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
6735       const char *ConstRef
6736         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6737                                                         : " const &";
6738       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
6739         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
6740 
6741       // FIXME: Rather that making the constructor invalid, we should endeavor
6742       // to fix the type.
6743       Constructor->setInvalidDecl();
6744     }
6745   }
6746 }
6747 
6748 /// CheckDestructor - Checks a fully-formed destructor definition for
6749 /// well-formedness, issuing any diagnostics required.  Returns true
6750 /// on error.
6751 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
6752   CXXRecordDecl *RD = Destructor->getParent();
6753 
6754   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
6755     SourceLocation Loc;
6756 
6757     if (!Destructor->isImplicit())
6758       Loc = Destructor->getLocation();
6759     else
6760       Loc = RD->getLocation();
6761 
6762     // If we have a virtual destructor, look up the deallocation function
6763     FunctionDecl *OperatorDelete = nullptr;
6764     DeclarationName Name =
6765     Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6766     if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
6767       return true;
6768     // If there's no class-specific operator delete, look up the global
6769     // non-array delete.
6770     if (!OperatorDelete)
6771       OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
6772 
6773     MarkFunctionReferenced(Loc, OperatorDelete);
6774 
6775     Destructor->setOperatorDelete(OperatorDelete);
6776   }
6777 
6778   return false;
6779 }
6780 
6781 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6782 /// the well-formednes of the destructor declarator @p D with type @p
6783 /// R. If there are any errors in the declarator, this routine will
6784 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
6785 /// will be updated to reflect a well-formed type for the destructor and
6786 /// returned.
6787 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
6788                                          StorageClass& SC) {
6789   // C++ [class.dtor]p1:
6790   //   [...] A typedef-name that names a class is a class-name
6791   //   (7.1.3); however, a typedef-name that names a class shall not
6792   //   be used as the identifier in the declarator for a destructor
6793   //   declaration.
6794   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
6795   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
6796     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6797       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
6798   else if (const TemplateSpecializationType *TST =
6799              DeclaratorType->getAs<TemplateSpecializationType>())
6800     if (TST->isTypeAlias())
6801       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6802         << DeclaratorType << 1;
6803 
6804   // C++ [class.dtor]p2:
6805   //   A destructor is used to destroy objects of its class type. A
6806   //   destructor takes no parameters, and no return type can be
6807   //   specified for it (not even void). The address of a destructor
6808   //   shall not be taken. A destructor shall not be static. A
6809   //   destructor can be invoked for a const, volatile or const
6810   //   volatile object. A destructor shall not be declared const,
6811   //   volatile or const volatile (9.3.2).
6812   if (SC == SC_Static) {
6813     if (!D.isInvalidType())
6814       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6815         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6816         << SourceRange(D.getIdentifierLoc())
6817         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6818 
6819     SC = SC_None;
6820   }
6821   if (!D.isInvalidType()) {
6822     // Destructors don't have return types, but the parser will
6823     // happily parse something like:
6824     //
6825     //   class X {
6826     //     float ~X();
6827     //   };
6828     //
6829     // The return type will be eliminated later.
6830     if (D.getDeclSpec().hasTypeSpecifier())
6831       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6832         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6833         << SourceRange(D.getIdentifierLoc());
6834     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6835       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
6836                                 SourceLocation(),
6837                                 D.getDeclSpec().getConstSpecLoc(),
6838                                 D.getDeclSpec().getVolatileSpecLoc(),
6839                                 D.getDeclSpec().getRestrictSpecLoc(),
6840                                 D.getDeclSpec().getAtomicSpecLoc());
6841       D.setInvalidType();
6842     }
6843   }
6844 
6845   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6846   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
6847     if (FTI.TypeQuals & Qualifiers::Const)
6848       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6849         << "const" << SourceRange(D.getIdentifierLoc());
6850     if (FTI.TypeQuals & Qualifiers::Volatile)
6851       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6852         << "volatile" << SourceRange(D.getIdentifierLoc());
6853     if (FTI.TypeQuals & Qualifiers::Restrict)
6854       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6855         << "restrict" << SourceRange(D.getIdentifierLoc());
6856     D.setInvalidType();
6857   }
6858 
6859   // C++0x [class.dtor]p2:
6860   //   A destructor shall not be declared with a ref-qualifier.
6861   if (FTI.hasRefQualifier()) {
6862     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6863       << FTI.RefQualifierIsLValueRef
6864       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6865     D.setInvalidType();
6866   }
6867 
6868   // Make sure we don't have any parameters.
6869   if (FTIHasNonVoidParameters(FTI)) {
6870     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6871 
6872     // Delete the parameters.
6873     FTI.freeParams();
6874     D.setInvalidType();
6875   }
6876 
6877   // Make sure the destructor isn't variadic.
6878   if (FTI.isVariadic) {
6879     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
6880     D.setInvalidType();
6881   }
6882 
6883   // Rebuild the function type "R" without any type qualifiers or
6884   // parameters (in case any of the errors above fired) and with
6885   // "void" as the return type, since destructors don't have return
6886   // types.
6887   if (!D.isInvalidType())
6888     return R;
6889 
6890   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6891   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6892   EPI.Variadic = false;
6893   EPI.TypeQuals = 0;
6894   EPI.RefQualifier = RQ_None;
6895   return Context.getFunctionType(Context.VoidTy, None, EPI);
6896 }
6897 
6898 static void extendLeft(SourceRange &R, const SourceRange &Before) {
6899   if (Before.isInvalid())
6900     return;
6901   R.setBegin(Before.getBegin());
6902   if (R.getEnd().isInvalid())
6903     R.setEnd(Before.getEnd());
6904 }
6905 
6906 static void extendRight(SourceRange &R, const SourceRange &After) {
6907   if (After.isInvalid())
6908     return;
6909   if (R.getBegin().isInvalid())
6910     R.setBegin(After.getBegin());
6911   R.setEnd(After.getEnd());
6912 }
6913 
6914 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6915 /// well-formednes of the conversion function declarator @p D with
6916 /// type @p R. If there are any errors in the declarator, this routine
6917 /// will emit diagnostics and return true. Otherwise, it will return
6918 /// false. Either way, the type @p R will be updated to reflect a
6919 /// well-formed type for the conversion operator.
6920 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
6921                                      StorageClass& SC) {
6922   // C++ [class.conv.fct]p1:
6923   //   Neither parameter types nor return type can be specified. The
6924   //   type of a conversion function (8.3.5) is "function taking no
6925   //   parameter returning conversion-type-id."
6926   if (SC == SC_Static) {
6927     if (!D.isInvalidType())
6928       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
6929         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6930         << D.getName().getSourceRange();
6931     D.setInvalidType();
6932     SC = SC_None;
6933   }
6934 
6935   TypeSourceInfo *ConvTSI = nullptr;
6936   QualType ConvType =
6937       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
6938 
6939   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
6940     // Conversion functions don't have return types, but the parser will
6941     // happily parse something like:
6942     //
6943     //   class X {
6944     //     float operator bool();
6945     //   };
6946     //
6947     // The return type will be changed later anyway.
6948     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6949       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6950       << SourceRange(D.getIdentifierLoc());
6951     D.setInvalidType();
6952   }
6953 
6954   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6955 
6956   // Make sure we don't have any parameters.
6957   if (Proto->getNumParams() > 0) {
6958     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6959 
6960     // Delete the parameters.
6961     D.getFunctionTypeInfo().freeParams();
6962     D.setInvalidType();
6963   } else if (Proto->isVariadic()) {
6964     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
6965     D.setInvalidType();
6966   }
6967 
6968   // Diagnose "&operator bool()" and other such nonsense.  This
6969   // is actually a gcc extension which we don't support.
6970   if (Proto->getReturnType() != ConvType) {
6971     bool NeedsTypedef = false;
6972     SourceRange Before, After;
6973 
6974     // Walk the chunks and extract information on them for our diagnostic.
6975     bool PastFunctionChunk = false;
6976     for (auto &Chunk : D.type_objects()) {
6977       switch (Chunk.Kind) {
6978       case DeclaratorChunk::Function:
6979         if (!PastFunctionChunk) {
6980           if (Chunk.Fun.HasTrailingReturnType) {
6981             TypeSourceInfo *TRT = nullptr;
6982             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
6983             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
6984           }
6985           PastFunctionChunk = true;
6986           break;
6987         }
6988         // Fall through.
6989       case DeclaratorChunk::Array:
6990         NeedsTypedef = true;
6991         extendRight(After, Chunk.getSourceRange());
6992         break;
6993 
6994       case DeclaratorChunk::Pointer:
6995       case DeclaratorChunk::BlockPointer:
6996       case DeclaratorChunk::Reference:
6997       case DeclaratorChunk::MemberPointer:
6998         extendLeft(Before, Chunk.getSourceRange());
6999         break;
7000 
7001       case DeclaratorChunk::Paren:
7002         extendLeft(Before, Chunk.Loc);
7003         extendRight(After, Chunk.EndLoc);
7004         break;
7005       }
7006     }
7007 
7008     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
7009                          After.isValid()  ? After.getBegin() :
7010                                             D.getIdentifierLoc();
7011     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
7012     DB << Before << After;
7013 
7014     if (!NeedsTypedef) {
7015       DB << /*don't need a typedef*/0;
7016 
7017       // If we can provide a correct fix-it hint, do so.
7018       if (After.isInvalid() && ConvTSI) {
7019         SourceLocation InsertLoc =
7020             PP.getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
7021         DB << FixItHint::CreateInsertion(InsertLoc, " ")
7022            << FixItHint::CreateInsertionFromRange(
7023                   InsertLoc, CharSourceRange::getTokenRange(Before))
7024            << FixItHint::CreateRemoval(Before);
7025       }
7026     } else if (!Proto->getReturnType()->isDependentType()) {
7027       DB << /*typedef*/1 << Proto->getReturnType();
7028     } else if (getLangOpts().CPlusPlus11) {
7029       DB << /*alias template*/2 << Proto->getReturnType();
7030     } else {
7031       DB << /*might not be fixable*/3;
7032     }
7033 
7034     // Recover by incorporating the other type chunks into the result type.
7035     // Note, this does *not* change the name of the function. This is compatible
7036     // with the GCC extension:
7037     //   struct S { &operator int(); } s;
7038     //   int &r = s.operator int(); // ok in GCC
7039     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
7040     ConvType = Proto->getReturnType();
7041   }
7042 
7043   // C++ [class.conv.fct]p4:
7044   //   The conversion-type-id shall not represent a function type nor
7045   //   an array type.
7046   if (ConvType->isArrayType()) {
7047     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
7048     ConvType = Context.getPointerType(ConvType);
7049     D.setInvalidType();
7050   } else if (ConvType->isFunctionType()) {
7051     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
7052     ConvType = Context.getPointerType(ConvType);
7053     D.setInvalidType();
7054   }
7055 
7056   // Rebuild the function type "R" without any parameters (in case any
7057   // of the errors above fired) and with the conversion type as the
7058   // return type.
7059   if (D.isInvalidType())
7060     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
7061 
7062   // C++0x explicit conversion operators.
7063   if (D.getDeclSpec().isExplicitSpecified())
7064     Diag(D.getDeclSpec().getExplicitSpecLoc(),
7065          getLangOpts().CPlusPlus11 ?
7066            diag::warn_cxx98_compat_explicit_conversion_functions :
7067            diag::ext_explicit_conversion_functions)
7068       << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
7069 }
7070 
7071 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
7072 /// the declaration of the given C++ conversion function. This routine
7073 /// is responsible for recording the conversion function in the C++
7074 /// class, if possible.
7075 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
7076   assert(Conversion && "Expected to receive a conversion function declaration");
7077 
7078   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
7079 
7080   // Make sure we aren't redeclaring the conversion function.
7081   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
7082 
7083   // C++ [class.conv.fct]p1:
7084   //   [...] A conversion function is never used to convert a
7085   //   (possibly cv-qualified) object to the (possibly cv-qualified)
7086   //   same object type (or a reference to it), to a (possibly
7087   //   cv-qualified) base class of that type (or a reference to it),
7088   //   or to (possibly cv-qualified) void.
7089   // FIXME: Suppress this warning if the conversion function ends up being a
7090   // virtual function that overrides a virtual function in a base class.
7091   QualType ClassType
7092     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
7093   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
7094     ConvType = ConvTypeRef->getPointeeType();
7095   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
7096       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
7097     /* Suppress diagnostics for instantiations. */;
7098   else if (ConvType->isRecordType()) {
7099     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
7100     if (ConvType == ClassType)
7101       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
7102         << ClassType;
7103     else if (IsDerivedFrom(ClassType, ConvType))
7104       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
7105         <<  ClassType << ConvType;
7106   } else if (ConvType->isVoidType()) {
7107     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
7108       << ClassType << ConvType;
7109   }
7110 
7111   if (FunctionTemplateDecl *ConversionTemplate
7112                                 = Conversion->getDescribedFunctionTemplate())
7113     return ConversionTemplate;
7114 
7115   return Conversion;
7116 }
7117 
7118 //===----------------------------------------------------------------------===//
7119 // Namespace Handling
7120 //===----------------------------------------------------------------------===//
7121 
7122 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
7123 /// reopened.
7124 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
7125                                             SourceLocation Loc,
7126                                             IdentifierInfo *II, bool *IsInline,
7127                                             NamespaceDecl *PrevNS) {
7128   assert(*IsInline != PrevNS->isInline());
7129 
7130   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
7131   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
7132   // inline namespaces, with the intention of bringing names into namespace std.
7133   //
7134   // We support this just well enough to get that case working; this is not
7135   // sufficient to support reopening namespaces as inline in general.
7136   if (*IsInline && II && II->getName().startswith("__atomic") &&
7137       S.getSourceManager().isInSystemHeader(Loc)) {
7138     // Mark all prior declarations of the namespace as inline.
7139     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
7140          NS = NS->getPreviousDecl())
7141       NS->setInline(*IsInline);
7142     // Patch up the lookup table for the containing namespace. This isn't really
7143     // correct, but it's good enough for this particular case.
7144     for (auto *I : PrevNS->decls())
7145       if (auto *ND = dyn_cast<NamedDecl>(I))
7146         PrevNS->getParent()->makeDeclVisibleInContext(ND);
7147     return;
7148   }
7149 
7150   if (PrevNS->isInline())
7151     // The user probably just forgot the 'inline', so suggest that it
7152     // be added back.
7153     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
7154       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
7155   else
7156     S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
7157 
7158   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
7159   *IsInline = PrevNS->isInline();
7160 }
7161 
7162 /// ActOnStartNamespaceDef - This is called at the start of a namespace
7163 /// definition.
7164 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
7165                                    SourceLocation InlineLoc,
7166                                    SourceLocation NamespaceLoc,
7167                                    SourceLocation IdentLoc,
7168                                    IdentifierInfo *II,
7169                                    SourceLocation LBrace,
7170                                    AttributeList *AttrList) {
7171   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
7172   // For anonymous namespace, take the location of the left brace.
7173   SourceLocation Loc = II ? IdentLoc : LBrace;
7174   bool IsInline = InlineLoc.isValid();
7175   bool IsInvalid = false;
7176   bool IsStd = false;
7177   bool AddToKnown = false;
7178   Scope *DeclRegionScope = NamespcScope->getParent();
7179 
7180   NamespaceDecl *PrevNS = nullptr;
7181   if (II) {
7182     // C++ [namespace.def]p2:
7183     //   The identifier in an original-namespace-definition shall not
7184     //   have been previously defined in the declarative region in
7185     //   which the original-namespace-definition appears. The
7186     //   identifier in an original-namespace-definition is the name of
7187     //   the namespace. Subsequently in that declarative region, it is
7188     //   treated as an original-namespace-name.
7189     //
7190     // Since namespace names are unique in their scope, and we don't
7191     // look through using directives, just look for any ordinary names.
7192 
7193     const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
7194     Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
7195     Decl::IDNS_Namespace;
7196     NamedDecl *PrevDecl = nullptr;
7197     DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
7198     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
7199          ++I) {
7200       if ((*I)->getIdentifierNamespace() & IDNS) {
7201         PrevDecl = *I;
7202         break;
7203       }
7204     }
7205 
7206     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
7207 
7208     if (PrevNS) {
7209       // This is an extended namespace definition.
7210       if (IsInline != PrevNS->isInline())
7211         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
7212                                         &IsInline, PrevNS);
7213     } else if (PrevDecl) {
7214       // This is an invalid name redefinition.
7215       Diag(Loc, diag::err_redefinition_different_kind)
7216         << II;
7217       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
7218       IsInvalid = true;
7219       // Continue on to push Namespc as current DeclContext and return it.
7220     } else if (II->isStr("std") &&
7221                CurContext->getRedeclContext()->isTranslationUnit()) {
7222       // This is the first "real" definition of the namespace "std", so update
7223       // our cache of the "std" namespace to point at this definition.
7224       PrevNS = getStdNamespace();
7225       IsStd = true;
7226       AddToKnown = !IsInline;
7227     } else {
7228       // We've seen this namespace for the first time.
7229       AddToKnown = !IsInline;
7230     }
7231   } else {
7232     // Anonymous namespaces.
7233 
7234     // Determine whether the parent already has an anonymous namespace.
7235     DeclContext *Parent = CurContext->getRedeclContext();
7236     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7237       PrevNS = TU->getAnonymousNamespace();
7238     } else {
7239       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
7240       PrevNS = ND->getAnonymousNamespace();
7241     }
7242 
7243     if (PrevNS && IsInline != PrevNS->isInline())
7244       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
7245                                       &IsInline, PrevNS);
7246   }
7247 
7248   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
7249                                                  StartLoc, Loc, II, PrevNS);
7250   if (IsInvalid)
7251     Namespc->setInvalidDecl();
7252 
7253   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
7254 
7255   // FIXME: Should we be merging attributes?
7256   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
7257     PushNamespaceVisibilityAttr(Attr, Loc);
7258 
7259   if (IsStd)
7260     StdNamespace = Namespc;
7261   if (AddToKnown)
7262     KnownNamespaces[Namespc] = false;
7263 
7264   if (II) {
7265     PushOnScopeChains(Namespc, DeclRegionScope);
7266   } else {
7267     // Link the anonymous namespace into its parent.
7268     DeclContext *Parent = CurContext->getRedeclContext();
7269     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7270       TU->setAnonymousNamespace(Namespc);
7271     } else {
7272       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
7273     }
7274 
7275     CurContext->addDecl(Namespc);
7276 
7277     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
7278     //   behaves as if it were replaced by
7279     //     namespace unique { /* empty body */ }
7280     //     using namespace unique;
7281     //     namespace unique { namespace-body }
7282     //   where all occurrences of 'unique' in a translation unit are
7283     //   replaced by the same identifier and this identifier differs
7284     //   from all other identifiers in the entire program.
7285 
7286     // We just create the namespace with an empty name and then add an
7287     // implicit using declaration, just like the standard suggests.
7288     //
7289     // CodeGen enforces the "universally unique" aspect by giving all
7290     // declarations semantically contained within an anonymous
7291     // namespace internal linkage.
7292 
7293     if (!PrevNS) {
7294       UsingDirectiveDecl* UD
7295         = UsingDirectiveDecl::Create(Context, Parent,
7296                                      /* 'using' */ LBrace,
7297                                      /* 'namespace' */ SourceLocation(),
7298                                      /* qualifier */ NestedNameSpecifierLoc(),
7299                                      /* identifier */ SourceLocation(),
7300                                      Namespc,
7301                                      /* Ancestor */ Parent);
7302       UD->setImplicit();
7303       Parent->addDecl(UD);
7304     }
7305   }
7306 
7307   ActOnDocumentableDecl(Namespc);
7308 
7309   // Although we could have an invalid decl (i.e. the namespace name is a
7310   // redefinition), push it as current DeclContext and try to continue parsing.
7311   // FIXME: We should be able to push Namespc here, so that the each DeclContext
7312   // for the namespace has the declarations that showed up in that particular
7313   // namespace definition.
7314   PushDeclContext(NamespcScope, Namespc);
7315   return Namespc;
7316 }
7317 
7318 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
7319 /// is a namespace alias, returns the namespace it points to.
7320 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
7321   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
7322     return AD->getNamespace();
7323   return dyn_cast_or_null<NamespaceDecl>(D);
7324 }
7325 
7326 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
7327 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
7328 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
7329   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
7330   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
7331   Namespc->setRBraceLoc(RBrace);
7332   PopDeclContext();
7333   if (Namespc->hasAttr<VisibilityAttr>())
7334     PopPragmaVisibility(true, RBrace);
7335 }
7336 
7337 CXXRecordDecl *Sema::getStdBadAlloc() const {
7338   return cast_or_null<CXXRecordDecl>(
7339                                   StdBadAlloc.get(Context.getExternalSource()));
7340 }
7341 
7342 NamespaceDecl *Sema::getStdNamespace() const {
7343   return cast_or_null<NamespaceDecl>(
7344                                  StdNamespace.get(Context.getExternalSource()));
7345 }
7346 
7347 /// \brief Retrieve the special "std" namespace, which may require us to
7348 /// implicitly define the namespace.
7349 NamespaceDecl *Sema::getOrCreateStdNamespace() {
7350   if (!StdNamespace) {
7351     // The "std" namespace has not yet been defined, so build one implicitly.
7352     StdNamespace = NamespaceDecl::Create(Context,
7353                                          Context.getTranslationUnitDecl(),
7354                                          /*Inline=*/false,
7355                                          SourceLocation(), SourceLocation(),
7356                                          &PP.getIdentifierTable().get("std"),
7357                                          /*PrevDecl=*/nullptr);
7358     getStdNamespace()->setImplicit(true);
7359   }
7360 
7361   return getStdNamespace();
7362 }
7363 
7364 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
7365   assert(getLangOpts().CPlusPlus &&
7366          "Looking for std::initializer_list outside of C++.");
7367 
7368   // We're looking for implicit instantiations of
7369   // template <typename E> class std::initializer_list.
7370 
7371   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
7372     return false;
7373 
7374   ClassTemplateDecl *Template = nullptr;
7375   const TemplateArgument *Arguments = nullptr;
7376 
7377   if (const RecordType *RT = Ty->getAs<RecordType>()) {
7378 
7379     ClassTemplateSpecializationDecl *Specialization =
7380         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
7381     if (!Specialization)
7382       return false;
7383 
7384     Template = Specialization->getSpecializedTemplate();
7385     Arguments = Specialization->getTemplateArgs().data();
7386   } else if (const TemplateSpecializationType *TST =
7387                  Ty->getAs<TemplateSpecializationType>()) {
7388     Template = dyn_cast_or_null<ClassTemplateDecl>(
7389         TST->getTemplateName().getAsTemplateDecl());
7390     Arguments = TST->getArgs();
7391   }
7392   if (!Template)
7393     return false;
7394 
7395   if (!StdInitializerList) {
7396     // Haven't recognized std::initializer_list yet, maybe this is it.
7397     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
7398     if (TemplateClass->getIdentifier() !=
7399             &PP.getIdentifierTable().get("initializer_list") ||
7400         !getStdNamespace()->InEnclosingNamespaceSetOf(
7401             TemplateClass->getDeclContext()))
7402       return false;
7403     // This is a template called std::initializer_list, but is it the right
7404     // template?
7405     TemplateParameterList *Params = Template->getTemplateParameters();
7406     if (Params->getMinRequiredArguments() != 1)
7407       return false;
7408     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
7409       return false;
7410 
7411     // It's the right template.
7412     StdInitializerList = Template;
7413   }
7414 
7415   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
7416     return false;
7417 
7418   // This is an instance of std::initializer_list. Find the argument type.
7419   if (Element)
7420     *Element = Arguments[0].getAsType();
7421   return true;
7422 }
7423 
7424 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
7425   NamespaceDecl *Std = S.getStdNamespace();
7426   if (!Std) {
7427     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
7428     return nullptr;
7429   }
7430 
7431   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
7432                       Loc, Sema::LookupOrdinaryName);
7433   if (!S.LookupQualifiedName(Result, Std)) {
7434     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
7435     return nullptr;
7436   }
7437   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
7438   if (!Template) {
7439     Result.suppressDiagnostics();
7440     // We found something weird. Complain about the first thing we found.
7441     NamedDecl *Found = *Result.begin();
7442     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
7443     return nullptr;
7444   }
7445 
7446   // We found some template called std::initializer_list. Now verify that it's
7447   // correct.
7448   TemplateParameterList *Params = Template->getTemplateParameters();
7449   if (Params->getMinRequiredArguments() != 1 ||
7450       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
7451     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
7452     return nullptr;
7453   }
7454 
7455   return Template;
7456 }
7457 
7458 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
7459   if (!StdInitializerList) {
7460     StdInitializerList = LookupStdInitializerList(*this, Loc);
7461     if (!StdInitializerList)
7462       return QualType();
7463   }
7464 
7465   TemplateArgumentListInfo Args(Loc, Loc);
7466   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
7467                                        Context.getTrivialTypeSourceInfo(Element,
7468                                                                         Loc)));
7469   return Context.getCanonicalType(
7470       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
7471 }
7472 
7473 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
7474   // C++ [dcl.init.list]p2:
7475   //   A constructor is an initializer-list constructor if its first parameter
7476   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
7477   //   std::initializer_list<E> for some type E, and either there are no other
7478   //   parameters or else all other parameters have default arguments.
7479   if (Ctor->getNumParams() < 1 ||
7480       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
7481     return false;
7482 
7483   QualType ArgType = Ctor->getParamDecl(0)->getType();
7484   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
7485     ArgType = RT->getPointeeType().getUnqualifiedType();
7486 
7487   return isStdInitializerList(ArgType, nullptr);
7488 }
7489 
7490 /// \brief Determine whether a using statement is in a context where it will be
7491 /// apply in all contexts.
7492 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
7493   switch (CurContext->getDeclKind()) {
7494     case Decl::TranslationUnit:
7495       return true;
7496     case Decl::LinkageSpec:
7497       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
7498     default:
7499       return false;
7500   }
7501 }
7502 
7503 namespace {
7504 
7505 // Callback to only accept typo corrections that are namespaces.
7506 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
7507 public:
7508   bool ValidateCandidate(const TypoCorrection &candidate) override {
7509     if (NamedDecl *ND = candidate.getCorrectionDecl())
7510       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
7511     return false;
7512   }
7513 };
7514 
7515 }
7516 
7517 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
7518                                        CXXScopeSpec &SS,
7519                                        SourceLocation IdentLoc,
7520                                        IdentifierInfo *Ident) {
7521   R.clear();
7522   if (TypoCorrection Corrected =
7523           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
7524                         llvm::make_unique<NamespaceValidatorCCC>(),
7525                         Sema::CTK_ErrorRecovery)) {
7526     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
7527       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
7528       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
7529                               Ident->getName().equals(CorrectedStr);
7530       S.diagnoseTypo(Corrected,
7531                      S.PDiag(diag::err_using_directive_member_suggest)
7532                        << Ident << DC << DroppedSpecifier << SS.getRange(),
7533                      S.PDiag(diag::note_namespace_defined_here));
7534     } else {
7535       S.diagnoseTypo(Corrected,
7536                      S.PDiag(diag::err_using_directive_suggest) << Ident,
7537                      S.PDiag(diag::note_namespace_defined_here));
7538     }
7539     R.addDecl(Corrected.getCorrectionDecl());
7540     return true;
7541   }
7542   return false;
7543 }
7544 
7545 Decl *Sema::ActOnUsingDirective(Scope *S,
7546                                           SourceLocation UsingLoc,
7547                                           SourceLocation NamespcLoc,
7548                                           CXXScopeSpec &SS,
7549                                           SourceLocation IdentLoc,
7550                                           IdentifierInfo *NamespcName,
7551                                           AttributeList *AttrList) {
7552   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7553   assert(NamespcName && "Invalid NamespcName.");
7554   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
7555 
7556   // This can only happen along a recovery path.
7557   while (S->getFlags() & Scope::TemplateParamScope)
7558     S = S->getParent();
7559   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7560 
7561   UsingDirectiveDecl *UDir = nullptr;
7562   NestedNameSpecifier *Qualifier = nullptr;
7563   if (SS.isSet())
7564     Qualifier = SS.getScopeRep();
7565 
7566   // Lookup namespace name.
7567   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7568   LookupParsedName(R, S, &SS);
7569   if (R.isAmbiguous())
7570     return nullptr;
7571 
7572   if (R.empty()) {
7573     R.clear();
7574     // Allow "using namespace std;" or "using namespace ::std;" even if
7575     // "std" hasn't been defined yet, for GCC compatibility.
7576     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7577         NamespcName->isStr("std")) {
7578       Diag(IdentLoc, diag::ext_using_undefined_std);
7579       R.addDecl(getOrCreateStdNamespace());
7580       R.resolveKind();
7581     }
7582     // Otherwise, attempt typo correction.
7583     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
7584   }
7585 
7586   if (!R.empty()) {
7587     NamedDecl *Named = R.getFoundDecl();
7588     assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
7589         && "expected namespace decl");
7590 
7591     // The use of a nested name specifier may trigger deprecation warnings.
7592     DiagnoseUseOfDecl(Named, IdentLoc);
7593 
7594     // C++ [namespace.udir]p1:
7595     //   A using-directive specifies that the names in the nominated
7596     //   namespace can be used in the scope in which the
7597     //   using-directive appears after the using-directive. During
7598     //   unqualified name lookup (3.4.1), the names appear as if they
7599     //   were declared in the nearest enclosing namespace which
7600     //   contains both the using-directive and the nominated
7601     //   namespace. [Note: in this context, "contains" means "contains
7602     //   directly or indirectly". ]
7603 
7604     // Find enclosing context containing both using-directive and
7605     // nominated namespace.
7606     NamespaceDecl *NS = getNamespaceDecl(Named);
7607     DeclContext *CommonAncestor = cast<DeclContext>(NS);
7608     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7609       CommonAncestor = CommonAncestor->getParent();
7610 
7611     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
7612                                       SS.getWithLocInContext(Context),
7613                                       IdentLoc, Named, CommonAncestor);
7614 
7615     if (IsUsingDirectiveInToplevelContext(CurContext) &&
7616         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
7617       Diag(IdentLoc, diag::warn_using_directive_in_header);
7618     }
7619 
7620     PushUsingDirective(S, UDir);
7621   } else {
7622     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
7623   }
7624 
7625   if (UDir)
7626     ProcessDeclAttributeList(S, UDir, AttrList);
7627 
7628   return UDir;
7629 }
7630 
7631 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
7632   // If the scope has an associated entity and the using directive is at
7633   // namespace or translation unit scope, add the UsingDirectiveDecl into
7634   // its lookup structure so qualified name lookup can find it.
7635   DeclContext *Ctx = S->getEntity();
7636   if (Ctx && !Ctx->isFunctionOrMethod())
7637     Ctx->addDecl(UDir);
7638   else
7639     // Otherwise, it is at block scope. The using-directives will affect lookup
7640     // only to the end of the scope.
7641     S->PushUsingDirective(UDir);
7642 }
7643 
7644 
7645 Decl *Sema::ActOnUsingDeclaration(Scope *S,
7646                                   AccessSpecifier AS,
7647                                   bool HasUsingKeyword,
7648                                   SourceLocation UsingLoc,
7649                                   CXXScopeSpec &SS,
7650                                   UnqualifiedId &Name,
7651                                   AttributeList *AttrList,
7652                                   bool HasTypenameKeyword,
7653                                   SourceLocation TypenameLoc) {
7654   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7655 
7656   switch (Name.getKind()) {
7657   case UnqualifiedId::IK_ImplicitSelfParam:
7658   case UnqualifiedId::IK_Identifier:
7659   case UnqualifiedId::IK_OperatorFunctionId:
7660   case UnqualifiedId::IK_LiteralOperatorId:
7661   case UnqualifiedId::IK_ConversionFunctionId:
7662     break;
7663 
7664   case UnqualifiedId::IK_ConstructorName:
7665   case UnqualifiedId::IK_ConstructorTemplateId:
7666     // C++11 inheriting constructors.
7667     Diag(Name.getLocStart(),
7668          getLangOpts().CPlusPlus11 ?
7669            diag::warn_cxx98_compat_using_decl_constructor :
7670            diag::err_using_decl_constructor)
7671       << SS.getRange();
7672 
7673     if (getLangOpts().CPlusPlus11) break;
7674 
7675     return nullptr;
7676 
7677   case UnqualifiedId::IK_DestructorName:
7678     Diag(Name.getLocStart(), diag::err_using_decl_destructor)
7679       << SS.getRange();
7680     return nullptr;
7681 
7682   case UnqualifiedId::IK_TemplateId:
7683     Diag(Name.getLocStart(), diag::err_using_decl_template_id)
7684       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
7685     return nullptr;
7686   }
7687 
7688   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7689   DeclarationName TargetName = TargetNameInfo.getName();
7690   if (!TargetName)
7691     return nullptr;
7692 
7693   // Warn about access declarations.
7694   if (!HasUsingKeyword) {
7695     Diag(Name.getLocStart(),
7696          getLangOpts().CPlusPlus11 ? diag::err_access_decl
7697                                    : diag::warn_access_decl_deprecated)
7698       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
7699   }
7700 
7701   if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7702       DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7703     return nullptr;
7704 
7705   NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
7706                                         TargetNameInfo, AttrList,
7707                                         /* IsInstantiation */ false,
7708                                         HasTypenameKeyword, TypenameLoc);
7709   if (UD)
7710     PushOnScopeChains(UD, S, /*AddToContext*/ false);
7711 
7712   return UD;
7713 }
7714 
7715 /// \brief Determine whether a using declaration considers the given
7716 /// declarations as "equivalent", e.g., if they are redeclarations of
7717 /// the same entity or are both typedefs of the same type.
7718 static bool
7719 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7720   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
7721     return true;
7722 
7723   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
7724     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
7725       return Context.hasSameType(TD1->getUnderlyingType(),
7726                                  TD2->getUnderlyingType());
7727 
7728   return false;
7729 }
7730 
7731 
7732 /// Determines whether to create a using shadow decl for a particular
7733 /// decl, given the set of decls existing prior to this using lookup.
7734 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
7735                                 const LookupResult &Previous,
7736                                 UsingShadowDecl *&PrevShadow) {
7737   // Diagnose finding a decl which is not from a base class of the
7738   // current class.  We do this now because there are cases where this
7739   // function will silently decide not to build a shadow decl, which
7740   // will pre-empt further diagnostics.
7741   //
7742   // We don't need to do this in C++0x because we do the check once on
7743   // the qualifier.
7744   //
7745   // FIXME: diagnose the following if we care enough:
7746   //   struct A { int foo; };
7747   //   struct B : A { using A::foo; };
7748   //   template <class T> struct C : A {};
7749   //   template <class T> struct D : C<T> { using B::foo; } // <---
7750   // This is invalid (during instantiation) in C++03 because B::foo
7751   // resolves to the using decl in B, which is not a base class of D<T>.
7752   // We can't diagnose it immediately because C<T> is an unknown
7753   // specialization.  The UsingShadowDecl in D<T> then points directly
7754   // to A::foo, which will look well-formed when we instantiate.
7755   // The right solution is to not collapse the shadow-decl chain.
7756   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
7757     DeclContext *OrigDC = Orig->getDeclContext();
7758 
7759     // Handle enums and anonymous structs.
7760     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7761     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7762     while (OrigRec->isAnonymousStructOrUnion())
7763       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7764 
7765     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7766       if (OrigDC == CurContext) {
7767         Diag(Using->getLocation(),
7768              diag::err_using_decl_nested_name_specifier_is_current_class)
7769           << Using->getQualifierLoc().getSourceRange();
7770         Diag(Orig->getLocation(), diag::note_using_decl_target);
7771         return true;
7772       }
7773 
7774       Diag(Using->getQualifierLoc().getBeginLoc(),
7775            diag::err_using_decl_nested_name_specifier_is_not_base_class)
7776         << Using->getQualifier()
7777         << cast<CXXRecordDecl>(CurContext)
7778         << Using->getQualifierLoc().getSourceRange();
7779       Diag(Orig->getLocation(), diag::note_using_decl_target);
7780       return true;
7781     }
7782   }
7783 
7784   if (Previous.empty()) return false;
7785 
7786   NamedDecl *Target = Orig;
7787   if (isa<UsingShadowDecl>(Target))
7788     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7789 
7790   // If the target happens to be one of the previous declarations, we
7791   // don't have a conflict.
7792   //
7793   // FIXME: but we might be increasing its access, in which case we
7794   // should redeclare it.
7795   NamedDecl *NonTag = nullptr, *Tag = nullptr;
7796   bool FoundEquivalentDecl = false;
7797   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7798          I != E; ++I) {
7799     NamedDecl *D = (*I)->getUnderlyingDecl();
7800     if (IsEquivalentForUsingDecl(Context, D, Target)) {
7801       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7802         PrevShadow = Shadow;
7803       FoundEquivalentDecl = true;
7804     }
7805 
7806     (isa<TagDecl>(D) ? Tag : NonTag) = D;
7807   }
7808 
7809   if (FoundEquivalentDecl)
7810     return false;
7811 
7812   if (FunctionDecl *FD = Target->getAsFunction()) {
7813     NamedDecl *OldDecl = nullptr;
7814     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7815                           /*IsForUsingDecl*/ true)) {
7816     case Ovl_Overload:
7817       return false;
7818 
7819     case Ovl_NonFunction:
7820       Diag(Using->getLocation(), diag::err_using_decl_conflict);
7821       break;
7822 
7823     // We found a decl with the exact signature.
7824     case Ovl_Match:
7825       // If we're in a record, we want to hide the target, so we
7826       // return true (without a diagnostic) to tell the caller not to
7827       // build a shadow decl.
7828       if (CurContext->isRecord())
7829         return true;
7830 
7831       // If we're not in a record, this is an error.
7832       Diag(Using->getLocation(), diag::err_using_decl_conflict);
7833       break;
7834     }
7835 
7836     Diag(Target->getLocation(), diag::note_using_decl_target);
7837     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7838     return true;
7839   }
7840 
7841   // Target is not a function.
7842 
7843   if (isa<TagDecl>(Target)) {
7844     // No conflict between a tag and a non-tag.
7845     if (!Tag) return false;
7846 
7847     Diag(Using->getLocation(), diag::err_using_decl_conflict);
7848     Diag(Target->getLocation(), diag::note_using_decl_target);
7849     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7850     return true;
7851   }
7852 
7853   // No conflict between a tag and a non-tag.
7854   if (!NonTag) return false;
7855 
7856   Diag(Using->getLocation(), diag::err_using_decl_conflict);
7857   Diag(Target->getLocation(), diag::note_using_decl_target);
7858   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7859   return true;
7860 }
7861 
7862 /// Builds a shadow declaration corresponding to a 'using' declaration.
7863 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
7864                                             UsingDecl *UD,
7865                                             NamedDecl *Orig,
7866                                             UsingShadowDecl *PrevDecl) {
7867 
7868   // If we resolved to another shadow declaration, just coalesce them.
7869   NamedDecl *Target = Orig;
7870   if (isa<UsingShadowDecl>(Target)) {
7871     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7872     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
7873   }
7874 
7875   UsingShadowDecl *Shadow
7876     = UsingShadowDecl::Create(Context, CurContext,
7877                               UD->getLocation(), UD, Target);
7878   UD->addShadowDecl(Shadow);
7879 
7880   Shadow->setAccess(UD->getAccess());
7881   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7882     Shadow->setInvalidDecl();
7883 
7884   Shadow->setPreviousDecl(PrevDecl);
7885 
7886   if (S)
7887     PushOnScopeChains(Shadow, S);
7888   else
7889     CurContext->addDecl(Shadow);
7890 
7891 
7892   return Shadow;
7893 }
7894 
7895 /// Hides a using shadow declaration.  This is required by the current
7896 /// using-decl implementation when a resolvable using declaration in a
7897 /// class is followed by a declaration which would hide or override
7898 /// one or more of the using decl's targets; for example:
7899 ///
7900 ///   struct Base { void foo(int); };
7901 ///   struct Derived : Base {
7902 ///     using Base::foo;
7903 ///     void foo(int);
7904 ///   };
7905 ///
7906 /// The governing language is C++03 [namespace.udecl]p12:
7907 ///
7908 ///   When a using-declaration brings names from a base class into a
7909 ///   derived class scope, member functions in the derived class
7910 ///   override and/or hide member functions with the same name and
7911 ///   parameter types in a base class (rather than conflicting).
7912 ///
7913 /// There are two ways to implement this:
7914 ///   (1) optimistically create shadow decls when they're not hidden
7915 ///       by existing declarations, or
7916 ///   (2) don't create any shadow decls (or at least don't make them
7917 ///       visible) until we've fully parsed/instantiated the class.
7918 /// The problem with (1) is that we might have to retroactively remove
7919 /// a shadow decl, which requires several O(n) operations because the
7920 /// decl structures are (very reasonably) not designed for removal.
7921 /// (2) avoids this but is very fiddly and phase-dependent.
7922 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
7923   if (Shadow->getDeclName().getNameKind() ==
7924         DeclarationName::CXXConversionFunctionName)
7925     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7926 
7927   // Remove it from the DeclContext...
7928   Shadow->getDeclContext()->removeDecl(Shadow);
7929 
7930   // ...and the scope, if applicable...
7931   if (S) {
7932     S->RemoveDecl(Shadow);
7933     IdResolver.RemoveDecl(Shadow);
7934   }
7935 
7936   // ...and the using decl.
7937   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7938 
7939   // TODO: complain somehow if Shadow was used.  It shouldn't
7940   // be possible for this to happen, because...?
7941 }
7942 
7943 /// Find the base specifier for a base class with the given type.
7944 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7945                                                 QualType DesiredBase,
7946                                                 bool &AnyDependentBases) {
7947   // Check whether the named type is a direct base class.
7948   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7949   for (auto &Base : Derived->bases()) {
7950     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7951     if (CanonicalDesiredBase == BaseType)
7952       return &Base;
7953     if (BaseType->isDependentType())
7954       AnyDependentBases = true;
7955   }
7956   return nullptr;
7957 }
7958 
7959 namespace {
7960 class UsingValidatorCCC : public CorrectionCandidateCallback {
7961 public:
7962   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
7963                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
7964       : HasTypenameKeyword(HasTypenameKeyword),
7965         IsInstantiation(IsInstantiation), OldNNS(NNS),
7966         RequireMemberOf(RequireMemberOf) {}
7967 
7968   bool ValidateCandidate(const TypoCorrection &Candidate) override {
7969     NamedDecl *ND = Candidate.getCorrectionDecl();
7970 
7971     // Keywords are not valid here.
7972     if (!ND || isa<NamespaceDecl>(ND))
7973       return false;
7974 
7975     // Completely unqualified names are invalid for a 'using' declaration.
7976     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7977       return false;
7978 
7979     if (RequireMemberOf) {
7980       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
7981       if (FoundRecord && FoundRecord->isInjectedClassName()) {
7982         // No-one ever wants a using-declaration to name an injected-class-name
7983         // of a base class, unless they're declaring an inheriting constructor.
7984         ASTContext &Ctx = ND->getASTContext();
7985         if (!Ctx.getLangOpts().CPlusPlus11)
7986           return false;
7987         QualType FoundType = Ctx.getRecordType(FoundRecord);
7988 
7989         // Check that the injected-class-name is named as a member of its own
7990         // type; we don't want to suggest 'using Derived::Base;', since that
7991         // means something else.
7992         NestedNameSpecifier *Specifier =
7993             Candidate.WillReplaceSpecifier()
7994                 ? Candidate.getCorrectionSpecifier()
7995                 : OldNNS;
7996         if (!Specifier->getAsType() ||
7997             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
7998           return false;
7999 
8000         // Check that this inheriting constructor declaration actually names a
8001         // direct base class of the current class.
8002         bool AnyDependentBases = false;
8003         if (!findDirectBaseWithType(RequireMemberOf,
8004                                     Ctx.getRecordType(FoundRecord),
8005                                     AnyDependentBases) &&
8006             !AnyDependentBases)
8007           return false;
8008       } else {
8009         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
8010         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
8011           return false;
8012 
8013         // FIXME: Check that the base class member is accessible?
8014       }
8015     }
8016 
8017     if (isa<TypeDecl>(ND))
8018       return HasTypenameKeyword || !IsInstantiation;
8019 
8020     return !HasTypenameKeyword;
8021   }
8022 
8023 private:
8024   bool HasTypenameKeyword;
8025   bool IsInstantiation;
8026   NestedNameSpecifier *OldNNS;
8027   CXXRecordDecl *RequireMemberOf;
8028 };
8029 } // end anonymous namespace
8030 
8031 /// Builds a using declaration.
8032 ///
8033 /// \param IsInstantiation - Whether this call arises from an
8034 ///   instantiation of an unresolved using declaration.  We treat
8035 ///   the lookup differently for these declarations.
8036 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
8037                                        SourceLocation UsingLoc,
8038                                        CXXScopeSpec &SS,
8039                                        DeclarationNameInfo NameInfo,
8040                                        AttributeList *AttrList,
8041                                        bool IsInstantiation,
8042                                        bool HasTypenameKeyword,
8043                                        SourceLocation TypenameLoc) {
8044   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
8045   SourceLocation IdentLoc = NameInfo.getLoc();
8046   assert(IdentLoc.isValid() && "Invalid TargetName location.");
8047 
8048   // FIXME: We ignore attributes for now.
8049 
8050   if (SS.isEmpty()) {
8051     Diag(IdentLoc, diag::err_using_requires_qualname);
8052     return nullptr;
8053   }
8054 
8055   // Do the redeclaration lookup in the current scope.
8056   LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
8057                         ForRedeclaration);
8058   Previous.setHideTags(false);
8059   if (S) {
8060     LookupName(Previous, S);
8061 
8062     // It is really dumb that we have to do this.
8063     LookupResult::Filter F = Previous.makeFilter();
8064     while (F.hasNext()) {
8065       NamedDecl *D = F.next();
8066       if (!isDeclInScope(D, CurContext, S))
8067         F.erase();
8068       // If we found a local extern declaration that's not ordinarily visible,
8069       // and this declaration is being added to a non-block scope, ignore it.
8070       // We're only checking for scope conflicts here, not also for violations
8071       // of the linkage rules.
8072       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
8073                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
8074         F.erase();
8075     }
8076     F.done();
8077   } else {
8078     assert(IsInstantiation && "no scope in non-instantiation");
8079     assert(CurContext->isRecord() && "scope not record in instantiation");
8080     LookupQualifiedName(Previous, CurContext);
8081   }
8082 
8083   // Check for invalid redeclarations.
8084   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
8085                                   SS, IdentLoc, Previous))
8086     return nullptr;
8087 
8088   // Check for bad qualifiers.
8089   if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
8090     return nullptr;
8091 
8092   DeclContext *LookupContext = computeDeclContext(SS);
8093   NamedDecl *D;
8094   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
8095   if (!LookupContext) {
8096     if (HasTypenameKeyword) {
8097       // FIXME: not all declaration name kinds are legal here
8098       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
8099                                               UsingLoc, TypenameLoc,
8100                                               QualifierLoc,
8101                                               IdentLoc, NameInfo.getName());
8102     } else {
8103       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
8104                                            QualifierLoc, NameInfo);
8105     }
8106     D->setAccess(AS);
8107     CurContext->addDecl(D);
8108     return D;
8109   }
8110 
8111   auto Build = [&](bool Invalid) {
8112     UsingDecl *UD =
8113         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
8114                           HasTypenameKeyword);
8115     UD->setAccess(AS);
8116     CurContext->addDecl(UD);
8117     UD->setInvalidDecl(Invalid);
8118     return UD;
8119   };
8120   auto BuildInvalid = [&]{ return Build(true); };
8121   auto BuildValid = [&]{ return Build(false); };
8122 
8123   if (RequireCompleteDeclContext(SS, LookupContext))
8124     return BuildInvalid();
8125 
8126   // Look up the target name.
8127   LookupResult R(*this, NameInfo, LookupOrdinaryName);
8128 
8129   // Unlike most lookups, we don't always want to hide tag
8130   // declarations: tag names are visible through the using declaration
8131   // even if hidden by ordinary names, *except* in a dependent context
8132   // where it's important for the sanity of two-phase lookup.
8133   if (!IsInstantiation)
8134     R.setHideTags(false);
8135 
8136   // For the purposes of this lookup, we have a base object type
8137   // equal to that of the current context.
8138   if (CurContext->isRecord()) {
8139     R.setBaseObjectType(
8140                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
8141   }
8142 
8143   LookupQualifiedName(R, LookupContext);
8144 
8145   // Try to correct typos if possible. If constructor name lookup finds no
8146   // results, that means the named class has no explicit constructors, and we
8147   // suppressed declaring implicit ones (probably because it's dependent or
8148   // invalid).
8149   if (R.empty() &&
8150       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
8151     if (TypoCorrection Corrected = CorrectTypo(
8152             R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
8153             llvm::make_unique<UsingValidatorCCC>(
8154                 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
8155                 dyn_cast<CXXRecordDecl>(CurContext)),
8156             CTK_ErrorRecovery)) {
8157       // We reject any correction for which ND would be NULL.
8158       NamedDecl *ND = Corrected.getCorrectionDecl();
8159 
8160       // We reject candidates where DroppedSpecifier == true, hence the
8161       // literal '0' below.
8162       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
8163                                 << NameInfo.getName() << LookupContext << 0
8164                                 << SS.getRange());
8165 
8166       // If we corrected to an inheriting constructor, handle it as one.
8167       auto *RD = dyn_cast<CXXRecordDecl>(ND);
8168       if (RD && RD->isInjectedClassName()) {
8169         // Fix up the information we'll use to build the using declaration.
8170         if (Corrected.WillReplaceSpecifier()) {
8171           NestedNameSpecifierLocBuilder Builder;
8172           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
8173                               QualifierLoc.getSourceRange());
8174           QualifierLoc = Builder.getWithLocInContext(Context);
8175         }
8176 
8177         NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
8178             Context.getCanonicalType(Context.getRecordType(RD))));
8179         NameInfo.setNamedTypeInfo(nullptr);
8180         for (auto *Ctor : LookupConstructors(RD))
8181           R.addDecl(Ctor);
8182       } else {
8183         // FIXME: Pick up all the declarations if we found an overloaded function.
8184         R.addDecl(ND);
8185       }
8186     } else {
8187       Diag(IdentLoc, diag::err_no_member)
8188         << NameInfo.getName() << LookupContext << SS.getRange();
8189       return BuildInvalid();
8190     }
8191   }
8192 
8193   if (R.isAmbiguous())
8194     return BuildInvalid();
8195 
8196   if (HasTypenameKeyword) {
8197     // If we asked for a typename and got a non-type decl, error out.
8198     if (!R.getAsSingle<TypeDecl>()) {
8199       Diag(IdentLoc, diag::err_using_typename_non_type);
8200       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8201         Diag((*I)->getUnderlyingDecl()->getLocation(),
8202              diag::note_using_decl_target);
8203       return BuildInvalid();
8204     }
8205   } else {
8206     // If we asked for a non-typename and we got a type, error out,
8207     // but only if this is an instantiation of an unresolved using
8208     // decl.  Otherwise just silently find the type name.
8209     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
8210       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
8211       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
8212       return BuildInvalid();
8213     }
8214   }
8215 
8216   // C++0x N2914 [namespace.udecl]p6:
8217   // A using-declaration shall not name a namespace.
8218   if (R.getAsSingle<NamespaceDecl>()) {
8219     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
8220       << SS.getRange();
8221     return BuildInvalid();
8222   }
8223 
8224   UsingDecl *UD = BuildValid();
8225 
8226   // The normal rules do not apply to inheriting constructor declarations.
8227   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
8228     // Suppress access diagnostics; the access check is instead performed at the
8229     // point of use for an inheriting constructor.
8230     R.suppressDiagnostics();
8231     CheckInheritingConstructorUsingDecl(UD);
8232     return UD;
8233   }
8234 
8235   // Otherwise, look up the target name.
8236 
8237   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8238     UsingShadowDecl *PrevDecl = nullptr;
8239     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
8240       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
8241   }
8242 
8243   return UD;
8244 }
8245 
8246 /// Additional checks for a using declaration referring to a constructor name.
8247 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
8248   assert(!UD->hasTypename() && "expecting a constructor name");
8249 
8250   const Type *SourceType = UD->getQualifier()->getAsType();
8251   assert(SourceType &&
8252          "Using decl naming constructor doesn't have type in scope spec.");
8253   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
8254 
8255   // Check whether the named type is a direct base class.
8256   bool AnyDependentBases = false;
8257   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
8258                                       AnyDependentBases);
8259   if (!Base && !AnyDependentBases) {
8260     Diag(UD->getUsingLoc(),
8261          diag::err_using_decl_constructor_not_in_direct_base)
8262       << UD->getNameInfo().getSourceRange()
8263       << QualType(SourceType, 0) << TargetClass;
8264     UD->setInvalidDecl();
8265     return true;
8266   }
8267 
8268   if (Base)
8269     Base->setInheritConstructors();
8270 
8271   return false;
8272 }
8273 
8274 /// Checks that the given using declaration is not an invalid
8275 /// redeclaration.  Note that this is checking only for the using decl
8276 /// itself, not for any ill-formedness among the UsingShadowDecls.
8277 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
8278                                        bool HasTypenameKeyword,
8279                                        const CXXScopeSpec &SS,
8280                                        SourceLocation NameLoc,
8281                                        const LookupResult &Prev) {
8282   // C++03 [namespace.udecl]p8:
8283   // C++0x [namespace.udecl]p10:
8284   //   A using-declaration is a declaration and can therefore be used
8285   //   repeatedly where (and only where) multiple declarations are
8286   //   allowed.
8287   //
8288   // That's in non-member contexts.
8289   if (!CurContext->getRedeclContext()->isRecord())
8290     return false;
8291 
8292   NestedNameSpecifier *Qual = SS.getScopeRep();
8293 
8294   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
8295     NamedDecl *D = *I;
8296 
8297     bool DTypename;
8298     NestedNameSpecifier *DQual;
8299     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
8300       DTypename = UD->hasTypename();
8301       DQual = UD->getQualifier();
8302     } else if (UnresolvedUsingValueDecl *UD
8303                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
8304       DTypename = false;
8305       DQual = UD->getQualifier();
8306     } else if (UnresolvedUsingTypenameDecl *UD
8307                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
8308       DTypename = true;
8309       DQual = UD->getQualifier();
8310     } else continue;
8311 
8312     // using decls differ if one says 'typename' and the other doesn't.
8313     // FIXME: non-dependent using decls?
8314     if (HasTypenameKeyword != DTypename) continue;
8315 
8316     // using decls differ if they name different scopes (but note that
8317     // template instantiation can cause this check to trigger when it
8318     // didn't before instantiation).
8319     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
8320         Context.getCanonicalNestedNameSpecifier(DQual))
8321       continue;
8322 
8323     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
8324     Diag(D->getLocation(), diag::note_using_decl) << 1;
8325     return true;
8326   }
8327 
8328   return false;
8329 }
8330 
8331 
8332 /// Checks that the given nested-name qualifier used in a using decl
8333 /// in the current context is appropriately related to the current
8334 /// scope.  If an error is found, diagnoses it and returns true.
8335 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
8336                                    const CXXScopeSpec &SS,
8337                                    const DeclarationNameInfo &NameInfo,
8338                                    SourceLocation NameLoc) {
8339   DeclContext *NamedContext = computeDeclContext(SS);
8340 
8341   if (!CurContext->isRecord()) {
8342     // C++03 [namespace.udecl]p3:
8343     // C++0x [namespace.udecl]p8:
8344     //   A using-declaration for a class member shall be a member-declaration.
8345 
8346     // If we weren't able to compute a valid scope, it must be a
8347     // dependent class scope.
8348     if (!NamedContext || NamedContext->isRecord()) {
8349       auto *RD = dyn_cast_or_null<CXXRecordDecl>(NamedContext);
8350       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
8351         RD = nullptr;
8352 
8353       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
8354         << SS.getRange();
8355 
8356       // If we have a complete, non-dependent source type, try to suggest a
8357       // way to get the same effect.
8358       if (!RD)
8359         return true;
8360 
8361       // Find what this using-declaration was referring to.
8362       LookupResult R(*this, NameInfo, LookupOrdinaryName);
8363       R.setHideTags(false);
8364       R.suppressDiagnostics();
8365       LookupQualifiedName(R, RD);
8366 
8367       if (R.getAsSingle<TypeDecl>()) {
8368         if (getLangOpts().CPlusPlus11) {
8369           // Convert 'using X::Y;' to 'using Y = X::Y;'.
8370           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
8371             << 0 // alias declaration
8372             << FixItHint::CreateInsertion(SS.getBeginLoc(),
8373                                           NameInfo.getName().getAsString() +
8374                                               " = ");
8375         } else {
8376           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
8377           SourceLocation InsertLoc =
8378               PP.getLocForEndOfToken(NameInfo.getLocEnd());
8379           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
8380             << 1 // typedef declaration
8381             << FixItHint::CreateReplacement(UsingLoc, "typedef")
8382             << FixItHint::CreateInsertion(
8383                    InsertLoc, " " + NameInfo.getName().getAsString());
8384         }
8385       } else if (R.getAsSingle<VarDecl>()) {
8386         // Don't provide a fixit outside C++11 mode; we don't want to suggest
8387         // repeating the type of the static data member here.
8388         FixItHint FixIt;
8389         if (getLangOpts().CPlusPlus11) {
8390           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
8391           FixIt = FixItHint::CreateReplacement(
8392               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
8393         }
8394 
8395         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
8396           << 2 // reference declaration
8397           << FixIt;
8398       }
8399       return true;
8400     }
8401 
8402     // Otherwise, everything is known to be fine.
8403     return false;
8404   }
8405 
8406   // The current scope is a record.
8407 
8408   // If the named context is dependent, we can't decide much.
8409   if (!NamedContext) {
8410     // FIXME: in C++0x, we can diagnose if we can prove that the
8411     // nested-name-specifier does not refer to a base class, which is
8412     // still possible in some cases.
8413 
8414     // Otherwise we have to conservatively report that things might be
8415     // okay.
8416     return false;
8417   }
8418 
8419   if (!NamedContext->isRecord()) {
8420     // Ideally this would point at the last name in the specifier,
8421     // but we don't have that level of source info.
8422     Diag(SS.getRange().getBegin(),
8423          diag::err_using_decl_nested_name_specifier_is_not_class)
8424       << SS.getScopeRep() << SS.getRange();
8425     return true;
8426   }
8427 
8428   if (!NamedContext->isDependentContext() &&
8429       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
8430     return true;
8431 
8432   if (getLangOpts().CPlusPlus11) {
8433     // C++0x [namespace.udecl]p3:
8434     //   In a using-declaration used as a member-declaration, the
8435     //   nested-name-specifier shall name a base class of the class
8436     //   being defined.
8437 
8438     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
8439                                  cast<CXXRecordDecl>(NamedContext))) {
8440       if (CurContext == NamedContext) {
8441         Diag(NameLoc,
8442              diag::err_using_decl_nested_name_specifier_is_current_class)
8443           << SS.getRange();
8444         return true;
8445       }
8446 
8447       Diag(SS.getRange().getBegin(),
8448            diag::err_using_decl_nested_name_specifier_is_not_base_class)
8449         << SS.getScopeRep()
8450         << cast<CXXRecordDecl>(CurContext)
8451         << SS.getRange();
8452       return true;
8453     }
8454 
8455     return false;
8456   }
8457 
8458   // C++03 [namespace.udecl]p4:
8459   //   A using-declaration used as a member-declaration shall refer
8460   //   to a member of a base class of the class being defined [etc.].
8461 
8462   // Salient point: SS doesn't have to name a base class as long as
8463   // lookup only finds members from base classes.  Therefore we can
8464   // diagnose here only if we can prove that that can't happen,
8465   // i.e. if the class hierarchies provably don't intersect.
8466 
8467   // TODO: it would be nice if "definitely valid" results were cached
8468   // in the UsingDecl and UsingShadowDecl so that these checks didn't
8469   // need to be repeated.
8470 
8471   struct UserData {
8472     llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
8473 
8474     static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
8475       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8476       Data->Bases.insert(Base);
8477       return true;
8478     }
8479 
8480     bool hasDependentBases(const CXXRecordDecl *Class) {
8481       return !Class->forallBases(collect, this);
8482     }
8483 
8484     /// Returns true if the base is dependent or is one of the
8485     /// accumulated base classes.
8486     static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
8487       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8488       return !Data->Bases.count(Base);
8489     }
8490 
8491     bool mightShareBases(const CXXRecordDecl *Class) {
8492       return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
8493     }
8494   };
8495 
8496   UserData Data;
8497 
8498   // Returns false if we find a dependent base.
8499   if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
8500     return false;
8501 
8502   // Returns false if the class has a dependent base or if it or one
8503   // of its bases is present in the base set of the current context.
8504   if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
8505     return false;
8506 
8507   Diag(SS.getRange().getBegin(),
8508        diag::err_using_decl_nested_name_specifier_is_not_base_class)
8509     << SS.getScopeRep()
8510     << cast<CXXRecordDecl>(CurContext)
8511     << SS.getRange();
8512 
8513   return true;
8514 }
8515 
8516 Decl *Sema::ActOnAliasDeclaration(Scope *S,
8517                                   AccessSpecifier AS,
8518                                   MultiTemplateParamsArg TemplateParamLists,
8519                                   SourceLocation UsingLoc,
8520                                   UnqualifiedId &Name,
8521                                   AttributeList *AttrList,
8522                                   TypeResult Type,
8523                                   Decl *DeclFromDeclSpec) {
8524   // Skip up to the relevant declaration scope.
8525   while (S->getFlags() & Scope::TemplateParamScope)
8526     S = S->getParent();
8527   assert((S->getFlags() & Scope::DeclScope) &&
8528          "got alias-declaration outside of declaration scope");
8529 
8530   if (Type.isInvalid())
8531     return nullptr;
8532 
8533   bool Invalid = false;
8534   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
8535   TypeSourceInfo *TInfo = nullptr;
8536   GetTypeFromParser(Type.get(), &TInfo);
8537 
8538   if (DiagnoseClassNameShadow(CurContext, NameInfo))
8539     return nullptr;
8540 
8541   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
8542                                       UPPC_DeclarationType)) {
8543     Invalid = true;
8544     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8545                                              TInfo->getTypeLoc().getBeginLoc());
8546   }
8547 
8548   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
8549   LookupName(Previous, S);
8550 
8551   // Warn about shadowing the name of a template parameter.
8552   if (Previous.isSingleResult() &&
8553       Previous.getFoundDecl()->isTemplateParameter()) {
8554     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
8555     Previous.clear();
8556   }
8557 
8558   assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8559          "name in alias declaration must be an identifier");
8560   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
8561                                                Name.StartLocation,
8562                                                Name.Identifier, TInfo);
8563 
8564   NewTD->setAccess(AS);
8565 
8566   if (Invalid)
8567     NewTD->setInvalidDecl();
8568 
8569   ProcessDeclAttributeList(S, NewTD, AttrList);
8570 
8571   CheckTypedefForVariablyModifiedType(S, NewTD);
8572   Invalid |= NewTD->isInvalidDecl();
8573 
8574   bool Redeclaration = false;
8575 
8576   NamedDecl *NewND;
8577   if (TemplateParamLists.size()) {
8578     TypeAliasTemplateDecl *OldDecl = nullptr;
8579     TemplateParameterList *OldTemplateParams = nullptr;
8580 
8581     if (TemplateParamLists.size() != 1) {
8582       Diag(UsingLoc, diag::err_alias_template_extra_headers)
8583         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8584          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
8585     }
8586     TemplateParameterList *TemplateParams = TemplateParamLists[0];
8587 
8588     // Only consider previous declarations in the same scope.
8589     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8590                          /*ExplicitInstantiationOrSpecialization*/false);
8591     if (!Previous.empty()) {
8592       Redeclaration = true;
8593 
8594       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8595       if (!OldDecl && !Invalid) {
8596         Diag(UsingLoc, diag::err_redefinition_different_kind)
8597           << Name.Identifier;
8598 
8599         NamedDecl *OldD = Previous.getRepresentativeDecl();
8600         if (OldD->getLocation().isValid())
8601           Diag(OldD->getLocation(), diag::note_previous_definition);
8602 
8603         Invalid = true;
8604       }
8605 
8606       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8607         if (TemplateParameterListsAreEqual(TemplateParams,
8608                                            OldDecl->getTemplateParameters(),
8609                                            /*Complain=*/true,
8610                                            TPL_TemplateMatch))
8611           OldTemplateParams = OldDecl->getTemplateParameters();
8612         else
8613           Invalid = true;
8614 
8615         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8616         if (!Invalid &&
8617             !Context.hasSameType(OldTD->getUnderlyingType(),
8618                                  NewTD->getUnderlyingType())) {
8619           // FIXME: The C++0x standard does not clearly say this is ill-formed,
8620           // but we can't reasonably accept it.
8621           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8622             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8623           if (OldTD->getLocation().isValid())
8624             Diag(OldTD->getLocation(), diag::note_previous_definition);
8625           Invalid = true;
8626         }
8627       }
8628     }
8629 
8630     // Merge any previous default template arguments into our parameters,
8631     // and check the parameter list.
8632     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8633                                    TPC_TypeAliasTemplate))
8634       return nullptr;
8635 
8636     TypeAliasTemplateDecl *NewDecl =
8637       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8638                                     Name.Identifier, TemplateParams,
8639                                     NewTD);
8640     NewTD->setDescribedAliasTemplate(NewDecl);
8641 
8642     NewDecl->setAccess(AS);
8643 
8644     if (Invalid)
8645       NewDecl->setInvalidDecl();
8646     else if (OldDecl)
8647       NewDecl->setPreviousDecl(OldDecl);
8648 
8649     NewND = NewDecl;
8650   } else {
8651     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
8652       setTagNameForLinkagePurposes(TD, NewTD);
8653       handleTagNumbering(TD, S);
8654     }
8655     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8656     NewND = NewTD;
8657   }
8658 
8659   if (!Redeclaration)
8660     PushOnScopeChains(NewND, S);
8661 
8662   ActOnDocumentableDecl(NewND);
8663   return NewND;
8664 }
8665 
8666 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
8667                                    SourceLocation AliasLoc,
8668                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
8669                                    SourceLocation IdentLoc,
8670                                    IdentifierInfo *Ident) {
8671 
8672   // Lookup the namespace name.
8673   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8674   LookupParsedName(R, S, &SS);
8675 
8676   if (R.isAmbiguous())
8677     return nullptr;
8678 
8679   if (R.empty()) {
8680     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
8681       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
8682       return nullptr;
8683     }
8684   }
8685   assert(!R.isAmbiguous() && !R.empty());
8686 
8687   // Check if we have a previous declaration with the same name.
8688   NamedDecl *PrevDecl = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
8689                                          ForRedeclaration);
8690   if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
8691     PrevDecl = nullptr;
8692 
8693   NamedDecl *ND = R.getFoundDecl();
8694 
8695   if (PrevDecl) {
8696     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
8697       // We already have an alias with the same name that points to the same
8698       // namespace; check that it matches.
8699       if (!AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
8700         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
8701           << Alias;
8702         Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias)
8703           << AD->getNamespace();
8704         return nullptr;
8705       }
8706     } else {
8707       unsigned DiagID = isa<NamespaceDecl>(PrevDecl)
8708                             ? diag::err_redefinition
8709                             : diag::err_redefinition_different_kind;
8710       Diag(AliasLoc, DiagID) << Alias;
8711       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8712       return nullptr;
8713     }
8714   }
8715 
8716   // The use of a nested name specifier may trigger deprecation warnings.
8717   DiagnoseUseOfDecl(ND, IdentLoc);
8718 
8719   NamespaceAliasDecl *AliasDecl =
8720     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
8721                                Alias, SS.getWithLocInContext(Context),
8722                                IdentLoc, ND);
8723   if (PrevDecl)
8724     AliasDecl->setPreviousDecl(cast<NamespaceAliasDecl>(PrevDecl));
8725 
8726   PushOnScopeChains(AliasDecl, S);
8727   return AliasDecl;
8728 }
8729 
8730 Sema::ImplicitExceptionSpecification
8731 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8732                                                CXXMethodDecl *MD) {
8733   CXXRecordDecl *ClassDecl = MD->getParent();
8734 
8735   // C++ [except.spec]p14:
8736   //   An implicitly declared special member function (Clause 12) shall have an
8737   //   exception-specification. [...]
8738   ImplicitExceptionSpecification ExceptSpec(*this);
8739   if (ClassDecl->isInvalidDecl())
8740     return ExceptSpec;
8741 
8742   // Direct base-class constructors.
8743   for (const auto &B : ClassDecl->bases()) {
8744     if (B.isVirtual()) // Handled below.
8745       continue;
8746 
8747     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8748       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8749       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8750       // If this is a deleted function, add it anyway. This might be conformant
8751       // with the standard. This might not. I'm not sure. It might not matter.
8752       if (Constructor)
8753         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8754     }
8755   }
8756 
8757   // Virtual base-class constructors.
8758   for (const auto &B : ClassDecl->vbases()) {
8759     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8760       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8761       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8762       // If this is a deleted function, add it anyway. This might be conformant
8763       // with the standard. This might not. I'm not sure. It might not matter.
8764       if (Constructor)
8765         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8766     }
8767   }
8768 
8769   // Field constructors.
8770   for (const auto *F : ClassDecl->fields()) {
8771     if (F->hasInClassInitializer()) {
8772       if (Expr *E = F->getInClassInitializer())
8773         ExceptSpec.CalledExpr(E);
8774     } else if (const RecordType *RecordTy
8775               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8776       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8777       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8778       // If this is a deleted function, add it anyway. This might be conformant
8779       // with the standard. This might not. I'm not sure. It might not matter.
8780       // In particular, the problem is that this function never gets called. It
8781       // might just be ill-formed because this function attempts to refer to
8782       // a deleted function here.
8783       if (Constructor)
8784         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8785     }
8786   }
8787 
8788   return ExceptSpec;
8789 }
8790 
8791 Sema::ImplicitExceptionSpecification
8792 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8793   CXXRecordDecl *ClassDecl = CD->getParent();
8794 
8795   // C++ [except.spec]p14:
8796   //   An inheriting constructor [...] shall have an exception-specification. [...]
8797   ImplicitExceptionSpecification ExceptSpec(*this);
8798   if (ClassDecl->isInvalidDecl())
8799     return ExceptSpec;
8800 
8801   // Inherited constructor.
8802   const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8803   const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8804   // FIXME: Copying or moving the parameters could add extra exceptions to the
8805   // set, as could the default arguments for the inherited constructor. This
8806   // will be addressed when we implement the resolution of core issue 1351.
8807   ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8808 
8809   // Direct base-class constructors.
8810   for (const auto &B : ClassDecl->bases()) {
8811     if (B.isVirtual()) // Handled below.
8812       continue;
8813 
8814     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8815       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8816       if (BaseClassDecl == InheritedDecl)
8817         continue;
8818       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8819       if (Constructor)
8820         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8821     }
8822   }
8823 
8824   // Virtual base-class constructors.
8825   for (const auto &B : ClassDecl->vbases()) {
8826     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8827       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8828       if (BaseClassDecl == InheritedDecl)
8829         continue;
8830       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8831       if (Constructor)
8832         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8833     }
8834   }
8835 
8836   // Field constructors.
8837   for (const auto *F : ClassDecl->fields()) {
8838     if (F->hasInClassInitializer()) {
8839       if (Expr *E = F->getInClassInitializer())
8840         ExceptSpec.CalledExpr(E);
8841     } else if (const RecordType *RecordTy
8842               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8843       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8844       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8845       if (Constructor)
8846         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8847     }
8848   }
8849 
8850   return ExceptSpec;
8851 }
8852 
8853 namespace {
8854 /// RAII object to register a special member as being currently declared.
8855 struct DeclaringSpecialMember {
8856   Sema &S;
8857   Sema::SpecialMemberDecl D;
8858   bool WasAlreadyBeingDeclared;
8859 
8860   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8861     : S(S), D(RD, CSM) {
8862     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
8863     if (WasAlreadyBeingDeclared)
8864       // This almost never happens, but if it does, ensure that our cache
8865       // doesn't contain a stale result.
8866       S.SpecialMemberCache.clear();
8867 
8868     // FIXME: Register a note to be produced if we encounter an error while
8869     // declaring the special member.
8870   }
8871   ~DeclaringSpecialMember() {
8872     if (!WasAlreadyBeingDeclared)
8873       S.SpecialMembersBeingDeclared.erase(D);
8874   }
8875 
8876   /// \brief Are we already trying to declare this special member?
8877   bool isAlreadyBeingDeclared() const {
8878     return WasAlreadyBeingDeclared;
8879   }
8880 };
8881 }
8882 
8883 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8884                                                      CXXRecordDecl *ClassDecl) {
8885   // C++ [class.ctor]p5:
8886   //   A default constructor for a class X is a constructor of class X
8887   //   that can be called without an argument. If there is no
8888   //   user-declared constructor for class X, a default constructor is
8889   //   implicitly declared. An implicitly-declared default constructor
8890   //   is an inline public member of its class.
8891   assert(ClassDecl->needsImplicitDefaultConstructor() &&
8892          "Should not build implicit default constructor!");
8893 
8894   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8895   if (DSM.isAlreadyBeingDeclared())
8896     return nullptr;
8897 
8898   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8899                                                      CXXDefaultConstructor,
8900                                                      false);
8901 
8902   // Create the actual constructor declaration.
8903   CanQualType ClassType
8904     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8905   SourceLocation ClassLoc = ClassDecl->getLocation();
8906   DeclarationName Name
8907     = Context.DeclarationNames.getCXXConstructorName(ClassType);
8908   DeclarationNameInfo NameInfo(Name, ClassLoc);
8909   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
8910       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8911       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8912       /*isImplicitlyDeclared=*/true, Constexpr);
8913   DefaultCon->setAccess(AS_public);
8914   DefaultCon->setDefaulted();
8915 
8916   if (getLangOpts().CUDA) {
8917     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
8918                                             DefaultCon,
8919                                             /* ConstRHS */ false,
8920                                             /* Diagnose */ false);
8921   }
8922 
8923   // Build an exception specification pointing back at this constructor.
8924   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
8925   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8926 
8927   // We don't need to use SpecialMemberIsTrivial here; triviality for default
8928   // constructors is easy to compute.
8929   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8930 
8931   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
8932     SetDeclDeleted(DefaultCon, ClassLoc);
8933 
8934   // Note that we have declared this constructor.
8935   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
8936 
8937   if (Scope *S = getScopeForContext(ClassDecl))
8938     PushOnScopeChains(DefaultCon, S, false);
8939   ClassDecl->addDecl(DefaultCon);
8940 
8941   return DefaultCon;
8942 }
8943 
8944 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8945                                             CXXConstructorDecl *Constructor) {
8946   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
8947           !Constructor->doesThisDeclarationHaveABody() &&
8948           !Constructor->isDeleted()) &&
8949     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
8950 
8951   CXXRecordDecl *ClassDecl = Constructor->getParent();
8952   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
8953 
8954   SynthesizedFunctionScope Scope(*this, Constructor);
8955   DiagnosticErrorTrap Trap(Diags);
8956   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8957       Trap.hasErrorOccurred()) {
8958     Diag(CurrentLocation, diag::note_member_synthesized_at)
8959       << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
8960     Constructor->setInvalidDecl();
8961     return;
8962   }
8963 
8964   // The exception specification is needed because we are defining the
8965   // function.
8966   ResolveExceptionSpec(CurrentLocation,
8967                        Constructor->getType()->castAs<FunctionProtoType>());
8968 
8969   SourceLocation Loc = Constructor->getLocEnd().isValid()
8970                            ? Constructor->getLocEnd()
8971                            : Constructor->getLocation();
8972   Constructor->setBody(new (Context) CompoundStmt(Loc));
8973 
8974   Constructor->markUsed(Context);
8975   MarkVTableUsed(CurrentLocation, ClassDecl);
8976 
8977   if (ASTMutationListener *L = getASTMutationListener()) {
8978     L->CompletedImplicitDefinition(Constructor);
8979   }
8980 
8981   DiagnoseUninitializedFields(*this, Constructor);
8982 }
8983 
8984 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
8985   // Perform any delayed checks on exception specifications.
8986   CheckDelayedMemberExceptionSpecs();
8987 }
8988 
8989 namespace {
8990 /// Information on inheriting constructors to declare.
8991 class InheritingConstructorInfo {
8992 public:
8993   InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8994       : SemaRef(SemaRef), Derived(Derived) {
8995     // Mark the constructors that we already have in the derived class.
8996     //
8997     // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8998     //   unless there is a user-declared constructor with the same signature in
8999     //   the class where the using-declaration appears.
9000     visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
9001   }
9002 
9003   void inheritAll(CXXRecordDecl *RD) {
9004     visitAll(RD, &InheritingConstructorInfo::inherit);
9005   }
9006 
9007 private:
9008   /// Information about an inheriting constructor.
9009   struct InheritingConstructor {
9010     InheritingConstructor()
9011       : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
9012 
9013     /// If \c true, a constructor with this signature is already declared
9014     /// in the derived class.
9015     bool DeclaredInDerived;
9016 
9017     /// The constructor which is inherited.
9018     const CXXConstructorDecl *BaseCtor;
9019 
9020     /// The derived constructor we declared.
9021     CXXConstructorDecl *DerivedCtor;
9022   };
9023 
9024   /// Inheriting constructors with a given canonical type. There can be at
9025   /// most one such non-template constructor, and any number of templated
9026   /// constructors.
9027   struct InheritingConstructorsForType {
9028     InheritingConstructor NonTemplate;
9029     SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
9030         Templates;
9031 
9032     InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
9033       if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
9034         TemplateParameterList *ParamList = FTD->getTemplateParameters();
9035         for (unsigned I = 0, N = Templates.size(); I != N; ++I)
9036           if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
9037                                                false, S.TPL_TemplateMatch))
9038             return Templates[I].second;
9039         Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
9040         return Templates.back().second;
9041       }
9042 
9043       return NonTemplate;
9044     }
9045   };
9046 
9047   /// Get or create the inheriting constructor record for a constructor.
9048   InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
9049                                   QualType CtorType) {
9050     return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
9051         .getEntry(SemaRef, Ctor);
9052   }
9053 
9054   typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
9055 
9056   /// Process all constructors for a class.
9057   void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
9058     for (const auto *Ctor : RD->ctors())
9059       (this->*Callback)(Ctor);
9060     for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
9061              I(RD->decls_begin()), E(RD->decls_end());
9062          I != E; ++I) {
9063       const FunctionDecl *FD = (*I)->getTemplatedDecl();
9064       if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
9065         (this->*Callback)(CD);
9066     }
9067   }
9068 
9069   /// Note that a constructor (or constructor template) was declared in Derived.
9070   void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
9071     getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
9072   }
9073 
9074   /// Inherit a single constructor.
9075   void inherit(const CXXConstructorDecl *Ctor) {
9076     const FunctionProtoType *CtorType =
9077         Ctor->getType()->castAs<FunctionProtoType>();
9078     ArrayRef<QualType> ArgTypes = CtorType->getParamTypes();
9079     FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
9080 
9081     SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
9082 
9083     // Core issue (no number yet): the ellipsis is always discarded.
9084     if (EPI.Variadic) {
9085       SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
9086       SemaRef.Diag(Ctor->getLocation(),
9087                    diag::note_using_decl_constructor_ellipsis);
9088       EPI.Variadic = false;
9089     }
9090 
9091     // Declare a constructor for each number of parameters.
9092     //
9093     // C++11 [class.inhctor]p1:
9094     //   The candidate set of inherited constructors from the class X named in
9095     //   the using-declaration consists of [... modulo defects ...] for each
9096     //   constructor or constructor template of X, the set of constructors or
9097     //   constructor templates that results from omitting any ellipsis parameter
9098     //   specification and successively omitting parameters with a default
9099     //   argument from the end of the parameter-type-list
9100     unsigned MinParams = minParamsToInherit(Ctor);
9101     unsigned Params = Ctor->getNumParams();
9102     if (Params >= MinParams) {
9103       do
9104         declareCtor(UsingLoc, Ctor,
9105                     SemaRef.Context.getFunctionType(
9106                         Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
9107       while (Params > MinParams &&
9108              Ctor->getParamDecl(--Params)->hasDefaultArg());
9109     }
9110   }
9111 
9112   /// Find the using-declaration which specified that we should inherit the
9113   /// constructors of \p Base.
9114   SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
9115     // No fancy lookup required; just look for the base constructor name
9116     // directly within the derived class.
9117     ASTContext &Context = SemaRef.Context;
9118     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9119         Context.getCanonicalType(Context.getRecordType(Base)));
9120     DeclContext::lookup_result Decls = Derived->lookup(Name);
9121     return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
9122   }
9123 
9124   unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
9125     // C++11 [class.inhctor]p3:
9126     //   [F]or each constructor template in the candidate set of inherited
9127     //   constructors, a constructor template is implicitly declared
9128     if (Ctor->getDescribedFunctionTemplate())
9129       return 0;
9130 
9131     //   For each non-template constructor in the candidate set of inherited
9132     //   constructors other than a constructor having no parameters or a
9133     //   copy/move constructor having a single parameter, a constructor is
9134     //   implicitly declared [...]
9135     if (Ctor->getNumParams() == 0)
9136       return 1;
9137     if (Ctor->isCopyOrMoveConstructor())
9138       return 2;
9139 
9140     // Per discussion on core reflector, never inherit a constructor which
9141     // would become a default, copy, or move constructor of Derived either.
9142     const ParmVarDecl *PD = Ctor->getParamDecl(0);
9143     const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
9144     return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
9145   }
9146 
9147   /// Declare a single inheriting constructor, inheriting the specified
9148   /// constructor, with the given type.
9149   void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
9150                    QualType DerivedType) {
9151     InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
9152 
9153     // C++11 [class.inhctor]p3:
9154     //   ... a constructor is implicitly declared with the same constructor
9155     //   characteristics unless there is a user-declared constructor with
9156     //   the same signature in the class where the using-declaration appears
9157     if (Entry.DeclaredInDerived)
9158       return;
9159 
9160     // C++11 [class.inhctor]p7:
9161     //   If two using-declarations declare inheriting constructors with the
9162     //   same signature, the program is ill-formed
9163     if (Entry.DerivedCtor) {
9164       if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
9165         // Only diagnose this once per constructor.
9166         if (Entry.DerivedCtor->isInvalidDecl())
9167           return;
9168         Entry.DerivedCtor->setInvalidDecl();
9169 
9170         SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
9171         SemaRef.Diag(BaseCtor->getLocation(),
9172                      diag::note_using_decl_constructor_conflict_current_ctor);
9173         SemaRef.Diag(Entry.BaseCtor->getLocation(),
9174                      diag::note_using_decl_constructor_conflict_previous_ctor);
9175         SemaRef.Diag(Entry.DerivedCtor->getLocation(),
9176                      diag::note_using_decl_constructor_conflict_previous_using);
9177       } else {
9178         // Core issue (no number): if the same inheriting constructor is
9179         // produced by multiple base class constructors from the same base
9180         // class, the inheriting constructor is defined as deleted.
9181         SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
9182       }
9183 
9184       return;
9185     }
9186 
9187     ASTContext &Context = SemaRef.Context;
9188     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9189         Context.getCanonicalType(Context.getRecordType(Derived)));
9190     DeclarationNameInfo NameInfo(Name, UsingLoc);
9191 
9192     TemplateParameterList *TemplateParams = nullptr;
9193     if (const FunctionTemplateDecl *FTD =
9194             BaseCtor->getDescribedFunctionTemplate()) {
9195       TemplateParams = FTD->getTemplateParameters();
9196       // We're reusing template parameters from a different DeclContext. This
9197       // is questionable at best, but works out because the template depth in
9198       // both places is guaranteed to be 0.
9199       // FIXME: Rebuild the template parameters in the new context, and
9200       // transform the function type to refer to them.
9201     }
9202 
9203     // Build type source info pointing at the using-declaration. This is
9204     // required by template instantiation.
9205     TypeSourceInfo *TInfo =
9206         Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
9207     FunctionProtoTypeLoc ProtoLoc =
9208         TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
9209 
9210     CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
9211         Context, Derived, UsingLoc, NameInfo, DerivedType,
9212         TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
9213         /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
9214 
9215     // Build an unevaluated exception specification for this constructor.
9216     const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
9217     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9218     EPI.ExceptionSpec.Type = EST_Unevaluated;
9219     EPI.ExceptionSpec.SourceDecl = DerivedCtor;
9220     DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
9221                                                  FPT->getParamTypes(), EPI));
9222 
9223     // Build the parameter declarations.
9224     SmallVector<ParmVarDecl *, 16> ParamDecls;
9225     for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
9226       TypeSourceInfo *TInfo =
9227           Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
9228       ParmVarDecl *PD = ParmVarDecl::Create(
9229           Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
9230           FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
9231       PD->setScopeInfo(0, I);
9232       PD->setImplicit();
9233       ParamDecls.push_back(PD);
9234       ProtoLoc.setParam(I, PD);
9235     }
9236 
9237     // Set up the new constructor.
9238     DerivedCtor->setAccess(BaseCtor->getAccess());
9239     DerivedCtor->setParams(ParamDecls);
9240     DerivedCtor->setInheritedConstructor(BaseCtor);
9241     if (BaseCtor->isDeleted())
9242       SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
9243 
9244     // If this is a constructor template, build the template declaration.
9245     if (TemplateParams) {
9246       FunctionTemplateDecl *DerivedTemplate =
9247           FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
9248                                        TemplateParams, DerivedCtor);
9249       DerivedTemplate->setAccess(BaseCtor->getAccess());
9250       DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
9251       Derived->addDecl(DerivedTemplate);
9252     } else {
9253       Derived->addDecl(DerivedCtor);
9254     }
9255 
9256     Entry.BaseCtor = BaseCtor;
9257     Entry.DerivedCtor = DerivedCtor;
9258   }
9259 
9260   Sema &SemaRef;
9261   CXXRecordDecl *Derived;
9262   typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
9263   MapType Map;
9264 };
9265 }
9266 
9267 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
9268   // Defer declaring the inheriting constructors until the class is
9269   // instantiated.
9270   if (ClassDecl->isDependentContext())
9271     return;
9272 
9273   // Find base classes from which we might inherit constructors.
9274   SmallVector<CXXRecordDecl*, 4> InheritedBases;
9275   for (const auto &BaseIt : ClassDecl->bases())
9276     if (BaseIt.getInheritConstructors())
9277       InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
9278 
9279   // Go no further if we're not inheriting any constructors.
9280   if (InheritedBases.empty())
9281     return;
9282 
9283   // Declare the inherited constructors.
9284   InheritingConstructorInfo ICI(*this, ClassDecl);
9285   for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
9286     ICI.inheritAll(InheritedBases[I]);
9287 }
9288 
9289 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
9290                                        CXXConstructorDecl *Constructor) {
9291   CXXRecordDecl *ClassDecl = Constructor->getParent();
9292   assert(Constructor->getInheritedConstructor() &&
9293          !Constructor->doesThisDeclarationHaveABody() &&
9294          !Constructor->isDeleted());
9295 
9296   SynthesizedFunctionScope Scope(*this, Constructor);
9297   DiagnosticErrorTrap Trap(Diags);
9298   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
9299       Trap.hasErrorOccurred()) {
9300     Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
9301       << Context.getTagDeclType(ClassDecl);
9302     Constructor->setInvalidDecl();
9303     return;
9304   }
9305 
9306   SourceLocation Loc = Constructor->getLocation();
9307   Constructor->setBody(new (Context) CompoundStmt(Loc));
9308 
9309   Constructor->markUsed(Context);
9310   MarkVTableUsed(CurrentLocation, ClassDecl);
9311 
9312   if (ASTMutationListener *L = getASTMutationListener()) {
9313     L->CompletedImplicitDefinition(Constructor);
9314   }
9315 }
9316 
9317 
9318 Sema::ImplicitExceptionSpecification
9319 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
9320   CXXRecordDecl *ClassDecl = MD->getParent();
9321 
9322   // C++ [except.spec]p14:
9323   //   An implicitly declared special member function (Clause 12) shall have
9324   //   an exception-specification.
9325   ImplicitExceptionSpecification ExceptSpec(*this);
9326   if (ClassDecl->isInvalidDecl())
9327     return ExceptSpec;
9328 
9329   // Direct base-class destructors.
9330   for (const auto &B : ClassDecl->bases()) {
9331     if (B.isVirtual()) // Handled below.
9332       continue;
9333 
9334     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9335       ExceptSpec.CalledDecl(B.getLocStart(),
9336                    LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
9337   }
9338 
9339   // Virtual base-class destructors.
9340   for (const auto &B : ClassDecl->vbases()) {
9341     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9342       ExceptSpec.CalledDecl(B.getLocStart(),
9343                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
9344   }
9345 
9346   // Field destructors.
9347   for (const auto *F : ClassDecl->fields()) {
9348     if (const RecordType *RecordTy
9349         = Context.getBaseElementType(F->getType())->getAs<RecordType>())
9350       ExceptSpec.CalledDecl(F->getLocation(),
9351                   LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
9352   }
9353 
9354   return ExceptSpec;
9355 }
9356 
9357 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
9358   // C++ [class.dtor]p2:
9359   //   If a class has no user-declared destructor, a destructor is
9360   //   declared implicitly. An implicitly-declared destructor is an
9361   //   inline public member of its class.
9362   assert(ClassDecl->needsImplicitDestructor());
9363 
9364   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
9365   if (DSM.isAlreadyBeingDeclared())
9366     return nullptr;
9367 
9368   // Create the actual destructor declaration.
9369   CanQualType ClassType
9370     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
9371   SourceLocation ClassLoc = ClassDecl->getLocation();
9372   DeclarationName Name
9373     = Context.DeclarationNames.getCXXDestructorName(ClassType);
9374   DeclarationNameInfo NameInfo(Name, ClassLoc);
9375   CXXDestructorDecl *Destructor
9376       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
9377                                   QualType(), nullptr, /*isInline=*/true,
9378                                   /*isImplicitlyDeclared=*/true);
9379   Destructor->setAccess(AS_public);
9380   Destructor->setDefaulted();
9381 
9382   if (getLangOpts().CUDA) {
9383     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
9384                                             Destructor,
9385                                             /* ConstRHS */ false,
9386                                             /* Diagnose */ false);
9387   }
9388 
9389   // Build an exception specification pointing back at this destructor.
9390   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
9391   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9392 
9393   AddOverriddenMethods(ClassDecl, Destructor);
9394 
9395   // We don't need to use SpecialMemberIsTrivial here; triviality for
9396   // destructors is easy to compute.
9397   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
9398 
9399   if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
9400     SetDeclDeleted(Destructor, ClassLoc);
9401 
9402   // Note that we have declared this destructor.
9403   ++ASTContext::NumImplicitDestructorsDeclared;
9404 
9405   // Introduce this destructor into its scope.
9406   if (Scope *S = getScopeForContext(ClassDecl))
9407     PushOnScopeChains(Destructor, S, false);
9408   ClassDecl->addDecl(Destructor);
9409 
9410   return Destructor;
9411 }
9412 
9413 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
9414                                     CXXDestructorDecl *Destructor) {
9415   assert((Destructor->isDefaulted() &&
9416           !Destructor->doesThisDeclarationHaveABody() &&
9417           !Destructor->isDeleted()) &&
9418          "DefineImplicitDestructor - call it for implicit default dtor");
9419   CXXRecordDecl *ClassDecl = Destructor->getParent();
9420   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
9421 
9422   if (Destructor->isInvalidDecl())
9423     return;
9424 
9425   SynthesizedFunctionScope Scope(*this, Destructor);
9426 
9427   DiagnosticErrorTrap Trap(Diags);
9428   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9429                                          Destructor->getParent());
9430 
9431   if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
9432     Diag(CurrentLocation, diag::note_member_synthesized_at)
9433       << CXXDestructor << Context.getTagDeclType(ClassDecl);
9434 
9435     Destructor->setInvalidDecl();
9436     return;
9437   }
9438 
9439   // The exception specification is needed because we are defining the
9440   // function.
9441   ResolveExceptionSpec(CurrentLocation,
9442                        Destructor->getType()->castAs<FunctionProtoType>());
9443 
9444   SourceLocation Loc = Destructor->getLocEnd().isValid()
9445                            ? Destructor->getLocEnd()
9446                            : Destructor->getLocation();
9447   Destructor->setBody(new (Context) CompoundStmt(Loc));
9448   Destructor->markUsed(Context);
9449   MarkVTableUsed(CurrentLocation, ClassDecl);
9450 
9451   if (ASTMutationListener *L = getASTMutationListener()) {
9452     L->CompletedImplicitDefinition(Destructor);
9453   }
9454 }
9455 
9456 /// \brief Perform any semantic analysis which needs to be delayed until all
9457 /// pending class member declarations have been parsed.
9458 void Sema::ActOnFinishCXXMemberDecls() {
9459   // If the context is an invalid C++ class, just suppress these checks.
9460   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
9461     if (Record->isInvalidDecl()) {
9462       DelayedDefaultedMemberExceptionSpecs.clear();
9463       DelayedExceptionSpecChecks.clear();
9464       return;
9465     }
9466   }
9467 }
9468 
9469 static void getDefaultArgExprsForConstructors(Sema &S, CXXRecordDecl *Class) {
9470   // Don't do anything for template patterns.
9471   if (Class->getDescribedClassTemplate())
9472     return;
9473 
9474   for (Decl *Member : Class->decls()) {
9475     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
9476     if (!CD) {
9477       // Recurse on nested classes.
9478       if (auto *NestedRD = dyn_cast<CXXRecordDecl>(Member))
9479         getDefaultArgExprsForConstructors(S, NestedRD);
9480       continue;
9481     } else if (!CD->isDefaultConstructor() || !CD->hasAttr<DLLExportAttr>()) {
9482       continue;
9483     }
9484 
9485     for (unsigned I = 0, E = CD->getNumParams(); I != E; ++I) {
9486       // Skip any default arguments that we've already instantiated.
9487       if (S.Context.getDefaultArgExprForConstructor(CD, I))
9488         continue;
9489 
9490       Expr *DefaultArg = S.BuildCXXDefaultArgExpr(Class->getLocation(), CD,
9491                                                   CD->getParamDecl(I)).get();
9492       S.DiscardCleanupsInEvaluationContext();
9493       S.Context.addDefaultArgExprForConstructor(CD, I, DefaultArg);
9494     }
9495   }
9496 }
9497 
9498 void Sema::ActOnFinishCXXMemberDefaultArgs(Decl *D) {
9499   auto *RD = dyn_cast<CXXRecordDecl>(D);
9500 
9501   // Default constructors that are annotated with __declspec(dllexport) which
9502   // have default arguments or don't use the standard calling convention are
9503   // wrapped with a thunk called the default constructor closure.
9504   if (RD && Context.getTargetInfo().getCXXABI().isMicrosoft())
9505     getDefaultArgExprsForConstructors(*this, RD);
9506 }
9507 
9508 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
9509                                          CXXDestructorDecl *Destructor) {
9510   assert(getLangOpts().CPlusPlus11 &&
9511          "adjusting dtor exception specs was introduced in c++11");
9512 
9513   // C++11 [class.dtor]p3:
9514   //   A declaration of a destructor that does not have an exception-
9515   //   specification is implicitly considered to have the same exception-
9516   //   specification as an implicit declaration.
9517   const FunctionProtoType *DtorType = Destructor->getType()->
9518                                         getAs<FunctionProtoType>();
9519   if (DtorType->hasExceptionSpec())
9520     return;
9521 
9522   // Replace the destructor's type, building off the existing one. Fortunately,
9523   // the only thing of interest in the destructor type is its extended info.
9524   // The return and arguments are fixed.
9525   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
9526   EPI.ExceptionSpec.Type = EST_Unevaluated;
9527   EPI.ExceptionSpec.SourceDecl = Destructor;
9528   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9529 
9530   // FIXME: If the destructor has a body that could throw, and the newly created
9531   // spec doesn't allow exceptions, we should emit a warning, because this
9532   // change in behavior can break conforming C++03 programs at runtime.
9533   // However, we don't have a body or an exception specification yet, so it
9534   // needs to be done somewhere else.
9535 }
9536 
9537 namespace {
9538 /// \brief An abstract base class for all helper classes used in building the
9539 //  copy/move operators. These classes serve as factory functions and help us
9540 //  avoid using the same Expr* in the AST twice.
9541 class ExprBuilder {
9542   ExprBuilder(const ExprBuilder&) = delete;
9543   ExprBuilder &operator=(const ExprBuilder&) = delete;
9544 
9545 protected:
9546   static Expr *assertNotNull(Expr *E) {
9547     assert(E && "Expression construction must not fail.");
9548     return E;
9549   }
9550 
9551 public:
9552   ExprBuilder() {}
9553   virtual ~ExprBuilder() {}
9554 
9555   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
9556 };
9557 
9558 class RefBuilder: public ExprBuilder {
9559   VarDecl *Var;
9560   QualType VarType;
9561 
9562 public:
9563   Expr *build(Sema &S, SourceLocation Loc) const override {
9564     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
9565   }
9566 
9567   RefBuilder(VarDecl *Var, QualType VarType)
9568       : Var(Var), VarType(VarType) {}
9569 };
9570 
9571 class ThisBuilder: public ExprBuilder {
9572 public:
9573   Expr *build(Sema &S, SourceLocation Loc) const override {
9574     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
9575   }
9576 };
9577 
9578 class CastBuilder: public ExprBuilder {
9579   const ExprBuilder &Builder;
9580   QualType Type;
9581   ExprValueKind Kind;
9582   const CXXCastPath &Path;
9583 
9584 public:
9585   Expr *build(Sema &S, SourceLocation Loc) const override {
9586     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
9587                                              CK_UncheckedDerivedToBase, Kind,
9588                                              &Path).get());
9589   }
9590 
9591   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
9592               const CXXCastPath &Path)
9593       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
9594 };
9595 
9596 class DerefBuilder: public ExprBuilder {
9597   const ExprBuilder &Builder;
9598 
9599 public:
9600   Expr *build(Sema &S, SourceLocation Loc) const override {
9601     return assertNotNull(
9602         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
9603   }
9604 
9605   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9606 };
9607 
9608 class MemberBuilder: public ExprBuilder {
9609   const ExprBuilder &Builder;
9610   QualType Type;
9611   CXXScopeSpec SS;
9612   bool IsArrow;
9613   LookupResult &MemberLookup;
9614 
9615 public:
9616   Expr *build(Sema &S, SourceLocation Loc) const override {
9617     return assertNotNull(S.BuildMemberReferenceExpr(
9618         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
9619         nullptr, MemberLookup, nullptr).get());
9620   }
9621 
9622   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9623                 LookupResult &MemberLookup)
9624       : Builder(Builder), Type(Type), IsArrow(IsArrow),
9625         MemberLookup(MemberLookup) {}
9626 };
9627 
9628 class MoveCastBuilder: public ExprBuilder {
9629   const ExprBuilder &Builder;
9630 
9631 public:
9632   Expr *build(Sema &S, SourceLocation Loc) const override {
9633     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9634   }
9635 
9636   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9637 };
9638 
9639 class LvalueConvBuilder: public ExprBuilder {
9640   const ExprBuilder &Builder;
9641 
9642 public:
9643   Expr *build(Sema &S, SourceLocation Loc) const override {
9644     return assertNotNull(
9645         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
9646   }
9647 
9648   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9649 };
9650 
9651 class SubscriptBuilder: public ExprBuilder {
9652   const ExprBuilder &Base;
9653   const ExprBuilder &Index;
9654 
9655 public:
9656   Expr *build(Sema &S, SourceLocation Loc) const override {
9657     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
9658         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
9659   }
9660 
9661   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9662       : Base(Base), Index(Index) {}
9663 };
9664 
9665 } // end anonymous namespace
9666 
9667 /// When generating a defaulted copy or move assignment operator, if a field
9668 /// should be copied with __builtin_memcpy rather than via explicit assignments,
9669 /// do so. This optimization only applies for arrays of scalars, and for arrays
9670 /// of class type where the selected copy/move-assignment operator is trivial.
9671 static StmtResult
9672 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
9673                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
9674   // Compute the size of the memory buffer to be copied.
9675   QualType SizeType = S.Context.getSizeType();
9676   llvm::APInt Size(S.Context.getTypeSize(SizeType),
9677                    S.Context.getTypeSizeInChars(T).getQuantity());
9678 
9679   // Take the address of the field references for "from" and "to". We
9680   // directly construct UnaryOperators here because semantic analysis
9681   // does not permit us to take the address of an xvalue.
9682   Expr *From = FromB.build(S, Loc);
9683   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9684                          S.Context.getPointerType(From->getType()),
9685                          VK_RValue, OK_Ordinary, Loc);
9686   Expr *To = ToB.build(S, Loc);
9687   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9688                        S.Context.getPointerType(To->getType()),
9689                        VK_RValue, OK_Ordinary, Loc);
9690 
9691   const Type *E = T->getBaseElementTypeUnsafe();
9692   bool NeedsCollectableMemCpy =
9693     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9694 
9695   // Create a reference to the __builtin_objc_memmove_collectable function
9696   StringRef MemCpyName = NeedsCollectableMemCpy ?
9697     "__builtin_objc_memmove_collectable" :
9698     "__builtin_memcpy";
9699   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9700                  Sema::LookupOrdinaryName);
9701   S.LookupName(R, S.TUScope, true);
9702 
9703   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9704   if (!MemCpy)
9705     // Something went horribly wrong earlier, and we will have complained
9706     // about it.
9707     return StmtError();
9708 
9709   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
9710                                             VK_RValue, Loc, nullptr);
9711   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9712 
9713   Expr *CallArgs[] = {
9714     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9715   };
9716   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
9717                                     Loc, CallArgs, Loc);
9718 
9719   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
9720   return Call.getAs<Stmt>();
9721 }
9722 
9723 /// \brief Builds a statement that copies/moves the given entity from \p From to
9724 /// \c To.
9725 ///
9726 /// This routine is used to copy/move the members of a class with an
9727 /// implicitly-declared copy/move assignment operator. When the entities being
9728 /// copied are arrays, this routine builds for loops to copy them.
9729 ///
9730 /// \param S The Sema object used for type-checking.
9731 ///
9732 /// \param Loc The location where the implicit copy/move is being generated.
9733 ///
9734 /// \param T The type of the expressions being copied/moved. Both expressions
9735 /// must have this type.
9736 ///
9737 /// \param To The expression we are copying/moving to.
9738 ///
9739 /// \param From The expression we are copying/moving from.
9740 ///
9741 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
9742 /// Otherwise, it's a non-static member subobject.
9743 ///
9744 /// \param Copying Whether we're copying or moving.
9745 ///
9746 /// \param Depth Internal parameter recording the depth of the recursion.
9747 ///
9748 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9749 /// if a memcpy should be used instead.
9750 static StmtResult
9751 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
9752                                  const ExprBuilder &To, const ExprBuilder &From,
9753                                  bool CopyingBaseSubobject, bool Copying,
9754                                  unsigned Depth = 0) {
9755   // C++11 [class.copy]p28:
9756   //   Each subobject is assigned in the manner appropriate to its type:
9757   //
9758   //     - if the subobject is of class type, as if by a call to operator= with
9759   //       the subobject as the object expression and the corresponding
9760   //       subobject of x as a single function argument (as if by explicit
9761   //       qualification; that is, ignoring any possible virtual overriding
9762   //       functions in more derived classes);
9763   //
9764   // C++03 [class.copy]p13:
9765   //     - if the subobject is of class type, the copy assignment operator for
9766   //       the class is used (as if by explicit qualification; that is,
9767   //       ignoring any possible virtual overriding functions in more derived
9768   //       classes);
9769   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9770     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9771 
9772     // Look for operator=.
9773     DeclarationName Name
9774       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9775     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9776     S.LookupQualifiedName(OpLookup, ClassDecl, false);
9777 
9778     // Prior to C++11, filter out any result that isn't a copy/move-assignment
9779     // operator.
9780     if (!S.getLangOpts().CPlusPlus11) {
9781       LookupResult::Filter F = OpLookup.makeFilter();
9782       while (F.hasNext()) {
9783         NamedDecl *D = F.next();
9784         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9785           if (Method->isCopyAssignmentOperator() ||
9786               (!Copying && Method->isMoveAssignmentOperator()))
9787             continue;
9788 
9789         F.erase();
9790       }
9791       F.done();
9792     }
9793 
9794     // Suppress the protected check (C++ [class.protected]) for each of the
9795     // assignment operators we found. This strange dance is required when
9796     // we're assigning via a base classes's copy-assignment operator. To
9797     // ensure that we're getting the right base class subobject (without
9798     // ambiguities), we need to cast "this" to that subobject type; to
9799     // ensure that we don't go through the virtual call mechanism, we need
9800     // to qualify the operator= name with the base class (see below). However,
9801     // this means that if the base class has a protected copy assignment
9802     // operator, the protected member access check will fail. So, we
9803     // rewrite "protected" access to "public" access in this case, since we
9804     // know by construction that we're calling from a derived class.
9805     if (CopyingBaseSubobject) {
9806       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9807            L != LEnd; ++L) {
9808         if (L.getAccess() == AS_protected)
9809           L.setAccess(AS_public);
9810       }
9811     }
9812 
9813     // Create the nested-name-specifier that will be used to qualify the
9814     // reference to operator=; this is required to suppress the virtual
9815     // call mechanism.
9816     CXXScopeSpec SS;
9817     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
9818     SS.MakeTrivial(S.Context,
9819                    NestedNameSpecifier::Create(S.Context, nullptr, false,
9820                                                CanonicalT),
9821                    Loc);
9822 
9823     // Create the reference to operator=.
9824     ExprResult OpEqualRef
9825       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9826                                    SS, /*TemplateKWLoc=*/SourceLocation(),
9827                                    /*FirstQualifierInScope=*/nullptr,
9828                                    OpLookup,
9829                                    /*TemplateArgs=*/nullptr,
9830                                    /*SuppressQualifierCheck=*/true);
9831     if (OpEqualRef.isInvalid())
9832       return StmtError();
9833 
9834     // Build the call to the assignment operator.
9835 
9836     Expr *FromInst = From.build(S, Loc);
9837     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
9838                                                   OpEqualRef.getAs<Expr>(),
9839                                                   Loc, FromInst, Loc);
9840     if (Call.isInvalid())
9841       return StmtError();
9842 
9843     // If we built a call to a trivial 'operator=' while copying an array,
9844     // bail out. We'll replace the whole shebang with a memcpy.
9845     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9846     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9847       return StmtResult((Stmt*)nullptr);
9848 
9849     // Convert to an expression-statement, and clean up any produced
9850     // temporaries.
9851     return S.ActOnExprStmt(Call);
9852   }
9853 
9854   //     - if the subobject is of scalar type, the built-in assignment
9855   //       operator is used.
9856   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
9857   if (!ArrayTy) {
9858     ExprResult Assignment = S.CreateBuiltinBinOp(
9859         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
9860     if (Assignment.isInvalid())
9861       return StmtError();
9862     return S.ActOnExprStmt(Assignment);
9863   }
9864 
9865   //     - if the subobject is an array, each element is assigned, in the
9866   //       manner appropriate to the element type;
9867 
9868   // Construct a loop over the array bounds, e.g.,
9869   //
9870   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9871   //
9872   // that will copy each of the array elements.
9873   QualType SizeType = S.Context.getSizeType();
9874 
9875   // Create the iteration variable.
9876   IdentifierInfo *IterationVarName = nullptr;
9877   {
9878     SmallString<8> Str;
9879     llvm::raw_svector_ostream OS(Str);
9880     OS << "__i" << Depth;
9881     IterationVarName = &S.Context.Idents.get(OS.str());
9882   }
9883   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
9884                                           IterationVarName, SizeType,
9885                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
9886                                           SC_None);
9887 
9888   // Initialize the iteration variable to zero.
9889   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
9890   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
9891 
9892   // Creates a reference to the iteration variable.
9893   RefBuilder IterationVarRef(IterationVar, SizeType);
9894   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
9895 
9896   // Create the DeclStmt that holds the iteration variable.
9897   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
9898 
9899   // Subscript the "from" and "to" expressions with the iteration variable.
9900   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9901   MoveCastBuilder FromIndexMove(FromIndexCopy);
9902   const ExprBuilder *FromIndex;
9903   if (Copying)
9904     FromIndex = &FromIndexCopy;
9905   else
9906     FromIndex = &FromIndexMove;
9907 
9908   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
9909 
9910   // Build the copy/move for an individual element of the array.
9911   StmtResult Copy =
9912     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
9913                                      ToIndex, *FromIndex, CopyingBaseSubobject,
9914                                      Copying, Depth + 1);
9915   // Bail out if copying fails or if we determined that we should use memcpy.
9916   if (Copy.isInvalid() || !Copy.get())
9917     return Copy;
9918 
9919   // Create the comparison against the array bound.
9920   llvm::APInt Upper
9921     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9922   Expr *Comparison
9923     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
9924                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9925                                      BO_NE, S.Context.BoolTy,
9926                                      VK_RValue, OK_Ordinary, Loc, false);
9927 
9928   // Create the pre-increment of the iteration variable.
9929   Expr *Increment
9930     = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9931                                     SizeType, VK_LValue, OK_Ordinary, Loc);
9932 
9933   // Construct the loop that copies all elements of this array.
9934   return S.ActOnForStmt(Loc, Loc, InitStmt,
9935                         S.MakeFullExpr(Comparison),
9936                         nullptr, S.MakeFullDiscardedValueExpr(Increment),
9937                         Loc, Copy.get());
9938 }
9939 
9940 static StmtResult
9941 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
9942                       const ExprBuilder &To, const ExprBuilder &From,
9943                       bool CopyingBaseSubobject, bool Copying) {
9944   // Maybe we should use a memcpy?
9945   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9946       T.isTriviallyCopyableType(S.Context))
9947     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9948 
9949   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9950                                                      CopyingBaseSubobject,
9951                                                      Copying, 0));
9952 
9953   // If we ended up picking a trivial assignment operator for an array of a
9954   // non-trivially-copyable class type, just emit a memcpy.
9955   if (!Result.isInvalid() && !Result.get())
9956     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9957 
9958   return Result;
9959 }
9960 
9961 Sema::ImplicitExceptionSpecification
9962 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9963   CXXRecordDecl *ClassDecl = MD->getParent();
9964 
9965   ImplicitExceptionSpecification ExceptSpec(*this);
9966   if (ClassDecl->isInvalidDecl())
9967     return ExceptSpec;
9968 
9969   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9970   assert(T->getNumParams() == 1 && "not a copy assignment op");
9971   unsigned ArgQuals =
9972       T->getParamType(0).getNonReferenceType().getCVRQualifiers();
9973 
9974   // C++ [except.spec]p14:
9975   //   An implicitly declared special member function (Clause 12) shall have an
9976   //   exception-specification. [...]
9977 
9978   // It is unspecified whether or not an implicit copy assignment operator
9979   // attempts to deduplicate calls to assignment operators of virtual bases are
9980   // made. As such, this exception specification is effectively unspecified.
9981   // Based on a similar decision made for constness in C++0x, we're erring on
9982   // the side of assuming such calls to be made regardless of whether they
9983   // actually happen.
9984   for (const auto &Base : ClassDecl->bases()) {
9985     if (Base.isVirtual())
9986       continue;
9987 
9988     CXXRecordDecl *BaseClassDecl
9989       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9990     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9991                                                             ArgQuals, false, 0))
9992       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
9993   }
9994 
9995   for (const auto &Base : ClassDecl->vbases()) {
9996     CXXRecordDecl *BaseClassDecl
9997       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9998     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9999                                                             ArgQuals, false, 0))
10000       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
10001   }
10002 
10003   for (const auto *Field : ClassDecl->fields()) {
10004     QualType FieldType = Context.getBaseElementType(Field->getType());
10005     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10006       if (CXXMethodDecl *CopyAssign =
10007           LookupCopyingAssignment(FieldClassDecl,
10008                                   ArgQuals | FieldType.getCVRQualifiers(),
10009                                   false, 0))
10010         ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
10011     }
10012   }
10013 
10014   return ExceptSpec;
10015 }
10016 
10017 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
10018   // Note: The following rules are largely analoguous to the copy
10019   // constructor rules. Note that virtual bases are not taken into account
10020   // for determining the argument type of the operator. Note also that
10021   // operators taking an object instead of a reference are allowed.
10022   assert(ClassDecl->needsImplicitCopyAssignment());
10023 
10024   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
10025   if (DSM.isAlreadyBeingDeclared())
10026     return nullptr;
10027 
10028   QualType ArgType = Context.getTypeDeclType(ClassDecl);
10029   QualType RetType = Context.getLValueReferenceType(ArgType);
10030   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
10031   if (Const)
10032     ArgType = ArgType.withConst();
10033   ArgType = Context.getLValueReferenceType(ArgType);
10034 
10035   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10036                                                      CXXCopyAssignment,
10037                                                      Const);
10038 
10039   //   An implicitly-declared copy assignment operator is an inline public
10040   //   member of its class.
10041   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10042   SourceLocation ClassLoc = ClassDecl->getLocation();
10043   DeclarationNameInfo NameInfo(Name, ClassLoc);
10044   CXXMethodDecl *CopyAssignment =
10045       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
10046                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10047                             /*isInline=*/true, Constexpr, SourceLocation());
10048   CopyAssignment->setAccess(AS_public);
10049   CopyAssignment->setDefaulted();
10050   CopyAssignment->setImplicit();
10051 
10052   if (getLangOpts().CUDA) {
10053     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
10054                                             CopyAssignment,
10055                                             /* ConstRHS */ Const,
10056                                             /* Diagnose */ false);
10057   }
10058 
10059   // Build an exception specification pointing back at this member.
10060   FunctionProtoType::ExtProtoInfo EPI =
10061       getImplicitMethodEPI(*this, CopyAssignment);
10062   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
10063 
10064   // Add the parameter to the operator.
10065   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
10066                                                ClassLoc, ClassLoc,
10067                                                /*Id=*/nullptr, ArgType,
10068                                                /*TInfo=*/nullptr, SC_None,
10069                                                nullptr);
10070   CopyAssignment->setParams(FromParam);
10071 
10072   AddOverriddenMethods(ClassDecl, CopyAssignment);
10073 
10074   CopyAssignment->setTrivial(
10075     ClassDecl->needsOverloadResolutionForCopyAssignment()
10076       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
10077       : ClassDecl->hasTrivialCopyAssignment());
10078 
10079   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
10080     SetDeclDeleted(CopyAssignment, ClassLoc);
10081 
10082   // Note that we have added this copy-assignment operator.
10083   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
10084 
10085   if (Scope *S = getScopeForContext(ClassDecl))
10086     PushOnScopeChains(CopyAssignment, S, false);
10087   ClassDecl->addDecl(CopyAssignment);
10088 
10089   return CopyAssignment;
10090 }
10091 
10092 /// Diagnose an implicit copy operation for a class which is odr-used, but
10093 /// which is deprecated because the class has a user-declared copy constructor,
10094 /// copy assignment operator, or destructor.
10095 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
10096                                             SourceLocation UseLoc) {
10097   assert(CopyOp->isImplicit());
10098 
10099   CXXRecordDecl *RD = CopyOp->getParent();
10100   CXXMethodDecl *UserDeclaredOperation = nullptr;
10101 
10102   // In Microsoft mode, assignment operations don't affect constructors and
10103   // vice versa.
10104   if (RD->hasUserDeclaredDestructor()) {
10105     UserDeclaredOperation = RD->getDestructor();
10106   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
10107              RD->hasUserDeclaredCopyConstructor() &&
10108              !S.getLangOpts().MSVCCompat) {
10109     // Find any user-declared copy constructor.
10110     for (auto *I : RD->ctors()) {
10111       if (I->isCopyConstructor()) {
10112         UserDeclaredOperation = I;
10113         break;
10114       }
10115     }
10116     assert(UserDeclaredOperation);
10117   } else if (isa<CXXConstructorDecl>(CopyOp) &&
10118              RD->hasUserDeclaredCopyAssignment() &&
10119              !S.getLangOpts().MSVCCompat) {
10120     // Find any user-declared move assignment operator.
10121     for (auto *I : RD->methods()) {
10122       if (I->isCopyAssignmentOperator()) {
10123         UserDeclaredOperation = I;
10124         break;
10125       }
10126     }
10127     assert(UserDeclaredOperation);
10128   }
10129 
10130   if (UserDeclaredOperation) {
10131     S.Diag(UserDeclaredOperation->getLocation(),
10132          diag::warn_deprecated_copy_operation)
10133       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
10134       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
10135     S.Diag(UseLoc, diag::note_member_synthesized_at)
10136       << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
10137                                           : Sema::CXXCopyAssignment)
10138       << RD;
10139   }
10140 }
10141 
10142 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
10143                                         CXXMethodDecl *CopyAssignOperator) {
10144   assert((CopyAssignOperator->isDefaulted() &&
10145           CopyAssignOperator->isOverloadedOperator() &&
10146           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
10147           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
10148           !CopyAssignOperator->isDeleted()) &&
10149          "DefineImplicitCopyAssignment called for wrong function");
10150 
10151   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
10152 
10153   if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
10154     CopyAssignOperator->setInvalidDecl();
10155     return;
10156   }
10157 
10158   // C++11 [class.copy]p18:
10159   //   The [definition of an implicitly declared copy assignment operator] is
10160   //   deprecated if the class has a user-declared copy constructor or a
10161   //   user-declared destructor.
10162   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
10163     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
10164 
10165   CopyAssignOperator->markUsed(Context);
10166 
10167   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
10168   DiagnosticErrorTrap Trap(Diags);
10169 
10170   // C++0x [class.copy]p30:
10171   //   The implicitly-defined or explicitly-defaulted copy assignment operator
10172   //   for a non-union class X performs memberwise copy assignment of its
10173   //   subobjects. The direct base classes of X are assigned first, in the
10174   //   order of their declaration in the base-specifier-list, and then the
10175   //   immediate non-static data members of X are assigned, in the order in
10176   //   which they were declared in the class definition.
10177 
10178   // The statements that form the synthesized function body.
10179   SmallVector<Stmt*, 8> Statements;
10180 
10181   // The parameter for the "other" object, which we are copying from.
10182   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
10183   Qualifiers OtherQuals = Other->getType().getQualifiers();
10184   QualType OtherRefType = Other->getType();
10185   if (const LValueReferenceType *OtherRef
10186                                 = OtherRefType->getAs<LValueReferenceType>()) {
10187     OtherRefType = OtherRef->getPointeeType();
10188     OtherQuals = OtherRefType.getQualifiers();
10189   }
10190 
10191   // Our location for everything implicitly-generated.
10192   SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
10193                            ? CopyAssignOperator->getLocEnd()
10194                            : CopyAssignOperator->getLocation();
10195 
10196   // Builds a DeclRefExpr for the "other" object.
10197   RefBuilder OtherRef(Other, OtherRefType);
10198 
10199   // Builds the "this" pointer.
10200   ThisBuilder This;
10201 
10202   // Assign base classes.
10203   bool Invalid = false;
10204   for (auto &Base : ClassDecl->bases()) {
10205     // Form the assignment:
10206     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
10207     QualType BaseType = Base.getType().getUnqualifiedType();
10208     if (!BaseType->isRecordType()) {
10209       Invalid = true;
10210       continue;
10211     }
10212 
10213     CXXCastPath BasePath;
10214     BasePath.push_back(&Base);
10215 
10216     // Construct the "from" expression, which is an implicit cast to the
10217     // appropriately-qualified base type.
10218     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
10219                      VK_LValue, BasePath);
10220 
10221     // Dereference "this".
10222     DerefBuilder DerefThis(This);
10223     CastBuilder To(DerefThis,
10224                    Context.getCVRQualifiedType(
10225                        BaseType, CopyAssignOperator->getTypeQualifiers()),
10226                    VK_LValue, BasePath);
10227 
10228     // Build the copy.
10229     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
10230                                             To, From,
10231                                             /*CopyingBaseSubobject=*/true,
10232                                             /*Copying=*/true);
10233     if (Copy.isInvalid()) {
10234       Diag(CurrentLocation, diag::note_member_synthesized_at)
10235         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10236       CopyAssignOperator->setInvalidDecl();
10237       return;
10238     }
10239 
10240     // Success! Record the copy.
10241     Statements.push_back(Copy.getAs<Expr>());
10242   }
10243 
10244   // Assign non-static members.
10245   for (auto *Field : ClassDecl->fields()) {
10246     // FIXME: We should form some kind of AST representation for the implied
10247     // memcpy in a union copy operation.
10248     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
10249       continue;
10250 
10251     if (Field->isInvalidDecl()) {
10252       Invalid = true;
10253       continue;
10254     }
10255 
10256     // Check for members of reference type; we can't copy those.
10257     if (Field->getType()->isReferenceType()) {
10258       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10259         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10260       Diag(Field->getLocation(), diag::note_declared_at);
10261       Diag(CurrentLocation, diag::note_member_synthesized_at)
10262         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10263       Invalid = true;
10264       continue;
10265     }
10266 
10267     // Check for members of const-qualified, non-class type.
10268     QualType BaseType = Context.getBaseElementType(Field->getType());
10269     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10270       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10271         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10272       Diag(Field->getLocation(), diag::note_declared_at);
10273       Diag(CurrentLocation, diag::note_member_synthesized_at)
10274         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10275       Invalid = true;
10276       continue;
10277     }
10278 
10279     // Suppress assigning zero-width bitfields.
10280     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10281       continue;
10282 
10283     QualType FieldType = Field->getType().getNonReferenceType();
10284     if (FieldType->isIncompleteArrayType()) {
10285       assert(ClassDecl->hasFlexibleArrayMember() &&
10286              "Incomplete array type is not valid");
10287       continue;
10288     }
10289 
10290     // Build references to the field in the object we're copying from and to.
10291     CXXScopeSpec SS; // Intentionally empty
10292     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10293                               LookupMemberName);
10294     MemberLookup.addDecl(Field);
10295     MemberLookup.resolveKind();
10296 
10297     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
10298 
10299     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
10300 
10301     // Build the copy of this field.
10302     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
10303                                             To, From,
10304                                             /*CopyingBaseSubobject=*/false,
10305                                             /*Copying=*/true);
10306     if (Copy.isInvalid()) {
10307       Diag(CurrentLocation, diag::note_member_synthesized_at)
10308         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10309       CopyAssignOperator->setInvalidDecl();
10310       return;
10311     }
10312 
10313     // Success! Record the copy.
10314     Statements.push_back(Copy.getAs<Stmt>());
10315   }
10316 
10317   if (!Invalid) {
10318     // Add a "return *this;"
10319     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10320 
10321     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
10322     if (Return.isInvalid())
10323       Invalid = true;
10324     else {
10325       Statements.push_back(Return.getAs<Stmt>());
10326 
10327       if (Trap.hasErrorOccurred()) {
10328         Diag(CurrentLocation, diag::note_member_synthesized_at)
10329           << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10330         Invalid = true;
10331       }
10332     }
10333   }
10334 
10335   // The exception specification is needed because we are defining the
10336   // function.
10337   ResolveExceptionSpec(CurrentLocation,
10338                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
10339 
10340   if (Invalid) {
10341     CopyAssignOperator->setInvalidDecl();
10342     return;
10343   }
10344 
10345   StmtResult Body;
10346   {
10347     CompoundScopeRAII CompoundScope(*this);
10348     Body = ActOnCompoundStmt(Loc, Loc, Statements,
10349                              /*isStmtExpr=*/false);
10350     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10351   }
10352   CopyAssignOperator->setBody(Body.getAs<Stmt>());
10353 
10354   if (ASTMutationListener *L = getASTMutationListener()) {
10355     L->CompletedImplicitDefinition(CopyAssignOperator);
10356   }
10357 }
10358 
10359 Sema::ImplicitExceptionSpecification
10360 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
10361   CXXRecordDecl *ClassDecl = MD->getParent();
10362 
10363   ImplicitExceptionSpecification ExceptSpec(*this);
10364   if (ClassDecl->isInvalidDecl())
10365     return ExceptSpec;
10366 
10367   // C++0x [except.spec]p14:
10368   //   An implicitly declared special member function (Clause 12) shall have an
10369   //   exception-specification. [...]
10370 
10371   // It is unspecified whether or not an implicit move assignment operator
10372   // attempts to deduplicate calls to assignment operators of virtual bases are
10373   // made. As such, this exception specification is effectively unspecified.
10374   // Based on a similar decision made for constness in C++0x, we're erring on
10375   // the side of assuming such calls to be made regardless of whether they
10376   // actually happen.
10377   // Note that a move constructor is not implicitly declared when there are
10378   // virtual bases, but it can still be user-declared and explicitly defaulted.
10379   for (const auto &Base : ClassDecl->bases()) {
10380     if (Base.isVirtual())
10381       continue;
10382 
10383     CXXRecordDecl *BaseClassDecl
10384       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10385     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
10386                                                            0, false, 0))
10387       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
10388   }
10389 
10390   for (const auto &Base : ClassDecl->vbases()) {
10391     CXXRecordDecl *BaseClassDecl
10392       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10393     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
10394                                                            0, false, 0))
10395       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
10396   }
10397 
10398   for (const auto *Field : ClassDecl->fields()) {
10399     QualType FieldType = Context.getBaseElementType(Field->getType());
10400     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10401       if (CXXMethodDecl *MoveAssign =
10402               LookupMovingAssignment(FieldClassDecl,
10403                                      FieldType.getCVRQualifiers(),
10404                                      false, 0))
10405         ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
10406     }
10407   }
10408 
10409   return ExceptSpec;
10410 }
10411 
10412 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
10413   assert(ClassDecl->needsImplicitMoveAssignment());
10414 
10415   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
10416   if (DSM.isAlreadyBeingDeclared())
10417     return nullptr;
10418 
10419   // Note: The following rules are largely analoguous to the move
10420   // constructor rules.
10421 
10422   QualType ArgType = Context.getTypeDeclType(ClassDecl);
10423   QualType RetType = Context.getLValueReferenceType(ArgType);
10424   ArgType = Context.getRValueReferenceType(ArgType);
10425 
10426   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10427                                                      CXXMoveAssignment,
10428                                                      false);
10429 
10430   //   An implicitly-declared move assignment operator is an inline public
10431   //   member of its class.
10432   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10433   SourceLocation ClassLoc = ClassDecl->getLocation();
10434   DeclarationNameInfo NameInfo(Name, ClassLoc);
10435   CXXMethodDecl *MoveAssignment =
10436       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
10437                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10438                             /*isInline=*/true, Constexpr, SourceLocation());
10439   MoveAssignment->setAccess(AS_public);
10440   MoveAssignment->setDefaulted();
10441   MoveAssignment->setImplicit();
10442 
10443   if (getLangOpts().CUDA) {
10444     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
10445                                             MoveAssignment,
10446                                             /* ConstRHS */ false,
10447                                             /* Diagnose */ false);
10448   }
10449 
10450   // Build an exception specification pointing back at this member.
10451   FunctionProtoType::ExtProtoInfo EPI =
10452       getImplicitMethodEPI(*this, MoveAssignment);
10453   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
10454 
10455   // Add the parameter to the operator.
10456   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
10457                                                ClassLoc, ClassLoc,
10458                                                /*Id=*/nullptr, ArgType,
10459                                                /*TInfo=*/nullptr, SC_None,
10460                                                nullptr);
10461   MoveAssignment->setParams(FromParam);
10462 
10463   AddOverriddenMethods(ClassDecl, MoveAssignment);
10464 
10465   MoveAssignment->setTrivial(
10466     ClassDecl->needsOverloadResolutionForMoveAssignment()
10467       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
10468       : ClassDecl->hasTrivialMoveAssignment());
10469 
10470   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
10471     ClassDecl->setImplicitMoveAssignmentIsDeleted();
10472     SetDeclDeleted(MoveAssignment, ClassLoc);
10473   }
10474 
10475   // Note that we have added this copy-assignment operator.
10476   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
10477 
10478   if (Scope *S = getScopeForContext(ClassDecl))
10479     PushOnScopeChains(MoveAssignment, S, false);
10480   ClassDecl->addDecl(MoveAssignment);
10481 
10482   return MoveAssignment;
10483 }
10484 
10485 /// Check if we're implicitly defining a move assignment operator for a class
10486 /// with virtual bases. Such a move assignment might move-assign the virtual
10487 /// base multiple times.
10488 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
10489                                                SourceLocation CurrentLocation) {
10490   assert(!Class->isDependentContext() && "should not define dependent move");
10491 
10492   // Only a virtual base could get implicitly move-assigned multiple times.
10493   // Only a non-trivial move assignment can observe this. We only want to
10494   // diagnose if we implicitly define an assignment operator that assigns
10495   // two base classes, both of which move-assign the same virtual base.
10496   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
10497       Class->getNumBases() < 2)
10498     return;
10499 
10500   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
10501   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
10502   VBaseMap VBases;
10503 
10504   for (auto &BI : Class->bases()) {
10505     Worklist.push_back(&BI);
10506     while (!Worklist.empty()) {
10507       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
10508       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
10509 
10510       // If the base has no non-trivial move assignment operators,
10511       // we don't care about moves from it.
10512       if (!Base->hasNonTrivialMoveAssignment())
10513         continue;
10514 
10515       // If there's nothing virtual here, skip it.
10516       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
10517         continue;
10518 
10519       // If we're not actually going to call a move assignment for this base,
10520       // or the selected move assignment is trivial, skip it.
10521       Sema::SpecialMemberOverloadResult *SMOR =
10522         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
10523                               /*ConstArg*/false, /*VolatileArg*/false,
10524                               /*RValueThis*/true, /*ConstThis*/false,
10525                               /*VolatileThis*/false);
10526       if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
10527           !SMOR->getMethod()->isMoveAssignmentOperator())
10528         continue;
10529 
10530       if (BaseSpec->isVirtual()) {
10531         // We're going to move-assign this virtual base, and its move
10532         // assignment operator is not trivial. If this can happen for
10533         // multiple distinct direct bases of Class, diagnose it. (If it
10534         // only happens in one base, we'll diagnose it when synthesizing
10535         // that base class's move assignment operator.)
10536         CXXBaseSpecifier *&Existing =
10537             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
10538                 .first->second;
10539         if (Existing && Existing != &BI) {
10540           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
10541             << Class << Base;
10542           S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
10543             << (Base->getCanonicalDecl() ==
10544                 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10545             << Base << Existing->getType() << Existing->getSourceRange();
10546           S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
10547             << (Base->getCanonicalDecl() ==
10548                 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10549             << Base << BI.getType() << BaseSpec->getSourceRange();
10550 
10551           // Only diagnose each vbase once.
10552           Existing = nullptr;
10553         }
10554       } else {
10555         // Only walk over bases that have defaulted move assignment operators.
10556         // We assume that any user-provided move assignment operator handles
10557         // the multiple-moves-of-vbase case itself somehow.
10558         if (!SMOR->getMethod()->isDefaulted())
10559           continue;
10560 
10561         // We're going to move the base classes of Base. Add them to the list.
10562         for (auto &BI : Base->bases())
10563           Worklist.push_back(&BI);
10564       }
10565     }
10566   }
10567 }
10568 
10569 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
10570                                         CXXMethodDecl *MoveAssignOperator) {
10571   assert((MoveAssignOperator->isDefaulted() &&
10572           MoveAssignOperator->isOverloadedOperator() &&
10573           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
10574           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
10575           !MoveAssignOperator->isDeleted()) &&
10576          "DefineImplicitMoveAssignment called for wrong function");
10577 
10578   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
10579 
10580   if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
10581     MoveAssignOperator->setInvalidDecl();
10582     return;
10583   }
10584 
10585   MoveAssignOperator->markUsed(Context);
10586 
10587   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
10588   DiagnosticErrorTrap Trap(Diags);
10589 
10590   // C++0x [class.copy]p28:
10591   //   The implicitly-defined or move assignment operator for a non-union class
10592   //   X performs memberwise move assignment of its subobjects. The direct base
10593   //   classes of X are assigned first, in the order of their declaration in the
10594   //   base-specifier-list, and then the immediate non-static data members of X
10595   //   are assigned, in the order in which they were declared in the class
10596   //   definition.
10597 
10598   // Issue a warning if our implicit move assignment operator will move
10599   // from a virtual base more than once.
10600   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
10601 
10602   // The statements that form the synthesized function body.
10603   SmallVector<Stmt*, 8> Statements;
10604 
10605   // The parameter for the "other" object, which we are move from.
10606   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
10607   QualType OtherRefType = Other->getType()->
10608       getAs<RValueReferenceType>()->getPointeeType();
10609   assert(!OtherRefType.getQualifiers() &&
10610          "Bad argument type of defaulted move assignment");
10611 
10612   // Our location for everything implicitly-generated.
10613   SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
10614                            ? MoveAssignOperator->getLocEnd()
10615                            : MoveAssignOperator->getLocation();
10616 
10617   // Builds a reference to the "other" object.
10618   RefBuilder OtherRef(Other, OtherRefType);
10619   // Cast to rvalue.
10620   MoveCastBuilder MoveOther(OtherRef);
10621 
10622   // Builds the "this" pointer.
10623   ThisBuilder This;
10624 
10625   // Assign base classes.
10626   bool Invalid = false;
10627   for (auto &Base : ClassDecl->bases()) {
10628     // C++11 [class.copy]p28:
10629     //   It is unspecified whether subobjects representing virtual base classes
10630     //   are assigned more than once by the implicitly-defined copy assignment
10631     //   operator.
10632     // FIXME: Do not assign to a vbase that will be assigned by some other base
10633     // class. For a move-assignment, this can result in the vbase being moved
10634     // multiple times.
10635 
10636     // Form the assignment:
10637     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
10638     QualType BaseType = Base.getType().getUnqualifiedType();
10639     if (!BaseType->isRecordType()) {
10640       Invalid = true;
10641       continue;
10642     }
10643 
10644     CXXCastPath BasePath;
10645     BasePath.push_back(&Base);
10646 
10647     // Construct the "from" expression, which is an implicit cast to the
10648     // appropriately-qualified base type.
10649     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
10650 
10651     // Dereference "this".
10652     DerefBuilder DerefThis(This);
10653 
10654     // Implicitly cast "this" to the appropriately-qualified base type.
10655     CastBuilder To(DerefThis,
10656                    Context.getCVRQualifiedType(
10657                        BaseType, MoveAssignOperator->getTypeQualifiers()),
10658                    VK_LValue, BasePath);
10659 
10660     // Build the move.
10661     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
10662                                             To, From,
10663                                             /*CopyingBaseSubobject=*/true,
10664                                             /*Copying=*/false);
10665     if (Move.isInvalid()) {
10666       Diag(CurrentLocation, diag::note_member_synthesized_at)
10667         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10668       MoveAssignOperator->setInvalidDecl();
10669       return;
10670     }
10671 
10672     // Success! Record the move.
10673     Statements.push_back(Move.getAs<Expr>());
10674   }
10675 
10676   // Assign non-static members.
10677   for (auto *Field : ClassDecl->fields()) {
10678     // FIXME: We should form some kind of AST representation for the implied
10679     // memcpy in a union copy operation.
10680     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
10681       continue;
10682 
10683     if (Field->isInvalidDecl()) {
10684       Invalid = true;
10685       continue;
10686     }
10687 
10688     // Check for members of reference type; we can't move those.
10689     if (Field->getType()->isReferenceType()) {
10690       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10691         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10692       Diag(Field->getLocation(), diag::note_declared_at);
10693       Diag(CurrentLocation, diag::note_member_synthesized_at)
10694         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10695       Invalid = true;
10696       continue;
10697     }
10698 
10699     // Check for members of const-qualified, non-class type.
10700     QualType BaseType = Context.getBaseElementType(Field->getType());
10701     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10702       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10703         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10704       Diag(Field->getLocation(), diag::note_declared_at);
10705       Diag(CurrentLocation, diag::note_member_synthesized_at)
10706         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10707       Invalid = true;
10708       continue;
10709     }
10710 
10711     // Suppress assigning zero-width bitfields.
10712     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10713       continue;
10714 
10715     QualType FieldType = Field->getType().getNonReferenceType();
10716     if (FieldType->isIncompleteArrayType()) {
10717       assert(ClassDecl->hasFlexibleArrayMember() &&
10718              "Incomplete array type is not valid");
10719       continue;
10720     }
10721 
10722     // Build references to the field in the object we're copying from and to.
10723     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10724                               LookupMemberName);
10725     MemberLookup.addDecl(Field);
10726     MemberLookup.resolveKind();
10727     MemberBuilder From(MoveOther, OtherRefType,
10728                        /*IsArrow=*/false, MemberLookup);
10729     MemberBuilder To(This, getCurrentThisType(),
10730                      /*IsArrow=*/true, MemberLookup);
10731 
10732     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
10733         "Member reference with rvalue base must be rvalue except for reference "
10734         "members, which aren't allowed for move assignment.");
10735 
10736     // Build the move of this field.
10737     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
10738                                             To, From,
10739                                             /*CopyingBaseSubobject=*/false,
10740                                             /*Copying=*/false);
10741     if (Move.isInvalid()) {
10742       Diag(CurrentLocation, diag::note_member_synthesized_at)
10743         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10744       MoveAssignOperator->setInvalidDecl();
10745       return;
10746     }
10747 
10748     // Success! Record the copy.
10749     Statements.push_back(Move.getAs<Stmt>());
10750   }
10751 
10752   if (!Invalid) {
10753     // Add a "return *this;"
10754     ExprResult ThisObj =
10755         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10756 
10757     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
10758     if (Return.isInvalid())
10759       Invalid = true;
10760     else {
10761       Statements.push_back(Return.getAs<Stmt>());
10762 
10763       if (Trap.hasErrorOccurred()) {
10764         Diag(CurrentLocation, diag::note_member_synthesized_at)
10765           << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10766         Invalid = true;
10767       }
10768     }
10769   }
10770 
10771   // The exception specification is needed because we are defining the
10772   // function.
10773   ResolveExceptionSpec(CurrentLocation,
10774                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
10775 
10776   if (Invalid) {
10777     MoveAssignOperator->setInvalidDecl();
10778     return;
10779   }
10780 
10781   StmtResult Body;
10782   {
10783     CompoundScopeRAII CompoundScope(*this);
10784     Body = ActOnCompoundStmt(Loc, Loc, Statements,
10785                              /*isStmtExpr=*/false);
10786     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10787   }
10788   MoveAssignOperator->setBody(Body.getAs<Stmt>());
10789 
10790   if (ASTMutationListener *L = getASTMutationListener()) {
10791     L->CompletedImplicitDefinition(MoveAssignOperator);
10792   }
10793 }
10794 
10795 Sema::ImplicitExceptionSpecification
10796 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10797   CXXRecordDecl *ClassDecl = MD->getParent();
10798 
10799   ImplicitExceptionSpecification ExceptSpec(*this);
10800   if (ClassDecl->isInvalidDecl())
10801     return ExceptSpec;
10802 
10803   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
10804   assert(T->getNumParams() >= 1 && "not a copy ctor");
10805   unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
10806 
10807   // C++ [except.spec]p14:
10808   //   An implicitly declared special member function (Clause 12) shall have an
10809   //   exception-specification. [...]
10810   for (const auto &Base : ClassDecl->bases()) {
10811     // Virtual bases are handled below.
10812     if (Base.isVirtual())
10813       continue;
10814 
10815     CXXRecordDecl *BaseClassDecl
10816       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10817     if (CXXConstructorDecl *CopyConstructor =
10818           LookupCopyingConstructor(BaseClassDecl, Quals))
10819       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10820   }
10821   for (const auto &Base : ClassDecl->vbases()) {
10822     CXXRecordDecl *BaseClassDecl
10823       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10824     if (CXXConstructorDecl *CopyConstructor =
10825           LookupCopyingConstructor(BaseClassDecl, Quals))
10826       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10827   }
10828   for (const auto *Field : ClassDecl->fields()) {
10829     QualType FieldType = Context.getBaseElementType(Field->getType());
10830     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10831       if (CXXConstructorDecl *CopyConstructor =
10832               LookupCopyingConstructor(FieldClassDecl,
10833                                        Quals | FieldType.getCVRQualifiers()))
10834       ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
10835     }
10836   }
10837 
10838   return ExceptSpec;
10839 }
10840 
10841 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10842                                                     CXXRecordDecl *ClassDecl) {
10843   // C++ [class.copy]p4:
10844   //   If the class definition does not explicitly declare a copy
10845   //   constructor, one is declared implicitly.
10846   assert(ClassDecl->needsImplicitCopyConstructor());
10847 
10848   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10849   if (DSM.isAlreadyBeingDeclared())
10850     return nullptr;
10851 
10852   QualType ClassType = Context.getTypeDeclType(ClassDecl);
10853   QualType ArgType = ClassType;
10854   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
10855   if (Const)
10856     ArgType = ArgType.withConst();
10857   ArgType = Context.getLValueReferenceType(ArgType);
10858 
10859   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10860                                                      CXXCopyConstructor,
10861                                                      Const);
10862 
10863   DeclarationName Name
10864     = Context.DeclarationNames.getCXXConstructorName(
10865                                            Context.getCanonicalType(ClassType));
10866   SourceLocation ClassLoc = ClassDecl->getLocation();
10867   DeclarationNameInfo NameInfo(Name, ClassLoc);
10868 
10869   //   An implicitly-declared copy constructor is an inline public
10870   //   member of its class.
10871   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
10872       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
10873       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10874       Constexpr);
10875   CopyConstructor->setAccess(AS_public);
10876   CopyConstructor->setDefaulted();
10877 
10878   if (getLangOpts().CUDA) {
10879     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
10880                                             CopyConstructor,
10881                                             /* ConstRHS */ Const,
10882                                             /* Diagnose */ false);
10883   }
10884 
10885   // Build an exception specification pointing back at this member.
10886   FunctionProtoType::ExtProtoInfo EPI =
10887       getImplicitMethodEPI(*this, CopyConstructor);
10888   CopyConstructor->setType(
10889       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10890 
10891   // Add the parameter to the constructor.
10892   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
10893                                                ClassLoc, ClassLoc,
10894                                                /*IdentifierInfo=*/nullptr,
10895                                                ArgType, /*TInfo=*/nullptr,
10896                                                SC_None, nullptr);
10897   CopyConstructor->setParams(FromParam);
10898 
10899   CopyConstructor->setTrivial(
10900     ClassDecl->needsOverloadResolutionForCopyConstructor()
10901       ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10902       : ClassDecl->hasTrivialCopyConstructor());
10903 
10904   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
10905     SetDeclDeleted(CopyConstructor, ClassLoc);
10906 
10907   // Note that we have declared this constructor.
10908   ++ASTContext::NumImplicitCopyConstructorsDeclared;
10909 
10910   if (Scope *S = getScopeForContext(ClassDecl))
10911     PushOnScopeChains(CopyConstructor, S, false);
10912   ClassDecl->addDecl(CopyConstructor);
10913 
10914   return CopyConstructor;
10915 }
10916 
10917 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
10918                                    CXXConstructorDecl *CopyConstructor) {
10919   assert((CopyConstructor->isDefaulted() &&
10920           CopyConstructor->isCopyConstructor() &&
10921           !CopyConstructor->doesThisDeclarationHaveABody() &&
10922           !CopyConstructor->isDeleted()) &&
10923          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
10924 
10925   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
10926   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
10927 
10928   // C++11 [class.copy]p7:
10929   //   The [definition of an implicitly declared copy constructor] is
10930   //   deprecated if the class has a user-declared copy assignment operator
10931   //   or a user-declared destructor.
10932   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10933     diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10934 
10935   SynthesizedFunctionScope Scope(*this, CopyConstructor);
10936   DiagnosticErrorTrap Trap(Diags);
10937 
10938   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
10939       Trap.hasErrorOccurred()) {
10940     Diag(CurrentLocation, diag::note_member_synthesized_at)
10941       << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
10942     CopyConstructor->setInvalidDecl();
10943   }  else {
10944     SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
10945                              ? CopyConstructor->getLocEnd()
10946                              : CopyConstructor->getLocation();
10947     Sema::CompoundScopeRAII CompoundScope(*this);
10948     CopyConstructor->setBody(
10949         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
10950   }
10951 
10952   // The exception specification is needed because we are defining the
10953   // function.
10954   ResolveExceptionSpec(CurrentLocation,
10955                        CopyConstructor->getType()->castAs<FunctionProtoType>());
10956 
10957   CopyConstructor->markUsed(Context);
10958   MarkVTableUsed(CurrentLocation, ClassDecl);
10959 
10960   if (ASTMutationListener *L = getASTMutationListener()) {
10961     L->CompletedImplicitDefinition(CopyConstructor);
10962   }
10963 }
10964 
10965 Sema::ImplicitExceptionSpecification
10966 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10967   CXXRecordDecl *ClassDecl = MD->getParent();
10968 
10969   // C++ [except.spec]p14:
10970   //   An implicitly declared special member function (Clause 12) shall have an
10971   //   exception-specification. [...]
10972   ImplicitExceptionSpecification ExceptSpec(*this);
10973   if (ClassDecl->isInvalidDecl())
10974     return ExceptSpec;
10975 
10976   // Direct base-class constructors.
10977   for (const auto &B : ClassDecl->bases()) {
10978     if (B.isVirtual()) // Handled below.
10979       continue;
10980 
10981     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
10982       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10983       CXXConstructorDecl *Constructor =
10984           LookupMovingConstructor(BaseClassDecl, 0);
10985       // If this is a deleted function, add it anyway. This might be conformant
10986       // with the standard. This might not. I'm not sure. It might not matter.
10987       if (Constructor)
10988         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
10989     }
10990   }
10991 
10992   // Virtual base-class constructors.
10993   for (const auto &B : ClassDecl->vbases()) {
10994     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
10995       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10996       CXXConstructorDecl *Constructor =
10997           LookupMovingConstructor(BaseClassDecl, 0);
10998       // If this is a deleted function, add it anyway. This might be conformant
10999       // with the standard. This might not. I'm not sure. It might not matter.
11000       if (Constructor)
11001         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
11002     }
11003   }
11004 
11005   // Field constructors.
11006   for (const auto *F : ClassDecl->fields()) {
11007     QualType FieldType = Context.getBaseElementType(F->getType());
11008     if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
11009       CXXConstructorDecl *Constructor =
11010           LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
11011       // If this is a deleted function, add it anyway. This might be conformant
11012       // with the standard. This might not. I'm not sure. It might not matter.
11013       // In particular, the problem is that this function never gets called. It
11014       // might just be ill-formed because this function attempts to refer to
11015       // a deleted function here.
11016       if (Constructor)
11017         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
11018     }
11019   }
11020 
11021   return ExceptSpec;
11022 }
11023 
11024 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
11025                                                     CXXRecordDecl *ClassDecl) {
11026   assert(ClassDecl->needsImplicitMoveConstructor());
11027 
11028   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
11029   if (DSM.isAlreadyBeingDeclared())
11030     return nullptr;
11031 
11032   QualType ClassType = Context.getTypeDeclType(ClassDecl);
11033   QualType ArgType = Context.getRValueReferenceType(ClassType);
11034 
11035   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11036                                                      CXXMoveConstructor,
11037                                                      false);
11038 
11039   DeclarationName Name
11040     = Context.DeclarationNames.getCXXConstructorName(
11041                                            Context.getCanonicalType(ClassType));
11042   SourceLocation ClassLoc = ClassDecl->getLocation();
11043   DeclarationNameInfo NameInfo(Name, ClassLoc);
11044 
11045   // C++11 [class.copy]p11:
11046   //   An implicitly-declared copy/move constructor is an inline public
11047   //   member of its class.
11048   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
11049       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
11050       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
11051       Constexpr);
11052   MoveConstructor->setAccess(AS_public);
11053   MoveConstructor->setDefaulted();
11054 
11055   if (getLangOpts().CUDA) {
11056     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
11057                                             MoveConstructor,
11058                                             /* ConstRHS */ false,
11059                                             /* Diagnose */ false);
11060   }
11061 
11062   // Build an exception specification pointing back at this member.
11063   FunctionProtoType::ExtProtoInfo EPI =
11064       getImplicitMethodEPI(*this, MoveConstructor);
11065   MoveConstructor->setType(
11066       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
11067 
11068   // Add the parameter to the constructor.
11069   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
11070                                                ClassLoc, ClassLoc,
11071                                                /*IdentifierInfo=*/nullptr,
11072                                                ArgType, /*TInfo=*/nullptr,
11073                                                SC_None, nullptr);
11074   MoveConstructor->setParams(FromParam);
11075 
11076   MoveConstructor->setTrivial(
11077     ClassDecl->needsOverloadResolutionForMoveConstructor()
11078       ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
11079       : ClassDecl->hasTrivialMoveConstructor());
11080 
11081   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
11082     ClassDecl->setImplicitMoveConstructorIsDeleted();
11083     SetDeclDeleted(MoveConstructor, ClassLoc);
11084   }
11085 
11086   // Note that we have declared this constructor.
11087   ++ASTContext::NumImplicitMoveConstructorsDeclared;
11088 
11089   if (Scope *S = getScopeForContext(ClassDecl))
11090     PushOnScopeChains(MoveConstructor, S, false);
11091   ClassDecl->addDecl(MoveConstructor);
11092 
11093   return MoveConstructor;
11094 }
11095 
11096 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
11097                                    CXXConstructorDecl *MoveConstructor) {
11098   assert((MoveConstructor->isDefaulted() &&
11099           MoveConstructor->isMoveConstructor() &&
11100           !MoveConstructor->doesThisDeclarationHaveABody() &&
11101           !MoveConstructor->isDeleted()) &&
11102          "DefineImplicitMoveConstructor - call it for implicit move ctor");
11103 
11104   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
11105   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
11106 
11107   SynthesizedFunctionScope Scope(*this, MoveConstructor);
11108   DiagnosticErrorTrap Trap(Diags);
11109 
11110   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
11111       Trap.hasErrorOccurred()) {
11112     Diag(CurrentLocation, diag::note_member_synthesized_at)
11113       << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
11114     MoveConstructor->setInvalidDecl();
11115   }  else {
11116     SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
11117                              ? MoveConstructor->getLocEnd()
11118                              : MoveConstructor->getLocation();
11119     Sema::CompoundScopeRAII CompoundScope(*this);
11120     MoveConstructor->setBody(ActOnCompoundStmt(
11121         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
11122   }
11123 
11124   // The exception specification is needed because we are defining the
11125   // function.
11126   ResolveExceptionSpec(CurrentLocation,
11127                        MoveConstructor->getType()->castAs<FunctionProtoType>());
11128 
11129   MoveConstructor->markUsed(Context);
11130   MarkVTableUsed(CurrentLocation, ClassDecl);
11131 
11132   if (ASTMutationListener *L = getASTMutationListener()) {
11133     L->CompletedImplicitDefinition(MoveConstructor);
11134   }
11135 }
11136 
11137 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
11138   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
11139 }
11140 
11141 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
11142                             SourceLocation CurrentLocation,
11143                             CXXConversionDecl *Conv) {
11144   CXXRecordDecl *Lambda = Conv->getParent();
11145   CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
11146   // If we are defining a specialization of a conversion to function-ptr
11147   // cache the deduced template arguments for this specialization
11148   // so that we can use them to retrieve the corresponding call-operator
11149   // and static-invoker.
11150   const TemplateArgumentList *DeducedTemplateArgs = nullptr;
11151 
11152   // Retrieve the corresponding call-operator specialization.
11153   if (Lambda->isGenericLambda()) {
11154     assert(Conv->isFunctionTemplateSpecialization());
11155     FunctionTemplateDecl *CallOpTemplate =
11156         CallOp->getDescribedFunctionTemplate();
11157     DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
11158     void *InsertPos = nullptr;
11159     FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
11160                                                 DeducedTemplateArgs->asArray(),
11161                                                 InsertPos);
11162     assert(CallOpSpec &&
11163           "Conversion operator must have a corresponding call operator");
11164     CallOp = cast<CXXMethodDecl>(CallOpSpec);
11165   }
11166   // Mark the call operator referenced (and add to pending instantiations
11167   // if necessary).
11168   // For both the conversion and static-invoker template specializations
11169   // we construct their body's in this function, so no need to add them
11170   // to the PendingInstantiations.
11171   MarkFunctionReferenced(CurrentLocation, CallOp);
11172 
11173   SynthesizedFunctionScope Scope(*this, Conv);
11174   DiagnosticErrorTrap Trap(Diags);
11175 
11176   // Retrieve the static invoker...
11177   CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
11178   // ... and get the corresponding specialization for a generic lambda.
11179   if (Lambda->isGenericLambda()) {
11180     assert(DeducedTemplateArgs &&
11181       "Must have deduced template arguments from Conversion Operator");
11182     FunctionTemplateDecl *InvokeTemplate =
11183                           Invoker->getDescribedFunctionTemplate();
11184     void *InsertPos = nullptr;
11185     FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
11186                                                 DeducedTemplateArgs->asArray(),
11187                                                 InsertPos);
11188     assert(InvokeSpec &&
11189       "Must have a corresponding static invoker specialization");
11190     Invoker = cast<CXXMethodDecl>(InvokeSpec);
11191   }
11192   // Construct the body of the conversion function { return __invoke; }.
11193   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
11194                                         VK_LValue, Conv->getLocation()).get();
11195    assert(FunctionRef && "Can't refer to __invoke function?");
11196    Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
11197    Conv->setBody(new (Context) CompoundStmt(Context, Return,
11198                                             Conv->getLocation(),
11199                                             Conv->getLocation()));
11200 
11201   Conv->markUsed(Context);
11202   Conv->setReferenced();
11203 
11204   // Fill in the __invoke function with a dummy implementation. IR generation
11205   // will fill in the actual details.
11206   Invoker->markUsed(Context);
11207   Invoker->setReferenced();
11208   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
11209 
11210   if (ASTMutationListener *L = getASTMutationListener()) {
11211     L->CompletedImplicitDefinition(Conv);
11212     L->CompletedImplicitDefinition(Invoker);
11213    }
11214 }
11215 
11216 
11217 
11218 void Sema::DefineImplicitLambdaToBlockPointerConversion(
11219        SourceLocation CurrentLocation,
11220        CXXConversionDecl *Conv)
11221 {
11222   assert(!Conv->getParent()->isGenericLambda());
11223 
11224   Conv->markUsed(Context);
11225 
11226   SynthesizedFunctionScope Scope(*this, Conv);
11227   DiagnosticErrorTrap Trap(Diags);
11228 
11229   // Copy-initialize the lambda object as needed to capture it.
11230   Expr *This = ActOnCXXThis(CurrentLocation).get();
11231   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
11232 
11233   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
11234                                                         Conv->getLocation(),
11235                                                         Conv, DerefThis);
11236 
11237   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
11238   // behavior.  Note that only the general conversion function does this
11239   // (since it's unusable otherwise); in the case where we inline the
11240   // block literal, it has block literal lifetime semantics.
11241   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
11242     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
11243                                           CK_CopyAndAutoreleaseBlockObject,
11244                                           BuildBlock.get(), nullptr, VK_RValue);
11245 
11246   if (BuildBlock.isInvalid()) {
11247     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11248     Conv->setInvalidDecl();
11249     return;
11250   }
11251 
11252   // Create the return statement that returns the block from the conversion
11253   // function.
11254   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
11255   if (Return.isInvalid()) {
11256     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11257     Conv->setInvalidDecl();
11258     return;
11259   }
11260 
11261   // Set the body of the conversion function.
11262   Stmt *ReturnS = Return.get();
11263   Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
11264                                            Conv->getLocation(),
11265                                            Conv->getLocation()));
11266 
11267   // We're done; notify the mutation listener, if any.
11268   if (ASTMutationListener *L = getASTMutationListener()) {
11269     L->CompletedImplicitDefinition(Conv);
11270   }
11271 }
11272 
11273 /// \brief Determine whether the given list arguments contains exactly one
11274 /// "real" (non-default) argument.
11275 static bool hasOneRealArgument(MultiExprArg Args) {
11276   switch (Args.size()) {
11277   case 0:
11278     return false;
11279 
11280   default:
11281     if (!Args[1]->isDefaultArgument())
11282       return false;
11283 
11284     // fall through
11285   case 1:
11286     return !Args[0]->isDefaultArgument();
11287   }
11288 
11289   return false;
11290 }
11291 
11292 ExprResult
11293 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11294                             CXXConstructorDecl *Constructor,
11295                             MultiExprArg ExprArgs,
11296                             bool HadMultipleCandidates,
11297                             bool IsListInitialization,
11298                             bool IsStdInitListInitialization,
11299                             bool RequiresZeroInit,
11300                             unsigned ConstructKind,
11301                             SourceRange ParenRange) {
11302   bool Elidable = false;
11303 
11304   // C++0x [class.copy]p34:
11305   //   When certain criteria are met, an implementation is allowed to
11306   //   omit the copy/move construction of a class object, even if the
11307   //   copy/move constructor and/or destructor for the object have
11308   //   side effects. [...]
11309   //     - when a temporary class object that has not been bound to a
11310   //       reference (12.2) would be copied/moved to a class object
11311   //       with the same cv-unqualified type, the copy/move operation
11312   //       can be omitted by constructing the temporary object
11313   //       directly into the target of the omitted copy/move
11314   if (ConstructKind == CXXConstructExpr::CK_Complete &&
11315       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
11316     Expr *SubExpr = ExprArgs[0];
11317     Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
11318   }
11319 
11320   return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
11321                                Elidable, ExprArgs, HadMultipleCandidates,
11322                                IsListInitialization,
11323                                IsStdInitListInitialization, RequiresZeroInit,
11324                                ConstructKind, ParenRange);
11325 }
11326 
11327 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
11328 /// including handling of its default argument expressions.
11329 ExprResult
11330 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11331                             CXXConstructorDecl *Constructor, bool Elidable,
11332                             MultiExprArg ExprArgs,
11333                             bool HadMultipleCandidates,
11334                             bool IsListInitialization,
11335                             bool IsStdInitListInitialization,
11336                             bool RequiresZeroInit,
11337                             unsigned ConstructKind,
11338                             SourceRange ParenRange) {
11339   MarkFunctionReferenced(ConstructLoc, Constructor);
11340   return CXXConstructExpr::Create(
11341       Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
11342       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
11343       RequiresZeroInit,
11344       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
11345       ParenRange);
11346 }
11347 
11348 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
11349   assert(Field->hasInClassInitializer());
11350 
11351   // If we already have the in-class initializer nothing needs to be done.
11352   if (Field->getInClassInitializer())
11353     return CXXDefaultInitExpr::Create(Context, Loc, Field);
11354 
11355   // Maybe we haven't instantiated the in-class initializer. Go check the
11356   // pattern FieldDecl to see if it has one.
11357   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
11358 
11359   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
11360     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
11361     DeclContext::lookup_result Lookup =
11362         ClassPattern->lookup(Field->getDeclName());
11363     assert(Lookup.size() == 1);
11364     FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]);
11365     if (InstantiateInClassInitializer(Loc, Field, Pattern,
11366                                       getTemplateInstantiationArgs(Field)))
11367       return ExprError();
11368     return CXXDefaultInitExpr::Create(Context, Loc, Field);
11369   }
11370 
11371   // DR1351:
11372   //   If the brace-or-equal-initializer of a non-static data member
11373   //   invokes a defaulted default constructor of its class or of an
11374   //   enclosing class in a potentially evaluated subexpression, the
11375   //   program is ill-formed.
11376   //
11377   // This resolution is unworkable: the exception specification of the
11378   // default constructor can be needed in an unevaluated context, in
11379   // particular, in the operand of a noexcept-expression, and we can be
11380   // unable to compute an exception specification for an enclosed class.
11381   //
11382   // Any attempt to resolve the exception specification of a defaulted default
11383   // constructor before the initializer is lexically complete will ultimately
11384   // come here at which point we can diagnose it.
11385   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
11386   if (OutermostClass == ParentRD) {
11387     Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
11388         << ParentRD << Field;
11389   } else {
11390     Diag(Field->getLocEnd(),
11391          diag::err_in_class_initializer_not_yet_parsed_outer_class)
11392         << ParentRD << OutermostClass << Field;
11393   }
11394 
11395   return ExprError();
11396 }
11397 
11398 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
11399   if (VD->isInvalidDecl()) return;
11400 
11401   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
11402   if (ClassDecl->isInvalidDecl()) return;
11403   if (ClassDecl->hasIrrelevantDestructor()) return;
11404   if (ClassDecl->isDependentContext()) return;
11405 
11406   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
11407   MarkFunctionReferenced(VD->getLocation(), Destructor);
11408   CheckDestructorAccess(VD->getLocation(), Destructor,
11409                         PDiag(diag::err_access_dtor_var)
11410                         << VD->getDeclName()
11411                         << VD->getType());
11412   DiagnoseUseOfDecl(Destructor, VD->getLocation());
11413 
11414   if (Destructor->isTrivial()) return;
11415   if (!VD->hasGlobalStorage()) return;
11416 
11417   // Emit warning for non-trivial dtor in global scope (a real global,
11418   // class-static, function-static).
11419   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
11420 
11421   // TODO: this should be re-enabled for static locals by !CXAAtExit
11422   if (!VD->isStaticLocal())
11423     Diag(VD->getLocation(), diag::warn_global_destructor);
11424 }
11425 
11426 /// \brief Given a constructor and the set of arguments provided for the
11427 /// constructor, convert the arguments and add any required default arguments
11428 /// to form a proper call to this constructor.
11429 ///
11430 /// \returns true if an error occurred, false otherwise.
11431 bool
11432 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
11433                               MultiExprArg ArgsPtr,
11434                               SourceLocation Loc,
11435                               SmallVectorImpl<Expr*> &ConvertedArgs,
11436                               bool AllowExplicit,
11437                               bool IsListInitialization) {
11438   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
11439   unsigned NumArgs = ArgsPtr.size();
11440   Expr **Args = ArgsPtr.data();
11441 
11442   const FunctionProtoType *Proto
11443     = Constructor->getType()->getAs<FunctionProtoType>();
11444   assert(Proto && "Constructor without a prototype?");
11445   unsigned NumParams = Proto->getNumParams();
11446 
11447   // If too few arguments are available, we'll fill in the rest with defaults.
11448   if (NumArgs < NumParams)
11449     ConvertedArgs.reserve(NumParams);
11450   else
11451     ConvertedArgs.reserve(NumArgs);
11452 
11453   VariadicCallType CallType =
11454     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
11455   SmallVector<Expr *, 8> AllArgs;
11456   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
11457                                         Proto, 0,
11458                                         llvm::makeArrayRef(Args, NumArgs),
11459                                         AllArgs,
11460                                         CallType, AllowExplicit,
11461                                         IsListInitialization);
11462   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
11463 
11464   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
11465 
11466   CheckConstructorCall(Constructor,
11467                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
11468                        Proto, Loc);
11469 
11470   return Invalid;
11471 }
11472 
11473 static inline bool
11474 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
11475                                        const FunctionDecl *FnDecl) {
11476   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
11477   if (isa<NamespaceDecl>(DC)) {
11478     return SemaRef.Diag(FnDecl->getLocation(),
11479                         diag::err_operator_new_delete_declared_in_namespace)
11480       << FnDecl->getDeclName();
11481   }
11482 
11483   if (isa<TranslationUnitDecl>(DC) &&
11484       FnDecl->getStorageClass() == SC_Static) {
11485     return SemaRef.Diag(FnDecl->getLocation(),
11486                         diag::err_operator_new_delete_declared_static)
11487       << FnDecl->getDeclName();
11488   }
11489 
11490   return false;
11491 }
11492 
11493 static inline bool
11494 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
11495                             CanQualType ExpectedResultType,
11496                             CanQualType ExpectedFirstParamType,
11497                             unsigned DependentParamTypeDiag,
11498                             unsigned InvalidParamTypeDiag) {
11499   QualType ResultType =
11500       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
11501 
11502   // Check that the result type is not dependent.
11503   if (ResultType->isDependentType())
11504     return SemaRef.Diag(FnDecl->getLocation(),
11505                         diag::err_operator_new_delete_dependent_result_type)
11506     << FnDecl->getDeclName() << ExpectedResultType;
11507 
11508   // Check that the result type is what we expect.
11509   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
11510     return SemaRef.Diag(FnDecl->getLocation(),
11511                         diag::err_operator_new_delete_invalid_result_type)
11512     << FnDecl->getDeclName() << ExpectedResultType;
11513 
11514   // A function template must have at least 2 parameters.
11515   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
11516     return SemaRef.Diag(FnDecl->getLocation(),
11517                       diag::err_operator_new_delete_template_too_few_parameters)
11518         << FnDecl->getDeclName();
11519 
11520   // The function decl must have at least 1 parameter.
11521   if (FnDecl->getNumParams() == 0)
11522     return SemaRef.Diag(FnDecl->getLocation(),
11523                         diag::err_operator_new_delete_too_few_parameters)
11524       << FnDecl->getDeclName();
11525 
11526   // Check the first parameter type is not dependent.
11527   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
11528   if (FirstParamType->isDependentType())
11529     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
11530       << FnDecl->getDeclName() << ExpectedFirstParamType;
11531 
11532   // Check that the first parameter type is what we expect.
11533   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
11534       ExpectedFirstParamType)
11535     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
11536     << FnDecl->getDeclName() << ExpectedFirstParamType;
11537 
11538   return false;
11539 }
11540 
11541 static bool
11542 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
11543   // C++ [basic.stc.dynamic.allocation]p1:
11544   //   A program is ill-formed if an allocation function is declared in a
11545   //   namespace scope other than global scope or declared static in global
11546   //   scope.
11547   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11548     return true;
11549 
11550   CanQualType SizeTy =
11551     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
11552 
11553   // C++ [basic.stc.dynamic.allocation]p1:
11554   //  The return type shall be void*. The first parameter shall have type
11555   //  std::size_t.
11556   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
11557                                   SizeTy,
11558                                   diag::err_operator_new_dependent_param_type,
11559                                   diag::err_operator_new_param_type))
11560     return true;
11561 
11562   // C++ [basic.stc.dynamic.allocation]p1:
11563   //  The first parameter shall not have an associated default argument.
11564   if (FnDecl->getParamDecl(0)->hasDefaultArg())
11565     return SemaRef.Diag(FnDecl->getLocation(),
11566                         diag::err_operator_new_default_arg)
11567       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
11568 
11569   return false;
11570 }
11571 
11572 static bool
11573 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
11574   // C++ [basic.stc.dynamic.deallocation]p1:
11575   //   A program is ill-formed if deallocation functions are declared in a
11576   //   namespace scope other than global scope or declared static in global
11577   //   scope.
11578   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11579     return true;
11580 
11581   // C++ [basic.stc.dynamic.deallocation]p2:
11582   //   Each deallocation function shall return void and its first parameter
11583   //   shall be void*.
11584   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
11585                                   SemaRef.Context.VoidPtrTy,
11586                                  diag::err_operator_delete_dependent_param_type,
11587                                  diag::err_operator_delete_param_type))
11588     return true;
11589 
11590   return false;
11591 }
11592 
11593 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
11594 /// of this overloaded operator is well-formed. If so, returns false;
11595 /// otherwise, emits appropriate diagnostics and returns true.
11596 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
11597   assert(FnDecl && FnDecl->isOverloadedOperator() &&
11598          "Expected an overloaded operator declaration");
11599 
11600   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
11601 
11602   // C++ [over.oper]p5:
11603   //   The allocation and deallocation functions, operator new,
11604   //   operator new[], operator delete and operator delete[], are
11605   //   described completely in 3.7.3. The attributes and restrictions
11606   //   found in the rest of this subclause do not apply to them unless
11607   //   explicitly stated in 3.7.3.
11608   if (Op == OO_Delete || Op == OO_Array_Delete)
11609     return CheckOperatorDeleteDeclaration(*this, FnDecl);
11610 
11611   if (Op == OO_New || Op == OO_Array_New)
11612     return CheckOperatorNewDeclaration(*this, FnDecl);
11613 
11614   // C++ [over.oper]p6:
11615   //   An operator function shall either be a non-static member
11616   //   function or be a non-member function and have at least one
11617   //   parameter whose type is a class, a reference to a class, an
11618   //   enumeration, or a reference to an enumeration.
11619   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
11620     if (MethodDecl->isStatic())
11621       return Diag(FnDecl->getLocation(),
11622                   diag::err_operator_overload_static) << FnDecl->getDeclName();
11623   } else {
11624     bool ClassOrEnumParam = false;
11625     for (auto Param : FnDecl->params()) {
11626       QualType ParamType = Param->getType().getNonReferenceType();
11627       if (ParamType->isDependentType() || ParamType->isRecordType() ||
11628           ParamType->isEnumeralType()) {
11629         ClassOrEnumParam = true;
11630         break;
11631       }
11632     }
11633 
11634     if (!ClassOrEnumParam)
11635       return Diag(FnDecl->getLocation(),
11636                   diag::err_operator_overload_needs_class_or_enum)
11637         << FnDecl->getDeclName();
11638   }
11639 
11640   // C++ [over.oper]p8:
11641   //   An operator function cannot have default arguments (8.3.6),
11642   //   except where explicitly stated below.
11643   //
11644   // Only the function-call operator allows default arguments
11645   // (C++ [over.call]p1).
11646   if (Op != OO_Call) {
11647     for (auto Param : FnDecl->params()) {
11648       if (Param->hasDefaultArg())
11649         return Diag(Param->getLocation(),
11650                     diag::err_operator_overload_default_arg)
11651           << FnDecl->getDeclName() << Param->getDefaultArgRange();
11652     }
11653   }
11654 
11655   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
11656     { false, false, false }
11657 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11658     , { Unary, Binary, MemberOnly }
11659 #include "clang/Basic/OperatorKinds.def"
11660   };
11661 
11662   bool CanBeUnaryOperator = OperatorUses[Op][0];
11663   bool CanBeBinaryOperator = OperatorUses[Op][1];
11664   bool MustBeMemberOperator = OperatorUses[Op][2];
11665 
11666   // C++ [over.oper]p8:
11667   //   [...] Operator functions cannot have more or fewer parameters
11668   //   than the number required for the corresponding operator, as
11669   //   described in the rest of this subclause.
11670   unsigned NumParams = FnDecl->getNumParams()
11671                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
11672   if (Op != OO_Call &&
11673       ((NumParams == 1 && !CanBeUnaryOperator) ||
11674        (NumParams == 2 && !CanBeBinaryOperator) ||
11675        (NumParams < 1) || (NumParams > 2))) {
11676     // We have the wrong number of parameters.
11677     unsigned ErrorKind;
11678     if (CanBeUnaryOperator && CanBeBinaryOperator) {
11679       ErrorKind = 2;  // 2 -> unary or binary.
11680     } else if (CanBeUnaryOperator) {
11681       ErrorKind = 0;  // 0 -> unary
11682     } else {
11683       assert(CanBeBinaryOperator &&
11684              "All non-call overloaded operators are unary or binary!");
11685       ErrorKind = 1;  // 1 -> binary
11686     }
11687 
11688     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
11689       << FnDecl->getDeclName() << NumParams << ErrorKind;
11690   }
11691 
11692   // Overloaded operators other than operator() cannot be variadic.
11693   if (Op != OO_Call &&
11694       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
11695     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
11696       << FnDecl->getDeclName();
11697   }
11698 
11699   // Some operators must be non-static member functions.
11700   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
11701     return Diag(FnDecl->getLocation(),
11702                 diag::err_operator_overload_must_be_member)
11703       << FnDecl->getDeclName();
11704   }
11705 
11706   // C++ [over.inc]p1:
11707   //   The user-defined function called operator++ implements the
11708   //   prefix and postfix ++ operator. If this function is a member
11709   //   function with no parameters, or a non-member function with one
11710   //   parameter of class or enumeration type, it defines the prefix
11711   //   increment operator ++ for objects of that type. If the function
11712   //   is a member function with one parameter (which shall be of type
11713   //   int) or a non-member function with two parameters (the second
11714   //   of which shall be of type int), it defines the postfix
11715   //   increment operator ++ for objects of that type.
11716   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11717     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
11718     QualType ParamType = LastParam->getType();
11719 
11720     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11721         !ParamType->isDependentType())
11722       return Diag(LastParam->getLocation(),
11723                   diag::err_operator_overload_post_incdec_must_be_int)
11724         << LastParam->getType() << (Op == OO_MinusMinus);
11725   }
11726 
11727   return false;
11728 }
11729 
11730 /// CheckLiteralOperatorDeclaration - Check whether the declaration
11731 /// of this literal operator function is well-formed. If so, returns
11732 /// false; otherwise, emits appropriate diagnostics and returns true.
11733 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
11734   if (isa<CXXMethodDecl>(FnDecl)) {
11735     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11736       << FnDecl->getDeclName();
11737     return true;
11738   }
11739 
11740   if (FnDecl->isExternC()) {
11741     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11742     return true;
11743   }
11744 
11745   bool Valid = false;
11746 
11747   // This might be the definition of a literal operator template.
11748   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11749   // This might be a specialization of a literal operator template.
11750   if (!TpDecl)
11751     TpDecl = FnDecl->getPrimaryTemplate();
11752 
11753   // template <char...> type operator "" name() and
11754   // template <class T, T...> type operator "" name() are the only valid
11755   // template signatures, and the only valid signatures with no parameters.
11756   if (TpDecl) {
11757     if (FnDecl->param_size() == 0) {
11758       // Must have one or two template parameters
11759       TemplateParameterList *Params = TpDecl->getTemplateParameters();
11760       if (Params->size() == 1) {
11761         NonTypeTemplateParmDecl *PmDecl =
11762           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
11763 
11764         // The template parameter must be a char parameter pack.
11765         if (PmDecl && PmDecl->isTemplateParameterPack() &&
11766             Context.hasSameType(PmDecl->getType(), Context.CharTy))
11767           Valid = true;
11768       } else if (Params->size() == 2) {
11769         TemplateTypeParmDecl *PmType =
11770           dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
11771         NonTypeTemplateParmDecl *PmArgs =
11772           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
11773 
11774         // The second template parameter must be a parameter pack with the
11775         // first template parameter as its type.
11776         if (PmType && PmArgs &&
11777             !PmType->isTemplateParameterPack() &&
11778             PmArgs->isTemplateParameterPack()) {
11779           const TemplateTypeParmType *TArgs =
11780             PmArgs->getType()->getAs<TemplateTypeParmType>();
11781           if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11782               TArgs->getIndex() == PmType->getIndex()) {
11783             Valid = true;
11784             if (ActiveTemplateInstantiations.empty())
11785               Diag(FnDecl->getLocation(),
11786                    diag::ext_string_literal_operator_template);
11787           }
11788         }
11789       }
11790     }
11791   } else if (FnDecl->param_size()) {
11792     // Check the first parameter
11793     FunctionDecl::param_iterator Param = FnDecl->param_begin();
11794 
11795     QualType T = (*Param)->getType().getUnqualifiedType();
11796 
11797     // unsigned long long int, long double, and any character type are allowed
11798     // as the only parameters.
11799     if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
11800         Context.hasSameType(T, Context.LongDoubleTy) ||
11801         Context.hasSameType(T, Context.CharTy) ||
11802         Context.hasSameType(T, Context.WideCharTy) ||
11803         Context.hasSameType(T, Context.Char16Ty) ||
11804         Context.hasSameType(T, Context.Char32Ty)) {
11805       if (++Param == FnDecl->param_end())
11806         Valid = true;
11807       goto FinishedParams;
11808     }
11809 
11810     // Otherwise it must be a pointer to const; let's strip those qualifiers.
11811     const PointerType *PT = T->getAs<PointerType>();
11812     if (!PT)
11813       goto FinishedParams;
11814     T = PT->getPointeeType();
11815     if (!T.isConstQualified() || T.isVolatileQualified())
11816       goto FinishedParams;
11817     T = T.getUnqualifiedType();
11818 
11819     // Move on to the second parameter;
11820     ++Param;
11821 
11822     // If there is no second parameter, the first must be a const char *
11823     if (Param == FnDecl->param_end()) {
11824       if (Context.hasSameType(T, Context.CharTy))
11825         Valid = true;
11826       goto FinishedParams;
11827     }
11828 
11829     // const char *, const wchar_t*, const char16_t*, and const char32_t*
11830     // are allowed as the first parameter to a two-parameter function
11831     if (!(Context.hasSameType(T, Context.CharTy) ||
11832           Context.hasSameType(T, Context.WideCharTy) ||
11833           Context.hasSameType(T, Context.Char16Ty) ||
11834           Context.hasSameType(T, Context.Char32Ty)))
11835       goto FinishedParams;
11836 
11837     // The second and final parameter must be an std::size_t
11838     T = (*Param)->getType().getUnqualifiedType();
11839     if (Context.hasSameType(T, Context.getSizeType()) &&
11840         ++Param == FnDecl->param_end())
11841       Valid = true;
11842   }
11843 
11844   // FIXME: This diagnostic is absolutely terrible.
11845 FinishedParams:
11846   if (!Valid) {
11847     Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11848       << FnDecl->getDeclName();
11849     return true;
11850   }
11851 
11852   // A parameter-declaration-clause containing a default argument is not
11853   // equivalent to any of the permitted forms.
11854   for (auto Param : FnDecl->params()) {
11855     if (Param->hasDefaultArg()) {
11856       Diag(Param->getDefaultArgRange().getBegin(),
11857            diag::err_literal_operator_default_argument)
11858         << Param->getDefaultArgRange();
11859       break;
11860     }
11861   }
11862 
11863   StringRef LiteralName
11864     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11865   if (LiteralName[0] != '_') {
11866     // C++11 [usrlit.suffix]p1:
11867     //   Literal suffix identifiers that do not start with an underscore
11868     //   are reserved for future standardization.
11869     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11870       << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
11871   }
11872 
11873   return false;
11874 }
11875 
11876 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11877 /// linkage specification, including the language and (if present)
11878 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
11879 /// language string literal. LBraceLoc, if valid, provides the location of
11880 /// the '{' brace. Otherwise, this linkage specification does not
11881 /// have any braces.
11882 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
11883                                            Expr *LangStr,
11884                                            SourceLocation LBraceLoc) {
11885   StringLiteral *Lit = cast<StringLiteral>(LangStr);
11886   if (!Lit->isAscii()) {
11887     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11888       << LangStr->getSourceRange();
11889     return nullptr;
11890   }
11891 
11892   StringRef Lang = Lit->getString();
11893   LinkageSpecDecl::LanguageIDs Language;
11894   if (Lang == "C")
11895     Language = LinkageSpecDecl::lang_c;
11896   else if (Lang == "C++")
11897     Language = LinkageSpecDecl::lang_cxx;
11898   else {
11899     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11900       << LangStr->getSourceRange();
11901     return nullptr;
11902   }
11903 
11904   // FIXME: Add all the various semantics of linkage specifications
11905 
11906   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11907                                                LangStr->getExprLoc(), Language,
11908                                                LBraceLoc.isValid());
11909   CurContext->addDecl(D);
11910   PushDeclContext(S, D);
11911   return D;
11912 }
11913 
11914 /// ActOnFinishLinkageSpecification - Complete the definition of
11915 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
11916 /// valid, it's the position of the closing '}' brace in a linkage
11917 /// specification that uses braces.
11918 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
11919                                             Decl *LinkageSpec,
11920                                             SourceLocation RBraceLoc) {
11921   if (RBraceLoc.isValid()) {
11922     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11923     LSDecl->setRBraceLoc(RBraceLoc);
11924   }
11925   PopDeclContext();
11926   return LinkageSpec;
11927 }
11928 
11929 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11930                                   AttributeList *AttrList,
11931                                   SourceLocation SemiLoc) {
11932   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11933   // Attribute declarations appertain to empty declaration so we handle
11934   // them here.
11935   if (AttrList)
11936     ProcessDeclAttributeList(S, ED, AttrList);
11937 
11938   CurContext->addDecl(ED);
11939   return ED;
11940 }
11941 
11942 /// \brief Perform semantic analysis for the variable declaration that
11943 /// occurs within a C++ catch clause, returning the newly-created
11944 /// variable.
11945 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
11946                                          TypeSourceInfo *TInfo,
11947                                          SourceLocation StartLoc,
11948                                          SourceLocation Loc,
11949                                          IdentifierInfo *Name) {
11950   bool Invalid = false;
11951   QualType ExDeclType = TInfo->getType();
11952 
11953   // Arrays and functions decay.
11954   if (ExDeclType->isArrayType())
11955     ExDeclType = Context.getArrayDecayedType(ExDeclType);
11956   else if (ExDeclType->isFunctionType())
11957     ExDeclType = Context.getPointerType(ExDeclType);
11958 
11959   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11960   // The exception-declaration shall not denote a pointer or reference to an
11961   // incomplete type, other than [cv] void*.
11962   // N2844 forbids rvalue references.
11963   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
11964     Diag(Loc, diag::err_catch_rvalue_ref);
11965     Invalid = true;
11966   }
11967 
11968   QualType BaseType = ExDeclType;
11969   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
11970   unsigned DK = diag::err_catch_incomplete;
11971   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
11972     BaseType = Ptr->getPointeeType();
11973     Mode = 1;
11974     DK = diag::err_catch_incomplete_ptr;
11975   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
11976     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
11977     BaseType = Ref->getPointeeType();
11978     Mode = 2;
11979     DK = diag::err_catch_incomplete_ref;
11980   }
11981   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
11982       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
11983     Invalid = true;
11984 
11985   if (!Invalid && !ExDeclType->isDependentType() &&
11986       RequireNonAbstractType(Loc, ExDeclType,
11987                              diag::err_abstract_type_in_decl,
11988                              AbstractVariableType))
11989     Invalid = true;
11990 
11991   // Only the non-fragile NeXT runtime currently supports C++ catches
11992   // of ObjC types, and no runtime supports catching ObjC types by value.
11993   if (!Invalid && getLangOpts().ObjC1) {
11994     QualType T = ExDeclType;
11995     if (const ReferenceType *RT = T->getAs<ReferenceType>())
11996       T = RT->getPointeeType();
11997 
11998     if (T->isObjCObjectType()) {
11999       Diag(Loc, diag::err_objc_object_catch);
12000       Invalid = true;
12001     } else if (T->isObjCObjectPointerType()) {
12002       // FIXME: should this be a test for macosx-fragile specifically?
12003       if (getLangOpts().ObjCRuntime.isFragile())
12004         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
12005     }
12006   }
12007 
12008   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
12009                                     ExDeclType, TInfo, SC_None);
12010   ExDecl->setExceptionVariable(true);
12011 
12012   // In ARC, infer 'retaining' for variables of retainable type.
12013   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
12014     Invalid = true;
12015 
12016   if (!Invalid && !ExDeclType->isDependentType()) {
12017     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
12018       // Insulate this from anything else we might currently be parsing.
12019       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
12020 
12021       // C++ [except.handle]p16:
12022       //   The object declared in an exception-declaration or, if the
12023       //   exception-declaration does not specify a name, a temporary (12.2) is
12024       //   copy-initialized (8.5) from the exception object. [...]
12025       //   The object is destroyed when the handler exits, after the destruction
12026       //   of any automatic objects initialized within the handler.
12027       //
12028       // We just pretend to initialize the object with itself, then make sure
12029       // it can be destroyed later.
12030       QualType initType = Context.getExceptionObjectType(ExDeclType);
12031 
12032       InitializedEntity entity =
12033         InitializedEntity::InitializeVariable(ExDecl);
12034       InitializationKind initKind =
12035         InitializationKind::CreateCopy(Loc, SourceLocation());
12036 
12037       Expr *opaqueValue =
12038         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
12039       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
12040       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
12041       if (result.isInvalid())
12042         Invalid = true;
12043       else {
12044         // If the constructor used was non-trivial, set this as the
12045         // "initializer".
12046         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
12047         if (!construct->getConstructor()->isTrivial()) {
12048           Expr *init = MaybeCreateExprWithCleanups(construct);
12049           ExDecl->setInit(init);
12050         }
12051 
12052         // And make sure it's destructable.
12053         FinalizeVarWithDestructor(ExDecl, recordType);
12054       }
12055     }
12056   }
12057 
12058   if (Invalid)
12059     ExDecl->setInvalidDecl();
12060 
12061   return ExDecl;
12062 }
12063 
12064 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
12065 /// handler.
12066 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
12067   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12068   bool Invalid = D.isInvalidType();
12069 
12070   // Check for unexpanded parameter packs.
12071   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12072                                       UPPC_ExceptionType)) {
12073     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12074                                              D.getIdentifierLoc());
12075     Invalid = true;
12076   }
12077 
12078   IdentifierInfo *II = D.getIdentifier();
12079   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
12080                                              LookupOrdinaryName,
12081                                              ForRedeclaration)) {
12082     // The scope should be freshly made just for us. There is just no way
12083     // it contains any previous declaration, except for function parameters in
12084     // a function-try-block's catch statement.
12085     assert(!S->isDeclScope(PrevDecl));
12086     if (isDeclInScope(PrevDecl, CurContext, S)) {
12087       Diag(D.getIdentifierLoc(), diag::err_redefinition)
12088         << D.getIdentifier();
12089       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12090       Invalid = true;
12091     } else if (PrevDecl->isTemplateParameter())
12092       // Maybe we will complain about the shadowed template parameter.
12093       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12094   }
12095 
12096   if (D.getCXXScopeSpec().isSet() && !Invalid) {
12097     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
12098       << D.getCXXScopeSpec().getRange();
12099     Invalid = true;
12100   }
12101 
12102   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
12103                                               D.getLocStart(),
12104                                               D.getIdentifierLoc(),
12105                                               D.getIdentifier());
12106   if (Invalid)
12107     ExDecl->setInvalidDecl();
12108 
12109   // Add the exception declaration into this scope.
12110   if (II)
12111     PushOnScopeChains(ExDecl, S);
12112   else
12113     CurContext->addDecl(ExDecl);
12114 
12115   ProcessDeclAttributes(S, ExDecl, D);
12116   return ExDecl;
12117 }
12118 
12119 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
12120                                          Expr *AssertExpr,
12121                                          Expr *AssertMessageExpr,
12122                                          SourceLocation RParenLoc) {
12123   StringLiteral *AssertMessage =
12124       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
12125 
12126   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
12127     return nullptr;
12128 
12129   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
12130                                       AssertMessage, RParenLoc, false);
12131 }
12132 
12133 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
12134                                          Expr *AssertExpr,
12135                                          StringLiteral *AssertMessage,
12136                                          SourceLocation RParenLoc,
12137                                          bool Failed) {
12138   assert(AssertExpr != nullptr && "Expected non-null condition");
12139   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
12140       !Failed) {
12141     // In a static_assert-declaration, the constant-expression shall be a
12142     // constant expression that can be contextually converted to bool.
12143     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
12144     if (Converted.isInvalid())
12145       Failed = true;
12146 
12147     llvm::APSInt Cond;
12148     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
12149           diag::err_static_assert_expression_is_not_constant,
12150           /*AllowFold=*/false).isInvalid())
12151       Failed = true;
12152 
12153     if (!Failed && !Cond) {
12154       SmallString<256> MsgBuffer;
12155       llvm::raw_svector_ostream Msg(MsgBuffer);
12156       if (AssertMessage)
12157         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
12158       Diag(StaticAssertLoc, diag::err_static_assert_failed)
12159         << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
12160       Failed = true;
12161     }
12162   }
12163 
12164   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
12165                                         AssertExpr, AssertMessage, RParenLoc,
12166                                         Failed);
12167 
12168   CurContext->addDecl(Decl);
12169   return Decl;
12170 }
12171 
12172 /// \brief Perform semantic analysis of the given friend type declaration.
12173 ///
12174 /// \returns A friend declaration that.
12175 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
12176                                       SourceLocation FriendLoc,
12177                                       TypeSourceInfo *TSInfo) {
12178   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
12179 
12180   QualType T = TSInfo->getType();
12181   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
12182 
12183   // C++03 [class.friend]p2:
12184   //   An elaborated-type-specifier shall be used in a friend declaration
12185   //   for a class.*
12186   //
12187   //   * The class-key of the elaborated-type-specifier is required.
12188   if (!ActiveTemplateInstantiations.empty()) {
12189     // Do not complain about the form of friend template types during
12190     // template instantiation; we will already have complained when the
12191     // template was declared.
12192   } else {
12193     if (!T->isElaboratedTypeSpecifier()) {
12194       // If we evaluated the type to a record type, suggest putting
12195       // a tag in front.
12196       if (const RecordType *RT = T->getAs<RecordType>()) {
12197         RecordDecl *RD = RT->getDecl();
12198 
12199         SmallString<16> InsertionText(" ");
12200         InsertionText += RD->getKindName();
12201 
12202         Diag(TypeRange.getBegin(),
12203              getLangOpts().CPlusPlus11 ?
12204                diag::warn_cxx98_compat_unelaborated_friend_type :
12205                diag::ext_unelaborated_friend_type)
12206           << (unsigned) RD->getTagKind()
12207           << T
12208           << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
12209                                         InsertionText);
12210       } else {
12211         Diag(FriendLoc,
12212              getLangOpts().CPlusPlus11 ?
12213                diag::warn_cxx98_compat_nonclass_type_friend :
12214                diag::ext_nonclass_type_friend)
12215           << T
12216           << TypeRange;
12217       }
12218     } else if (T->getAs<EnumType>()) {
12219       Diag(FriendLoc,
12220            getLangOpts().CPlusPlus11 ?
12221              diag::warn_cxx98_compat_enum_friend :
12222              diag::ext_enum_friend)
12223         << T
12224         << TypeRange;
12225     }
12226 
12227     // C++11 [class.friend]p3:
12228     //   A friend declaration that does not declare a function shall have one
12229     //   of the following forms:
12230     //     friend elaborated-type-specifier ;
12231     //     friend simple-type-specifier ;
12232     //     friend typename-specifier ;
12233     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
12234       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
12235   }
12236 
12237   //   If the type specifier in a friend declaration designates a (possibly
12238   //   cv-qualified) class type, that class is declared as a friend; otherwise,
12239   //   the friend declaration is ignored.
12240   return FriendDecl::Create(Context, CurContext,
12241                             TSInfo->getTypeLoc().getLocStart(), TSInfo,
12242                             FriendLoc);
12243 }
12244 
12245 /// Handle a friend tag declaration where the scope specifier was
12246 /// templated.
12247 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
12248                                     unsigned TagSpec, SourceLocation TagLoc,
12249                                     CXXScopeSpec &SS,
12250                                     IdentifierInfo *Name,
12251                                     SourceLocation NameLoc,
12252                                     AttributeList *Attr,
12253                                     MultiTemplateParamsArg TempParamLists) {
12254   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12255 
12256   bool isExplicitSpecialization = false;
12257   bool Invalid = false;
12258 
12259   if (TemplateParameterList *TemplateParams =
12260           MatchTemplateParametersToScopeSpecifier(
12261               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
12262               isExplicitSpecialization, Invalid)) {
12263     if (TemplateParams->size() > 0) {
12264       // This is a declaration of a class template.
12265       if (Invalid)
12266         return nullptr;
12267 
12268       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
12269                                 NameLoc, Attr, TemplateParams, AS_public,
12270                                 /*ModulePrivateLoc=*/SourceLocation(),
12271                                 FriendLoc, TempParamLists.size() - 1,
12272                                 TempParamLists.data()).get();
12273     } else {
12274       // The "template<>" header is extraneous.
12275       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12276         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12277       isExplicitSpecialization = true;
12278     }
12279   }
12280 
12281   if (Invalid) return nullptr;
12282 
12283   bool isAllExplicitSpecializations = true;
12284   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
12285     if (TempParamLists[I]->size()) {
12286       isAllExplicitSpecializations = false;
12287       break;
12288     }
12289   }
12290 
12291   // FIXME: don't ignore attributes.
12292 
12293   // If it's explicit specializations all the way down, just forget
12294   // about the template header and build an appropriate non-templated
12295   // friend.  TODO: for source fidelity, remember the headers.
12296   if (isAllExplicitSpecializations) {
12297     if (SS.isEmpty()) {
12298       bool Owned = false;
12299       bool IsDependent = false;
12300       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
12301                       Attr, AS_public,
12302                       /*ModulePrivateLoc=*/SourceLocation(),
12303                       MultiTemplateParamsArg(), Owned, IsDependent,
12304                       /*ScopedEnumKWLoc=*/SourceLocation(),
12305                       /*ScopedEnumUsesClassTag=*/false,
12306                       /*UnderlyingType=*/TypeResult(),
12307                       /*IsTypeSpecifier=*/false);
12308     }
12309 
12310     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12311     ElaboratedTypeKeyword Keyword
12312       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12313     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
12314                                    *Name, NameLoc);
12315     if (T.isNull())
12316       return nullptr;
12317 
12318     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12319     if (isa<DependentNameType>(T)) {
12320       DependentNameTypeLoc TL =
12321           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
12322       TL.setElaboratedKeywordLoc(TagLoc);
12323       TL.setQualifierLoc(QualifierLoc);
12324       TL.setNameLoc(NameLoc);
12325     } else {
12326       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
12327       TL.setElaboratedKeywordLoc(TagLoc);
12328       TL.setQualifierLoc(QualifierLoc);
12329       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
12330     }
12331 
12332     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
12333                                             TSI, FriendLoc, TempParamLists);
12334     Friend->setAccess(AS_public);
12335     CurContext->addDecl(Friend);
12336     return Friend;
12337   }
12338 
12339   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
12340 
12341 
12342 
12343   // Handle the case of a templated-scope friend class.  e.g.
12344   //   template <class T> class A<T>::B;
12345   // FIXME: we don't support these right now.
12346   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
12347     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
12348   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12349   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
12350   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12351   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
12352   TL.setElaboratedKeywordLoc(TagLoc);
12353   TL.setQualifierLoc(SS.getWithLocInContext(Context));
12354   TL.setNameLoc(NameLoc);
12355 
12356   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
12357                                           TSI, FriendLoc, TempParamLists);
12358   Friend->setAccess(AS_public);
12359   Friend->setUnsupportedFriend(true);
12360   CurContext->addDecl(Friend);
12361   return Friend;
12362 }
12363 
12364 
12365 /// Handle a friend type declaration.  This works in tandem with
12366 /// ActOnTag.
12367 ///
12368 /// Notes on friend class templates:
12369 ///
12370 /// We generally treat friend class declarations as if they were
12371 /// declaring a class.  So, for example, the elaborated type specifier
12372 /// in a friend declaration is required to obey the restrictions of a
12373 /// class-head (i.e. no typedefs in the scope chain), template
12374 /// parameters are required to match up with simple template-ids, &c.
12375 /// However, unlike when declaring a template specialization, it's
12376 /// okay to refer to a template specialization without an empty
12377 /// template parameter declaration, e.g.
12378 ///   friend class A<T>::B<unsigned>;
12379 /// We permit this as a special case; if there are any template
12380 /// parameters present at all, require proper matching, i.e.
12381 ///   template <> template \<class T> friend class A<int>::B;
12382 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
12383                                 MultiTemplateParamsArg TempParams) {
12384   SourceLocation Loc = DS.getLocStart();
12385 
12386   assert(DS.isFriendSpecified());
12387   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12388 
12389   // Try to convert the decl specifier to a type.  This works for
12390   // friend templates because ActOnTag never produces a ClassTemplateDecl
12391   // for a TUK_Friend.
12392   Declarator TheDeclarator(DS, Declarator::MemberContext);
12393   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
12394   QualType T = TSI->getType();
12395   if (TheDeclarator.isInvalidType())
12396     return nullptr;
12397 
12398   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
12399     return nullptr;
12400 
12401   // This is definitely an error in C++98.  It's probably meant to
12402   // be forbidden in C++0x, too, but the specification is just
12403   // poorly written.
12404   //
12405   // The problem is with declarations like the following:
12406   //   template <T> friend A<T>::foo;
12407   // where deciding whether a class C is a friend or not now hinges
12408   // on whether there exists an instantiation of A that causes
12409   // 'foo' to equal C.  There are restrictions on class-heads
12410   // (which we declare (by fiat) elaborated friend declarations to
12411   // be) that makes this tractable.
12412   //
12413   // FIXME: handle "template <> friend class A<T>;", which
12414   // is possibly well-formed?  Who even knows?
12415   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
12416     Diag(Loc, diag::err_tagless_friend_type_template)
12417       << DS.getSourceRange();
12418     return nullptr;
12419   }
12420 
12421   // C++98 [class.friend]p1: A friend of a class is a function
12422   //   or class that is not a member of the class . . .
12423   // This is fixed in DR77, which just barely didn't make the C++03
12424   // deadline.  It's also a very silly restriction that seriously
12425   // affects inner classes and which nobody else seems to implement;
12426   // thus we never diagnose it, not even in -pedantic.
12427   //
12428   // But note that we could warn about it: it's always useless to
12429   // friend one of your own members (it's not, however, worthless to
12430   // friend a member of an arbitrary specialization of your template).
12431 
12432   Decl *D;
12433   if (unsigned NumTempParamLists = TempParams.size())
12434     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
12435                                    NumTempParamLists,
12436                                    TempParams.data(),
12437                                    TSI,
12438                                    DS.getFriendSpecLoc());
12439   else
12440     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
12441 
12442   if (!D)
12443     return nullptr;
12444 
12445   D->setAccess(AS_public);
12446   CurContext->addDecl(D);
12447 
12448   return D;
12449 }
12450 
12451 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
12452                                         MultiTemplateParamsArg TemplateParams) {
12453   const DeclSpec &DS = D.getDeclSpec();
12454 
12455   assert(DS.isFriendSpecified());
12456   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12457 
12458   SourceLocation Loc = D.getIdentifierLoc();
12459   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12460 
12461   // C++ [class.friend]p1
12462   //   A friend of a class is a function or class....
12463   // Note that this sees through typedefs, which is intended.
12464   // It *doesn't* see through dependent types, which is correct
12465   // according to [temp.arg.type]p3:
12466   //   If a declaration acquires a function type through a
12467   //   type dependent on a template-parameter and this causes
12468   //   a declaration that does not use the syntactic form of a
12469   //   function declarator to have a function type, the program
12470   //   is ill-formed.
12471   if (!TInfo->getType()->isFunctionType()) {
12472     Diag(Loc, diag::err_unexpected_friend);
12473 
12474     // It might be worthwhile to try to recover by creating an
12475     // appropriate declaration.
12476     return nullptr;
12477   }
12478 
12479   // C++ [namespace.memdef]p3
12480   //  - If a friend declaration in a non-local class first declares a
12481   //    class or function, the friend class or function is a member
12482   //    of the innermost enclosing namespace.
12483   //  - The name of the friend is not found by simple name lookup
12484   //    until a matching declaration is provided in that namespace
12485   //    scope (either before or after the class declaration granting
12486   //    friendship).
12487   //  - If a friend function is called, its name may be found by the
12488   //    name lookup that considers functions from namespaces and
12489   //    classes associated with the types of the function arguments.
12490   //  - When looking for a prior declaration of a class or a function
12491   //    declared as a friend, scopes outside the innermost enclosing
12492   //    namespace scope are not considered.
12493 
12494   CXXScopeSpec &SS = D.getCXXScopeSpec();
12495   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
12496   DeclarationName Name = NameInfo.getName();
12497   assert(Name);
12498 
12499   // Check for unexpanded parameter packs.
12500   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
12501       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
12502       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
12503     return nullptr;
12504 
12505   // The context we found the declaration in, or in which we should
12506   // create the declaration.
12507   DeclContext *DC;
12508   Scope *DCScope = S;
12509   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12510                         ForRedeclaration);
12511 
12512   // There are five cases here.
12513   //   - There's no scope specifier and we're in a local class. Only look
12514   //     for functions declared in the immediately-enclosing block scope.
12515   // We recover from invalid scope qualifiers as if they just weren't there.
12516   FunctionDecl *FunctionContainingLocalClass = nullptr;
12517   if ((SS.isInvalid() || !SS.isSet()) &&
12518       (FunctionContainingLocalClass =
12519            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
12520     // C++11 [class.friend]p11:
12521     //   If a friend declaration appears in a local class and the name
12522     //   specified is an unqualified name, a prior declaration is
12523     //   looked up without considering scopes that are outside the
12524     //   innermost enclosing non-class scope. For a friend function
12525     //   declaration, if there is no prior declaration, the program is
12526     //   ill-formed.
12527 
12528     // Find the innermost enclosing non-class scope. This is the block
12529     // scope containing the local class definition (or for a nested class,
12530     // the outer local class).
12531     DCScope = S->getFnParent();
12532 
12533     // Look up the function name in the scope.
12534     Previous.clear(LookupLocalFriendName);
12535     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
12536 
12537     if (!Previous.empty()) {
12538       // All possible previous declarations must have the same context:
12539       // either they were declared at block scope or they are members of
12540       // one of the enclosing local classes.
12541       DC = Previous.getRepresentativeDecl()->getDeclContext();
12542     } else {
12543       // This is ill-formed, but provide the context that we would have
12544       // declared the function in, if we were permitted to, for error recovery.
12545       DC = FunctionContainingLocalClass;
12546     }
12547     adjustContextForLocalExternDecl(DC);
12548 
12549     // C++ [class.friend]p6:
12550     //   A function can be defined in a friend declaration of a class if and
12551     //   only if the class is a non-local class (9.8), the function name is
12552     //   unqualified, and the function has namespace scope.
12553     if (D.isFunctionDefinition()) {
12554       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
12555     }
12556 
12557   //   - There's no scope specifier, in which case we just go to the
12558   //     appropriate scope and look for a function or function template
12559   //     there as appropriate.
12560   } else if (SS.isInvalid() || !SS.isSet()) {
12561     // C++11 [namespace.memdef]p3:
12562     //   If the name in a friend declaration is neither qualified nor
12563     //   a template-id and the declaration is a function or an
12564     //   elaborated-type-specifier, the lookup to determine whether
12565     //   the entity has been previously declared shall not consider
12566     //   any scopes outside the innermost enclosing namespace.
12567     bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
12568 
12569     // Find the appropriate context according to the above.
12570     DC = CurContext;
12571 
12572     // Skip class contexts.  If someone can cite chapter and verse
12573     // for this behavior, that would be nice --- it's what GCC and
12574     // EDG do, and it seems like a reasonable intent, but the spec
12575     // really only says that checks for unqualified existing
12576     // declarations should stop at the nearest enclosing namespace,
12577     // not that they should only consider the nearest enclosing
12578     // namespace.
12579     while (DC->isRecord())
12580       DC = DC->getParent();
12581 
12582     DeclContext *LookupDC = DC;
12583     while (LookupDC->isTransparentContext())
12584       LookupDC = LookupDC->getParent();
12585 
12586     while (true) {
12587       LookupQualifiedName(Previous, LookupDC);
12588 
12589       if (!Previous.empty()) {
12590         DC = LookupDC;
12591         break;
12592       }
12593 
12594       if (isTemplateId) {
12595         if (isa<TranslationUnitDecl>(LookupDC)) break;
12596       } else {
12597         if (LookupDC->isFileContext()) break;
12598       }
12599       LookupDC = LookupDC->getParent();
12600     }
12601 
12602     DCScope = getScopeForDeclContext(S, DC);
12603 
12604   //   - There's a non-dependent scope specifier, in which case we
12605   //     compute it and do a previous lookup there for a function
12606   //     or function template.
12607   } else if (!SS.getScopeRep()->isDependent()) {
12608     DC = computeDeclContext(SS);
12609     if (!DC) return nullptr;
12610 
12611     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
12612 
12613     LookupQualifiedName(Previous, DC);
12614 
12615     // Ignore things found implicitly in the wrong scope.
12616     // TODO: better diagnostics for this case.  Suggesting the right
12617     // qualified scope would be nice...
12618     LookupResult::Filter F = Previous.makeFilter();
12619     while (F.hasNext()) {
12620       NamedDecl *D = F.next();
12621       if (!DC->InEnclosingNamespaceSetOf(
12622               D->getDeclContext()->getRedeclContext()))
12623         F.erase();
12624     }
12625     F.done();
12626 
12627     if (Previous.empty()) {
12628       D.setInvalidType();
12629       Diag(Loc, diag::err_qualified_friend_not_found)
12630           << Name << TInfo->getType();
12631       return nullptr;
12632     }
12633 
12634     // C++ [class.friend]p1: A friend of a class is a function or
12635     //   class that is not a member of the class . . .
12636     if (DC->Equals(CurContext))
12637       Diag(DS.getFriendSpecLoc(),
12638            getLangOpts().CPlusPlus11 ?
12639              diag::warn_cxx98_compat_friend_is_member :
12640              diag::err_friend_is_member);
12641 
12642     if (D.isFunctionDefinition()) {
12643       // C++ [class.friend]p6:
12644       //   A function can be defined in a friend declaration of a class if and
12645       //   only if the class is a non-local class (9.8), the function name is
12646       //   unqualified, and the function has namespace scope.
12647       SemaDiagnosticBuilder DB
12648         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
12649 
12650       DB << SS.getScopeRep();
12651       if (DC->isFileContext())
12652         DB << FixItHint::CreateRemoval(SS.getRange());
12653       SS.clear();
12654     }
12655 
12656   //   - There's a scope specifier that does not match any template
12657   //     parameter lists, in which case we use some arbitrary context,
12658   //     create a method or method template, and wait for instantiation.
12659   //   - There's a scope specifier that does match some template
12660   //     parameter lists, which we don't handle right now.
12661   } else {
12662     if (D.isFunctionDefinition()) {
12663       // C++ [class.friend]p6:
12664       //   A function can be defined in a friend declaration of a class if and
12665       //   only if the class is a non-local class (9.8), the function name is
12666       //   unqualified, and the function has namespace scope.
12667       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
12668         << SS.getScopeRep();
12669     }
12670 
12671     DC = CurContext;
12672     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
12673   }
12674 
12675   if (!DC->isRecord()) {
12676     // This implies that it has to be an operator or function.
12677     if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
12678         D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
12679         D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
12680       Diag(Loc, diag::err_introducing_special_friend) <<
12681         (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
12682          D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
12683       return nullptr;
12684     }
12685   }
12686 
12687   // FIXME: This is an egregious hack to cope with cases where the scope stack
12688   // does not contain the declaration context, i.e., in an out-of-line
12689   // definition of a class.
12690   Scope FakeDCScope(S, Scope::DeclScope, Diags);
12691   if (!DCScope) {
12692     FakeDCScope.setEntity(DC);
12693     DCScope = &FakeDCScope;
12694   }
12695 
12696   bool AddToScope = true;
12697   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
12698                                           TemplateParams, AddToScope);
12699   if (!ND) return nullptr;
12700 
12701   assert(ND->getLexicalDeclContext() == CurContext);
12702 
12703   // If we performed typo correction, we might have added a scope specifier
12704   // and changed the decl context.
12705   DC = ND->getDeclContext();
12706 
12707   // Add the function declaration to the appropriate lookup tables,
12708   // adjusting the redeclarations list as necessary.  We don't
12709   // want to do this yet if the friending class is dependent.
12710   //
12711   // Also update the scope-based lookup if the target context's
12712   // lookup context is in lexical scope.
12713   if (!CurContext->isDependentContext()) {
12714     DC = DC->getRedeclContext();
12715     DC->makeDeclVisibleInContext(ND);
12716     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
12717       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
12718   }
12719 
12720   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
12721                                        D.getIdentifierLoc(), ND,
12722                                        DS.getFriendSpecLoc());
12723   FrD->setAccess(AS_public);
12724   CurContext->addDecl(FrD);
12725 
12726   if (ND->isInvalidDecl()) {
12727     FrD->setInvalidDecl();
12728   } else {
12729     if (DC->isRecord()) CheckFriendAccess(ND);
12730 
12731     FunctionDecl *FD;
12732     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12733       FD = FTD->getTemplatedDecl();
12734     else
12735       FD = cast<FunctionDecl>(ND);
12736 
12737     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12738     // default argument expression, that declaration shall be a definition
12739     // and shall be the only declaration of the function or function
12740     // template in the translation unit.
12741     if (functionDeclHasDefaultArgument(FD)) {
12742       if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12743         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12744         Diag(OldFD->getLocation(), diag::note_previous_declaration);
12745       } else if (!D.isFunctionDefinition())
12746         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12747     }
12748 
12749     // Mark templated-scope function declarations as unsupported.
12750     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
12751       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
12752         << SS.getScopeRep() << SS.getRange()
12753         << cast<CXXRecordDecl>(CurContext);
12754       FrD->setUnsupportedFriend(true);
12755     }
12756   }
12757 
12758   return ND;
12759 }
12760 
12761 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12762   AdjustDeclIfTemplate(Dcl);
12763 
12764   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
12765   if (!Fn) {
12766     Diag(DelLoc, diag::err_deleted_non_function);
12767     return;
12768   }
12769 
12770   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
12771     // Don't consider the implicit declaration we generate for explicit
12772     // specializations. FIXME: Do not generate these implicit declarations.
12773     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12774          Prev->getPreviousDecl()) &&
12775         !Prev->isDefined()) {
12776       Diag(DelLoc, diag::err_deleted_decl_not_first);
12777       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12778            Prev->isImplicit() ? diag::note_previous_implicit_declaration
12779                               : diag::note_previous_declaration);
12780     }
12781     // If the declaration wasn't the first, we delete the function anyway for
12782     // recovery.
12783     Fn = Fn->getCanonicalDecl();
12784   }
12785 
12786   // dllimport/dllexport cannot be deleted.
12787   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12788     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12789     Fn->setInvalidDecl();
12790   }
12791 
12792   if (Fn->isDeleted())
12793     return;
12794 
12795   // See if we're deleting a function which is already known to override a
12796   // non-deleted virtual function.
12797   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
12798     bool IssuedDiagnostic = false;
12799     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
12800                                         E = MD->end_overridden_methods();
12801          I != E; ++I) {
12802       if (!(*MD->begin_overridden_methods())->isDeleted()) {
12803         if (!IssuedDiagnostic) {
12804           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
12805           IssuedDiagnostic = true;
12806         }
12807         Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
12808       }
12809     }
12810   }
12811 
12812   // C++11 [basic.start.main]p3:
12813   //   A program that defines main as deleted [...] is ill-formed.
12814   if (Fn->isMain())
12815     Diag(DelLoc, diag::err_deleted_main);
12816 
12817   Fn->setDeletedAsWritten();
12818 }
12819 
12820 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
12821   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
12822 
12823   if (MD) {
12824     if (MD->getParent()->isDependentType()) {
12825       MD->setDefaulted();
12826       MD->setExplicitlyDefaulted();
12827       return;
12828     }
12829 
12830     CXXSpecialMember Member = getSpecialMember(MD);
12831     if (Member == CXXInvalid) {
12832       if (!MD->isInvalidDecl())
12833         Diag(DefaultLoc, diag::err_default_special_members);
12834       return;
12835     }
12836 
12837     MD->setDefaulted();
12838     MD->setExplicitlyDefaulted();
12839 
12840     // If this definition appears within the record, do the checking when
12841     // the record is complete.
12842     const FunctionDecl *Primary = MD;
12843     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
12844       // Find the uninstantiated declaration that actually had the '= default'
12845       // on it.
12846       Pattern->isDefined(Primary);
12847 
12848     // If the method was defaulted on its first declaration, we will have
12849     // already performed the checking in CheckCompletedCXXClass. Such a
12850     // declaration doesn't trigger an implicit definition.
12851     if (Primary == Primary->getCanonicalDecl())
12852       return;
12853 
12854     CheckExplicitlyDefaultedSpecialMember(MD);
12855 
12856     if (MD->isInvalidDecl())
12857       return;
12858 
12859     switch (Member) {
12860     case CXXDefaultConstructor:
12861       DefineImplicitDefaultConstructor(DefaultLoc,
12862                                        cast<CXXConstructorDecl>(MD));
12863       break;
12864     case CXXCopyConstructor:
12865       DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
12866       break;
12867     case CXXCopyAssignment:
12868       DefineImplicitCopyAssignment(DefaultLoc, MD);
12869       break;
12870     case CXXDestructor:
12871       DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
12872       break;
12873     case CXXMoveConstructor:
12874       DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
12875       break;
12876     case CXXMoveAssignment:
12877       DefineImplicitMoveAssignment(DefaultLoc, MD);
12878       break;
12879     case CXXInvalid:
12880       llvm_unreachable("Invalid special member.");
12881     }
12882   } else {
12883     Diag(DefaultLoc, diag::err_default_special_members);
12884   }
12885 }
12886 
12887 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
12888   for (Stmt *SubStmt : S->children()) {
12889     if (!SubStmt)
12890       continue;
12891     if (isa<ReturnStmt>(SubStmt))
12892       Self.Diag(SubStmt->getLocStart(),
12893            diag::err_return_in_constructor_handler);
12894     if (!isa<Expr>(SubStmt))
12895       SearchForReturnInStmt(Self, SubStmt);
12896   }
12897 }
12898 
12899 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12900   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12901     CXXCatchStmt *Handler = TryBlock->getHandler(I);
12902     SearchForReturnInStmt(*this, Handler);
12903   }
12904 }
12905 
12906 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
12907                                              const CXXMethodDecl *Old) {
12908   const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12909   const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12910 
12911   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12912 
12913   // If the calling conventions match, everything is fine
12914   if (NewCC == OldCC)
12915     return false;
12916 
12917   // If the calling conventions mismatch because the new function is static,
12918   // suppress the calling convention mismatch error; the error about static
12919   // function override (err_static_overrides_virtual from
12920   // Sema::CheckFunctionDeclaration) is more clear.
12921   if (New->getStorageClass() == SC_Static)
12922     return false;
12923 
12924   Diag(New->getLocation(),
12925        diag::err_conflicting_overriding_cc_attributes)
12926     << New->getDeclName() << New->getType() << Old->getType();
12927   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12928   return true;
12929 }
12930 
12931 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
12932                                              const CXXMethodDecl *Old) {
12933   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12934   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
12935 
12936   if (Context.hasSameType(NewTy, OldTy) ||
12937       NewTy->isDependentType() || OldTy->isDependentType())
12938     return false;
12939 
12940   // Check if the return types are covariant
12941   QualType NewClassTy, OldClassTy;
12942 
12943   /// Both types must be pointers or references to classes.
12944   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12945     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
12946       NewClassTy = NewPT->getPointeeType();
12947       OldClassTy = OldPT->getPointeeType();
12948     }
12949   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12950     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12951       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12952         NewClassTy = NewRT->getPointeeType();
12953         OldClassTy = OldRT->getPointeeType();
12954       }
12955     }
12956   }
12957 
12958   // The return types aren't either both pointers or references to a class type.
12959   if (NewClassTy.isNull()) {
12960     Diag(New->getLocation(),
12961          diag::err_different_return_type_for_overriding_virtual_function)
12962         << New->getDeclName() << NewTy << OldTy
12963         << New->getReturnTypeSourceRange();
12964     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12965         << Old->getReturnTypeSourceRange();
12966 
12967     return true;
12968   }
12969 
12970   // C++ [class.virtual]p6:
12971   //   If the return type of D::f differs from the return type of B::f, the
12972   //   class type in the return type of D::f shall be complete at the point of
12973   //   declaration of D::f or shall be the class type D.
12974   if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12975     if (!RT->isBeingDefined() &&
12976         RequireCompleteType(New->getLocation(), NewClassTy,
12977                             diag::err_covariant_return_incomplete,
12978                             New->getDeclName()))
12979     return true;
12980   }
12981 
12982   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
12983     // Check if the new class derives from the old class.
12984     if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12985       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
12986           << New->getDeclName() << NewTy << OldTy
12987           << New->getReturnTypeSourceRange();
12988       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12989           << Old->getReturnTypeSourceRange();
12990       return true;
12991     }
12992 
12993     // Check if we the conversion from derived to base is valid.
12994     if (CheckDerivedToBaseConversion(
12995             NewClassTy, OldClassTy,
12996             diag::err_covariant_return_inaccessible_base,
12997             diag::err_covariant_return_ambiguous_derived_to_base_conv,
12998             New->getLocation(), New->getReturnTypeSourceRange(),
12999             New->getDeclName(), nullptr)) {
13000       // FIXME: this note won't trigger for delayed access control
13001       // diagnostics, and it's impossible to get an undelayed error
13002       // here from access control during the original parse because
13003       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
13004       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13005           << Old->getReturnTypeSourceRange();
13006       return true;
13007     }
13008   }
13009 
13010   // The qualifiers of the return types must be the same.
13011   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
13012     Diag(New->getLocation(),
13013          diag::err_covariant_return_type_different_qualifications)
13014         << New->getDeclName() << NewTy << OldTy
13015         << New->getReturnTypeSourceRange();
13016     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13017         << Old->getReturnTypeSourceRange();
13018     return true;
13019   };
13020 
13021 
13022   // The new class type must have the same or less qualifiers as the old type.
13023   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
13024     Diag(New->getLocation(),
13025          diag::err_covariant_return_type_class_type_more_qualified)
13026         << New->getDeclName() << NewTy << OldTy
13027         << New->getReturnTypeSourceRange();
13028     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13029         << Old->getReturnTypeSourceRange();
13030     return true;
13031   };
13032 
13033   return false;
13034 }
13035 
13036 /// \brief Mark the given method pure.
13037 ///
13038 /// \param Method the method to be marked pure.
13039 ///
13040 /// \param InitRange the source range that covers the "0" initializer.
13041 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
13042   SourceLocation EndLoc = InitRange.getEnd();
13043   if (EndLoc.isValid())
13044     Method->setRangeEnd(EndLoc);
13045 
13046   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
13047     Method->setPure();
13048     return false;
13049   }
13050 
13051   if (!Method->isInvalidDecl())
13052     Diag(Method->getLocation(), diag::err_non_virtual_pure)
13053       << Method->getDeclName() << InitRange;
13054   return true;
13055 }
13056 
13057 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
13058   if (D->getFriendObjectKind())
13059     Diag(D->getLocation(), diag::err_pure_friend);
13060   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
13061     CheckPureMethod(M, ZeroLoc);
13062   else
13063     Diag(D->getLocation(), diag::err_illegal_initializer);
13064 }
13065 
13066 /// \brief Determine whether the given declaration is a static data member.
13067 static bool isStaticDataMember(const Decl *D) {
13068   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
13069     return Var->isStaticDataMember();
13070 
13071   return false;
13072 }
13073 
13074 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
13075 /// an initializer for the out-of-line declaration 'Dcl'.  The scope
13076 /// is a fresh scope pushed for just this purpose.
13077 ///
13078 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
13079 /// static data member of class X, names should be looked up in the scope of
13080 /// class X.
13081 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
13082   // If there is no declaration, there was an error parsing it.
13083   if (!D || D->isInvalidDecl())
13084     return;
13085 
13086   // We will always have a nested name specifier here, but this declaration
13087   // might not be out of line if the specifier names the current namespace:
13088   //   extern int n;
13089   //   int ::n = 0;
13090   if (D->isOutOfLine())
13091     EnterDeclaratorContext(S, D->getDeclContext());
13092 
13093   // If we are parsing the initializer for a static data member, push a
13094   // new expression evaluation context that is associated with this static
13095   // data member.
13096   if (isStaticDataMember(D))
13097     PushExpressionEvaluationContext(PotentiallyEvaluated, D);
13098 }
13099 
13100 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
13101 /// initializer for the out-of-line declaration 'D'.
13102 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
13103   // If there is no declaration, there was an error parsing it.
13104   if (!D || D->isInvalidDecl())
13105     return;
13106 
13107   if (isStaticDataMember(D))
13108     PopExpressionEvaluationContext();
13109 
13110   if (D->isOutOfLine())
13111     ExitDeclaratorContext(S);
13112 }
13113 
13114 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
13115 /// C++ if/switch/while/for statement.
13116 /// e.g: "if (int x = f()) {...}"
13117 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
13118   // C++ 6.4p2:
13119   // The declarator shall not specify a function or an array.
13120   // The type-specifier-seq shall not contain typedef and shall not declare a
13121   // new class or enumeration.
13122   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
13123          "Parser allowed 'typedef' as storage class of condition decl.");
13124 
13125   Decl *Dcl = ActOnDeclarator(S, D);
13126   if (!Dcl)
13127     return true;
13128 
13129   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
13130     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
13131       << D.getSourceRange();
13132     return true;
13133   }
13134 
13135   return Dcl;
13136 }
13137 
13138 void Sema::LoadExternalVTableUses() {
13139   if (!ExternalSource)
13140     return;
13141 
13142   SmallVector<ExternalVTableUse, 4> VTables;
13143   ExternalSource->ReadUsedVTables(VTables);
13144   SmallVector<VTableUse, 4> NewUses;
13145   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
13146     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
13147       = VTablesUsed.find(VTables[I].Record);
13148     // Even if a definition wasn't required before, it may be required now.
13149     if (Pos != VTablesUsed.end()) {
13150       if (!Pos->second && VTables[I].DefinitionRequired)
13151         Pos->second = true;
13152       continue;
13153     }
13154 
13155     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
13156     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
13157   }
13158 
13159   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
13160 }
13161 
13162 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
13163                           bool DefinitionRequired) {
13164   // Ignore any vtable uses in unevaluated operands or for classes that do
13165   // not have a vtable.
13166   if (!Class->isDynamicClass() || Class->isDependentContext() ||
13167       CurContext->isDependentContext() || isUnevaluatedContext())
13168     return;
13169 
13170   // Try to insert this class into the map.
13171   LoadExternalVTableUses();
13172   Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13173   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
13174     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
13175   if (!Pos.second) {
13176     // If we already had an entry, check to see if we are promoting this vtable
13177     // to require a definition. If so, we need to reappend to the VTableUses
13178     // list, since we may have already processed the first entry.
13179     if (DefinitionRequired && !Pos.first->second) {
13180       Pos.first->second = true;
13181     } else {
13182       // Otherwise, we can early exit.
13183       return;
13184     }
13185   } else {
13186     // The Microsoft ABI requires that we perform the destructor body
13187     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
13188     // the deleting destructor is emitted with the vtable, not with the
13189     // destructor definition as in the Itanium ABI.
13190     // If it has a definition, we do the check at that point instead.
13191     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13192         Class->hasUserDeclaredDestructor() &&
13193         !Class->getDestructor()->isDefined() &&
13194         !Class->getDestructor()->isDeleted()) {
13195       CXXDestructorDecl *DD = Class->getDestructor();
13196       ContextRAII SavedContext(*this, DD);
13197       CheckDestructor(DD);
13198     }
13199   }
13200 
13201   // Local classes need to have their virtual members marked
13202   // immediately. For all other classes, we mark their virtual members
13203   // at the end of the translation unit.
13204   if (Class->isLocalClass())
13205     MarkVirtualMembersReferenced(Loc, Class);
13206   else
13207     VTableUses.push_back(std::make_pair(Class, Loc));
13208 }
13209 
13210 bool Sema::DefineUsedVTables() {
13211   LoadExternalVTableUses();
13212   if (VTableUses.empty())
13213     return false;
13214 
13215   // Note: The VTableUses vector could grow as a result of marking
13216   // the members of a class as "used", so we check the size each
13217   // time through the loop and prefer indices (which are stable) to
13218   // iterators (which are not).
13219   bool DefinedAnything = false;
13220   for (unsigned I = 0; I != VTableUses.size(); ++I) {
13221     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
13222     if (!Class)
13223       continue;
13224 
13225     SourceLocation Loc = VTableUses[I].second;
13226 
13227     bool DefineVTable = true;
13228 
13229     // If this class has a key function, but that key function is
13230     // defined in another translation unit, we don't need to emit the
13231     // vtable even though we're using it.
13232     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
13233     if (KeyFunction && !KeyFunction->hasBody()) {
13234       // The key function is in another translation unit.
13235       DefineVTable = false;
13236       TemplateSpecializationKind TSK =
13237           KeyFunction->getTemplateSpecializationKind();
13238       assert(TSK != TSK_ExplicitInstantiationDefinition &&
13239              TSK != TSK_ImplicitInstantiation &&
13240              "Instantiations don't have key functions");
13241       (void)TSK;
13242     } else if (!KeyFunction) {
13243       // If we have a class with no key function that is the subject
13244       // of an explicit instantiation declaration, suppress the
13245       // vtable; it will live with the explicit instantiation
13246       // definition.
13247       bool IsExplicitInstantiationDeclaration
13248         = Class->getTemplateSpecializationKind()
13249                                       == TSK_ExplicitInstantiationDeclaration;
13250       for (auto R : Class->redecls()) {
13251         TemplateSpecializationKind TSK
13252           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
13253         if (TSK == TSK_ExplicitInstantiationDeclaration)
13254           IsExplicitInstantiationDeclaration = true;
13255         else if (TSK == TSK_ExplicitInstantiationDefinition) {
13256           IsExplicitInstantiationDeclaration = false;
13257           break;
13258         }
13259       }
13260 
13261       if (IsExplicitInstantiationDeclaration)
13262         DefineVTable = false;
13263     }
13264 
13265     // The exception specifications for all virtual members may be needed even
13266     // if we are not providing an authoritative form of the vtable in this TU.
13267     // We may choose to emit it available_externally anyway.
13268     if (!DefineVTable) {
13269       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
13270       continue;
13271     }
13272 
13273     // Mark all of the virtual members of this class as referenced, so
13274     // that we can build a vtable. Then, tell the AST consumer that a
13275     // vtable for this class is required.
13276     DefinedAnything = true;
13277     MarkVirtualMembersReferenced(Loc, Class);
13278     CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13279     if (VTablesUsed[Canonical])
13280       Consumer.HandleVTable(Class);
13281 
13282     // Optionally warn if we're emitting a weak vtable.
13283     if (Class->isExternallyVisible() &&
13284         Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
13285       const FunctionDecl *KeyFunctionDef = nullptr;
13286       if (!KeyFunction ||
13287           (KeyFunction->hasBody(KeyFunctionDef) &&
13288            KeyFunctionDef->isInlined()))
13289         Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
13290              TSK_ExplicitInstantiationDefinition
13291              ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
13292           << Class;
13293     }
13294   }
13295   VTableUses.clear();
13296 
13297   return DefinedAnything;
13298 }
13299 
13300 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
13301                                                  const CXXRecordDecl *RD) {
13302   for (const auto *I : RD->methods())
13303     if (I->isVirtual() && !I->isPure())
13304       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
13305 }
13306 
13307 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
13308                                         const CXXRecordDecl *RD) {
13309   // Mark all functions which will appear in RD's vtable as used.
13310   CXXFinalOverriderMap FinalOverriders;
13311   RD->getFinalOverriders(FinalOverriders);
13312   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
13313                                             E = FinalOverriders.end();
13314        I != E; ++I) {
13315     for (OverridingMethods::const_iterator OI = I->second.begin(),
13316                                            OE = I->second.end();
13317          OI != OE; ++OI) {
13318       assert(OI->second.size() > 0 && "no final overrider");
13319       CXXMethodDecl *Overrider = OI->second.front().Method;
13320 
13321       // C++ [basic.def.odr]p2:
13322       //   [...] A virtual member function is used if it is not pure. [...]
13323       if (!Overrider->isPure())
13324         MarkFunctionReferenced(Loc, Overrider);
13325     }
13326   }
13327 
13328   // Only classes that have virtual bases need a VTT.
13329   if (RD->getNumVBases() == 0)
13330     return;
13331 
13332   for (const auto &I : RD->bases()) {
13333     const CXXRecordDecl *Base =
13334         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
13335     if (Base->getNumVBases() == 0)
13336       continue;
13337     MarkVirtualMembersReferenced(Loc, Base);
13338   }
13339 }
13340 
13341 /// SetIvarInitializers - This routine builds initialization ASTs for the
13342 /// Objective-C implementation whose ivars need be initialized.
13343 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
13344   if (!getLangOpts().CPlusPlus)
13345     return;
13346   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
13347     SmallVector<ObjCIvarDecl*, 8> ivars;
13348     CollectIvarsToConstructOrDestruct(OID, ivars);
13349     if (ivars.empty())
13350       return;
13351     SmallVector<CXXCtorInitializer*, 32> AllToInit;
13352     for (unsigned i = 0; i < ivars.size(); i++) {
13353       FieldDecl *Field = ivars[i];
13354       if (Field->isInvalidDecl())
13355         continue;
13356 
13357       CXXCtorInitializer *Member;
13358       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
13359       InitializationKind InitKind =
13360         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
13361 
13362       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
13363       ExprResult MemberInit =
13364         InitSeq.Perform(*this, InitEntity, InitKind, None);
13365       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
13366       // Note, MemberInit could actually come back empty if no initialization
13367       // is required (e.g., because it would call a trivial default constructor)
13368       if (!MemberInit.get() || MemberInit.isInvalid())
13369         continue;
13370 
13371       Member =
13372         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
13373                                          SourceLocation(),
13374                                          MemberInit.getAs<Expr>(),
13375                                          SourceLocation());
13376       AllToInit.push_back(Member);
13377 
13378       // Be sure that the destructor is accessible and is marked as referenced.
13379       if (const RecordType *RecordTy =
13380               Context.getBaseElementType(Field->getType())
13381                   ->getAs<RecordType>()) {
13382         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
13383         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
13384           MarkFunctionReferenced(Field->getLocation(), Destructor);
13385           CheckDestructorAccess(Field->getLocation(), Destructor,
13386                             PDiag(diag::err_access_dtor_ivar)
13387                               << Context.getBaseElementType(Field->getType()));
13388         }
13389       }
13390     }
13391     ObjCImplementation->setIvarInitializers(Context,
13392                                             AllToInit.data(), AllToInit.size());
13393   }
13394 }
13395 
13396 static
13397 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
13398                            llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
13399                            llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
13400                            llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
13401                            Sema &S) {
13402   if (Ctor->isInvalidDecl())
13403     return;
13404 
13405   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
13406 
13407   // Target may not be determinable yet, for instance if this is a dependent
13408   // call in an uninstantiated template.
13409   if (Target) {
13410     const FunctionDecl *FNTarget = nullptr;
13411     (void)Target->hasBody(FNTarget);
13412     Target = const_cast<CXXConstructorDecl*>(
13413       cast_or_null<CXXConstructorDecl>(FNTarget));
13414   }
13415 
13416   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
13417                      // Avoid dereferencing a null pointer here.
13418                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
13419 
13420   if (!Current.insert(Canonical).second)
13421     return;
13422 
13423   // We know that beyond here, we aren't chaining into a cycle.
13424   if (!Target || !Target->isDelegatingConstructor() ||
13425       Target->isInvalidDecl() || Valid.count(TCanonical)) {
13426     Valid.insert(Current.begin(), Current.end());
13427     Current.clear();
13428   // We've hit a cycle.
13429   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
13430              Current.count(TCanonical)) {
13431     // If we haven't diagnosed this cycle yet, do so now.
13432     if (!Invalid.count(TCanonical)) {
13433       S.Diag((*Ctor->init_begin())->getSourceLocation(),
13434              diag::warn_delegating_ctor_cycle)
13435         << Ctor;
13436 
13437       // Don't add a note for a function delegating directly to itself.
13438       if (TCanonical != Canonical)
13439         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
13440 
13441       CXXConstructorDecl *C = Target;
13442       while (C->getCanonicalDecl() != Canonical) {
13443         const FunctionDecl *FNTarget = nullptr;
13444         (void)C->getTargetConstructor()->hasBody(FNTarget);
13445         assert(FNTarget && "Ctor cycle through bodiless function");
13446 
13447         C = const_cast<CXXConstructorDecl*>(
13448           cast<CXXConstructorDecl>(FNTarget));
13449         S.Diag(C->getLocation(), diag::note_which_delegates_to);
13450       }
13451     }
13452 
13453     Invalid.insert(Current.begin(), Current.end());
13454     Current.clear();
13455   } else {
13456     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
13457   }
13458 }
13459 
13460 
13461 void Sema::CheckDelegatingCtorCycles() {
13462   llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
13463 
13464   for (DelegatingCtorDeclsType::iterator
13465          I = DelegatingCtorDecls.begin(ExternalSource),
13466          E = DelegatingCtorDecls.end();
13467        I != E; ++I)
13468     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
13469 
13470   for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
13471                                                          CE = Invalid.end();
13472        CI != CE; ++CI)
13473     (*CI)->setInvalidDecl();
13474 }
13475 
13476 namespace {
13477   /// \brief AST visitor that finds references to the 'this' expression.
13478   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
13479     Sema &S;
13480 
13481   public:
13482     explicit FindCXXThisExpr(Sema &S) : S(S) { }
13483 
13484     bool VisitCXXThisExpr(CXXThisExpr *E) {
13485       S.Diag(E->getLocation(), diag::err_this_static_member_func)
13486         << E->isImplicit();
13487       return false;
13488     }
13489   };
13490 }
13491 
13492 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
13493   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13494   if (!TSInfo)
13495     return false;
13496 
13497   TypeLoc TL = TSInfo->getTypeLoc();
13498   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
13499   if (!ProtoTL)
13500     return false;
13501 
13502   // C++11 [expr.prim.general]p3:
13503   //   [The expression this] shall not appear before the optional
13504   //   cv-qualifier-seq and it shall not appear within the declaration of a
13505   //   static member function (although its type and value category are defined
13506   //   within a static member function as they are within a non-static member
13507   //   function). [ Note: this is because declaration matching does not occur
13508   //  until the complete declarator is known. - end note ]
13509   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
13510   FindCXXThisExpr Finder(*this);
13511 
13512   // If the return type came after the cv-qualifier-seq, check it now.
13513   if (Proto->hasTrailingReturn() &&
13514       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
13515     return true;
13516 
13517   // Check the exception specification.
13518   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
13519     return true;
13520 
13521   return checkThisInStaticMemberFunctionAttributes(Method);
13522 }
13523 
13524 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
13525   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13526   if (!TSInfo)
13527     return false;
13528 
13529   TypeLoc TL = TSInfo->getTypeLoc();
13530   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
13531   if (!ProtoTL)
13532     return false;
13533 
13534   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
13535   FindCXXThisExpr Finder(*this);
13536 
13537   switch (Proto->getExceptionSpecType()) {
13538   case EST_Unparsed:
13539   case EST_Uninstantiated:
13540   case EST_Unevaluated:
13541   case EST_BasicNoexcept:
13542   case EST_DynamicNone:
13543   case EST_MSAny:
13544   case EST_None:
13545     break;
13546 
13547   case EST_ComputedNoexcept:
13548     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
13549       return true;
13550 
13551   case EST_Dynamic:
13552     for (const auto &E : Proto->exceptions()) {
13553       if (!Finder.TraverseType(E))
13554         return true;
13555     }
13556     break;
13557   }
13558 
13559   return false;
13560 }
13561 
13562 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
13563   FindCXXThisExpr Finder(*this);
13564 
13565   // Check attributes.
13566   for (const auto *A : Method->attrs()) {
13567     // FIXME: This should be emitted by tblgen.
13568     Expr *Arg = nullptr;
13569     ArrayRef<Expr *> Args;
13570     if (const auto *G = dyn_cast<GuardedByAttr>(A))
13571       Arg = G->getArg();
13572     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
13573       Arg = G->getArg();
13574     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
13575       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
13576     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
13577       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
13578     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
13579       Arg = ETLF->getSuccessValue();
13580       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
13581     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
13582       Arg = STLF->getSuccessValue();
13583       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
13584     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
13585       Arg = LR->getArg();
13586     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
13587       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
13588     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
13589       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
13590     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
13591       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
13592     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
13593       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
13594     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
13595       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
13596 
13597     if (Arg && !Finder.TraverseStmt(Arg))
13598       return true;
13599 
13600     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
13601       if (!Finder.TraverseStmt(Args[I]))
13602         return true;
13603     }
13604   }
13605 
13606   return false;
13607 }
13608 
13609 void Sema::checkExceptionSpecification(
13610     bool IsTopLevel, ExceptionSpecificationType EST,
13611     ArrayRef<ParsedType> DynamicExceptions,
13612     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
13613     SmallVectorImpl<QualType> &Exceptions,
13614     FunctionProtoType::ExceptionSpecInfo &ESI) {
13615   Exceptions.clear();
13616   ESI.Type = EST;
13617   if (EST == EST_Dynamic) {
13618     Exceptions.reserve(DynamicExceptions.size());
13619     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
13620       // FIXME: Preserve type source info.
13621       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
13622 
13623       if (IsTopLevel) {
13624         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13625         collectUnexpandedParameterPacks(ET, Unexpanded);
13626         if (!Unexpanded.empty()) {
13627           DiagnoseUnexpandedParameterPacks(
13628               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
13629               Unexpanded);
13630           continue;
13631         }
13632       }
13633 
13634       // Check that the type is valid for an exception spec, and
13635       // drop it if not.
13636       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
13637         Exceptions.push_back(ET);
13638     }
13639     ESI.Exceptions = Exceptions;
13640     return;
13641   }
13642 
13643   if (EST == EST_ComputedNoexcept) {
13644     // If an error occurred, there's no expression here.
13645     if (NoexceptExpr) {
13646       assert((NoexceptExpr->isTypeDependent() ||
13647               NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
13648               Context.BoolTy) &&
13649              "Parser should have made sure that the expression is boolean");
13650       if (IsTopLevel && NoexceptExpr &&
13651           DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
13652         ESI.Type = EST_BasicNoexcept;
13653         return;
13654       }
13655 
13656       if (!NoexceptExpr->isValueDependent())
13657         NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
13658                          diag::err_noexcept_needs_constant_expression,
13659                          /*AllowFold*/ false).get();
13660       ESI.NoexceptExpr = NoexceptExpr;
13661     }
13662     return;
13663   }
13664 }
13665 
13666 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
13667              ExceptionSpecificationType EST,
13668              SourceRange SpecificationRange,
13669              ArrayRef<ParsedType> DynamicExceptions,
13670              ArrayRef<SourceRange> DynamicExceptionRanges,
13671              Expr *NoexceptExpr) {
13672   if (!MethodD)
13673     return;
13674 
13675   // Dig out the method we're referring to.
13676   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
13677     MethodD = FunTmpl->getTemplatedDecl();
13678 
13679   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
13680   if (!Method)
13681     return;
13682 
13683   // Check the exception specification.
13684   llvm::SmallVector<QualType, 4> Exceptions;
13685   FunctionProtoType::ExceptionSpecInfo ESI;
13686   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
13687                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
13688                               ESI);
13689 
13690   // Update the exception specification on the function type.
13691   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
13692 
13693   if (Method->isStatic())
13694     checkThisInStaticMemberFunctionExceptionSpec(Method);
13695 
13696   if (Method->isVirtual()) {
13697     // Check overrides, which we previously had to delay.
13698     for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
13699                                      OEnd = Method->end_overridden_methods();
13700          O != OEnd; ++O)
13701       CheckOverridingFunctionExceptionSpec(Method, *O);
13702   }
13703 }
13704 
13705 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
13706 ///
13707 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
13708                                        SourceLocation DeclStart,
13709                                        Declarator &D, Expr *BitWidth,
13710                                        InClassInitStyle InitStyle,
13711                                        AccessSpecifier AS,
13712                                        AttributeList *MSPropertyAttr) {
13713   IdentifierInfo *II = D.getIdentifier();
13714   if (!II) {
13715     Diag(DeclStart, diag::err_anonymous_property);
13716     return nullptr;
13717   }
13718   SourceLocation Loc = D.getIdentifierLoc();
13719 
13720   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13721   QualType T = TInfo->getType();
13722   if (getLangOpts().CPlusPlus) {
13723     CheckExtraCXXDefaultArguments(D);
13724 
13725     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13726                                         UPPC_DataMemberType)) {
13727       D.setInvalidType();
13728       T = Context.IntTy;
13729       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13730     }
13731   }
13732 
13733   DiagnoseFunctionSpecifiers(D.getDeclSpec());
13734 
13735   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13736     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13737          diag::err_invalid_thread)
13738       << DeclSpec::getSpecifierName(TSCS);
13739 
13740   // Check to see if this name was declared as a member previously
13741   NamedDecl *PrevDecl = nullptr;
13742   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13743   LookupName(Previous, S);
13744   switch (Previous.getResultKind()) {
13745   case LookupResult::Found:
13746   case LookupResult::FoundUnresolvedValue:
13747     PrevDecl = Previous.getAsSingle<NamedDecl>();
13748     break;
13749 
13750   case LookupResult::FoundOverloaded:
13751     PrevDecl = Previous.getRepresentativeDecl();
13752     break;
13753 
13754   case LookupResult::NotFound:
13755   case LookupResult::NotFoundInCurrentInstantiation:
13756   case LookupResult::Ambiguous:
13757     break;
13758   }
13759 
13760   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13761     // Maybe we will complain about the shadowed template parameter.
13762     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13763     // Just pretend that we didn't see the previous declaration.
13764     PrevDecl = nullptr;
13765   }
13766 
13767   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13768     PrevDecl = nullptr;
13769 
13770   SourceLocation TSSL = D.getLocStart();
13771   const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
13772   MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13773       Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
13774   ProcessDeclAttributes(TUScope, NewPD, D);
13775   NewPD->setAccess(AS);
13776 
13777   if (NewPD->isInvalidDecl())
13778     Record->setInvalidDecl();
13779 
13780   if (D.getDeclSpec().isModulePrivateSpecified())
13781     NewPD->setModulePrivate();
13782 
13783   if (NewPD->isInvalidDecl() && PrevDecl) {
13784     // Don't introduce NewFD into scope; there's already something
13785     // with the same name in the same scope.
13786   } else if (II) {
13787     PushOnScopeChains(NewPD, S);
13788   } else
13789     Record->addDecl(NewPD);
13790 
13791   return NewPD;
13792 }
13793