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       if (!OK)
1234         return false;
1235     } else 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,
1557                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
1558  if (Bases.empty())
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 < Bases.size(); ++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 (Bases.size() > 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.data(), 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,
1658                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
1659   if (!ClassDecl || Bases.empty())
1660     return;
1661 
1662   AdjustDeclIfTemplate(ClassDecl);
1663   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
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(SourceLocation Loc, 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: In a modules build, do we need the entire path to be visible for us
1686   // to be able to use the inheritance relationship?
1687   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
1688     return false;
1689 
1690   return DerivedRD->isDerivedFrom(BaseRD);
1691 }
1692 
1693 /// \brief Determine whether the type \p Derived is a C++ class that is
1694 /// derived from the type \p Base.
1695 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
1696                          CXXBasePaths &Paths) {
1697   if (!getLangOpts().CPlusPlus)
1698     return false;
1699 
1700   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1701   if (!DerivedRD)
1702     return false;
1703 
1704   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1705   if (!BaseRD)
1706     return false;
1707 
1708   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
1709     return false;
1710 
1711   return DerivedRD->isDerivedFrom(BaseRD, Paths);
1712 }
1713 
1714 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1715                               CXXCastPath &BasePathArray) {
1716   assert(BasePathArray.empty() && "Base path array must be empty!");
1717   assert(Paths.isRecordingPaths() && "Must record paths!");
1718 
1719   const CXXBasePath &Path = Paths.front();
1720 
1721   // We first go backward and check if we have a virtual base.
1722   // FIXME: It would be better if CXXBasePath had the base specifier for
1723   // the nearest virtual base.
1724   unsigned Start = 0;
1725   for (unsigned I = Path.size(); I != 0; --I) {
1726     if (Path[I - 1].Base->isVirtual()) {
1727       Start = I - 1;
1728       break;
1729     }
1730   }
1731 
1732   // Now add all bases.
1733   for (unsigned I = Start, E = Path.size(); I != E; ++I)
1734     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1735 }
1736 
1737 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1738 /// conversion (where Derived and Base are class types) is
1739 /// well-formed, meaning that the conversion is unambiguous (and
1740 /// that all of the base classes are accessible). Returns true
1741 /// and emits a diagnostic if the code is ill-formed, returns false
1742 /// otherwise. Loc is the location where this routine should point to
1743 /// if there is an error, and Range is the source range to highlight
1744 /// if there is an error.
1745 ///
1746 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
1747 /// diagnostic for the respective type of error will be suppressed, but the
1748 /// check for ill-formed code will still be performed.
1749 bool
1750 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1751                                    unsigned InaccessibleBaseID,
1752                                    unsigned AmbigiousBaseConvID,
1753                                    SourceLocation Loc, SourceRange Range,
1754                                    DeclarationName Name,
1755                                    CXXCastPath *BasePath,
1756                                    bool IgnoreAccess) {
1757   // First, determine whether the path from Derived to Base is
1758   // ambiguous. This is slightly more expensive than checking whether
1759   // the Derived to Base conversion exists, because here we need to
1760   // explore multiple paths to determine if there is an ambiguity.
1761   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1762                      /*DetectVirtual=*/false);
1763   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
1764   assert(DerivationOkay &&
1765          "Can only be used with a derived-to-base conversion");
1766   (void)DerivationOkay;
1767 
1768   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1769     if (!IgnoreAccess) {
1770       // Check that the base class can be accessed.
1771       switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1772                                    InaccessibleBaseID)) {
1773         case AR_inaccessible:
1774           return true;
1775         case AR_accessible:
1776         case AR_dependent:
1777         case AR_delayed:
1778           break;
1779       }
1780     }
1781 
1782     // Build a base path if necessary.
1783     if (BasePath)
1784       BuildBasePathArray(Paths, *BasePath);
1785     return false;
1786   }
1787 
1788   if (AmbigiousBaseConvID) {
1789     // We know that the derived-to-base conversion is ambiguous, and
1790     // we're going to produce a diagnostic. Perform the derived-to-base
1791     // search just one more time to compute all of the possible paths so
1792     // that we can print them out. This is more expensive than any of
1793     // the previous derived-to-base checks we've done, but at this point
1794     // performance isn't as much of an issue.
1795     Paths.clear();
1796     Paths.setRecordingPaths(true);
1797     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
1798     assert(StillOkay && "Can only be used with a derived-to-base conversion");
1799     (void)StillOkay;
1800 
1801     // Build up a textual representation of the ambiguous paths, e.g.,
1802     // D -> B -> A, that will be used to illustrate the ambiguous
1803     // conversions in the diagnostic. We only print one of the paths
1804     // to each base class subobject.
1805     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1806 
1807     Diag(Loc, AmbigiousBaseConvID)
1808     << Derived << Base << PathDisplayStr << Range << Name;
1809   }
1810   return true;
1811 }
1812 
1813 bool
1814 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1815                                    SourceLocation Loc, SourceRange Range,
1816                                    CXXCastPath *BasePath,
1817                                    bool IgnoreAccess) {
1818   return CheckDerivedToBaseConversion(
1819       Derived, Base, diag::err_upcast_to_inaccessible_base,
1820       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
1821       BasePath, IgnoreAccess);
1822 }
1823 
1824 
1825 /// @brief Builds a string representing ambiguous paths from a
1826 /// specific derived class to different subobjects of the same base
1827 /// class.
1828 ///
1829 /// This function builds a string that can be used in error messages
1830 /// to show the different paths that one can take through the
1831 /// inheritance hierarchy to go from the derived class to different
1832 /// subobjects of a base class. The result looks something like this:
1833 /// @code
1834 /// struct D -> struct B -> struct A
1835 /// struct D -> struct C -> struct A
1836 /// @endcode
1837 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1838   std::string PathDisplayStr;
1839   std::set<unsigned> DisplayedPaths;
1840   for (CXXBasePaths::paths_iterator Path = Paths.begin();
1841        Path != Paths.end(); ++Path) {
1842     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1843       // We haven't displayed a path to this particular base
1844       // class subobject yet.
1845       PathDisplayStr += "\n    ";
1846       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1847       for (CXXBasePath::const_iterator Element = Path->begin();
1848            Element != Path->end(); ++Element)
1849         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1850     }
1851   }
1852 
1853   return PathDisplayStr;
1854 }
1855 
1856 //===----------------------------------------------------------------------===//
1857 // C++ class member Handling
1858 //===----------------------------------------------------------------------===//
1859 
1860 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1861 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1862                                 SourceLocation ASLoc,
1863                                 SourceLocation ColonLoc,
1864                                 AttributeList *Attrs) {
1865   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1866   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1867                                                   ASLoc, ColonLoc);
1868   CurContext->addHiddenDecl(ASDecl);
1869   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1870 }
1871 
1872 /// CheckOverrideControl - Check C++11 override control semantics.
1873 void Sema::CheckOverrideControl(NamedDecl *D) {
1874   if (D->isInvalidDecl())
1875     return;
1876 
1877   // We only care about "override" and "final" declarations.
1878   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1879     return;
1880 
1881   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1882 
1883   // We can't check dependent instance methods.
1884   if (MD && MD->isInstance() &&
1885       (MD->getParent()->hasAnyDependentBases() ||
1886        MD->getType()->isDependentType()))
1887     return;
1888 
1889   if (MD && !MD->isVirtual()) {
1890     // If we have a non-virtual method, check if if hides a virtual method.
1891     // (In that case, it's most likely the method has the wrong type.)
1892     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1893     FindHiddenVirtualMethods(MD, OverloadedMethods);
1894 
1895     if (!OverloadedMethods.empty()) {
1896       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1897         Diag(OA->getLocation(),
1898              diag::override_keyword_hides_virtual_member_function)
1899           << "override" << (OverloadedMethods.size() > 1);
1900       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1901         Diag(FA->getLocation(),
1902              diag::override_keyword_hides_virtual_member_function)
1903           << (FA->isSpelledAsSealed() ? "sealed" : "final")
1904           << (OverloadedMethods.size() > 1);
1905       }
1906       NoteHiddenVirtualMethods(MD, OverloadedMethods);
1907       MD->setInvalidDecl();
1908       return;
1909     }
1910     // Fall through into the general case diagnostic.
1911     // FIXME: We might want to attempt typo correction here.
1912   }
1913 
1914   if (!MD || !MD->isVirtual()) {
1915     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1916       Diag(OA->getLocation(),
1917            diag::override_keyword_only_allowed_on_virtual_member_functions)
1918         << "override" << FixItHint::CreateRemoval(OA->getLocation());
1919       D->dropAttr<OverrideAttr>();
1920     }
1921     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1922       Diag(FA->getLocation(),
1923            diag::override_keyword_only_allowed_on_virtual_member_functions)
1924         << (FA->isSpelledAsSealed() ? "sealed" : "final")
1925         << FixItHint::CreateRemoval(FA->getLocation());
1926       D->dropAttr<FinalAttr>();
1927     }
1928     return;
1929   }
1930 
1931   // C++11 [class.virtual]p5:
1932   //   If a function is marked with the virt-specifier override and
1933   //   does not override a member function of a base class, the program is
1934   //   ill-formed.
1935   bool HasOverriddenMethods =
1936     MD->begin_overridden_methods() != MD->end_overridden_methods();
1937   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1938     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1939       << MD->getDeclName();
1940 }
1941 
1942 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
1943   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
1944     return;
1945   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1946   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
1947       isa<CXXDestructorDecl>(MD))
1948     return;
1949 
1950   SourceLocation Loc = MD->getLocation();
1951   SourceLocation SpellingLoc = Loc;
1952   if (getSourceManager().isMacroArgExpansion(Loc))
1953     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
1954   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
1955   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
1956       return;
1957 
1958   if (MD->size_overridden_methods() > 0) {
1959     Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
1960       << MD->getDeclName();
1961     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
1962     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
1963   }
1964 }
1965 
1966 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1967 /// function overrides a virtual member function marked 'final', according to
1968 /// C++11 [class.virtual]p4.
1969 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1970                                                   const CXXMethodDecl *Old) {
1971   FinalAttr *FA = Old->getAttr<FinalAttr>();
1972   if (!FA)
1973     return false;
1974 
1975   Diag(New->getLocation(), diag::err_final_function_overridden)
1976     << New->getDeclName()
1977     << FA->isSpelledAsSealed();
1978   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1979   return true;
1980 }
1981 
1982 static bool InitializationHasSideEffects(const FieldDecl &FD) {
1983   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1984   // FIXME: Destruction of ObjC lifetime types has side-effects.
1985   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1986     return !RD->isCompleteDefinition() ||
1987            !RD->hasTrivialDefaultConstructor() ||
1988            !RD->hasTrivialDestructor();
1989   return false;
1990 }
1991 
1992 static AttributeList *getMSPropertyAttr(AttributeList *list) {
1993   for (AttributeList *it = list; it != nullptr; it = it->getNext())
1994     if (it->isDeclspecPropertyAttribute())
1995       return it;
1996   return nullptr;
1997 }
1998 
1999 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2000 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2001 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
2002 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2003 /// present (but parsing it has been deferred).
2004 NamedDecl *
2005 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2006                                MultiTemplateParamsArg TemplateParameterLists,
2007                                Expr *BW, const VirtSpecifiers &VS,
2008                                InClassInitStyle InitStyle) {
2009   const DeclSpec &DS = D.getDeclSpec();
2010   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2011   DeclarationName Name = NameInfo.getName();
2012   SourceLocation Loc = NameInfo.getLoc();
2013 
2014   // For anonymous bitfields, the location should point to the type.
2015   if (Loc.isInvalid())
2016     Loc = D.getLocStart();
2017 
2018   Expr *BitWidth = static_cast<Expr*>(BW);
2019 
2020   assert(isa<CXXRecordDecl>(CurContext));
2021   assert(!DS.isFriendSpecified());
2022 
2023   bool isFunc = D.isDeclarationOfFunction();
2024 
2025   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2026     // The Microsoft extension __interface only permits public member functions
2027     // and prohibits constructors, destructors, operators, non-public member
2028     // functions, static methods and data members.
2029     unsigned InvalidDecl;
2030     bool ShowDeclName = true;
2031     if (!isFunc)
2032       InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
2033     else if (AS != AS_public)
2034       InvalidDecl = 2;
2035     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2036       InvalidDecl = 3;
2037     else switch (Name.getNameKind()) {
2038       case DeclarationName::CXXConstructorName:
2039         InvalidDecl = 4;
2040         ShowDeclName = false;
2041         break;
2042 
2043       case DeclarationName::CXXDestructorName:
2044         InvalidDecl = 5;
2045         ShowDeclName = false;
2046         break;
2047 
2048       case DeclarationName::CXXOperatorName:
2049       case DeclarationName::CXXConversionFunctionName:
2050         InvalidDecl = 6;
2051         break;
2052 
2053       default:
2054         InvalidDecl = 0;
2055         break;
2056     }
2057 
2058     if (InvalidDecl) {
2059       if (ShowDeclName)
2060         Diag(Loc, diag::err_invalid_member_in_interface)
2061           << (InvalidDecl-1) << Name;
2062       else
2063         Diag(Loc, diag::err_invalid_member_in_interface)
2064           << (InvalidDecl-1) << "";
2065       return nullptr;
2066     }
2067   }
2068 
2069   // C++ 9.2p6: A member shall not be declared to have automatic storage
2070   // duration (auto, register) or with the extern storage-class-specifier.
2071   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2072   // data members and cannot be applied to names declared const or static,
2073   // and cannot be applied to reference members.
2074   switch (DS.getStorageClassSpec()) {
2075   case DeclSpec::SCS_unspecified:
2076   case DeclSpec::SCS_typedef:
2077   case DeclSpec::SCS_static:
2078     break;
2079   case DeclSpec::SCS_mutable:
2080     if (isFunc) {
2081       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2082 
2083       // FIXME: It would be nicer if the keyword was ignored only for this
2084       // declarator. Otherwise we could get follow-up errors.
2085       D.getMutableDeclSpec().ClearStorageClassSpecs();
2086     }
2087     break;
2088   default:
2089     Diag(DS.getStorageClassSpecLoc(),
2090          diag::err_storageclass_invalid_for_member);
2091     D.getMutableDeclSpec().ClearStorageClassSpecs();
2092     break;
2093   }
2094 
2095   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2096                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
2097                       !isFunc);
2098 
2099   if (DS.isConstexprSpecified() && isInstField) {
2100     SemaDiagnosticBuilder B =
2101         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2102     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2103     if (InitStyle == ICIS_NoInit) {
2104       B << 0 << 0;
2105       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2106         B << FixItHint::CreateRemoval(ConstexprLoc);
2107       else {
2108         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2109         D.getMutableDeclSpec().ClearConstexprSpec();
2110         const char *PrevSpec;
2111         unsigned DiagID;
2112         bool Failed = D.getMutableDeclSpec().SetTypeQual(
2113             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2114         (void)Failed;
2115         assert(!Failed && "Making a constexpr member const shouldn't fail");
2116       }
2117     } else {
2118       B << 1;
2119       const char *PrevSpec;
2120       unsigned DiagID;
2121       if (D.getMutableDeclSpec().SetStorageClassSpec(
2122           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2123           Context.getPrintingPolicy())) {
2124         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
2125                "This is the only DeclSpec that should fail to be applied");
2126         B << 1;
2127       } else {
2128         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2129         isInstField = false;
2130       }
2131     }
2132   }
2133 
2134   NamedDecl *Member;
2135   if (isInstField) {
2136     CXXScopeSpec &SS = D.getCXXScopeSpec();
2137 
2138     // Data members must have identifiers for names.
2139     if (!Name.isIdentifier()) {
2140       Diag(Loc, diag::err_bad_variable_name)
2141         << Name;
2142       return nullptr;
2143     }
2144 
2145     IdentifierInfo *II = Name.getAsIdentifierInfo();
2146 
2147     // Member field could not be with "template" keyword.
2148     // So TemplateParameterLists should be empty in this case.
2149     if (TemplateParameterLists.size()) {
2150       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
2151       if (TemplateParams->size()) {
2152         // There is no such thing as a member field template.
2153         Diag(D.getIdentifierLoc(), diag::err_template_member)
2154             << II
2155             << SourceRange(TemplateParams->getTemplateLoc(),
2156                 TemplateParams->getRAngleLoc());
2157       } else {
2158         // There is an extraneous 'template<>' for this member.
2159         Diag(TemplateParams->getTemplateLoc(),
2160             diag::err_template_member_noparams)
2161             << II
2162             << SourceRange(TemplateParams->getTemplateLoc(),
2163                 TemplateParams->getRAngleLoc());
2164       }
2165       return nullptr;
2166     }
2167 
2168     if (SS.isSet() && !SS.isInvalid()) {
2169       // The user provided a superfluous scope specifier inside a class
2170       // definition:
2171       //
2172       // class X {
2173       //   int X::member;
2174       // };
2175       if (DeclContext *DC = computeDeclContext(SS, false))
2176         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
2177       else
2178         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2179           << Name << SS.getRange();
2180 
2181       SS.clear();
2182     }
2183 
2184     AttributeList *MSPropertyAttr =
2185       getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
2186     if (MSPropertyAttr) {
2187       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2188                                 BitWidth, InitStyle, AS, MSPropertyAttr);
2189       if (!Member)
2190         return nullptr;
2191       isInstField = false;
2192     } else {
2193       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2194                                 BitWidth, InitStyle, AS);
2195       assert(Member && "HandleField never returns null");
2196     }
2197   } else {
2198     Member = HandleDeclarator(S, D, TemplateParameterLists);
2199     if (!Member)
2200       return nullptr;
2201 
2202     // Non-instance-fields can't have a bitfield.
2203     if (BitWidth) {
2204       if (Member->isInvalidDecl()) {
2205         // don't emit another diagnostic.
2206       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
2207         // C++ 9.6p3: A bit-field shall not be a static member.
2208         // "static member 'A' cannot be a bit-field"
2209         Diag(Loc, diag::err_static_not_bitfield)
2210           << Name << BitWidth->getSourceRange();
2211       } else if (isa<TypedefDecl>(Member)) {
2212         // "typedef member 'x' cannot be a bit-field"
2213         Diag(Loc, diag::err_typedef_not_bitfield)
2214           << Name << BitWidth->getSourceRange();
2215       } else {
2216         // A function typedef ("typedef int f(); f a;").
2217         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2218         Diag(Loc, diag::err_not_integral_type_bitfield)
2219           << Name << cast<ValueDecl>(Member)->getType()
2220           << BitWidth->getSourceRange();
2221       }
2222 
2223       BitWidth = nullptr;
2224       Member->setInvalidDecl();
2225     }
2226 
2227     Member->setAccess(AS);
2228 
2229     // If we have declared a member function template or static data member
2230     // template, set the access of the templated declaration as well.
2231     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2232       FunTmpl->getTemplatedDecl()->setAccess(AS);
2233     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2234       VarTmpl->getTemplatedDecl()->setAccess(AS);
2235   }
2236 
2237   if (VS.isOverrideSpecified())
2238     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
2239   if (VS.isFinalSpecified())
2240     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2241                                             VS.isFinalSpelledSealed()));
2242 
2243   if (VS.getLastLocation().isValid()) {
2244     // Update the end location of a method that has a virt-specifiers.
2245     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2246       MD->setRangeEnd(VS.getLastLocation());
2247   }
2248 
2249   CheckOverrideControl(Member);
2250 
2251   assert((Name || isInstField) && "No identifier for non-field ?");
2252 
2253   if (isInstField) {
2254     FieldDecl *FD = cast<FieldDecl>(Member);
2255     FieldCollector->Add(FD);
2256 
2257     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
2258       // Remember all explicit private FieldDecls that have a name, no side
2259       // effects and are not part of a dependent type declaration.
2260       if (!FD->isImplicit() && FD->getDeclName() &&
2261           FD->getAccess() == AS_private &&
2262           !FD->hasAttr<UnusedAttr>() &&
2263           !FD->getParent()->isDependentContext() &&
2264           !InitializationHasSideEffects(*FD))
2265         UnusedPrivateFields.insert(FD);
2266     }
2267   }
2268 
2269   return Member;
2270 }
2271 
2272 namespace {
2273   class UninitializedFieldVisitor
2274       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2275     Sema &S;
2276     // List of Decls to generate a warning on.  Also remove Decls that become
2277     // initialized.
2278     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
2279     // List of base classes of the record.  Classes are removed after their
2280     // initializers.
2281     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
2282     // Vector of decls to be removed from the Decl set prior to visiting the
2283     // nodes.  These Decls may have been initialized in the prior initializer.
2284     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
2285     // If non-null, add a note to the warning pointing back to the constructor.
2286     const CXXConstructorDecl *Constructor;
2287     // Variables to hold state when processing an initializer list.  When
2288     // InitList is true, special case initialization of FieldDecls matching
2289     // InitListFieldDecl.
2290     bool InitList;
2291     FieldDecl *InitListFieldDecl;
2292     llvm::SmallVector<unsigned, 4> InitFieldIndex;
2293 
2294   public:
2295     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2296     UninitializedFieldVisitor(Sema &S,
2297                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
2298                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
2299       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
2300         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
2301 
2302     // Returns true if the use of ME is not an uninitialized use.
2303     bool IsInitListMemberExprInitialized(MemberExpr *ME,
2304                                          bool CheckReferenceOnly) {
2305       llvm::SmallVector<FieldDecl*, 4> Fields;
2306       bool ReferenceField = false;
2307       while (ME) {
2308         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
2309         if (!FD)
2310           return false;
2311         Fields.push_back(FD);
2312         if (FD->getType()->isReferenceType())
2313           ReferenceField = true;
2314         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
2315       }
2316 
2317       // Binding a reference to an unintialized field is not an
2318       // uninitialized use.
2319       if (CheckReferenceOnly && !ReferenceField)
2320         return true;
2321 
2322       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
2323       // Discard the first field since it is the field decl that is being
2324       // initialized.
2325       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
2326         UsedFieldIndex.push_back((*I)->getFieldIndex());
2327       }
2328 
2329       for (auto UsedIter = UsedFieldIndex.begin(),
2330                 UsedEnd = UsedFieldIndex.end(),
2331                 OrigIter = InitFieldIndex.begin(),
2332                 OrigEnd = InitFieldIndex.end();
2333            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
2334         if (*UsedIter < *OrigIter)
2335           return true;
2336         if (*UsedIter > *OrigIter)
2337           break;
2338       }
2339 
2340       return false;
2341     }
2342 
2343     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
2344                           bool AddressOf) {
2345       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2346         return;
2347 
2348       // FieldME is the inner-most MemberExpr that is not an anonymous struct
2349       // or union.
2350       MemberExpr *FieldME = ME;
2351 
2352       bool AllPODFields = FieldME->getType().isPODType(S.Context);
2353 
2354       Expr *Base = ME;
2355       while (MemberExpr *SubME =
2356                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
2357 
2358         if (isa<VarDecl>(SubME->getMemberDecl()))
2359           return;
2360 
2361         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
2362           if (!FD->isAnonymousStructOrUnion())
2363             FieldME = SubME;
2364 
2365         if (!FieldME->getType().isPODType(S.Context))
2366           AllPODFields = false;
2367 
2368         Base = SubME->getBase();
2369       }
2370 
2371       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
2372         return;
2373 
2374       if (AddressOf && AllPODFields)
2375         return;
2376 
2377       ValueDecl* FoundVD = FieldME->getMemberDecl();
2378 
2379       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
2380         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
2381           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
2382         }
2383 
2384         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
2385           QualType T = BaseCast->getType();
2386           if (T->isPointerType() &&
2387               BaseClasses.count(T->getPointeeType())) {
2388             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
2389                 << T->getPointeeType() << FoundVD;
2390           }
2391         }
2392       }
2393 
2394       if (!Decls.count(FoundVD))
2395         return;
2396 
2397       const bool IsReference = FoundVD->getType()->isReferenceType();
2398 
2399       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
2400         // Special checking for initializer lists.
2401         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
2402           return;
2403         }
2404       } else {
2405         // Prevent double warnings on use of unbounded references.
2406         if (CheckReferenceOnly && !IsReference)
2407           return;
2408       }
2409 
2410       unsigned diag = IsReference
2411           ? diag::warn_reference_field_is_uninit
2412           : diag::warn_field_is_uninit;
2413       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2414       if (Constructor)
2415         S.Diag(Constructor->getLocation(),
2416                diag::note_uninit_in_this_constructor)
2417           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2418 
2419     }
2420 
2421     void HandleValue(Expr *E, bool AddressOf) {
2422       E = E->IgnoreParens();
2423 
2424       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2425         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
2426                          AddressOf /*AddressOf*/);
2427         return;
2428       }
2429 
2430       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2431         Visit(CO->getCond());
2432         HandleValue(CO->getTrueExpr(), AddressOf);
2433         HandleValue(CO->getFalseExpr(), AddressOf);
2434         return;
2435       }
2436 
2437       if (BinaryConditionalOperator *BCO =
2438               dyn_cast<BinaryConditionalOperator>(E)) {
2439         Visit(BCO->getCond());
2440         HandleValue(BCO->getFalseExpr(), AddressOf);
2441         return;
2442       }
2443 
2444       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
2445         HandleValue(OVE->getSourceExpr(), AddressOf);
2446         return;
2447       }
2448 
2449       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2450         switch (BO->getOpcode()) {
2451         default:
2452           break;
2453         case(BO_PtrMemD):
2454         case(BO_PtrMemI):
2455           HandleValue(BO->getLHS(), AddressOf);
2456           Visit(BO->getRHS());
2457           return;
2458         case(BO_Comma):
2459           Visit(BO->getLHS());
2460           HandleValue(BO->getRHS(), AddressOf);
2461           return;
2462         }
2463       }
2464 
2465       Visit(E);
2466     }
2467 
2468     void CheckInitListExpr(InitListExpr *ILE) {
2469       InitFieldIndex.push_back(0);
2470       for (auto Child : ILE->children()) {
2471         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
2472           CheckInitListExpr(SubList);
2473         } else {
2474           Visit(Child);
2475         }
2476         ++InitFieldIndex.back();
2477       }
2478       InitFieldIndex.pop_back();
2479     }
2480 
2481     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
2482                           FieldDecl *Field, const Type *BaseClass) {
2483       // Remove Decls that may have been initialized in the previous
2484       // initializer.
2485       for (ValueDecl* VD : DeclsToRemove)
2486         Decls.erase(VD);
2487       DeclsToRemove.clear();
2488 
2489       Constructor = FieldConstructor;
2490       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
2491 
2492       if (ILE && Field) {
2493         InitList = true;
2494         InitListFieldDecl = Field;
2495         InitFieldIndex.clear();
2496         CheckInitListExpr(ILE);
2497       } else {
2498         InitList = false;
2499         Visit(E);
2500       }
2501 
2502       if (Field)
2503         Decls.erase(Field);
2504       if (BaseClass)
2505         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
2506     }
2507 
2508     void VisitMemberExpr(MemberExpr *ME) {
2509       // All uses of unbounded reference fields will warn.
2510       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
2511     }
2512 
2513     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2514       if (E->getCastKind() == CK_LValueToRValue) {
2515         HandleValue(E->getSubExpr(), false /*AddressOf*/);
2516         return;
2517       }
2518 
2519       Inherited::VisitImplicitCastExpr(E);
2520     }
2521 
2522     void VisitCXXConstructExpr(CXXConstructExpr *E) {
2523       if (E->getConstructor()->isCopyConstructor()) {
2524         Expr *ArgExpr = E->getArg(0);
2525         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
2526           if (ILE->getNumInits() == 1)
2527             ArgExpr = ILE->getInit(0);
2528         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
2529           if (ICE->getCastKind() == CK_NoOp)
2530             ArgExpr = ICE->getSubExpr();
2531         HandleValue(ArgExpr, false /*AddressOf*/);
2532         return;
2533       }
2534       Inherited::VisitCXXConstructExpr(E);
2535     }
2536 
2537     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2538       Expr *Callee = E->getCallee();
2539       if (isa<MemberExpr>(Callee)) {
2540         HandleValue(Callee, false /*AddressOf*/);
2541         for (auto Arg : E->arguments())
2542           Visit(Arg);
2543         return;
2544       }
2545 
2546       Inherited::VisitCXXMemberCallExpr(E);
2547     }
2548 
2549     void VisitCallExpr(CallExpr *E) {
2550       // Treat std::move as a use.
2551       if (E->getNumArgs() == 1) {
2552         if (FunctionDecl *FD = E->getDirectCallee()) {
2553           if (FD->isInStdNamespace() && FD->getIdentifier() &&
2554               FD->getIdentifier()->isStr("move")) {
2555             HandleValue(E->getArg(0), false /*AddressOf*/);
2556             return;
2557           }
2558         }
2559       }
2560 
2561       Inherited::VisitCallExpr(E);
2562     }
2563 
2564     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
2565       Expr *Callee = E->getCallee();
2566 
2567       if (isa<UnresolvedLookupExpr>(Callee))
2568         return Inherited::VisitCXXOperatorCallExpr(E);
2569 
2570       Visit(Callee);
2571       for (auto Arg : E->arguments())
2572         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
2573     }
2574 
2575     void VisitBinaryOperator(BinaryOperator *E) {
2576       // If a field assignment is detected, remove the field from the
2577       // uninitiailized field set.
2578       if (E->getOpcode() == BO_Assign)
2579         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2580           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2581             if (!FD->getType()->isReferenceType())
2582               DeclsToRemove.push_back(FD);
2583 
2584       if (E->isCompoundAssignmentOp()) {
2585         HandleValue(E->getLHS(), false /*AddressOf*/);
2586         Visit(E->getRHS());
2587         return;
2588       }
2589 
2590       Inherited::VisitBinaryOperator(E);
2591     }
2592 
2593     void VisitUnaryOperator(UnaryOperator *E) {
2594       if (E->isIncrementDecrementOp()) {
2595         HandleValue(E->getSubExpr(), false /*AddressOf*/);
2596         return;
2597       }
2598       if (E->getOpcode() == UO_AddrOf) {
2599         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
2600           HandleValue(ME->getBase(), true /*AddressOf*/);
2601           return;
2602         }
2603       }
2604 
2605       Inherited::VisitUnaryOperator(E);
2606     }
2607   };
2608 
2609   // Diagnose value-uses of fields to initialize themselves, e.g.
2610   //   foo(foo)
2611   // where foo is not also a parameter to the constructor.
2612   // Also diagnose across field uninitialized use such as
2613   //   x(y), y(x)
2614   // TODO: implement -Wuninitialized and fold this into that framework.
2615   static void DiagnoseUninitializedFields(
2616       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2617 
2618     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
2619                                            Constructor->getLocation())) {
2620       return;
2621     }
2622 
2623     if (Constructor->isInvalidDecl())
2624       return;
2625 
2626     const CXXRecordDecl *RD = Constructor->getParent();
2627 
2628     if (RD->getDescribedClassTemplate())
2629       return;
2630 
2631     // Holds fields that are uninitialized.
2632     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2633 
2634     // At the beginning, all fields are uninitialized.
2635     for (auto *I : RD->decls()) {
2636       if (auto *FD = dyn_cast<FieldDecl>(I)) {
2637         UninitializedFields.insert(FD);
2638       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
2639         UninitializedFields.insert(IFD->getAnonField());
2640       }
2641     }
2642 
2643     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
2644     for (auto I : RD->bases())
2645       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
2646 
2647     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
2648       return;
2649 
2650     UninitializedFieldVisitor UninitializedChecker(SemaRef,
2651                                                    UninitializedFields,
2652                                                    UninitializedBaseClasses);
2653 
2654     for (const auto *FieldInit : Constructor->inits()) {
2655       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
2656         break;
2657 
2658       Expr *InitExpr = FieldInit->getInit();
2659       if (!InitExpr)
2660         continue;
2661 
2662       if (CXXDefaultInitExpr *Default =
2663               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
2664         InitExpr = Default->getExpr();
2665         if (!InitExpr)
2666           continue;
2667         // In class initializers will point to the constructor.
2668         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
2669                                               FieldInit->getAnyMember(),
2670                                               FieldInit->getBaseClass());
2671       } else {
2672         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
2673                                               FieldInit->getAnyMember(),
2674                                               FieldInit->getBaseClass());
2675       }
2676     }
2677   }
2678 } // namespace
2679 
2680 /// \brief Enter a new C++ default initializer scope. After calling this, the
2681 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2682 /// parsing or instantiating the initializer failed.
2683 void Sema::ActOnStartCXXInClassMemberInitializer() {
2684   // Create a synthetic function scope to represent the call to the constructor
2685   // that notionally surrounds a use of this initializer.
2686   PushFunctionScope();
2687 }
2688 
2689 /// \brief This is invoked after parsing an in-class initializer for a
2690 /// non-static C++ class member, and after instantiating an in-class initializer
2691 /// in a class template. Such actions are deferred until the class is complete.
2692 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2693                                                   SourceLocation InitLoc,
2694                                                   Expr *InitExpr) {
2695   // Pop the notional constructor scope we created earlier.
2696   PopFunctionScopeInfo(nullptr, D);
2697 
2698   FieldDecl *FD = dyn_cast<FieldDecl>(D);
2699   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
2700          "must set init style when field is created");
2701 
2702   if (!InitExpr) {
2703     D->setInvalidDecl();
2704     if (FD)
2705       FD->removeInClassInitializer();
2706     return;
2707   }
2708 
2709   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2710     FD->setInvalidDecl();
2711     FD->removeInClassInitializer();
2712     return;
2713   }
2714 
2715   ExprResult Init = InitExpr;
2716   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
2717     InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
2718     InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
2719         ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
2720         : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
2721     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2722     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
2723     if (Init.isInvalid()) {
2724       FD->setInvalidDecl();
2725       return;
2726     }
2727   }
2728 
2729   // C++11 [class.base.init]p7:
2730   //   The initialization of each base and member constitutes a
2731   //   full-expression.
2732   Init = ActOnFinishFullExpr(Init.get(), InitLoc);
2733   if (Init.isInvalid()) {
2734     FD->setInvalidDecl();
2735     return;
2736   }
2737 
2738   InitExpr = Init.get();
2739 
2740   FD->setInClassInitializer(InitExpr);
2741 }
2742 
2743 /// \brief Find the direct and/or virtual base specifiers that
2744 /// correspond to the given base type, for use in base initialization
2745 /// within a constructor.
2746 static bool FindBaseInitializer(Sema &SemaRef,
2747                                 CXXRecordDecl *ClassDecl,
2748                                 QualType BaseType,
2749                                 const CXXBaseSpecifier *&DirectBaseSpec,
2750                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
2751   // First, check for a direct base class.
2752   DirectBaseSpec = nullptr;
2753   for (const auto &Base : ClassDecl->bases()) {
2754     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
2755       // We found a direct base of this type. That's what we're
2756       // initializing.
2757       DirectBaseSpec = &Base;
2758       break;
2759     }
2760   }
2761 
2762   // Check for a virtual base class.
2763   // FIXME: We might be able to short-circuit this if we know in advance that
2764   // there are no virtual bases.
2765   VirtualBaseSpec = nullptr;
2766   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2767     // We haven't found a base yet; search the class hierarchy for a
2768     // virtual base class.
2769     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2770                        /*DetectVirtual=*/false);
2771     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
2772                               SemaRef.Context.getTypeDeclType(ClassDecl),
2773                               BaseType, Paths)) {
2774       for (CXXBasePaths::paths_iterator Path = Paths.begin();
2775            Path != Paths.end(); ++Path) {
2776         if (Path->back().Base->isVirtual()) {
2777           VirtualBaseSpec = Path->back().Base;
2778           break;
2779         }
2780       }
2781     }
2782   }
2783 
2784   return DirectBaseSpec || VirtualBaseSpec;
2785 }
2786 
2787 /// \brief Handle a C++ member initializer using braced-init-list syntax.
2788 MemInitResult
2789 Sema::ActOnMemInitializer(Decl *ConstructorD,
2790                           Scope *S,
2791                           CXXScopeSpec &SS,
2792                           IdentifierInfo *MemberOrBase,
2793                           ParsedType TemplateTypeTy,
2794                           const DeclSpec &DS,
2795                           SourceLocation IdLoc,
2796                           Expr *InitList,
2797                           SourceLocation EllipsisLoc) {
2798   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2799                              DS, IdLoc, InitList,
2800                              EllipsisLoc);
2801 }
2802 
2803 /// \brief Handle a C++ member initializer using parentheses syntax.
2804 MemInitResult
2805 Sema::ActOnMemInitializer(Decl *ConstructorD,
2806                           Scope *S,
2807                           CXXScopeSpec &SS,
2808                           IdentifierInfo *MemberOrBase,
2809                           ParsedType TemplateTypeTy,
2810                           const DeclSpec &DS,
2811                           SourceLocation IdLoc,
2812                           SourceLocation LParenLoc,
2813                           ArrayRef<Expr *> Args,
2814                           SourceLocation RParenLoc,
2815                           SourceLocation EllipsisLoc) {
2816   Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2817                                            Args, RParenLoc);
2818   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2819                              DS, IdLoc, List, EllipsisLoc);
2820 }
2821 
2822 namespace {
2823 
2824 // Callback to only accept typo corrections that can be a valid C++ member
2825 // intializer: either a non-static field member or a base class.
2826 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2827 public:
2828   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2829       : ClassDecl(ClassDecl) {}
2830 
2831   bool ValidateCandidate(const TypoCorrection &candidate) override {
2832     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2833       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2834         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2835       return isa<TypeDecl>(ND);
2836     }
2837     return false;
2838   }
2839 
2840 private:
2841   CXXRecordDecl *ClassDecl;
2842 };
2843 
2844 }
2845 
2846 /// \brief Handle a C++ member initializer.
2847 MemInitResult
2848 Sema::BuildMemInitializer(Decl *ConstructorD,
2849                           Scope *S,
2850                           CXXScopeSpec &SS,
2851                           IdentifierInfo *MemberOrBase,
2852                           ParsedType TemplateTypeTy,
2853                           const DeclSpec &DS,
2854                           SourceLocation IdLoc,
2855                           Expr *Init,
2856                           SourceLocation EllipsisLoc) {
2857   ExprResult Res = CorrectDelayedTyposInExpr(Init);
2858   if (!Res.isUsable())
2859     return true;
2860   Init = Res.get();
2861 
2862   if (!ConstructorD)
2863     return true;
2864 
2865   AdjustDeclIfTemplate(ConstructorD);
2866 
2867   CXXConstructorDecl *Constructor
2868     = dyn_cast<CXXConstructorDecl>(ConstructorD);
2869   if (!Constructor) {
2870     // The user wrote a constructor initializer on a function that is
2871     // not a C++ constructor. Ignore the error for now, because we may
2872     // have more member initializers coming; we'll diagnose it just
2873     // once in ActOnMemInitializers.
2874     return true;
2875   }
2876 
2877   CXXRecordDecl *ClassDecl = Constructor->getParent();
2878 
2879   // C++ [class.base.init]p2:
2880   //   Names in a mem-initializer-id are looked up in the scope of the
2881   //   constructor's class and, if not found in that scope, are looked
2882   //   up in the scope containing the constructor's definition.
2883   //   [Note: if the constructor's class contains a member with the
2884   //   same name as a direct or virtual base class of the class, a
2885   //   mem-initializer-id naming the member or base class and composed
2886   //   of a single identifier refers to the class member. A
2887   //   mem-initializer-id for the hidden base class may be specified
2888   //   using a qualified name. ]
2889   if (!SS.getScopeRep() && !TemplateTypeTy) {
2890     // Look for a member, first.
2891     DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
2892     if (!Result.empty()) {
2893       ValueDecl *Member;
2894       if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2895           (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
2896         if (EllipsisLoc.isValid())
2897           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
2898             << MemberOrBase
2899             << SourceRange(IdLoc, Init->getSourceRange().getEnd());
2900 
2901         return BuildMemberInitializer(Member, Init, IdLoc);
2902       }
2903     }
2904   }
2905   // It didn't name a member, so see if it names a class.
2906   QualType BaseType;
2907   TypeSourceInfo *TInfo = nullptr;
2908 
2909   if (TemplateTypeTy) {
2910     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
2911   } else if (DS.getTypeSpecType() == TST_decltype) {
2912     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
2913   } else {
2914     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2915     LookupParsedName(R, S, &SS);
2916 
2917     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2918     if (!TyD) {
2919       if (R.isAmbiguous()) return true;
2920 
2921       // We don't want access-control diagnostics here.
2922       R.suppressDiagnostics();
2923 
2924       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2925         bool NotUnknownSpecialization = false;
2926         DeclContext *DC = computeDeclContext(SS, false);
2927         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2928           NotUnknownSpecialization = !Record->hasAnyDependentBases();
2929 
2930         if (!NotUnknownSpecialization) {
2931           // When the scope specifier can refer to a member of an unknown
2932           // specialization, we take it as a type name.
2933           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2934                                        SS.getWithLocInContext(Context),
2935                                        *MemberOrBase, IdLoc);
2936           if (BaseType.isNull())
2937             return true;
2938 
2939           R.clear();
2940           R.setLookupName(MemberOrBase);
2941         }
2942       }
2943 
2944       // If no results were found, try to correct typos.
2945       TypoCorrection Corr;
2946       if (R.empty() && BaseType.isNull() &&
2947           (Corr = CorrectTypo(
2948                R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2949                llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
2950                CTK_ErrorRecovery, ClassDecl))) {
2951         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
2952           // We have found a non-static data member with a similar
2953           // name to what was typed; complain and initialize that
2954           // member.
2955           diagnoseTypo(Corr,
2956                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
2957                          << MemberOrBase << true);
2958           return BuildMemberInitializer(Member, Init, IdLoc);
2959         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
2960           const CXXBaseSpecifier *DirectBaseSpec;
2961           const CXXBaseSpecifier *VirtualBaseSpec;
2962           if (FindBaseInitializer(*this, ClassDecl,
2963                                   Context.getTypeDeclType(Type),
2964                                   DirectBaseSpec, VirtualBaseSpec)) {
2965             // We have found a direct or virtual base class with a
2966             // similar name to what was typed; complain and initialize
2967             // that base class.
2968             diagnoseTypo(Corr,
2969                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
2970                            << MemberOrBase << false,
2971                          PDiag() /*Suppress note, we provide our own.*/);
2972 
2973             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2974                                                               : VirtualBaseSpec;
2975             Diag(BaseSpec->getLocStart(),
2976                  diag::note_base_class_specified_here)
2977               << BaseSpec->getType()
2978               << BaseSpec->getSourceRange();
2979 
2980             TyD = Type;
2981           }
2982         }
2983       }
2984 
2985       if (!TyD && BaseType.isNull()) {
2986         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
2987           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
2988         return true;
2989       }
2990     }
2991 
2992     if (BaseType.isNull()) {
2993       BaseType = Context.getTypeDeclType(TyD);
2994       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
2995       if (SS.isSet()) {
2996         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2997                                              BaseType);
2998         TInfo = Context.CreateTypeSourceInfo(BaseType);
2999         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3000         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3001         TL.setElaboratedKeywordLoc(SourceLocation());
3002         TL.setQualifierLoc(SS.getWithLocInContext(Context));
3003       }
3004     }
3005   }
3006 
3007   if (!TInfo)
3008     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
3009 
3010   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
3011 }
3012 
3013 /// Checks a member initializer expression for cases where reference (or
3014 /// pointer) members are bound to by-value parameters (or their addresses).
3015 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3016                                                Expr *Init,
3017                                                SourceLocation IdLoc) {
3018   QualType MemberTy = Member->getType();
3019 
3020   // We only handle pointers and references currently.
3021   // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3022   if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3023     return;
3024 
3025   const bool IsPointer = MemberTy->isPointerType();
3026   if (IsPointer) {
3027     if (const UnaryOperator *Op
3028           = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3029       // The only case we're worried about with pointers requires taking the
3030       // address.
3031       if (Op->getOpcode() != UO_AddrOf)
3032         return;
3033 
3034       Init = Op->getSubExpr();
3035     } else {
3036       // We only handle address-of expression initializers for pointers.
3037       return;
3038     }
3039   }
3040 
3041   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
3042     // We only warn when referring to a non-reference parameter declaration.
3043     const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3044     if (!Parameter || Parameter->getType()->isReferenceType())
3045       return;
3046 
3047     S.Diag(Init->getExprLoc(),
3048            IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3049                      : diag::warn_bind_ref_member_to_parameter)
3050       << Member << Parameter << Init->getSourceRange();
3051   } else {
3052     // Other initializers are fine.
3053     return;
3054   }
3055 
3056   S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3057     << (unsigned)IsPointer;
3058 }
3059 
3060 MemInitResult
3061 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3062                              SourceLocation IdLoc) {
3063   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3064   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3065   assert((DirectMember || IndirectMember) &&
3066          "Member must be a FieldDecl or IndirectFieldDecl");
3067 
3068   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3069     return true;
3070 
3071   if (Member->isInvalidDecl())
3072     return true;
3073 
3074   MultiExprArg Args;
3075   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3076     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3077   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3078     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
3079   } else {
3080     // Template instantiation doesn't reconstruct ParenListExprs for us.
3081     Args = Init;
3082   }
3083 
3084   SourceRange InitRange = Init->getSourceRange();
3085 
3086   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
3087     // Can't check initialization for a member of dependent type or when
3088     // any of the arguments are type-dependent expressions.
3089     DiscardCleanupsInEvaluationContext();
3090   } else {
3091     bool InitList = false;
3092     if (isa<InitListExpr>(Init)) {
3093       InitList = true;
3094       Args = Init;
3095     }
3096 
3097     // Initialize the member.
3098     InitializedEntity MemberEntity =
3099       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3100                    : InitializedEntity::InitializeMember(IndirectMember,
3101                                                          nullptr);
3102     InitializationKind Kind =
3103       InitList ? InitializationKind::CreateDirectList(IdLoc)
3104                : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3105                                                   InitRange.getEnd());
3106 
3107     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
3108     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3109                                             nullptr);
3110     if (MemberInit.isInvalid())
3111       return true;
3112 
3113     CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3114 
3115     // C++11 [class.base.init]p7:
3116     //   The initialization of each base and member constitutes a
3117     //   full-expression.
3118     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
3119     if (MemberInit.isInvalid())
3120       return true;
3121 
3122     Init = MemberInit.get();
3123   }
3124 
3125   if (DirectMember) {
3126     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3127                                             InitRange.getBegin(), Init,
3128                                             InitRange.getEnd());
3129   } else {
3130     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3131                                             InitRange.getBegin(), Init,
3132                                             InitRange.getEnd());
3133   }
3134 }
3135 
3136 MemInitResult
3137 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
3138                                  CXXRecordDecl *ClassDecl) {
3139   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
3140   if (!LangOpts.CPlusPlus11)
3141     return Diag(NameLoc, diag::err_delegating_ctor)
3142       << TInfo->getTypeLoc().getLocalSourceRange();
3143   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
3144 
3145   bool InitList = true;
3146   MultiExprArg Args = Init;
3147   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3148     InitList = false;
3149     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3150   }
3151 
3152   SourceRange InitRange = Init->getSourceRange();
3153   // Initialize the object.
3154   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3155                                      QualType(ClassDecl->getTypeForDecl(), 0));
3156   InitializationKind Kind =
3157     InitList ? InitializationKind::CreateDirectList(NameLoc)
3158              : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3159                                                 InitRange.getEnd());
3160   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
3161   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
3162                                               Args, nullptr);
3163   if (DelegationInit.isInvalid())
3164     return true;
3165 
3166   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3167          "Delegating constructor with no target?");
3168 
3169   // C++11 [class.base.init]p7:
3170   //   The initialization of each base and member constitutes a
3171   //   full-expression.
3172   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
3173                                        InitRange.getBegin());
3174   if (DelegationInit.isInvalid())
3175     return true;
3176 
3177   // If we are in a dependent context, template instantiation will
3178   // perform this type-checking again. Just save the arguments that we
3179   // received in a ParenListExpr.
3180   // FIXME: This isn't quite ideal, since our ASTs don't capture all
3181   // of the information that we have about the base
3182   // initializer. However, deconstructing the ASTs is a dicey process,
3183   // and this approach is far more likely to get the corner cases right.
3184   if (CurContext->isDependentContext())
3185     DelegationInit = Init;
3186 
3187   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
3188                                           DelegationInit.getAs<Expr>(),
3189                                           InitRange.getEnd());
3190 }
3191 
3192 MemInitResult
3193 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
3194                            Expr *Init, CXXRecordDecl *ClassDecl,
3195                            SourceLocation EllipsisLoc) {
3196   SourceLocation BaseLoc
3197     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
3198 
3199   if (!BaseType->isDependentType() && !BaseType->isRecordType())
3200     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
3201              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3202 
3203   // C++ [class.base.init]p2:
3204   //   [...] Unless the mem-initializer-id names a nonstatic data
3205   //   member of the constructor's class or a direct or virtual base
3206   //   of that class, the mem-initializer is ill-formed. A
3207   //   mem-initializer-list can initialize a base class using any
3208   //   name that denotes that base class type.
3209   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
3210 
3211   SourceRange InitRange = Init->getSourceRange();
3212   if (EllipsisLoc.isValid()) {
3213     // This is a pack expansion.
3214     if (!BaseType->containsUnexpandedParameterPack())  {
3215       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
3216         << SourceRange(BaseLoc, InitRange.getEnd());
3217 
3218       EllipsisLoc = SourceLocation();
3219     }
3220   } else {
3221     // Check for any unexpanded parameter packs.
3222     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
3223       return true;
3224 
3225     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3226       return true;
3227   }
3228 
3229   // Check for direct and virtual base classes.
3230   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
3231   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
3232   if (!Dependent) {
3233     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
3234                                        BaseType))
3235       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
3236 
3237     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
3238                         VirtualBaseSpec);
3239 
3240     // C++ [base.class.init]p2:
3241     // Unless the mem-initializer-id names a nonstatic data member of the
3242     // constructor's class or a direct or virtual base of that class, the
3243     // mem-initializer is ill-formed.
3244     if (!DirectBaseSpec && !VirtualBaseSpec) {
3245       // If the class has any dependent bases, then it's possible that
3246       // one of those types will resolve to the same type as
3247       // BaseType. Therefore, just treat this as a dependent base
3248       // class initialization.  FIXME: Should we try to check the
3249       // initialization anyway? It seems odd.
3250       if (ClassDecl->hasAnyDependentBases())
3251         Dependent = true;
3252       else
3253         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
3254           << BaseType << Context.getTypeDeclType(ClassDecl)
3255           << BaseTInfo->getTypeLoc().getLocalSourceRange();
3256     }
3257   }
3258 
3259   if (Dependent) {
3260     DiscardCleanupsInEvaluationContext();
3261 
3262     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3263                                             /*IsVirtual=*/false,
3264                                             InitRange.getBegin(), Init,
3265                                             InitRange.getEnd(), EllipsisLoc);
3266   }
3267 
3268   // C++ [base.class.init]p2:
3269   //   If a mem-initializer-id is ambiguous because it designates both
3270   //   a direct non-virtual base class and an inherited virtual base
3271   //   class, the mem-initializer is ill-formed.
3272   if (DirectBaseSpec && VirtualBaseSpec)
3273     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
3274       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3275 
3276   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
3277   if (!BaseSpec)
3278     BaseSpec = VirtualBaseSpec;
3279 
3280   // Initialize the base.
3281   bool InitList = true;
3282   MultiExprArg Args = Init;
3283   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3284     InitList = false;
3285     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3286   }
3287 
3288   InitializedEntity BaseEntity =
3289     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
3290   InitializationKind Kind =
3291     InitList ? InitializationKind::CreateDirectList(BaseLoc)
3292              : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
3293                                                 InitRange.getEnd());
3294   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
3295   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
3296   if (BaseInit.isInvalid())
3297     return true;
3298 
3299   // C++11 [class.base.init]p7:
3300   //   The initialization of each base and member constitutes a
3301   //   full-expression.
3302   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
3303   if (BaseInit.isInvalid())
3304     return true;
3305 
3306   // If we are in a dependent context, template instantiation will
3307   // perform this type-checking again. Just save the arguments that we
3308   // received in a ParenListExpr.
3309   // FIXME: This isn't quite ideal, since our ASTs don't capture all
3310   // of the information that we have about the base
3311   // initializer. However, deconstructing the ASTs is a dicey process,
3312   // and this approach is far more likely to get the corner cases right.
3313   if (CurContext->isDependentContext())
3314     BaseInit = Init;
3315 
3316   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3317                                           BaseSpec->isVirtual(),
3318                                           InitRange.getBegin(),
3319                                           BaseInit.getAs<Expr>(),
3320                                           InitRange.getEnd(), EllipsisLoc);
3321 }
3322 
3323 // Create a static_cast\<T&&>(expr).
3324 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
3325   if (T.isNull()) T = E->getType();
3326   QualType TargetType = SemaRef.BuildReferenceType(
3327       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
3328   SourceLocation ExprLoc = E->getLocStart();
3329   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
3330       TargetType, ExprLoc);
3331 
3332   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
3333                                    SourceRange(ExprLoc, ExprLoc),
3334                                    E->getSourceRange()).get();
3335 }
3336 
3337 /// ImplicitInitializerKind - How an implicit base or member initializer should
3338 /// initialize its base or member.
3339 enum ImplicitInitializerKind {
3340   IIK_Default,
3341   IIK_Copy,
3342   IIK_Move,
3343   IIK_Inherit
3344 };
3345 
3346 static bool
3347 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3348                              ImplicitInitializerKind ImplicitInitKind,
3349                              CXXBaseSpecifier *BaseSpec,
3350                              bool IsInheritedVirtualBase,
3351                              CXXCtorInitializer *&CXXBaseInit) {
3352   InitializedEntity InitEntity
3353     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3354                                         IsInheritedVirtualBase);
3355 
3356   ExprResult BaseInit;
3357 
3358   switch (ImplicitInitKind) {
3359   case IIK_Inherit: {
3360     const CXXRecordDecl *Inherited =
3361         Constructor->getInheritedConstructor()->getParent();
3362     const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3363     if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3364       // C++11 [class.inhctor]p8:
3365       //   Each expression in the expression-list is of the form
3366       //   static_cast<T&&>(p), where p is the name of the corresponding
3367       //   constructor parameter and T is the declared type of p.
3368       SmallVector<Expr*, 16> Args;
3369       for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3370         ParmVarDecl *PD = Constructor->getParamDecl(I);
3371         ExprResult ArgExpr =
3372             SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3373                                      VK_LValue, SourceLocation());
3374         if (ArgExpr.isInvalid())
3375           return true;
3376         Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
3377       }
3378 
3379       InitializationKind InitKind = InitializationKind::CreateDirect(
3380           Constructor->getLocation(), SourceLocation(), SourceLocation());
3381       InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
3382       BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3383       break;
3384     }
3385   }
3386   // Fall through.
3387   case IIK_Default: {
3388     InitializationKind InitKind
3389       = InitializationKind::CreateDefault(Constructor->getLocation());
3390     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3391     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3392     break;
3393   }
3394 
3395   case IIK_Move:
3396   case IIK_Copy: {
3397     bool Moving = ImplicitInitKind == IIK_Move;
3398     ParmVarDecl *Param = Constructor->getParamDecl(0);
3399     QualType ParamType = Param->getType().getNonReferenceType();
3400 
3401     Expr *CopyCtorArg =
3402       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3403                           SourceLocation(), Param, false,
3404                           Constructor->getLocation(), ParamType,
3405                           VK_LValue, nullptr);
3406 
3407     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3408 
3409     // Cast to the base class to avoid ambiguities.
3410     QualType ArgTy =
3411       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3412                                        ParamType.getQualifiers());
3413 
3414     if (Moving) {
3415       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3416     }
3417 
3418     CXXCastPath BasePath;
3419     BasePath.push_back(BaseSpec);
3420     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3421                                             CK_UncheckedDerivedToBase,
3422                                             Moving ? VK_XValue : VK_LValue,
3423                                             &BasePath).get();
3424 
3425     InitializationKind InitKind
3426       = InitializationKind::CreateDirect(Constructor->getLocation(),
3427                                          SourceLocation(), SourceLocation());
3428     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3429     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
3430     break;
3431   }
3432   }
3433 
3434   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
3435   if (BaseInit.isInvalid())
3436     return true;
3437 
3438   CXXBaseInit =
3439     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3440                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3441                                                         SourceLocation()),
3442                                              BaseSpec->isVirtual(),
3443                                              SourceLocation(),
3444                                              BaseInit.getAs<Expr>(),
3445                                              SourceLocation(),
3446                                              SourceLocation());
3447 
3448   return false;
3449 }
3450 
3451 static bool RefersToRValueRef(Expr *MemRef) {
3452   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3453   return Referenced->getType()->isRValueReferenceType();
3454 }
3455 
3456 static bool
3457 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3458                                ImplicitInitializerKind ImplicitInitKind,
3459                                FieldDecl *Field, IndirectFieldDecl *Indirect,
3460                                CXXCtorInitializer *&CXXMemberInit) {
3461   if (Field->isInvalidDecl())
3462     return true;
3463 
3464   SourceLocation Loc = Constructor->getLocation();
3465 
3466   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3467     bool Moving = ImplicitInitKind == IIK_Move;
3468     ParmVarDecl *Param = Constructor->getParamDecl(0);
3469     QualType ParamType = Param->getType().getNonReferenceType();
3470 
3471     // Suppress copying zero-width bitfields.
3472     if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3473       return false;
3474 
3475     Expr *MemberExprBase =
3476       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3477                           SourceLocation(), Param, false,
3478                           Loc, ParamType, VK_LValue, nullptr);
3479 
3480     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3481 
3482     if (Moving) {
3483       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3484     }
3485 
3486     // Build a reference to this field within the parameter.
3487     CXXScopeSpec SS;
3488     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3489                               Sema::LookupMemberName);
3490     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3491                                   : cast<ValueDecl>(Field), AS_public);
3492     MemberLookup.resolveKind();
3493     ExprResult CtorArg
3494       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
3495                                          ParamType, Loc,
3496                                          /*IsArrow=*/false,
3497                                          SS,
3498                                          /*TemplateKWLoc=*/SourceLocation(),
3499                                          /*FirstQualifierInScope=*/nullptr,
3500                                          MemberLookup,
3501                                          /*TemplateArgs=*/nullptr,
3502                                          /*S*/nullptr);
3503     if (CtorArg.isInvalid())
3504       return true;
3505 
3506     // C++11 [class.copy]p15:
3507     //   - if a member m has rvalue reference type T&&, it is direct-initialized
3508     //     with static_cast<T&&>(x.m);
3509     if (RefersToRValueRef(CtorArg.get())) {
3510       CtorArg = CastForMoving(SemaRef, CtorArg.get());
3511     }
3512 
3513     // When the field we are copying is an array, create index variables for
3514     // each dimension of the array. We use these index variables to subscript
3515     // the source array, and other clients (e.g., CodeGen) will perform the
3516     // necessary iteration with these index variables.
3517     SmallVector<VarDecl *, 4> IndexVariables;
3518     QualType BaseType = Field->getType();
3519     QualType SizeType = SemaRef.Context.getSizeType();
3520     bool InitializingArray = false;
3521     while (const ConstantArrayType *Array
3522                           = SemaRef.Context.getAsConstantArrayType(BaseType)) {
3523       InitializingArray = true;
3524       // Create the iteration variable for this array index.
3525       IdentifierInfo *IterationVarName = nullptr;
3526       {
3527         SmallString<8> Str;
3528         llvm::raw_svector_ostream OS(Str);
3529         OS << "__i" << IndexVariables.size();
3530         IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3531       }
3532       VarDecl *IterationVar
3533         = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
3534                           IterationVarName, SizeType,
3535                         SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
3536                           SC_None);
3537       IndexVariables.push_back(IterationVar);
3538 
3539       // Create a reference to the iteration variable.
3540       ExprResult IterationVarRef
3541         = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
3542       assert(!IterationVarRef.isInvalid() &&
3543              "Reference to invented variable cannot fail!");
3544       IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
3545       assert(!IterationVarRef.isInvalid() &&
3546              "Conversion of invented variable cannot fail!");
3547 
3548       // Subscript the array with this iteration variable.
3549       CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3550                                                         IterationVarRef.get(),
3551                                                         Loc);
3552       if (CtorArg.isInvalid())
3553         return true;
3554 
3555       BaseType = Array->getElementType();
3556     }
3557 
3558     // The array subscript expression is an lvalue, which is wrong for moving.
3559     if (Moving && InitializingArray)
3560       CtorArg = CastForMoving(SemaRef, CtorArg.get());
3561 
3562     // Construct the entity that we will be initializing. For an array, this
3563     // will be first element in the array, which may require several levels
3564     // of array-subscript entities.
3565     SmallVector<InitializedEntity, 4> Entities;
3566     Entities.reserve(1 + IndexVariables.size());
3567     if (Indirect)
3568       Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3569     else
3570       Entities.push_back(InitializedEntity::InitializeMember(Field));
3571     for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3572       Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3573                                                               0,
3574                                                               Entities.back()));
3575 
3576     // Direct-initialize to use the copy constructor.
3577     InitializationKind InitKind =
3578       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3579 
3580     Expr *CtorArgE = CtorArg.getAs<Expr>();
3581     InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
3582                                    CtorArgE);
3583 
3584     ExprResult MemberInit
3585       = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
3586                         MultiExprArg(&CtorArgE, 1));
3587     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3588     if (MemberInit.isInvalid())
3589       return true;
3590 
3591     if (Indirect) {
3592       assert(IndexVariables.size() == 0 &&
3593              "Indirect field improperly initialized");
3594       CXXMemberInit
3595         = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3596                                                    Loc, Loc,
3597                                                    MemberInit.getAs<Expr>(),
3598                                                    Loc);
3599     } else
3600       CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3601                                                  Loc, MemberInit.getAs<Expr>(),
3602                                                  Loc,
3603                                                  IndexVariables.data(),
3604                                                  IndexVariables.size());
3605     return false;
3606   }
3607 
3608   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3609          "Unhandled implicit init kind!");
3610 
3611   QualType FieldBaseElementType =
3612     SemaRef.Context.getBaseElementType(Field->getType());
3613 
3614   if (FieldBaseElementType->isRecordType()) {
3615     InitializedEntity InitEntity
3616       = Indirect? InitializedEntity::InitializeMember(Indirect)
3617                 : InitializedEntity::InitializeMember(Field);
3618     InitializationKind InitKind =
3619       InitializationKind::CreateDefault(Loc);
3620 
3621     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3622     ExprResult MemberInit =
3623       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3624 
3625     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3626     if (MemberInit.isInvalid())
3627       return true;
3628 
3629     if (Indirect)
3630       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3631                                                                Indirect, Loc,
3632                                                                Loc,
3633                                                                MemberInit.get(),
3634                                                                Loc);
3635     else
3636       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3637                                                                Field, Loc, Loc,
3638                                                                MemberInit.get(),
3639                                                                Loc);
3640     return false;
3641   }
3642 
3643   if (!Field->getParent()->isUnion()) {
3644     if (FieldBaseElementType->isReferenceType()) {
3645       SemaRef.Diag(Constructor->getLocation(),
3646                    diag::err_uninitialized_member_in_ctor)
3647       << (int)Constructor->isImplicit()
3648       << SemaRef.Context.getTagDeclType(Constructor->getParent())
3649       << 0 << Field->getDeclName();
3650       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3651       return true;
3652     }
3653 
3654     if (FieldBaseElementType.isConstQualified()) {
3655       SemaRef.Diag(Constructor->getLocation(),
3656                    diag::err_uninitialized_member_in_ctor)
3657       << (int)Constructor->isImplicit()
3658       << SemaRef.Context.getTagDeclType(Constructor->getParent())
3659       << 1 << Field->getDeclName();
3660       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3661       return true;
3662     }
3663   }
3664 
3665   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
3666       FieldBaseElementType->isObjCRetainableType() &&
3667       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3668       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
3669     // ARC:
3670     //   Default-initialize Objective-C pointers to NULL.
3671     CXXMemberInit
3672       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3673                                                  Loc, Loc,
3674                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3675                                                  Loc);
3676     return false;
3677   }
3678 
3679   // Nothing to initialize.
3680   CXXMemberInit = nullptr;
3681   return false;
3682 }
3683 
3684 namespace {
3685 struct BaseAndFieldInfo {
3686   Sema &S;
3687   CXXConstructorDecl *Ctor;
3688   bool AnyErrorsInInits;
3689   ImplicitInitializerKind IIK;
3690   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
3691   SmallVector<CXXCtorInitializer*, 8> AllToInit;
3692   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
3693 
3694   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3695     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
3696     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3697     if (Generated && Ctor->isCopyConstructor())
3698       IIK = IIK_Copy;
3699     else if (Generated && Ctor->isMoveConstructor())
3700       IIK = IIK_Move;
3701     else if (Ctor->getInheritedConstructor())
3702       IIK = IIK_Inherit;
3703     else
3704       IIK = IIK_Default;
3705   }
3706 
3707   bool isImplicitCopyOrMove() const {
3708     switch (IIK) {
3709     case IIK_Copy:
3710     case IIK_Move:
3711       return true;
3712 
3713     case IIK_Default:
3714     case IIK_Inherit:
3715       return false;
3716     }
3717 
3718     llvm_unreachable("Invalid ImplicitInitializerKind!");
3719   }
3720 
3721   bool addFieldInitializer(CXXCtorInitializer *Init) {
3722     AllToInit.push_back(Init);
3723 
3724     // Check whether this initializer makes the field "used".
3725     if (Init->getInit()->HasSideEffects(S.Context))
3726       S.UnusedPrivateFields.remove(Init->getAnyMember());
3727 
3728     return false;
3729   }
3730 
3731   bool isInactiveUnionMember(FieldDecl *Field) {
3732     RecordDecl *Record = Field->getParent();
3733     if (!Record->isUnion())
3734       return false;
3735 
3736     if (FieldDecl *Active =
3737             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
3738       return Active != Field->getCanonicalDecl();
3739 
3740     // In an implicit copy or move constructor, ignore any in-class initializer.
3741     if (isImplicitCopyOrMove())
3742       return true;
3743 
3744     // If there's no explicit initialization, the field is active only if it
3745     // has an in-class initializer...
3746     if (Field->hasInClassInitializer())
3747       return false;
3748     // ... or it's an anonymous struct or union whose class has an in-class
3749     // initializer.
3750     if (!Field->isAnonymousStructOrUnion())
3751       return true;
3752     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3753     return !FieldRD->hasInClassInitializer();
3754   }
3755 
3756   /// \brief Determine whether the given field is, or is within, a union member
3757   /// that is inactive (because there was an initializer given for a different
3758   /// member of the union, or because the union was not initialized at all).
3759   bool isWithinInactiveUnionMember(FieldDecl *Field,
3760                                    IndirectFieldDecl *Indirect) {
3761     if (!Indirect)
3762       return isInactiveUnionMember(Field);
3763 
3764     for (auto *C : Indirect->chain()) {
3765       FieldDecl *Field = dyn_cast<FieldDecl>(C);
3766       if (Field && isInactiveUnionMember(Field))
3767         return true;
3768     }
3769     return false;
3770   }
3771 };
3772 }
3773 
3774 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
3775 /// array type.
3776 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3777   if (T->isIncompleteArrayType())
3778     return true;
3779 
3780   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3781     if (!ArrayT->getSize())
3782       return true;
3783 
3784     T = ArrayT->getElementType();
3785   }
3786 
3787   return false;
3788 }
3789 
3790 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
3791                                     FieldDecl *Field,
3792                                     IndirectFieldDecl *Indirect = nullptr) {
3793   if (Field->isInvalidDecl())
3794     return false;
3795 
3796   // Overwhelmingly common case: we have a direct initializer for this field.
3797   if (CXXCtorInitializer *Init =
3798           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
3799     return Info.addFieldInitializer(Init);
3800 
3801   // C++11 [class.base.init]p8:
3802   //   if the entity is a non-static data member that has a
3803   //   brace-or-equal-initializer and either
3804   //   -- the constructor's class is a union and no other variant member of that
3805   //      union is designated by a mem-initializer-id or
3806   //   -- the constructor's class is not a union, and, if the entity is a member
3807   //      of an anonymous union, no other member of that union is designated by
3808   //      a mem-initializer-id,
3809   //   the entity is initialized as specified in [dcl.init].
3810   //
3811   // We also apply the same rules to handle anonymous structs within anonymous
3812   // unions.
3813   if (Info.isWithinInactiveUnionMember(Field, Indirect))
3814     return false;
3815 
3816   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
3817     ExprResult DIE =
3818         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
3819     if (DIE.isInvalid())
3820       return true;
3821     CXXCtorInitializer *Init;
3822     if (Indirect)
3823       Init = new (SemaRef.Context)
3824           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
3825                              SourceLocation(), DIE.get(), SourceLocation());
3826     else
3827       Init = new (SemaRef.Context)
3828           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
3829                              SourceLocation(), DIE.get(), SourceLocation());
3830     return Info.addFieldInitializer(Init);
3831   }
3832 
3833   // Don't initialize incomplete or zero-length arrays.
3834   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3835     return false;
3836 
3837   // Don't try to build an implicit initializer if there were semantic
3838   // errors in any of the initializers (and therefore we might be
3839   // missing some that the user actually wrote).
3840   if (Info.AnyErrorsInInits)
3841     return false;
3842 
3843   CXXCtorInitializer *Init = nullptr;
3844   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3845                                      Indirect, Init))
3846     return true;
3847 
3848   if (!Init)
3849     return false;
3850 
3851   return Info.addFieldInitializer(Init);
3852 }
3853 
3854 bool
3855 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3856                                CXXCtorInitializer *Initializer) {
3857   assert(Initializer->isDelegatingInitializer());
3858   Constructor->setNumCtorInitializers(1);
3859   CXXCtorInitializer **initializer =
3860     new (Context) CXXCtorInitializer*[1];
3861   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3862   Constructor->setCtorInitializers(initializer);
3863 
3864   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
3865     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
3866     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3867   }
3868 
3869   DelegatingCtorDecls.push_back(Constructor);
3870 
3871   DiagnoseUninitializedFields(*this, Constructor);
3872 
3873   return false;
3874 }
3875 
3876 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3877                                ArrayRef<CXXCtorInitializer *> Initializers) {
3878   if (Constructor->isDependentContext()) {
3879     // Just store the initializers as written, they will be checked during
3880     // instantiation.
3881     if (!Initializers.empty()) {
3882       Constructor->setNumCtorInitializers(Initializers.size());
3883       CXXCtorInitializer **baseOrMemberInitializers =
3884         new (Context) CXXCtorInitializer*[Initializers.size()];
3885       memcpy(baseOrMemberInitializers, Initializers.data(),
3886              Initializers.size() * sizeof(CXXCtorInitializer*));
3887       Constructor->setCtorInitializers(baseOrMemberInitializers);
3888     }
3889 
3890     // Let template instantiation know whether we had errors.
3891     if (AnyErrors)
3892       Constructor->setInvalidDecl();
3893 
3894     return false;
3895   }
3896 
3897   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
3898 
3899   // We need to build the initializer AST according to order of construction
3900   // and not what user specified in the Initializers list.
3901   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
3902   if (!ClassDecl)
3903     return true;
3904 
3905   bool HadError = false;
3906 
3907   for (unsigned i = 0; i < Initializers.size(); i++) {
3908     CXXCtorInitializer *Member = Initializers[i];
3909 
3910     if (Member->isBaseInitializer())
3911       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
3912     else {
3913       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
3914 
3915       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
3916         for (auto *C : F->chain()) {
3917           FieldDecl *FD = dyn_cast<FieldDecl>(C);
3918           if (FD && FD->getParent()->isUnion())
3919             Info.ActiveUnionMember.insert(std::make_pair(
3920                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3921         }
3922       } else if (FieldDecl *FD = Member->getMember()) {
3923         if (FD->getParent()->isUnion())
3924           Info.ActiveUnionMember.insert(std::make_pair(
3925               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3926       }
3927     }
3928   }
3929 
3930   // Keep track of the direct virtual bases.
3931   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3932   for (auto &I : ClassDecl->bases()) {
3933     if (I.isVirtual())
3934       DirectVBases.insert(&I);
3935   }
3936 
3937   // Push virtual bases before others.
3938   for (auto &VBase : ClassDecl->vbases()) {
3939     if (CXXCtorInitializer *Value
3940         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
3941       // [class.base.init]p7, per DR257:
3942       //   A mem-initializer where the mem-initializer-id names a virtual base
3943       //   class is ignored during execution of a constructor of any class that
3944       //   is not the most derived class.
3945       if (ClassDecl->isAbstract()) {
3946         // FIXME: Provide a fixit to remove the base specifier. This requires
3947         // tracking the location of the associated comma for a base specifier.
3948         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3949           << VBase.getType() << ClassDecl;
3950         DiagnoseAbstractType(ClassDecl);
3951       }
3952 
3953       Info.AllToInit.push_back(Value);
3954     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3955       // [class.base.init]p8, per DR257:
3956       //   If a given [...] base class is not named by a mem-initializer-id
3957       //   [...] and the entity is not a virtual base class of an abstract
3958       //   class, then [...] the entity is default-initialized.
3959       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
3960       CXXCtorInitializer *CXXBaseInit;
3961       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3962                                        &VBase, IsInheritedVirtualBase,
3963                                        CXXBaseInit)) {
3964         HadError = true;
3965         continue;
3966       }
3967 
3968       Info.AllToInit.push_back(CXXBaseInit);
3969     }
3970   }
3971 
3972   // Non-virtual bases.
3973   for (auto &Base : ClassDecl->bases()) {
3974     // Virtuals are in the virtual base list and already constructed.
3975     if (Base.isVirtual())
3976       continue;
3977 
3978     if (CXXCtorInitializer *Value
3979           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
3980       Info.AllToInit.push_back(Value);
3981     } else if (!AnyErrors) {
3982       CXXCtorInitializer *CXXBaseInit;
3983       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3984                                        &Base, /*IsInheritedVirtualBase=*/false,
3985                                        CXXBaseInit)) {
3986         HadError = true;
3987         continue;
3988       }
3989 
3990       Info.AllToInit.push_back(CXXBaseInit);
3991     }
3992   }
3993 
3994   // Fields.
3995   for (auto *Mem : ClassDecl->decls()) {
3996     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
3997       // C++ [class.bit]p2:
3998       //   A declaration for a bit-field that omits the identifier declares an
3999       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
4000       //   initialized.
4001       if (F->isUnnamedBitfield())
4002         continue;
4003 
4004       // If we're not generating the implicit copy/move constructor, then we'll
4005       // handle anonymous struct/union fields based on their individual
4006       // indirect fields.
4007       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4008         continue;
4009 
4010       if (CollectFieldInitializer(*this, Info, F))
4011         HadError = true;
4012       continue;
4013     }
4014 
4015     // Beyond this point, we only consider default initialization.
4016     if (Info.isImplicitCopyOrMove())
4017       continue;
4018 
4019     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4020       if (F->getType()->isIncompleteArrayType()) {
4021         assert(ClassDecl->hasFlexibleArrayMember() &&
4022                "Incomplete array type is not valid");
4023         continue;
4024       }
4025 
4026       // Initialize each field of an anonymous struct individually.
4027       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4028         HadError = true;
4029 
4030       continue;
4031     }
4032   }
4033 
4034   unsigned NumInitializers = Info.AllToInit.size();
4035   if (NumInitializers > 0) {
4036     Constructor->setNumCtorInitializers(NumInitializers);
4037     CXXCtorInitializer **baseOrMemberInitializers =
4038       new (Context) CXXCtorInitializer*[NumInitializers];
4039     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4040            NumInitializers * sizeof(CXXCtorInitializer*));
4041     Constructor->setCtorInitializers(baseOrMemberInitializers);
4042 
4043     // Constructors implicitly reference the base and member
4044     // destructors.
4045     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4046                                            Constructor->getParent());
4047   }
4048 
4049   return HadError;
4050 }
4051 
4052 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4053   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4054     const RecordDecl *RD = RT->getDecl();
4055     if (RD->isAnonymousStructOrUnion()) {
4056       for (auto *Field : RD->fields())
4057         PopulateKeysForFields(Field, IdealInits);
4058       return;
4059     }
4060   }
4061   IdealInits.push_back(Field->getCanonicalDecl());
4062 }
4063 
4064 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4065   return Context.getCanonicalType(BaseType).getTypePtr();
4066 }
4067 
4068 static const void *GetKeyForMember(ASTContext &Context,
4069                                    CXXCtorInitializer *Member) {
4070   if (!Member->isAnyMemberInitializer())
4071     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4072 
4073   return Member->getAnyMember()->getCanonicalDecl();
4074 }
4075 
4076 static void DiagnoseBaseOrMemInitializerOrder(
4077     Sema &SemaRef, const CXXConstructorDecl *Constructor,
4078     ArrayRef<CXXCtorInitializer *> Inits) {
4079   if (Constructor->getDeclContext()->isDependentContext())
4080     return;
4081 
4082   // Don't check initializers order unless the warning is enabled at the
4083   // location of at least one initializer.
4084   bool ShouldCheckOrder = false;
4085   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4086     CXXCtorInitializer *Init = Inits[InitIndex];
4087     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4088                                  Init->getSourceLocation())) {
4089       ShouldCheckOrder = true;
4090       break;
4091     }
4092   }
4093   if (!ShouldCheckOrder)
4094     return;
4095 
4096   // Build the list of bases and members in the order that they'll
4097   // actually be initialized.  The explicit initializers should be in
4098   // this same order but may be missing things.
4099   SmallVector<const void*, 32> IdealInitKeys;
4100 
4101   const CXXRecordDecl *ClassDecl = Constructor->getParent();
4102 
4103   // 1. Virtual bases.
4104   for (const auto &VBase : ClassDecl->vbases())
4105     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4106 
4107   // 2. Non-virtual bases.
4108   for (const auto &Base : ClassDecl->bases()) {
4109     if (Base.isVirtual())
4110       continue;
4111     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4112   }
4113 
4114   // 3. Direct fields.
4115   for (auto *Field : ClassDecl->fields()) {
4116     if (Field->isUnnamedBitfield())
4117       continue;
4118 
4119     PopulateKeysForFields(Field, IdealInitKeys);
4120   }
4121 
4122   unsigned NumIdealInits = IdealInitKeys.size();
4123   unsigned IdealIndex = 0;
4124 
4125   CXXCtorInitializer *PrevInit = nullptr;
4126   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4127     CXXCtorInitializer *Init = Inits[InitIndex];
4128     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4129 
4130     // Scan forward to try to find this initializer in the idealized
4131     // initializers list.
4132     for (; IdealIndex != NumIdealInits; ++IdealIndex)
4133       if (InitKey == IdealInitKeys[IdealIndex])
4134         break;
4135 
4136     // If we didn't find this initializer, it must be because we
4137     // scanned past it on a previous iteration.  That can only
4138     // happen if we're out of order;  emit a warning.
4139     if (IdealIndex == NumIdealInits && PrevInit) {
4140       Sema::SemaDiagnosticBuilder D =
4141         SemaRef.Diag(PrevInit->getSourceLocation(),
4142                      diag::warn_initializer_out_of_order);
4143 
4144       if (PrevInit->isAnyMemberInitializer())
4145         D << 0 << PrevInit->getAnyMember()->getDeclName();
4146       else
4147         D << 1 << PrevInit->getTypeSourceInfo()->getType();
4148 
4149       if (Init->isAnyMemberInitializer())
4150         D << 0 << Init->getAnyMember()->getDeclName();
4151       else
4152         D << 1 << Init->getTypeSourceInfo()->getType();
4153 
4154       // Move back to the initializer's location in the ideal list.
4155       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4156         if (InitKey == IdealInitKeys[IdealIndex])
4157           break;
4158 
4159       assert(IdealIndex < NumIdealInits &&
4160              "initializer not found in initializer list");
4161     }
4162 
4163     PrevInit = Init;
4164   }
4165 }
4166 
4167 namespace {
4168 bool CheckRedundantInit(Sema &S,
4169                         CXXCtorInitializer *Init,
4170                         CXXCtorInitializer *&PrevInit) {
4171   if (!PrevInit) {
4172     PrevInit = Init;
4173     return false;
4174   }
4175 
4176   if (FieldDecl *Field = Init->getAnyMember())
4177     S.Diag(Init->getSourceLocation(),
4178            diag::err_multiple_mem_initialization)
4179       << Field->getDeclName()
4180       << Init->getSourceRange();
4181   else {
4182     const Type *BaseClass = Init->getBaseClass();
4183     assert(BaseClass && "neither field nor base");
4184     S.Diag(Init->getSourceLocation(),
4185            diag::err_multiple_base_initialization)
4186       << QualType(BaseClass, 0)
4187       << Init->getSourceRange();
4188   }
4189   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4190     << 0 << PrevInit->getSourceRange();
4191 
4192   return true;
4193 }
4194 
4195 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
4196 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4197 
4198 bool CheckRedundantUnionInit(Sema &S,
4199                              CXXCtorInitializer *Init,
4200                              RedundantUnionMap &Unions) {
4201   FieldDecl *Field = Init->getAnyMember();
4202   RecordDecl *Parent = Field->getParent();
4203   NamedDecl *Child = Field;
4204 
4205   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
4206     if (Parent->isUnion()) {
4207       UnionEntry &En = Unions[Parent];
4208       if (En.first && En.first != Child) {
4209         S.Diag(Init->getSourceLocation(),
4210                diag::err_multiple_mem_union_initialization)
4211           << Field->getDeclName()
4212           << Init->getSourceRange();
4213         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4214           << 0 << En.second->getSourceRange();
4215         return true;
4216       }
4217       if (!En.first) {
4218         En.first = Child;
4219         En.second = Init;
4220       }
4221       if (!Parent->isAnonymousStructOrUnion())
4222         return false;
4223     }
4224 
4225     Child = Parent;
4226     Parent = cast<RecordDecl>(Parent->getDeclContext());
4227   }
4228 
4229   return false;
4230 }
4231 }
4232 
4233 /// ActOnMemInitializers - Handle the member initializers for a constructor.
4234 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
4235                                 SourceLocation ColonLoc,
4236                                 ArrayRef<CXXCtorInitializer*> MemInits,
4237                                 bool AnyErrors) {
4238   if (!ConstructorDecl)
4239     return;
4240 
4241   AdjustDeclIfTemplate(ConstructorDecl);
4242 
4243   CXXConstructorDecl *Constructor
4244     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
4245 
4246   if (!Constructor) {
4247     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4248     return;
4249   }
4250 
4251   // Mapping for the duplicate initializers check.
4252   // For member initializers, this is keyed with a FieldDecl*.
4253   // For base initializers, this is keyed with a Type*.
4254   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
4255 
4256   // Mapping for the inconsistent anonymous-union initializers check.
4257   RedundantUnionMap MemberUnions;
4258 
4259   bool HadError = false;
4260   for (unsigned i = 0; i < MemInits.size(); i++) {
4261     CXXCtorInitializer *Init = MemInits[i];
4262 
4263     // Set the source order index.
4264     Init->setSourceOrder(i);
4265 
4266     if (Init->isAnyMemberInitializer()) {
4267       const void *Key = GetKeyForMember(Context, Init);
4268       if (CheckRedundantInit(*this, Init, Members[Key]) ||
4269           CheckRedundantUnionInit(*this, Init, MemberUnions))
4270         HadError = true;
4271     } else if (Init->isBaseInitializer()) {
4272       const void *Key = GetKeyForMember(Context, Init);
4273       if (CheckRedundantInit(*this, Init, Members[Key]))
4274         HadError = true;
4275     } else {
4276       assert(Init->isDelegatingInitializer());
4277       // This must be the only initializer
4278       if (MemInits.size() != 1) {
4279         Diag(Init->getSourceLocation(),
4280              diag::err_delegating_initializer_alone)
4281           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
4282         // We will treat this as being the only initializer.
4283       }
4284       SetDelegatingInitializer(Constructor, MemInits[i]);
4285       // Return immediately as the initializer is set.
4286       return;
4287     }
4288   }
4289 
4290   if (HadError)
4291     return;
4292 
4293   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
4294 
4295   SetCtorInitializers(Constructor, AnyErrors, MemInits);
4296 
4297   DiagnoseUninitializedFields(*this, Constructor);
4298 }
4299 
4300 void
4301 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
4302                                              CXXRecordDecl *ClassDecl) {
4303   // Ignore dependent contexts. Also ignore unions, since their members never
4304   // have destructors implicitly called.
4305   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
4306     return;
4307 
4308   // FIXME: all the access-control diagnostics are positioned on the
4309   // field/base declaration.  That's probably good; that said, the
4310   // user might reasonably want to know why the destructor is being
4311   // emitted, and we currently don't say.
4312 
4313   // Non-static data members.
4314   for (auto *Field : ClassDecl->fields()) {
4315     if (Field->isInvalidDecl())
4316       continue;
4317 
4318     // Don't destroy incomplete or zero-length arrays.
4319     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
4320       continue;
4321 
4322     QualType FieldType = Context.getBaseElementType(Field->getType());
4323 
4324     const RecordType* RT = FieldType->getAs<RecordType>();
4325     if (!RT)
4326       continue;
4327 
4328     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4329     if (FieldClassDecl->isInvalidDecl())
4330       continue;
4331     if (FieldClassDecl->hasIrrelevantDestructor())
4332       continue;
4333     // The destructor for an implicit anonymous union member is never invoked.
4334     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4335       continue;
4336 
4337     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
4338     assert(Dtor && "No dtor found for FieldClassDecl!");
4339     CheckDestructorAccess(Field->getLocation(), Dtor,
4340                           PDiag(diag::err_access_dtor_field)
4341                             << Field->getDeclName()
4342                             << FieldType);
4343 
4344     MarkFunctionReferenced(Location, Dtor);
4345     DiagnoseUseOfDecl(Dtor, Location);
4346   }
4347 
4348   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4349 
4350   // Bases.
4351   for (const auto &Base : ClassDecl->bases()) {
4352     // Bases are always records in a well-formed non-dependent class.
4353     const RecordType *RT = Base.getType()->getAs<RecordType>();
4354 
4355     // Remember direct virtual bases.
4356     if (Base.isVirtual())
4357       DirectVirtualBases.insert(RT);
4358 
4359     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4360     // If our base class is invalid, we probably can't get its dtor anyway.
4361     if (BaseClassDecl->isInvalidDecl())
4362       continue;
4363     if (BaseClassDecl->hasIrrelevantDestructor())
4364       continue;
4365 
4366     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4367     assert(Dtor && "No dtor found for BaseClassDecl!");
4368 
4369     // FIXME: caret should be on the start of the class name
4370     CheckDestructorAccess(Base.getLocStart(), Dtor,
4371                           PDiag(diag::err_access_dtor_base)
4372                             << Base.getType()
4373                             << Base.getSourceRange(),
4374                           Context.getTypeDeclType(ClassDecl));
4375 
4376     MarkFunctionReferenced(Location, Dtor);
4377     DiagnoseUseOfDecl(Dtor, Location);
4378   }
4379 
4380   // Virtual bases.
4381   for (const auto &VBase : ClassDecl->vbases()) {
4382     // Bases are always records in a well-formed non-dependent class.
4383     const RecordType *RT = VBase.getType()->castAs<RecordType>();
4384 
4385     // Ignore direct virtual bases.
4386     if (DirectVirtualBases.count(RT))
4387       continue;
4388 
4389     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4390     // If our base class is invalid, we probably can't get its dtor anyway.
4391     if (BaseClassDecl->isInvalidDecl())
4392       continue;
4393     if (BaseClassDecl->hasIrrelevantDestructor())
4394       continue;
4395 
4396     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4397     assert(Dtor && "No dtor found for BaseClassDecl!");
4398     if (CheckDestructorAccess(
4399             ClassDecl->getLocation(), Dtor,
4400             PDiag(diag::err_access_dtor_vbase)
4401                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
4402             Context.getTypeDeclType(ClassDecl)) ==
4403         AR_accessible) {
4404       CheckDerivedToBaseConversion(
4405           Context.getTypeDeclType(ClassDecl), VBase.getType(),
4406           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4407           SourceRange(), DeclarationName(), nullptr);
4408     }
4409 
4410     MarkFunctionReferenced(Location, Dtor);
4411     DiagnoseUseOfDecl(Dtor, Location);
4412   }
4413 }
4414 
4415 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
4416   if (!CDtorDecl)
4417     return;
4418 
4419   if (CXXConstructorDecl *Constructor
4420       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
4421     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
4422     DiagnoseUninitializedFields(*this, Constructor);
4423   }
4424 }
4425 
4426 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
4427   if (!getLangOpts().CPlusPlus)
4428     return false;
4429 
4430   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
4431   if (!RD)
4432     return false;
4433 
4434   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
4435   // class template specialization here, but doing so breaks a lot of code.
4436 
4437   // We can't answer whether something is abstract until it has a
4438   // definition. If it's currently being defined, we'll walk back
4439   // over all the declarations when we have a full definition.
4440   const CXXRecordDecl *Def = RD->getDefinition();
4441   if (!Def || Def->isBeingDefined())
4442     return false;
4443 
4444   return RD->isAbstract();
4445 }
4446 
4447 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4448                                   TypeDiagnoser &Diagnoser) {
4449   if (!isAbstractType(Loc, T))
4450     return false;
4451 
4452   T = Context.getBaseElementType(T);
4453   Diagnoser.diagnose(*this, Loc, T);
4454   DiagnoseAbstractType(T->getAsCXXRecordDecl());
4455   return true;
4456 }
4457 
4458 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4459   // Check if we've already emitted the list of pure virtual functions
4460   // for this class.
4461   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
4462     return;
4463 
4464   // If the diagnostic is suppressed, don't emit the notes. We're only
4465   // going to emit them once, so try to attach them to a diagnostic we're
4466   // actually going to show.
4467   if (Diags.isLastDiagnosticIgnored())
4468     return;
4469 
4470   CXXFinalOverriderMap FinalOverriders;
4471   RD->getFinalOverriders(FinalOverriders);
4472 
4473   // Keep a set of seen pure methods so we won't diagnose the same method
4474   // more than once.
4475   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4476 
4477   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4478                                    MEnd = FinalOverriders.end();
4479        M != MEnd;
4480        ++M) {
4481     for (OverridingMethods::iterator SO = M->second.begin(),
4482                                   SOEnd = M->second.end();
4483          SO != SOEnd; ++SO) {
4484       // C++ [class.abstract]p4:
4485       //   A class is abstract if it contains or inherits at least one
4486       //   pure virtual function for which the final overrider is pure
4487       //   virtual.
4488 
4489       //
4490       if (SO->second.size() != 1)
4491         continue;
4492 
4493       if (!SO->second.front().Method->isPure())
4494         continue;
4495 
4496       if (!SeenPureMethods.insert(SO->second.front().Method).second)
4497         continue;
4498 
4499       Diag(SO->second.front().Method->getLocation(),
4500            diag::note_pure_virtual_function)
4501         << SO->second.front().Method->getDeclName() << RD->getDeclName();
4502     }
4503   }
4504 
4505   if (!PureVirtualClassDiagSet)
4506     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4507   PureVirtualClassDiagSet->insert(RD);
4508 }
4509 
4510 namespace {
4511 struct AbstractUsageInfo {
4512   Sema &S;
4513   CXXRecordDecl *Record;
4514   CanQualType AbstractType;
4515   bool Invalid;
4516 
4517   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4518     : S(S), Record(Record),
4519       AbstractType(S.Context.getCanonicalType(
4520                    S.Context.getTypeDeclType(Record))),
4521       Invalid(false) {}
4522 
4523   void DiagnoseAbstractType() {
4524     if (Invalid) return;
4525     S.DiagnoseAbstractType(Record);
4526     Invalid = true;
4527   }
4528 
4529   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4530 };
4531 
4532 struct CheckAbstractUsage {
4533   AbstractUsageInfo &Info;
4534   const NamedDecl *Ctx;
4535 
4536   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4537     : Info(Info), Ctx(Ctx) {}
4538 
4539   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4540     switch (TL.getTypeLocClass()) {
4541 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4542 #define TYPELOC(CLASS, PARENT) \
4543     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
4544 #include "clang/AST/TypeLocNodes.def"
4545     }
4546   }
4547 
4548   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4549     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
4550     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4551       if (!TL.getParam(I))
4552         continue;
4553 
4554       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
4555       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
4556     }
4557   }
4558 
4559   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4560     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4561   }
4562 
4563   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4564     // Visit the type parameters from a permissive context.
4565     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4566       TemplateArgumentLoc TAL = TL.getArgLoc(I);
4567       if (TAL.getArgument().getKind() == TemplateArgument::Type)
4568         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4569           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4570       // TODO: other template argument types?
4571     }
4572   }
4573 
4574   // Visit pointee types from a permissive context.
4575 #define CheckPolymorphic(Type) \
4576   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4577     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4578   }
4579   CheckPolymorphic(PointerTypeLoc)
4580   CheckPolymorphic(ReferenceTypeLoc)
4581   CheckPolymorphic(MemberPointerTypeLoc)
4582   CheckPolymorphic(BlockPointerTypeLoc)
4583   CheckPolymorphic(AtomicTypeLoc)
4584 
4585   /// Handle all the types we haven't given a more specific
4586   /// implementation for above.
4587   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4588     // Every other kind of type that we haven't called out already
4589     // that has an inner type is either (1) sugar or (2) contains that
4590     // inner type in some way as a subobject.
4591     if (TypeLoc Next = TL.getNextTypeLoc())
4592       return Visit(Next, Sel);
4593 
4594     // If there's no inner type and we're in a permissive context,
4595     // don't diagnose.
4596     if (Sel == Sema::AbstractNone) return;
4597 
4598     // Check whether the type matches the abstract type.
4599     QualType T = TL.getType();
4600     if (T->isArrayType()) {
4601       Sel = Sema::AbstractArrayType;
4602       T = Info.S.Context.getBaseElementType(T);
4603     }
4604     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4605     if (CT != Info.AbstractType) return;
4606 
4607     // It matched; do some magic.
4608     if (Sel == Sema::AbstractArrayType) {
4609       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4610         << T << TL.getSourceRange();
4611     } else {
4612       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4613         << Sel << T << TL.getSourceRange();
4614     }
4615     Info.DiagnoseAbstractType();
4616   }
4617 };
4618 
4619 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4620                                   Sema::AbstractDiagSelID Sel) {
4621   CheckAbstractUsage(*this, D).Visit(TL, Sel);
4622 }
4623 
4624 }
4625 
4626 /// Check for invalid uses of an abstract type in a method declaration.
4627 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4628                                     CXXMethodDecl *MD) {
4629   // No need to do the check on definitions, which require that
4630   // the return/param types be complete.
4631   if (MD->doesThisDeclarationHaveABody())
4632     return;
4633 
4634   // For safety's sake, just ignore it if we don't have type source
4635   // information.  This should never happen for non-implicit methods,
4636   // but...
4637   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4638     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4639 }
4640 
4641 /// Check for invalid uses of an abstract type within a class definition.
4642 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4643                                     CXXRecordDecl *RD) {
4644   for (auto *D : RD->decls()) {
4645     if (D->isImplicit()) continue;
4646 
4647     // Methods and method templates.
4648     if (isa<CXXMethodDecl>(D)) {
4649       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4650     } else if (isa<FunctionTemplateDecl>(D)) {
4651       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4652       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4653 
4654     // Fields and static variables.
4655     } else if (isa<FieldDecl>(D)) {
4656       FieldDecl *FD = cast<FieldDecl>(D);
4657       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4658         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4659     } else if (isa<VarDecl>(D)) {
4660       VarDecl *VD = cast<VarDecl>(D);
4661       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4662         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4663 
4664     // Nested classes and class templates.
4665     } else if (isa<CXXRecordDecl>(D)) {
4666       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4667     } else if (isa<ClassTemplateDecl>(D)) {
4668       CheckAbstractClassUsage(Info,
4669                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4670     }
4671   }
4672 }
4673 
4674 static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) {
4675   Attr *ClassAttr = getDLLAttr(Class);
4676   if (!ClassAttr)
4677     return;
4678 
4679   assert(ClassAttr->getKind() == attr::DLLExport);
4680 
4681   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
4682 
4683   if (TSK == TSK_ExplicitInstantiationDeclaration)
4684     // Don't go any further if this is just an explicit instantiation
4685     // declaration.
4686     return;
4687 
4688   for (Decl *Member : Class->decls()) {
4689     auto *MD = dyn_cast<CXXMethodDecl>(Member);
4690     if (!MD)
4691       continue;
4692 
4693     if (Member->getAttr<DLLExportAttr>()) {
4694       if (MD->isUserProvided()) {
4695         // Instantiate non-default class member functions ...
4696 
4697         // .. except for certain kinds of template specializations.
4698         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
4699           continue;
4700 
4701         S.MarkFunctionReferenced(Class->getLocation(), MD);
4702 
4703         // The function will be passed to the consumer when its definition is
4704         // encountered.
4705       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4706                  MD->isCopyAssignmentOperator() ||
4707                  MD->isMoveAssignmentOperator()) {
4708         // Synthesize and instantiate non-trivial implicit methods, explicitly
4709         // defaulted methods, and the copy and move assignment operators. The
4710         // latter are exported even if they are trivial, because the address of
4711         // an operator can be taken and should compare equal accross libraries.
4712         DiagnosticErrorTrap Trap(S.Diags);
4713         S.MarkFunctionReferenced(Class->getLocation(), MD);
4714         if (Trap.hasErrorOccurred()) {
4715           S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
4716               << Class->getName() << !S.getLangOpts().CPlusPlus11;
4717           break;
4718         }
4719 
4720         // There is no later point when we will see the definition of this
4721         // function, so pass it to the consumer now.
4722         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
4723       }
4724     }
4725   }
4726 }
4727 
4728 /// \brief Check class-level dllimport/dllexport attribute.
4729 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
4730   Attr *ClassAttr = getDLLAttr(Class);
4731 
4732   // MSVC inherits DLL attributes to partial class template specializations.
4733   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
4734     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
4735       if (Attr *TemplateAttr =
4736               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
4737         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
4738         A->setInherited(true);
4739         ClassAttr = A;
4740       }
4741     }
4742   }
4743 
4744   if (!ClassAttr)
4745     return;
4746 
4747   if (!Class->isExternallyVisible()) {
4748     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
4749         << Class << ClassAttr;
4750     return;
4751   }
4752 
4753   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4754       !ClassAttr->isInherited()) {
4755     // Diagnose dll attributes on members of class with dll attribute.
4756     for (Decl *Member : Class->decls()) {
4757       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
4758         continue;
4759       InheritableAttr *MemberAttr = getDLLAttr(Member);
4760       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
4761         continue;
4762 
4763       Diag(MemberAttr->getLocation(),
4764              diag::err_attribute_dll_member_of_dll_class)
4765           << MemberAttr << ClassAttr;
4766       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
4767       Member->setInvalidDecl();
4768     }
4769   }
4770 
4771   if (Class->getDescribedClassTemplate())
4772     // Don't inherit dll attribute until the template is instantiated.
4773     return;
4774 
4775   // The class is either imported or exported.
4776   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4777   const bool ClassImported = !ClassExported;
4778 
4779   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
4780 
4781   // Ignore explicit dllexport on explicit class template instantiation declarations.
4782   if (ClassExported && !ClassAttr->isInherited() &&
4783       TSK == TSK_ExplicitInstantiationDeclaration) {
4784     Class->dropAttr<DLLExportAttr>();
4785     return;
4786   }
4787 
4788   // Force declaration of implicit members so they can inherit the attribute.
4789   ForceDeclarationOfImplicitMembers(Class);
4790 
4791   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4792   // seem to be true in practice?
4793 
4794   for (Decl *Member : Class->decls()) {
4795     VarDecl *VD = dyn_cast<VarDecl>(Member);
4796     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4797 
4798     // Only methods and static fields inherit the attributes.
4799     if (!VD && !MD)
4800       continue;
4801 
4802     if (MD) {
4803       // Don't process deleted methods.
4804       if (MD->isDeleted())
4805         continue;
4806 
4807       if (MD->isInlined()) {
4808         // MinGW does not import or export inline methods.
4809         if (!Context.getTargetInfo().getCXXABI().isMicrosoft())
4810           continue;
4811 
4812         // MSVC versions before 2015 don't export the move assignment operators,
4813         // so don't attempt to import them if we have a definition.
4814         if (ClassImported && MD->isMoveAssignmentOperator() &&
4815             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
4816           continue;
4817       }
4818     }
4819 
4820     if (!cast<NamedDecl>(Member)->isExternallyVisible())
4821       continue;
4822 
4823     if (!getDLLAttr(Member)) {
4824       auto *NewAttr =
4825           cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
4826       NewAttr->setInherited(true);
4827       Member->addAttr(NewAttr);
4828     }
4829   }
4830 
4831   if (ClassExported)
4832     DelayedDllExportClasses.push_back(Class);
4833 }
4834 
4835 /// \brief Perform propagation of DLL attributes from a derived class to a
4836 /// templated base class for MS compatibility.
4837 void Sema::propagateDLLAttrToBaseClassTemplate(
4838     CXXRecordDecl *Class, Attr *ClassAttr,
4839     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
4840   if (getDLLAttr(
4841           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
4842     // If the base class template has a DLL attribute, don't try to change it.
4843     return;
4844   }
4845 
4846   auto TSK = BaseTemplateSpec->getSpecializationKind();
4847   if (!getDLLAttr(BaseTemplateSpec) &&
4848       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
4849        TSK == TSK_ImplicitInstantiation)) {
4850     // The template hasn't been instantiated yet (or it has, but only as an
4851     // explicit instantiation declaration or implicit instantiation, which means
4852     // we haven't codegenned any members yet), so propagate the attribute.
4853     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
4854     NewAttr->setInherited(true);
4855     BaseTemplateSpec->addAttr(NewAttr);
4856 
4857     // If the template is already instantiated, checkDLLAttributeRedeclaration()
4858     // needs to be run again to work see the new attribute. Otherwise this will
4859     // get run whenever the template is instantiated.
4860     if (TSK != TSK_Undeclared)
4861       checkClassLevelDLLAttribute(BaseTemplateSpec);
4862 
4863     return;
4864   }
4865 
4866   if (getDLLAttr(BaseTemplateSpec)) {
4867     // The template has already been specialized or instantiated with an
4868     // attribute, explicitly or through propagation. We should not try to change
4869     // it.
4870     return;
4871   }
4872 
4873   // The template was previously instantiated or explicitly specialized without
4874   // a dll attribute, It's too late for us to add an attribute, so warn that
4875   // this is unsupported.
4876   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
4877       << BaseTemplateSpec->isExplicitSpecialization();
4878   Diag(ClassAttr->getLocation(), diag::note_attribute);
4879   if (BaseTemplateSpec->isExplicitSpecialization()) {
4880     Diag(BaseTemplateSpec->getLocation(),
4881            diag::note_template_class_explicit_specialization_was_here)
4882         << BaseTemplateSpec;
4883   } else {
4884     Diag(BaseTemplateSpec->getPointOfInstantiation(),
4885            diag::note_template_class_instantiation_was_here)
4886         << BaseTemplateSpec;
4887   }
4888 }
4889 
4890 /// \brief Perform semantic checks on a class definition that has been
4891 /// completing, introducing implicitly-declared members, checking for
4892 /// abstract types, etc.
4893 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
4894   if (!Record)
4895     return;
4896 
4897   if (Record->isAbstract() && !Record->isInvalidDecl()) {
4898     AbstractUsageInfo Info(*this, Record);
4899     CheckAbstractClassUsage(Info, Record);
4900   }
4901 
4902   // If this is not an aggregate type and has no user-declared constructor,
4903   // complain about any non-static data members of reference or const scalar
4904   // type, since they will never get initializers.
4905   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
4906       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4907       !Record->isLambda()) {
4908     bool Complained = false;
4909     for (const auto *F : Record->fields()) {
4910       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
4911         continue;
4912 
4913       if (F->getType()->isReferenceType() ||
4914           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
4915         if (!Complained) {
4916           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4917             << Record->getTagKind() << Record;
4918           Complained = true;
4919         }
4920 
4921         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4922           << F->getType()->isReferenceType()
4923           << F->getDeclName();
4924       }
4925     }
4926   }
4927 
4928   if (Record->getIdentifier()) {
4929     // C++ [class.mem]p13:
4930     //   If T is the name of a class, then each of the following shall have a
4931     //   name different from T:
4932     //     - every member of every anonymous union that is a member of class T.
4933     //
4934     // C++ [class.mem]p14:
4935     //   In addition, if class T has a user-declared constructor (12.1), every
4936     //   non-static data member of class T shall have a name different from T.
4937     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4938     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4939          ++I) {
4940       NamedDecl *D = *I;
4941       if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4942           isa<IndirectFieldDecl>(D)) {
4943         Diag(D->getLocation(), diag::err_member_name_of_class)
4944           << D->getDeclName();
4945         break;
4946       }
4947     }
4948   }
4949 
4950   // Warn if the class has virtual methods but non-virtual public destructor.
4951   if (Record->isPolymorphic() && !Record->isDependentType()) {
4952     CXXDestructorDecl *dtor = Record->getDestructor();
4953     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4954         !Record->hasAttr<FinalAttr>())
4955       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4956            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4957   }
4958 
4959   if (Record->isAbstract()) {
4960     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4961       Diag(Record->getLocation(), diag::warn_abstract_final_class)
4962         << FA->isSpelledAsSealed();
4963       DiagnoseAbstractType(Record);
4964     }
4965   }
4966 
4967   bool HasMethodWithOverrideControl = false,
4968        HasOverridingMethodWithoutOverrideControl = false;
4969   if (!Record->isDependentType()) {
4970     for (auto *M : Record->methods()) {
4971       // See if a method overloads virtual methods in a base
4972       // class without overriding any.
4973       if (!M->isStatic())
4974         DiagnoseHiddenVirtualMethods(M);
4975       if (M->hasAttr<OverrideAttr>())
4976         HasMethodWithOverrideControl = true;
4977       else if (M->size_overridden_methods() > 0)
4978         HasOverridingMethodWithoutOverrideControl = true;
4979       // Check whether the explicitly-defaulted special members are valid.
4980       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4981         CheckExplicitlyDefaultedSpecialMember(M);
4982 
4983       // For an explicitly defaulted or deleted special member, we defer
4984       // determining triviality until the class is complete. That time is now!
4985       if (!M->isImplicit() && !M->isUserProvided()) {
4986         CXXSpecialMember CSM = getSpecialMember(M);
4987         if (CSM != CXXInvalid) {
4988           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
4989 
4990           // Inform the class that we've finished declaring this member.
4991           Record->finishedDefaultedOrDeletedMember(M);
4992         }
4993       }
4994     }
4995   }
4996 
4997   if (HasMethodWithOverrideControl &&
4998       HasOverridingMethodWithoutOverrideControl) {
4999     // At least one method has the 'override' control declared.
5000     // Diagnose all other overridden methods which do not have 'override' specified on them.
5001     for (auto *M : Record->methods())
5002       DiagnoseAbsenceOfOverrideControl(M);
5003   }
5004 
5005   // ms_struct is a request to use the same ABI rules as MSVC.  Check
5006   // whether this class uses any C++ features that are implemented
5007   // completely differently in MSVC, and if so, emit a diagnostic.
5008   // That diagnostic defaults to an error, but we allow projects to
5009   // map it down to a warning (or ignore it).  It's a fairly common
5010   // practice among users of the ms_struct pragma to mass-annotate
5011   // headers, sweeping up a bunch of types that the project doesn't
5012   // really rely on MSVC-compatible layout for.  We must therefore
5013   // support "ms_struct except for C++ stuff" as a secondary ABI.
5014   if (Record->isMsStruct(Context) &&
5015       (Record->isPolymorphic() || Record->getNumBases())) {
5016     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
5017   }
5018 
5019   // Declare inheriting constructors. We do this eagerly here because:
5020   // - The standard requires an eager diagnostic for conflicting inheriting
5021   //   constructors from different classes.
5022   // - The lazy declaration of the other implicit constructors is so as to not
5023   //   waste space and performance on classes that are not meant to be
5024   //   instantiated (e.g. meta-functions). This doesn't apply to classes that
5025   //   have inheriting constructors.
5026   DeclareInheritingConstructors(Record);
5027 
5028   checkClassLevelDLLAttribute(Record);
5029 }
5030 
5031 /// Look up the special member function that would be called by a special
5032 /// member function for a subobject of class type.
5033 ///
5034 /// \param Class The class type of the subobject.
5035 /// \param CSM The kind of special member function.
5036 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
5037 /// \param ConstRHS True if this is a copy operation with a const object
5038 ///        on its RHS, that is, if the argument to the outer special member
5039 ///        function is 'const' and this is not a field marked 'mutable'.
5040 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
5041     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
5042     unsigned FieldQuals, bool ConstRHS) {
5043   unsigned LHSQuals = 0;
5044   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
5045     LHSQuals = FieldQuals;
5046 
5047   unsigned RHSQuals = FieldQuals;
5048   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
5049     RHSQuals = 0;
5050   else if (ConstRHS)
5051     RHSQuals |= Qualifiers::Const;
5052 
5053   return S.LookupSpecialMember(Class, CSM,
5054                                RHSQuals & Qualifiers::Const,
5055                                RHSQuals & Qualifiers::Volatile,
5056                                false,
5057                                LHSQuals & Qualifiers::Const,
5058                                LHSQuals & Qualifiers::Volatile);
5059 }
5060 
5061 /// Is the special member function which would be selected to perform the
5062 /// specified operation on the specified class type a constexpr constructor?
5063 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5064                                      Sema::CXXSpecialMember CSM,
5065                                      unsigned Quals, bool ConstRHS) {
5066   Sema::SpecialMemberOverloadResult *SMOR =
5067       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
5068   if (!SMOR || !SMOR->getMethod())
5069     // A constructor we wouldn't select can't be "involved in initializing"
5070     // anything.
5071     return true;
5072   return SMOR->getMethod()->isConstexpr();
5073 }
5074 
5075 /// Determine whether the specified special member function would be constexpr
5076 /// if it were implicitly defined.
5077 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5078                                               Sema::CXXSpecialMember CSM,
5079                                               bool ConstArg) {
5080   if (!S.getLangOpts().CPlusPlus11)
5081     return false;
5082 
5083   // C++11 [dcl.constexpr]p4:
5084   // In the definition of a constexpr constructor [...]
5085   bool Ctor = true;
5086   switch (CSM) {
5087   case Sema::CXXDefaultConstructor:
5088     // Since default constructor lookup is essentially trivial (and cannot
5089     // involve, for instance, template instantiation), we compute whether a
5090     // defaulted default constructor is constexpr directly within CXXRecordDecl.
5091     //
5092     // This is important for performance; we need to know whether the default
5093     // constructor is constexpr to determine whether the type is a literal type.
5094     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
5095 
5096   case Sema::CXXCopyConstructor:
5097   case Sema::CXXMoveConstructor:
5098     // For copy or move constructors, we need to perform overload resolution.
5099     break;
5100 
5101   case Sema::CXXCopyAssignment:
5102   case Sema::CXXMoveAssignment:
5103     if (!S.getLangOpts().CPlusPlus14)
5104       return false;
5105     // In C++1y, we need to perform overload resolution.
5106     Ctor = false;
5107     break;
5108 
5109   case Sema::CXXDestructor:
5110   case Sema::CXXInvalid:
5111     return false;
5112   }
5113 
5114   //   -- if the class is a non-empty union, or for each non-empty anonymous
5115   //      union member of a non-union class, exactly one non-static data member
5116   //      shall be initialized; [DR1359]
5117   //
5118   // If we squint, this is guaranteed, since exactly one non-static data member
5119   // will be initialized (if the constructor isn't deleted), we just don't know
5120   // which one.
5121   if (Ctor && ClassDecl->isUnion())
5122     return true;
5123 
5124   //   -- the class shall not have any virtual base classes;
5125   if (Ctor && ClassDecl->getNumVBases())
5126     return false;
5127 
5128   // C++1y [class.copy]p26:
5129   //   -- [the class] is a literal type, and
5130   if (!Ctor && !ClassDecl->isLiteral())
5131     return false;
5132 
5133   //   -- every constructor involved in initializing [...] base class
5134   //      sub-objects shall be a constexpr constructor;
5135   //   -- the assignment operator selected to copy/move each direct base
5136   //      class is a constexpr function, and
5137   for (const auto &B : ClassDecl->bases()) {
5138     const RecordType *BaseType = B.getType()->getAs<RecordType>();
5139     if (!BaseType) continue;
5140 
5141     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
5142     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
5143       return false;
5144   }
5145 
5146   //   -- every constructor involved in initializing non-static data members
5147   //      [...] shall be a constexpr constructor;
5148   //   -- every non-static data member and base class sub-object shall be
5149   //      initialized
5150   //   -- for each non-static data member of X that is of class type (or array
5151   //      thereof), the assignment operator selected to copy/move that member is
5152   //      a constexpr function
5153   for (const auto *F : ClassDecl->fields()) {
5154     if (F->isInvalidDecl())
5155       continue;
5156     QualType BaseType = S.Context.getBaseElementType(F->getType());
5157     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
5158       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5159       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
5160                                     BaseType.getCVRQualifiers(),
5161                                     ConstArg && !F->isMutable()))
5162         return false;
5163     }
5164   }
5165 
5166   // All OK, it's constexpr!
5167   return true;
5168 }
5169 
5170 static Sema::ImplicitExceptionSpecification
5171 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
5172   switch (S.getSpecialMember(MD)) {
5173   case Sema::CXXDefaultConstructor:
5174     return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
5175   case Sema::CXXCopyConstructor:
5176     return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
5177   case Sema::CXXCopyAssignment:
5178     return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
5179   case Sema::CXXMoveConstructor:
5180     return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
5181   case Sema::CXXMoveAssignment:
5182     return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
5183   case Sema::CXXDestructor:
5184     return S.ComputeDefaultedDtorExceptionSpec(MD);
5185   case Sema::CXXInvalid:
5186     break;
5187   }
5188   assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
5189          "only special members have implicit exception specs");
5190   return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
5191 }
5192 
5193 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
5194                                                             CXXMethodDecl *MD) {
5195   FunctionProtoType::ExtProtoInfo EPI;
5196 
5197   // Build an exception specification pointing back at this member.
5198   EPI.ExceptionSpec.Type = EST_Unevaluated;
5199   EPI.ExceptionSpec.SourceDecl = MD;
5200 
5201   // Set the calling convention to the default for C++ instance methods.
5202   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
5203       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5204                                             /*IsCXXMethod=*/true));
5205   return EPI;
5206 }
5207 
5208 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
5209   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
5210   if (FPT->getExceptionSpecType() != EST_Unevaluated)
5211     return;
5212 
5213   // Evaluate the exception specification.
5214   auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
5215 
5216   // Update the type of the special member to use it.
5217   UpdateExceptionSpec(MD, ESI);
5218 
5219   // A user-provided destructor can be defined outside the class. When that
5220   // happens, be sure to update the exception specification on both
5221   // declarations.
5222   const FunctionProtoType *CanonicalFPT =
5223     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
5224   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
5225     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
5226 }
5227 
5228 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
5229   CXXRecordDecl *RD = MD->getParent();
5230   CXXSpecialMember CSM = getSpecialMember(MD);
5231 
5232   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
5233          "not an explicitly-defaulted special member");
5234 
5235   // Whether this was the first-declared instance of the constructor.
5236   // This affects whether we implicitly add an exception spec and constexpr.
5237   bool First = MD == MD->getCanonicalDecl();
5238 
5239   bool HadError = false;
5240 
5241   // C++11 [dcl.fct.def.default]p1:
5242   //   A function that is explicitly defaulted shall
5243   //     -- be a special member function (checked elsewhere),
5244   //     -- have the same type (except for ref-qualifiers, and except that a
5245   //        copy operation can take a non-const reference) as an implicit
5246   //        declaration, and
5247   //     -- not have default arguments.
5248   unsigned ExpectedParams = 1;
5249   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
5250     ExpectedParams = 0;
5251   if (MD->getNumParams() != ExpectedParams) {
5252     // This also checks for default arguments: a copy or move constructor with a
5253     // default argument is classified as a default constructor, and assignment
5254     // operations and destructors can't have default arguments.
5255     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
5256       << CSM << MD->getSourceRange();
5257     HadError = true;
5258   } else if (MD->isVariadic()) {
5259     Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
5260       << CSM << MD->getSourceRange();
5261     HadError = true;
5262   }
5263 
5264   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
5265 
5266   bool CanHaveConstParam = false;
5267   if (CSM == CXXCopyConstructor)
5268     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
5269   else if (CSM == CXXCopyAssignment)
5270     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
5271 
5272   QualType ReturnType = Context.VoidTy;
5273   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
5274     // Check for return type matching.
5275     ReturnType = Type->getReturnType();
5276     QualType ExpectedReturnType =
5277         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
5278     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
5279       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
5280         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
5281       HadError = true;
5282     }
5283 
5284     // A defaulted special member cannot have cv-qualifiers.
5285     if (Type->getTypeQuals()) {
5286       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
5287         << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
5288       HadError = true;
5289     }
5290   }
5291 
5292   // Check for parameter type matching.
5293   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
5294   bool HasConstParam = false;
5295   if (ExpectedParams && ArgType->isReferenceType()) {
5296     // Argument must be reference to possibly-const T.
5297     QualType ReferentType = ArgType->getPointeeType();
5298     HasConstParam = ReferentType.isConstQualified();
5299 
5300     if (ReferentType.isVolatileQualified()) {
5301       Diag(MD->getLocation(),
5302            diag::err_defaulted_special_member_volatile_param) << CSM;
5303       HadError = true;
5304     }
5305 
5306     if (HasConstParam && !CanHaveConstParam) {
5307       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
5308         Diag(MD->getLocation(),
5309              diag::err_defaulted_special_member_copy_const_param)
5310           << (CSM == CXXCopyAssignment);
5311         // FIXME: Explain why this special member can't be const.
5312       } else {
5313         Diag(MD->getLocation(),
5314              diag::err_defaulted_special_member_move_const_param)
5315           << (CSM == CXXMoveAssignment);
5316       }
5317       HadError = true;
5318     }
5319   } else if (ExpectedParams) {
5320     // A copy assignment operator can take its argument by value, but a
5321     // defaulted one cannot.
5322     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
5323     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
5324     HadError = true;
5325   }
5326 
5327   // C++11 [dcl.fct.def.default]p2:
5328   //   An explicitly-defaulted function may be declared constexpr only if it
5329   //   would have been implicitly declared as constexpr,
5330   // Do not apply this rule to members of class templates, since core issue 1358
5331   // makes such functions always instantiate to constexpr functions. For
5332   // functions which cannot be constexpr (for non-constructors in C++11 and for
5333   // destructors in C++1y), this is checked elsewhere.
5334   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
5335                                                      HasConstParam);
5336   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
5337                                  : isa<CXXConstructorDecl>(MD)) &&
5338       MD->isConstexpr() && !Constexpr &&
5339       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
5340     Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
5341     // FIXME: Explain why the special member can't be constexpr.
5342     HadError = true;
5343   }
5344 
5345   //   and may have an explicit exception-specification only if it is compatible
5346   //   with the exception-specification on the implicit declaration.
5347   if (Type->hasExceptionSpec()) {
5348     // Delay the check if this is the first declaration of the special member,
5349     // since we may not have parsed some necessary in-class initializers yet.
5350     if (First) {
5351       // If the exception specification needs to be instantiated, do so now,
5352       // before we clobber it with an EST_Unevaluated specification below.
5353       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
5354         InstantiateExceptionSpec(MD->getLocStart(), MD);
5355         Type = MD->getType()->getAs<FunctionProtoType>();
5356       }
5357       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
5358     } else
5359       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
5360   }
5361 
5362   //   If a function is explicitly defaulted on its first declaration,
5363   if (First) {
5364     //  -- it is implicitly considered to be constexpr if the implicit
5365     //     definition would be,
5366     MD->setConstexpr(Constexpr);
5367 
5368     //  -- it is implicitly considered to have the same exception-specification
5369     //     as if it had been implicitly declared,
5370     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
5371     EPI.ExceptionSpec.Type = EST_Unevaluated;
5372     EPI.ExceptionSpec.SourceDecl = MD;
5373     MD->setType(Context.getFunctionType(ReturnType,
5374                                         llvm::makeArrayRef(&ArgType,
5375                                                            ExpectedParams),
5376                                         EPI));
5377   }
5378 
5379   if (ShouldDeleteSpecialMember(MD, CSM)) {
5380     if (First) {
5381       SetDeclDeleted(MD, MD->getLocation());
5382     } else {
5383       // C++11 [dcl.fct.def.default]p4:
5384       //   [For a] user-provided explicitly-defaulted function [...] if such a
5385       //   function is implicitly defined as deleted, the program is ill-formed.
5386       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
5387       ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
5388       HadError = true;
5389     }
5390   }
5391 
5392   if (HadError)
5393     MD->setInvalidDecl();
5394 }
5395 
5396 /// Check whether the exception specification provided for an
5397 /// explicitly-defaulted special member matches the exception specification
5398 /// that would have been generated for an implicit special member, per
5399 /// C++11 [dcl.fct.def.default]p2.
5400 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
5401     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
5402   // If the exception specification was explicitly specified but hadn't been
5403   // parsed when the method was defaulted, grab it now.
5404   if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
5405     SpecifiedType =
5406         MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
5407 
5408   // Compute the implicit exception specification.
5409   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5410                                                        /*IsCXXMethod=*/true);
5411   FunctionProtoType::ExtProtoInfo EPI(CC);
5412   EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
5413                           .getExceptionSpec();
5414   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
5415     Context.getFunctionType(Context.VoidTy, None, EPI));
5416 
5417   // Ensure that it matches.
5418   CheckEquivalentExceptionSpec(
5419     PDiag(diag::err_incorrect_defaulted_exception_spec)
5420       << getSpecialMember(MD), PDiag(),
5421     ImplicitType, SourceLocation(),
5422     SpecifiedType, MD->getLocation());
5423 }
5424 
5425 void Sema::CheckDelayedMemberExceptionSpecs() {
5426   decltype(DelayedExceptionSpecChecks) Checks;
5427   decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
5428 
5429   std::swap(Checks, DelayedExceptionSpecChecks);
5430   std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
5431 
5432   // Perform any deferred checking of exception specifications for virtual
5433   // destructors.
5434   for (auto &Check : Checks)
5435     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
5436 
5437   // Check that any explicitly-defaulted methods have exception specifications
5438   // compatible with their implicit exception specifications.
5439   for (auto &Spec : Specs)
5440     CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
5441 }
5442 
5443 namespace {
5444 struct SpecialMemberDeletionInfo {
5445   Sema &S;
5446   CXXMethodDecl *MD;
5447   Sema::CXXSpecialMember CSM;
5448   bool Diagnose;
5449 
5450   // Properties of the special member, computed for convenience.
5451   bool IsConstructor, IsAssignment, IsMove, ConstArg;
5452   SourceLocation Loc;
5453 
5454   bool AllFieldsAreConst;
5455 
5456   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
5457                             Sema::CXXSpecialMember CSM, bool Diagnose)
5458     : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
5459       IsConstructor(false), IsAssignment(false), IsMove(false),
5460       ConstArg(false), Loc(MD->getLocation()),
5461       AllFieldsAreConst(true) {
5462     switch (CSM) {
5463       case Sema::CXXDefaultConstructor:
5464       case Sema::CXXCopyConstructor:
5465         IsConstructor = true;
5466         break;
5467       case Sema::CXXMoveConstructor:
5468         IsConstructor = true;
5469         IsMove = true;
5470         break;
5471       case Sema::CXXCopyAssignment:
5472         IsAssignment = true;
5473         break;
5474       case Sema::CXXMoveAssignment:
5475         IsAssignment = true;
5476         IsMove = true;
5477         break;
5478       case Sema::CXXDestructor:
5479         break;
5480       case Sema::CXXInvalid:
5481         llvm_unreachable("invalid special member kind");
5482     }
5483 
5484     if (MD->getNumParams()) {
5485       if (const ReferenceType *RT =
5486               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5487         ConstArg = RT->getPointeeType().isConstQualified();
5488     }
5489   }
5490 
5491   bool inUnion() const { return MD->getParent()->isUnion(); }
5492 
5493   /// Look up the corresponding special member in the given class.
5494   Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
5495                                               unsigned Quals, bool IsMutable) {
5496     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5497                                        ConstArg && !IsMutable);
5498   }
5499 
5500   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
5501 
5502   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
5503   bool shouldDeleteForField(FieldDecl *FD);
5504   bool shouldDeleteForAllConstMembers();
5505 
5506   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5507                                      unsigned Quals);
5508   bool shouldDeleteForSubobjectCall(Subobject Subobj,
5509                                     Sema::SpecialMemberOverloadResult *SMOR,
5510                                     bool IsDtorCallInCtor);
5511 
5512   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
5513 };
5514 }
5515 
5516 /// Is the given special member inaccessible when used on the given
5517 /// sub-object.
5518 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5519                                              CXXMethodDecl *target) {
5520   /// If we're operating on a base class, the object type is the
5521   /// type of this special member.
5522   QualType objectTy;
5523   AccessSpecifier access = target->getAccess();
5524   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5525     objectTy = S.Context.getTypeDeclType(MD->getParent());
5526     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5527 
5528   // If we're operating on a field, the object type is the type of the field.
5529   } else {
5530     objectTy = S.Context.getTypeDeclType(target->getParent());
5531   }
5532 
5533   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5534 }
5535 
5536 /// Check whether we should delete a special member due to the implicit
5537 /// definition containing a call to a special member of a subobject.
5538 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5539     Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5540     bool IsDtorCallInCtor) {
5541   CXXMethodDecl *Decl = SMOR->getMethod();
5542   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5543 
5544   int DiagKind = -1;
5545 
5546   if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5547     DiagKind = !Decl ? 0 : 1;
5548   else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5549     DiagKind = 2;
5550   else if (!isAccessible(Subobj, Decl))
5551     DiagKind = 3;
5552   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5553            !Decl->isTrivial()) {
5554     // A member of a union must have a trivial corresponding special member.
5555     // As a weird special case, a destructor call from a union's constructor
5556     // must be accessible and non-deleted, but need not be trivial. Such a
5557     // destructor is never actually called, but is semantically checked as
5558     // if it were.
5559     DiagKind = 4;
5560   }
5561 
5562   if (DiagKind == -1)
5563     return false;
5564 
5565   if (Diagnose) {
5566     if (Field) {
5567       S.Diag(Field->getLocation(),
5568              diag::note_deleted_special_member_class_subobject)
5569         << CSM << MD->getParent() << /*IsField*/true
5570         << Field << DiagKind << IsDtorCallInCtor;
5571     } else {
5572       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5573       S.Diag(Base->getLocStart(),
5574              diag::note_deleted_special_member_class_subobject)
5575         << CSM << MD->getParent() << /*IsField*/false
5576         << Base->getType() << DiagKind << IsDtorCallInCtor;
5577     }
5578 
5579     if (DiagKind == 1)
5580       S.NoteDeletedFunction(Decl);
5581     // FIXME: Explain inaccessibility if DiagKind == 3.
5582   }
5583 
5584   return true;
5585 }
5586 
5587 /// Check whether we should delete a special member function due to having a
5588 /// direct or virtual base class or non-static data member of class type M.
5589 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
5590     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
5591   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5592   bool IsMutable = Field && Field->isMutable();
5593 
5594   // C++11 [class.ctor]p5:
5595   // -- any direct or virtual base class, or non-static data member with no
5596   //    brace-or-equal-initializer, has class type M (or array thereof) and
5597   //    either M has no default constructor or overload resolution as applied
5598   //    to M's default constructor results in an ambiguity or in a function
5599   //    that is deleted or inaccessible
5600   // C++11 [class.copy]p11, C++11 [class.copy]p23:
5601   // -- a direct or virtual base class B that cannot be copied/moved because
5602   //    overload resolution, as applied to B's corresponding special member,
5603   //    results in an ambiguity or a function that is deleted or inaccessible
5604   //    from the defaulted special member
5605   // C++11 [class.dtor]p5:
5606   // -- any direct or virtual base class [...] has a type with a destructor
5607   //    that is deleted or inaccessible
5608   if (!(CSM == Sema::CXXDefaultConstructor &&
5609         Field && Field->hasInClassInitializer()) &&
5610       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5611                                    false))
5612     return true;
5613 
5614   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5615   // -- any direct or virtual base class or non-static data member has a
5616   //    type with a destructor that is deleted or inaccessible
5617   if (IsConstructor) {
5618     Sema::SpecialMemberOverloadResult *SMOR =
5619         S.LookupSpecialMember(Class, Sema::CXXDestructor,
5620                               false, false, false, false, false);
5621     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5622       return true;
5623   }
5624 
5625   return false;
5626 }
5627 
5628 /// Check whether we should delete a special member function due to the class
5629 /// having a particular direct or virtual base class.
5630 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
5631   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
5632   // If program is correct, BaseClass cannot be null, but if it is, the error
5633   // must be reported elsewhere.
5634   return BaseClass && shouldDeleteForClassSubobject(BaseClass, Base, 0);
5635 }
5636 
5637 /// Check whether we should delete a special member function due to the class
5638 /// having a particular non-static data member.
5639 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5640   QualType FieldType = S.Context.getBaseElementType(FD->getType());
5641   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5642 
5643   if (CSM == Sema::CXXDefaultConstructor) {
5644     // For a default constructor, all references must be initialized in-class
5645     // and, if a union, it must have a non-const member.
5646     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5647       if (Diagnose)
5648         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5649           << MD->getParent() << FD << FieldType << /*Reference*/0;
5650       return true;
5651     }
5652     // C++11 [class.ctor]p5: any non-variant non-static data member of
5653     // const-qualified type (or array thereof) with no
5654     // brace-or-equal-initializer does not have a user-provided default
5655     // constructor.
5656     if (!inUnion() && FieldType.isConstQualified() &&
5657         !FD->hasInClassInitializer() &&
5658         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5659       if (Diagnose)
5660         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5661           << MD->getParent() << FD << FD->getType() << /*Const*/1;
5662       return true;
5663     }
5664 
5665     if (inUnion() && !FieldType.isConstQualified())
5666       AllFieldsAreConst = false;
5667   } else if (CSM == Sema::CXXCopyConstructor) {
5668     // For a copy constructor, data members must not be of rvalue reference
5669     // type.
5670     if (FieldType->isRValueReferenceType()) {
5671       if (Diagnose)
5672         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5673           << MD->getParent() << FD << FieldType;
5674       return true;
5675     }
5676   } else if (IsAssignment) {
5677     // For an assignment operator, data members must not be of reference type.
5678     if (FieldType->isReferenceType()) {
5679       if (Diagnose)
5680         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5681           << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
5682       return true;
5683     }
5684     if (!FieldRecord && FieldType.isConstQualified()) {
5685       // C++11 [class.copy]p23:
5686       // -- a non-static data member of const non-class type (or array thereof)
5687       if (Diagnose)
5688         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5689           << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
5690       return true;
5691     }
5692   }
5693 
5694   if (FieldRecord) {
5695     // Some additional restrictions exist on the variant members.
5696     if (!inUnion() && FieldRecord->isUnion() &&
5697         FieldRecord->isAnonymousStructOrUnion()) {
5698       bool AllVariantFieldsAreConst = true;
5699 
5700       // FIXME: Handle anonymous unions declared within anonymous unions.
5701       for (auto *UI : FieldRecord->fields()) {
5702         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
5703 
5704         if (!UnionFieldType.isConstQualified())
5705           AllVariantFieldsAreConst = false;
5706 
5707         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5708         if (UnionFieldRecord &&
5709             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
5710                                           UnionFieldType.getCVRQualifiers()))
5711           return true;
5712       }
5713 
5714       // At least one member in each anonymous union must be non-const
5715       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
5716           !FieldRecord->field_empty()) {
5717         if (Diagnose)
5718           S.Diag(FieldRecord->getLocation(),
5719                  diag::note_deleted_default_ctor_all_const)
5720             << MD->getParent() << /*anonymous union*/1;
5721         return true;
5722       }
5723 
5724       // Don't check the implicit member of the anonymous union type.
5725       // This is technically non-conformant, but sanity demands it.
5726       return false;
5727     }
5728 
5729     if (shouldDeleteForClassSubobject(FieldRecord, FD,
5730                                       FieldType.getCVRQualifiers()))
5731       return true;
5732   }
5733 
5734   return false;
5735 }
5736 
5737 /// C++11 [class.ctor] p5:
5738 ///   A defaulted default constructor for a class X is defined as deleted if
5739 /// X is a union and all of its variant members are of const-qualified type.
5740 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
5741   // This is a silly definition, because it gives an empty union a deleted
5742   // default constructor. Don't do that.
5743   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5744       !MD->getParent()->field_empty()) {
5745     if (Diagnose)
5746       S.Diag(MD->getParent()->getLocation(),
5747              diag::note_deleted_default_ctor_all_const)
5748         << MD->getParent() << /*not anonymous union*/0;
5749     return true;
5750   }
5751   return false;
5752 }
5753 
5754 /// Determine whether a defaulted special member function should be defined as
5755 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5756 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
5757 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5758                                      bool Diagnose) {
5759   if (MD->isInvalidDecl())
5760     return false;
5761   CXXRecordDecl *RD = MD->getParent();
5762   assert(!RD->isDependentType() && "do deletion after instantiation");
5763   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
5764     return false;
5765 
5766   // C++11 [expr.lambda.prim]p19:
5767   //   The closure type associated with a lambda-expression has a
5768   //   deleted (8.4.3) default constructor and a deleted copy
5769   //   assignment operator.
5770   if (RD->isLambda() &&
5771       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5772     if (Diagnose)
5773       Diag(RD->getLocation(), diag::note_lambda_decl);
5774     return true;
5775   }
5776 
5777   // For an anonymous struct or union, the copy and assignment special members
5778   // will never be used, so skip the check. For an anonymous union declared at
5779   // namespace scope, the constructor and destructor are used.
5780   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5781       RD->isAnonymousStructOrUnion())
5782     return false;
5783 
5784   // C++11 [class.copy]p7, p18:
5785   //   If the class definition declares a move constructor or move assignment
5786   //   operator, an implicitly declared copy constructor or copy assignment
5787   //   operator is defined as deleted.
5788   if (MD->isImplicit() &&
5789       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5790     CXXMethodDecl *UserDeclaredMove = nullptr;
5791 
5792     // In Microsoft mode, a user-declared move only causes the deletion of the
5793     // corresponding copy operation, not both copy operations.
5794     if (RD->hasUserDeclaredMoveConstructor() &&
5795         (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
5796       if (!Diagnose) return true;
5797 
5798       // Find any user-declared move constructor.
5799       for (auto *I : RD->ctors()) {
5800         if (I->isMoveConstructor()) {
5801           UserDeclaredMove = I;
5802           break;
5803         }
5804       }
5805       assert(UserDeclaredMove);
5806     } else if (RD->hasUserDeclaredMoveAssignment() &&
5807                (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
5808       if (!Diagnose) return true;
5809 
5810       // Find any user-declared move assignment operator.
5811       for (auto *I : RD->methods()) {
5812         if (I->isMoveAssignmentOperator()) {
5813           UserDeclaredMove = I;
5814           break;
5815         }
5816       }
5817       assert(UserDeclaredMove);
5818     }
5819 
5820     if (UserDeclaredMove) {
5821       Diag(UserDeclaredMove->getLocation(),
5822            diag::note_deleted_copy_user_declared_move)
5823         << (CSM == CXXCopyAssignment) << RD
5824         << UserDeclaredMove->isMoveAssignmentOperator();
5825       return true;
5826     }
5827   }
5828 
5829   // Do access control from the special member function
5830   ContextRAII MethodContext(*this, MD);
5831 
5832   // C++11 [class.dtor]p5:
5833   // -- for a virtual destructor, lookup of the non-array deallocation function
5834   //    results in an ambiguity or in a function that is deleted or inaccessible
5835   if (CSM == CXXDestructor && MD->isVirtual()) {
5836     FunctionDecl *OperatorDelete = nullptr;
5837     DeclarationName Name =
5838       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5839     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
5840                                  OperatorDelete, false)) {
5841       if (Diagnose)
5842         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
5843       return true;
5844     }
5845   }
5846 
5847   SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
5848 
5849   for (auto &BI : RD->bases())
5850     if (!BI.isVirtual() &&
5851         SMI.shouldDeleteForBase(&BI))
5852       return true;
5853 
5854   // Per DR1611, do not consider virtual bases of constructors of abstract
5855   // classes, since we are not going to construct them.
5856   if (!RD->isAbstract() || !SMI.IsConstructor) {
5857     for (auto &BI : RD->vbases())
5858       if (SMI.shouldDeleteForBase(&BI))
5859         return true;
5860   }
5861 
5862   for (auto *FI : RD->fields())
5863     if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
5864         SMI.shouldDeleteForField(FI))
5865       return true;
5866 
5867   if (SMI.shouldDeleteForAllConstMembers())
5868     return true;
5869 
5870   if (getLangOpts().CUDA) {
5871     // We should delete the special member in CUDA mode if target inference
5872     // failed.
5873     return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
5874                                                    Diagnose);
5875   }
5876 
5877   return false;
5878 }
5879 
5880 /// Perform lookup for a special member of the specified kind, and determine
5881 /// whether it is trivial. If the triviality can be determined without the
5882 /// lookup, skip it. This is intended for use when determining whether a
5883 /// special member of a containing object is trivial, and thus does not ever
5884 /// perform overload resolution for default constructors.
5885 ///
5886 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5887 /// member that was most likely to be intended to be trivial, if any.
5888 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5889                                      Sema::CXXSpecialMember CSM, unsigned Quals,
5890                                      bool ConstRHS, CXXMethodDecl **Selected) {
5891   if (Selected)
5892     *Selected = nullptr;
5893 
5894   switch (CSM) {
5895   case Sema::CXXInvalid:
5896     llvm_unreachable("not a special member");
5897 
5898   case Sema::CXXDefaultConstructor:
5899     // C++11 [class.ctor]p5:
5900     //   A default constructor is trivial if:
5901     //    - all the [direct subobjects] have trivial default constructors
5902     //
5903     // Note, no overload resolution is performed in this case.
5904     if (RD->hasTrivialDefaultConstructor())
5905       return true;
5906 
5907     if (Selected) {
5908       // If there's a default constructor which could have been trivial, dig it
5909       // out. Otherwise, if there's any user-provided default constructor, point
5910       // to that as an example of why there's not a trivial one.
5911       CXXConstructorDecl *DefCtor = nullptr;
5912       if (RD->needsImplicitDefaultConstructor())
5913         S.DeclareImplicitDefaultConstructor(RD);
5914       for (auto *CI : RD->ctors()) {
5915         if (!CI->isDefaultConstructor())
5916           continue;
5917         DefCtor = CI;
5918         if (!DefCtor->isUserProvided())
5919           break;
5920       }
5921 
5922       *Selected = DefCtor;
5923     }
5924 
5925     return false;
5926 
5927   case Sema::CXXDestructor:
5928     // C++11 [class.dtor]p5:
5929     //   A destructor is trivial if:
5930     //    - all the direct [subobjects] have trivial destructors
5931     if (RD->hasTrivialDestructor())
5932       return true;
5933 
5934     if (Selected) {
5935       if (RD->needsImplicitDestructor())
5936         S.DeclareImplicitDestructor(RD);
5937       *Selected = RD->getDestructor();
5938     }
5939 
5940     return false;
5941 
5942   case Sema::CXXCopyConstructor:
5943     // C++11 [class.copy]p12:
5944     //   A copy constructor is trivial if:
5945     //    - the constructor selected to copy each direct [subobject] is trivial
5946     if (RD->hasTrivialCopyConstructor()) {
5947       if (Quals == Qualifiers::Const)
5948         // We must either select the trivial copy constructor or reach an
5949         // ambiguity; no need to actually perform overload resolution.
5950         return true;
5951     } else if (!Selected) {
5952       return false;
5953     }
5954     // In C++98, we are not supposed to perform overload resolution here, but we
5955     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5956     // cases like B as having a non-trivial copy constructor:
5957     //   struct A { template<typename T> A(T&); };
5958     //   struct B { mutable A a; };
5959     goto NeedOverloadResolution;
5960 
5961   case Sema::CXXCopyAssignment:
5962     // C++11 [class.copy]p25:
5963     //   A copy assignment operator is trivial if:
5964     //    - the assignment operator selected to copy each direct [subobject] is
5965     //      trivial
5966     if (RD->hasTrivialCopyAssignment()) {
5967       if (Quals == Qualifiers::Const)
5968         return true;
5969     } else if (!Selected) {
5970       return false;
5971     }
5972     // In C++98, we are not supposed to perform overload resolution here, but we
5973     // treat that as a language defect.
5974     goto NeedOverloadResolution;
5975 
5976   case Sema::CXXMoveConstructor:
5977   case Sema::CXXMoveAssignment:
5978   NeedOverloadResolution:
5979     Sema::SpecialMemberOverloadResult *SMOR =
5980         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
5981 
5982     // The standard doesn't describe how to behave if the lookup is ambiguous.
5983     // We treat it as not making the member non-trivial, just like the standard
5984     // mandates for the default constructor. This should rarely matter, because
5985     // the member will also be deleted.
5986     if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5987       return true;
5988 
5989     if (!SMOR->getMethod()) {
5990       assert(SMOR->getKind() ==
5991              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5992       return false;
5993     }
5994 
5995     // We deliberately don't check if we found a deleted special member. We're
5996     // not supposed to!
5997     if (Selected)
5998       *Selected = SMOR->getMethod();
5999     return SMOR->getMethod()->isTrivial();
6000   }
6001 
6002   llvm_unreachable("unknown special method kind");
6003 }
6004 
6005 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
6006   for (auto *CI : RD->ctors())
6007     if (!CI->isImplicit())
6008       return CI;
6009 
6010   // Look for constructor templates.
6011   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
6012   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
6013     if (CXXConstructorDecl *CD =
6014           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
6015       return CD;
6016   }
6017 
6018   return nullptr;
6019 }
6020 
6021 /// The kind of subobject we are checking for triviality. The values of this
6022 /// enumeration are used in diagnostics.
6023 enum TrivialSubobjectKind {
6024   /// The subobject is a base class.
6025   TSK_BaseClass,
6026   /// The subobject is a non-static data member.
6027   TSK_Field,
6028   /// The object is actually the complete object.
6029   TSK_CompleteObject
6030 };
6031 
6032 /// Check whether the special member selected for a given type would be trivial.
6033 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
6034                                       QualType SubType, bool ConstRHS,
6035                                       Sema::CXXSpecialMember CSM,
6036                                       TrivialSubobjectKind Kind,
6037                                       bool Diagnose) {
6038   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
6039   if (!SubRD)
6040     return true;
6041 
6042   CXXMethodDecl *Selected;
6043   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
6044                                ConstRHS, Diagnose ? &Selected : nullptr))
6045     return true;
6046 
6047   if (Diagnose) {
6048     if (ConstRHS)
6049       SubType.addConst();
6050 
6051     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
6052       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
6053         << Kind << SubType.getUnqualifiedType();
6054       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
6055         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
6056     } else if (!Selected)
6057       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
6058         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
6059     else if (Selected->isUserProvided()) {
6060       if (Kind == TSK_CompleteObject)
6061         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
6062           << Kind << SubType.getUnqualifiedType() << CSM;
6063       else {
6064         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
6065           << Kind << SubType.getUnqualifiedType() << CSM;
6066         S.Diag(Selected->getLocation(), diag::note_declared_at);
6067       }
6068     } else {
6069       if (Kind != TSK_CompleteObject)
6070         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
6071           << Kind << SubType.getUnqualifiedType() << CSM;
6072 
6073       // Explain why the defaulted or deleted special member isn't trivial.
6074       S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
6075     }
6076   }
6077 
6078   return false;
6079 }
6080 
6081 /// Check whether the members of a class type allow a special member to be
6082 /// trivial.
6083 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
6084                                      Sema::CXXSpecialMember CSM,
6085                                      bool ConstArg, bool Diagnose) {
6086   for (const auto *FI : RD->fields()) {
6087     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
6088       continue;
6089 
6090     QualType FieldType = S.Context.getBaseElementType(FI->getType());
6091 
6092     // Pretend anonymous struct or union members are members of this class.
6093     if (FI->isAnonymousStructOrUnion()) {
6094       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
6095                                     CSM, ConstArg, Diagnose))
6096         return false;
6097       continue;
6098     }
6099 
6100     // C++11 [class.ctor]p5:
6101     //   A default constructor is trivial if [...]
6102     //    -- no non-static data member of its class has a
6103     //       brace-or-equal-initializer
6104     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
6105       if (Diagnose)
6106         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
6107       return false;
6108     }
6109 
6110     // Objective C ARC 4.3.5:
6111     //   [...] nontrivally ownership-qualified types are [...] not trivially
6112     //   default constructible, copy constructible, move constructible, copy
6113     //   assignable, move assignable, or destructible [...]
6114     if (S.getLangOpts().ObjCAutoRefCount &&
6115         FieldType.hasNonTrivialObjCLifetime()) {
6116       if (Diagnose)
6117         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
6118           << RD << FieldType.getObjCLifetime();
6119       return false;
6120     }
6121 
6122     bool ConstRHS = ConstArg && !FI->isMutable();
6123     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
6124                                    CSM, TSK_Field, Diagnose))
6125       return false;
6126   }
6127 
6128   return true;
6129 }
6130 
6131 /// Diagnose why the specified class does not have a trivial special member of
6132 /// the given kind.
6133 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
6134   QualType Ty = Context.getRecordType(RD);
6135 
6136   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
6137   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
6138                             TSK_CompleteObject, /*Diagnose*/true);
6139 }
6140 
6141 /// Determine whether a defaulted or deleted special member function is trivial,
6142 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6143 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
6144 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
6145                                   bool Diagnose) {
6146   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
6147 
6148   CXXRecordDecl *RD = MD->getParent();
6149 
6150   bool ConstArg = false;
6151 
6152   // C++11 [class.copy]p12, p25: [DR1593]
6153   //   A [special member] is trivial if [...] its parameter-type-list is
6154   //   equivalent to the parameter-type-list of an implicit declaration [...]
6155   switch (CSM) {
6156   case CXXDefaultConstructor:
6157   case CXXDestructor:
6158     // Trivial default constructors and destructors cannot have parameters.
6159     break;
6160 
6161   case CXXCopyConstructor:
6162   case CXXCopyAssignment: {
6163     // Trivial copy operations always have const, non-volatile parameter types.
6164     ConstArg = true;
6165     const ParmVarDecl *Param0 = MD->getParamDecl(0);
6166     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
6167     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
6168       if (Diagnose)
6169         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6170           << Param0->getSourceRange() << Param0->getType()
6171           << Context.getLValueReferenceType(
6172                Context.getRecordType(RD).withConst());
6173       return false;
6174     }
6175     break;
6176   }
6177 
6178   case CXXMoveConstructor:
6179   case CXXMoveAssignment: {
6180     // Trivial move operations always have non-cv-qualified parameters.
6181     const ParmVarDecl *Param0 = MD->getParamDecl(0);
6182     const RValueReferenceType *RT =
6183       Param0->getType()->getAs<RValueReferenceType>();
6184     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
6185       if (Diagnose)
6186         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6187           << Param0->getSourceRange() << Param0->getType()
6188           << Context.getRValueReferenceType(Context.getRecordType(RD));
6189       return false;
6190     }
6191     break;
6192   }
6193 
6194   case CXXInvalid:
6195     llvm_unreachable("not a special member");
6196   }
6197 
6198   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
6199     if (Diagnose)
6200       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
6201            diag::note_nontrivial_default_arg)
6202         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
6203     return false;
6204   }
6205   if (MD->isVariadic()) {
6206     if (Diagnose)
6207       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
6208     return false;
6209   }
6210 
6211   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6212   //   A copy/move [constructor or assignment operator] is trivial if
6213   //    -- the [member] selected to copy/move each direct base class subobject
6214   //       is trivial
6215   //
6216   // C++11 [class.copy]p12, C++11 [class.copy]p25:
6217   //   A [default constructor or destructor] is trivial if
6218   //    -- all the direct base classes have trivial [default constructors or
6219   //       destructors]
6220   for (const auto &BI : RD->bases())
6221     if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
6222                                    ConstArg, CSM, TSK_BaseClass, Diagnose))
6223       return false;
6224 
6225   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6226   //   A copy/move [constructor or assignment operator] for a class X is
6227   //   trivial if
6228   //    -- for each non-static data member of X that is of class type (or array
6229   //       thereof), the constructor selected to copy/move that member is
6230   //       trivial
6231   //
6232   // C++11 [class.copy]p12, C++11 [class.copy]p25:
6233   //   A [default constructor or destructor] is trivial if
6234   //    -- for all of the non-static data members of its class that are of class
6235   //       type (or array thereof), each such class has a trivial [default
6236   //       constructor or destructor]
6237   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
6238     return false;
6239 
6240   // C++11 [class.dtor]p5:
6241   //   A destructor is trivial if [...]
6242   //    -- the destructor is not virtual
6243   if (CSM == CXXDestructor && MD->isVirtual()) {
6244     if (Diagnose)
6245       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
6246     return false;
6247   }
6248 
6249   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
6250   //   A [special member] for class X is trivial if [...]
6251   //    -- class X has no virtual functions and no virtual base classes
6252   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
6253     if (!Diagnose)
6254       return false;
6255 
6256     if (RD->getNumVBases()) {
6257       // Check for virtual bases. We already know that the corresponding
6258       // member in all bases is trivial, so vbases must all be direct.
6259       CXXBaseSpecifier &BS = *RD->vbases_begin();
6260       assert(BS.isVirtual());
6261       Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
6262       return false;
6263     }
6264 
6265     // Must have a virtual method.
6266     for (const auto *MI : RD->methods()) {
6267       if (MI->isVirtual()) {
6268         SourceLocation MLoc = MI->getLocStart();
6269         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
6270         return false;
6271       }
6272     }
6273 
6274     llvm_unreachable("dynamic class with no vbases and no virtual functions");
6275   }
6276 
6277   // Looks like it's trivial!
6278   return true;
6279 }
6280 
6281 namespace {
6282 struct FindHiddenVirtualMethod {
6283   Sema *S;
6284   CXXMethodDecl *Method;
6285   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
6286   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6287 
6288 private:
6289   /// Check whether any most overriden method from MD in Methods
6290   static bool CheckMostOverridenMethods(
6291       const CXXMethodDecl *MD,
6292       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
6293     if (MD->size_overridden_methods() == 0)
6294       return Methods.count(MD->getCanonicalDecl());
6295     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6296                                         E = MD->end_overridden_methods();
6297          I != E; ++I)
6298       if (CheckMostOverridenMethods(*I, Methods))
6299         return true;
6300     return false;
6301   }
6302 
6303 public:
6304   /// Member lookup function that determines whether a given C++
6305   /// method overloads virtual methods in a base class without overriding any,
6306   /// to be used with CXXRecordDecl::lookupInBases().
6307   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
6308     RecordDecl *BaseRecord =
6309         Specifier->getType()->getAs<RecordType>()->getDecl();
6310 
6311     DeclarationName Name = Method->getDeclName();
6312     assert(Name.getNameKind() == DeclarationName::Identifier);
6313 
6314     bool foundSameNameMethod = false;
6315     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
6316     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
6317          Path.Decls = Path.Decls.slice(1)) {
6318       NamedDecl *D = Path.Decls.front();
6319       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6320         MD = MD->getCanonicalDecl();
6321         foundSameNameMethod = true;
6322         // Interested only in hidden virtual methods.
6323         if (!MD->isVirtual())
6324           continue;
6325         // If the method we are checking overrides a method from its base
6326         // don't warn about the other overloaded methods. Clang deviates from
6327         // GCC by only diagnosing overloads of inherited virtual functions that
6328         // do not override any other virtual functions in the base. GCC's
6329         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
6330         // function from a base class. These cases may be better served by a
6331         // warning (not specific to virtual functions) on call sites when the
6332         // call would select a different function from the base class, were it
6333         // visible.
6334         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
6335         if (!S->IsOverload(Method, MD, false))
6336           return true;
6337         // Collect the overload only if its hidden.
6338         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
6339           overloadedMethods.push_back(MD);
6340       }
6341     }
6342 
6343     if (foundSameNameMethod)
6344       OverloadedMethods.append(overloadedMethods.begin(),
6345                                overloadedMethods.end());
6346     return foundSameNameMethod;
6347   }
6348 };
6349 } // end anonymous namespace
6350 
6351 /// \brief Add the most overriden methods from MD to Methods
6352 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
6353                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
6354   if (MD->size_overridden_methods() == 0)
6355     Methods.insert(MD->getCanonicalDecl());
6356   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6357                                       E = MD->end_overridden_methods();
6358        I != E; ++I)
6359     AddMostOverridenMethods(*I, Methods);
6360 }
6361 
6362 /// \brief Check if a method overloads virtual methods in a base class without
6363 /// overriding any.
6364 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
6365                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6366   if (!MD->getDeclName().isIdentifier())
6367     return;
6368 
6369   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
6370                      /*bool RecordPaths=*/false,
6371                      /*bool DetectVirtual=*/false);
6372   FindHiddenVirtualMethod FHVM;
6373   FHVM.Method = MD;
6374   FHVM.S = this;
6375 
6376   // Keep the base methods that were overriden or introduced in the subclass
6377   // by 'using' in a set. A base method not in this set is hidden.
6378   CXXRecordDecl *DC = MD->getParent();
6379   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
6380   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
6381     NamedDecl *ND = *I;
6382     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
6383       ND = shad->getTargetDecl();
6384     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6385       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
6386   }
6387 
6388   if (DC->lookupInBases(FHVM, Paths))
6389     OverloadedMethods = FHVM.OverloadedMethods;
6390 }
6391 
6392 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6393                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6394   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
6395     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
6396     PartialDiagnostic PD = PDiag(
6397          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
6398     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
6399     Diag(overloadedMD->getLocation(), PD);
6400   }
6401 }
6402 
6403 /// \brief Diagnose methods which overload virtual methods in a base class
6404 /// without overriding any.
6405 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
6406   if (MD->isInvalidDecl())
6407     return;
6408 
6409   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
6410     return;
6411 
6412   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6413   FindHiddenVirtualMethods(MD, OverloadedMethods);
6414   if (!OverloadedMethods.empty()) {
6415     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
6416       << MD << (OverloadedMethods.size() > 1);
6417 
6418     NoteHiddenVirtualMethods(MD, OverloadedMethods);
6419   }
6420 }
6421 
6422 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
6423                                              Decl *TagDecl,
6424                                              SourceLocation LBrac,
6425                                              SourceLocation RBrac,
6426                                              AttributeList *AttrList) {
6427   if (!TagDecl)
6428     return;
6429 
6430   AdjustDeclIfTemplate(TagDecl);
6431 
6432   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6433     if (l->getKind() != AttributeList::AT_Visibility)
6434       continue;
6435     l->setInvalid();
6436     Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
6437       l->getName();
6438   }
6439 
6440   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
6441               // strict aliasing violation!
6442               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
6443               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
6444 
6445   CheckCompletedCXXClass(
6446                         dyn_cast_or_null<CXXRecordDecl>(TagDecl));
6447 }
6448 
6449 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6450 /// special functions, such as the default constructor, copy
6451 /// constructor, or destructor, to the given C++ class (C++
6452 /// [special]p1).  This routine can only be executed just before the
6453 /// definition of the class is complete.
6454 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
6455   if (!ClassDecl->hasUserDeclaredConstructor())
6456     ++ASTContext::NumImplicitDefaultConstructors;
6457 
6458   if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
6459     ++ASTContext::NumImplicitCopyConstructors;
6460 
6461     // If the properties or semantics of the copy constructor couldn't be
6462     // determined while the class was being declared, force a declaration
6463     // of it now.
6464     if (ClassDecl->needsOverloadResolutionForCopyConstructor())
6465       DeclareImplicitCopyConstructor(ClassDecl);
6466   }
6467 
6468   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
6469     ++ASTContext::NumImplicitMoveConstructors;
6470 
6471     if (ClassDecl->needsOverloadResolutionForMoveConstructor())
6472       DeclareImplicitMoveConstructor(ClassDecl);
6473   }
6474 
6475   if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6476     ++ASTContext::NumImplicitCopyAssignmentOperators;
6477 
6478     // If we have a dynamic class, then the copy assignment operator may be
6479     // virtual, so we have to declare it immediately. This ensures that, e.g.,
6480     // it shows up in the right place in the vtable and that we diagnose
6481     // problems with the implicit exception specification.
6482     if (ClassDecl->isDynamicClass() ||
6483         ClassDecl->needsOverloadResolutionForCopyAssignment())
6484       DeclareImplicitCopyAssignment(ClassDecl);
6485   }
6486 
6487   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
6488     ++ASTContext::NumImplicitMoveAssignmentOperators;
6489 
6490     // Likewise for the move assignment operator.
6491     if (ClassDecl->isDynamicClass() ||
6492         ClassDecl->needsOverloadResolutionForMoveAssignment())
6493       DeclareImplicitMoveAssignment(ClassDecl);
6494   }
6495 
6496   if (!ClassDecl->hasUserDeclaredDestructor()) {
6497     ++ASTContext::NumImplicitDestructors;
6498 
6499     // If we have a dynamic class, then the destructor may be virtual, so we
6500     // have to declare the destructor immediately. This ensures that, e.g., it
6501     // shows up in the right place in the vtable and that we diagnose problems
6502     // with the implicit exception specification.
6503     if (ClassDecl->isDynamicClass() ||
6504         ClassDecl->needsOverloadResolutionForDestructor())
6505       DeclareImplicitDestructor(ClassDecl);
6506   }
6507 }
6508 
6509 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
6510   if (!D)
6511     return 0;
6512 
6513   // The order of template parameters is not important here. All names
6514   // get added to the same scope.
6515   SmallVector<TemplateParameterList *, 4> ParameterLists;
6516 
6517   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6518     D = TD->getTemplatedDecl();
6519 
6520   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6521     ParameterLists.push_back(PSD->getTemplateParameters());
6522 
6523   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6524     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6525       ParameterLists.push_back(DD->getTemplateParameterList(i));
6526 
6527     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6528       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6529         ParameterLists.push_back(FTD->getTemplateParameters());
6530     }
6531   }
6532 
6533   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6534     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6535       ParameterLists.push_back(TD->getTemplateParameterList(i));
6536 
6537     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6538       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6539         ParameterLists.push_back(CTD->getTemplateParameters());
6540     }
6541   }
6542 
6543   unsigned Count = 0;
6544   for (TemplateParameterList *Params : ParameterLists) {
6545     if (Params->size() > 0)
6546       // Ignore explicit specializations; they don't contribute to the template
6547       // depth.
6548       ++Count;
6549     for (NamedDecl *Param : *Params) {
6550       if (Param->getDeclName()) {
6551         S->AddDecl(Param);
6552         IdResolver.AddDecl(Param);
6553       }
6554     }
6555   }
6556 
6557   return Count;
6558 }
6559 
6560 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6561   if (!RecordD) return;
6562   AdjustDeclIfTemplate(RecordD);
6563   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
6564   PushDeclContext(S, Record);
6565 }
6566 
6567 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6568   if (!RecordD) return;
6569   PopDeclContext();
6570 }
6571 
6572 /// This is used to implement the constant expression evaluation part of the
6573 /// attribute enable_if extension. There is nothing in standard C++ which would
6574 /// require reentering parameters.
6575 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6576   if (!Param)
6577     return;
6578 
6579   S->AddDecl(Param);
6580   if (Param->getDeclName())
6581     IdResolver.AddDecl(Param);
6582 }
6583 
6584 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
6585 /// parsing a top-level (non-nested) C++ class, and we are now
6586 /// parsing those parts of the given Method declaration that could
6587 /// not be parsed earlier (C++ [class.mem]p2), such as default
6588 /// arguments. This action should enter the scope of the given
6589 /// Method declaration as if we had just parsed the qualified method
6590 /// name. However, it should not bring the parameters into scope;
6591 /// that will be performed by ActOnDelayedCXXMethodParameter.
6592 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6593 }
6594 
6595 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
6596 /// C++ method declaration. We're (re-)introducing the given
6597 /// function parameter into scope for use in parsing later parts of
6598 /// the method declaration. For example, we could see an
6599 /// ActOnParamDefaultArgument event for this parameter.
6600 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
6601   if (!ParamD)
6602     return;
6603 
6604   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
6605 
6606   // If this parameter has an unparsed default argument, clear it out
6607   // to make way for the parsed default argument.
6608   if (Param->hasUnparsedDefaultArg())
6609     Param->setDefaultArg(nullptr);
6610 
6611   S->AddDecl(Param);
6612   if (Param->getDeclName())
6613     IdResolver.AddDecl(Param);
6614 }
6615 
6616 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6617 /// processing the delayed method declaration for Method. The method
6618 /// declaration is now considered finished. There may be a separate
6619 /// ActOnStartOfFunctionDef action later (not necessarily
6620 /// immediately!) for this method, if it was also defined inside the
6621 /// class body.
6622 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6623   if (!MethodD)
6624     return;
6625 
6626   AdjustDeclIfTemplate(MethodD);
6627 
6628   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
6629 
6630   // Now that we have our default arguments, check the constructor
6631   // again. It could produce additional diagnostics or affect whether
6632   // the class has implicitly-declared destructors, among other
6633   // things.
6634   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6635     CheckConstructor(Constructor);
6636 
6637   // Check the default arguments, which we may have added.
6638   if (!Method->isInvalidDecl())
6639     CheckCXXDefaultArguments(Method);
6640 }
6641 
6642 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
6643 /// the well-formedness of the constructor declarator @p D with type @p
6644 /// R. If there are any errors in the declarator, this routine will
6645 /// emit diagnostics and set the invalid bit to true.  In any case, the type
6646 /// will be updated to reflect a well-formed type for the constructor and
6647 /// returned.
6648 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
6649                                           StorageClass &SC) {
6650   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6651 
6652   // C++ [class.ctor]p3:
6653   //   A constructor shall not be virtual (10.3) or static (9.4). A
6654   //   constructor can be invoked for a const, volatile or const
6655   //   volatile object. A constructor shall not be declared const,
6656   //   volatile, or const volatile (9.3.2).
6657   if (isVirtual) {
6658     if (!D.isInvalidType())
6659       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6660         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6661         << SourceRange(D.getIdentifierLoc());
6662     D.setInvalidType();
6663   }
6664   if (SC == SC_Static) {
6665     if (!D.isInvalidType())
6666       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6667         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6668         << SourceRange(D.getIdentifierLoc());
6669     D.setInvalidType();
6670     SC = SC_None;
6671   }
6672 
6673   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6674     diagnoseIgnoredQualifiers(
6675         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
6676         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
6677         D.getDeclSpec().getRestrictSpecLoc(),
6678         D.getDeclSpec().getAtomicSpecLoc());
6679     D.setInvalidType();
6680   }
6681 
6682   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6683   if (FTI.TypeQuals != 0) {
6684     if (FTI.TypeQuals & Qualifiers::Const)
6685       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6686         << "const" << SourceRange(D.getIdentifierLoc());
6687     if (FTI.TypeQuals & Qualifiers::Volatile)
6688       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6689         << "volatile" << SourceRange(D.getIdentifierLoc());
6690     if (FTI.TypeQuals & Qualifiers::Restrict)
6691       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6692         << "restrict" << SourceRange(D.getIdentifierLoc());
6693     D.setInvalidType();
6694   }
6695 
6696   // C++0x [class.ctor]p4:
6697   //   A constructor shall not be declared with a ref-qualifier.
6698   if (FTI.hasRefQualifier()) {
6699     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6700       << FTI.RefQualifierIsLValueRef
6701       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6702     D.setInvalidType();
6703   }
6704 
6705   // Rebuild the function type "R" without any type qualifiers (in
6706   // case any of the errors above fired) and with "void" as the
6707   // return type, since constructors don't have return types.
6708   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6709   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
6710     return R;
6711 
6712   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6713   EPI.TypeQuals = 0;
6714   EPI.RefQualifier = RQ_None;
6715 
6716   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
6717 }
6718 
6719 /// CheckConstructor - Checks a fully-formed constructor for
6720 /// well-formedness, issuing any diagnostics required. Returns true if
6721 /// the constructor declarator is invalid.
6722 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
6723   CXXRecordDecl *ClassDecl
6724     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6725   if (!ClassDecl)
6726     return Constructor->setInvalidDecl();
6727 
6728   // C++ [class.copy]p3:
6729   //   A declaration of a constructor for a class X is ill-formed if
6730   //   its first parameter is of type (optionally cv-qualified) X and
6731   //   either there are no other parameters or else all other
6732   //   parameters have default arguments.
6733   if (!Constructor->isInvalidDecl() &&
6734       ((Constructor->getNumParams() == 1) ||
6735        (Constructor->getNumParams() > 1 &&
6736         Constructor->getParamDecl(1)->hasDefaultArg())) &&
6737       Constructor->getTemplateSpecializationKind()
6738                                               != TSK_ImplicitInstantiation) {
6739     QualType ParamType = Constructor->getParamDecl(0)->getType();
6740     QualType ClassTy = Context.getTagDeclType(ClassDecl);
6741     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
6742       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
6743       const char *ConstRef
6744         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6745                                                         : " const &";
6746       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
6747         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
6748 
6749       // FIXME: Rather that making the constructor invalid, we should endeavor
6750       // to fix the type.
6751       Constructor->setInvalidDecl();
6752     }
6753   }
6754 }
6755 
6756 /// CheckDestructor - Checks a fully-formed destructor definition for
6757 /// well-formedness, issuing any diagnostics required.  Returns true
6758 /// on error.
6759 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
6760   CXXRecordDecl *RD = Destructor->getParent();
6761 
6762   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
6763     SourceLocation Loc;
6764 
6765     if (!Destructor->isImplicit())
6766       Loc = Destructor->getLocation();
6767     else
6768       Loc = RD->getLocation();
6769 
6770     // If we have a virtual destructor, look up the deallocation function
6771     FunctionDecl *OperatorDelete = nullptr;
6772     DeclarationName Name =
6773     Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6774     if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
6775       return true;
6776     // If there's no class-specific operator delete, look up the global
6777     // non-array delete.
6778     if (!OperatorDelete)
6779       OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
6780 
6781     MarkFunctionReferenced(Loc, OperatorDelete);
6782 
6783     Destructor->setOperatorDelete(OperatorDelete);
6784   }
6785 
6786   return false;
6787 }
6788 
6789 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6790 /// the well-formednes of the destructor declarator @p D with type @p
6791 /// R. If there are any errors in the declarator, this routine will
6792 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
6793 /// will be updated to reflect a well-formed type for the destructor and
6794 /// returned.
6795 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
6796                                          StorageClass& SC) {
6797   // C++ [class.dtor]p1:
6798   //   [...] A typedef-name that names a class is a class-name
6799   //   (7.1.3); however, a typedef-name that names a class shall not
6800   //   be used as the identifier in the declarator for a destructor
6801   //   declaration.
6802   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
6803   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
6804     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6805       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
6806   else if (const TemplateSpecializationType *TST =
6807              DeclaratorType->getAs<TemplateSpecializationType>())
6808     if (TST->isTypeAlias())
6809       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6810         << DeclaratorType << 1;
6811 
6812   // C++ [class.dtor]p2:
6813   //   A destructor is used to destroy objects of its class type. A
6814   //   destructor takes no parameters, and no return type can be
6815   //   specified for it (not even void). The address of a destructor
6816   //   shall not be taken. A destructor shall not be static. A
6817   //   destructor can be invoked for a const, volatile or const
6818   //   volatile object. A destructor shall not be declared const,
6819   //   volatile or const volatile (9.3.2).
6820   if (SC == SC_Static) {
6821     if (!D.isInvalidType())
6822       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6823         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6824         << SourceRange(D.getIdentifierLoc())
6825         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6826 
6827     SC = SC_None;
6828   }
6829   if (!D.isInvalidType()) {
6830     // Destructors don't have return types, but the parser will
6831     // happily parse something like:
6832     //
6833     //   class X {
6834     //     float ~X();
6835     //   };
6836     //
6837     // The return type will be eliminated later.
6838     if (D.getDeclSpec().hasTypeSpecifier())
6839       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6840         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6841         << SourceRange(D.getIdentifierLoc());
6842     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6843       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
6844                                 SourceLocation(),
6845                                 D.getDeclSpec().getConstSpecLoc(),
6846                                 D.getDeclSpec().getVolatileSpecLoc(),
6847                                 D.getDeclSpec().getRestrictSpecLoc(),
6848                                 D.getDeclSpec().getAtomicSpecLoc());
6849       D.setInvalidType();
6850     }
6851   }
6852 
6853   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6854   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
6855     if (FTI.TypeQuals & Qualifiers::Const)
6856       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6857         << "const" << SourceRange(D.getIdentifierLoc());
6858     if (FTI.TypeQuals & Qualifiers::Volatile)
6859       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6860         << "volatile" << SourceRange(D.getIdentifierLoc());
6861     if (FTI.TypeQuals & Qualifiers::Restrict)
6862       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6863         << "restrict" << SourceRange(D.getIdentifierLoc());
6864     D.setInvalidType();
6865   }
6866 
6867   // C++0x [class.dtor]p2:
6868   //   A destructor shall not be declared with a ref-qualifier.
6869   if (FTI.hasRefQualifier()) {
6870     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6871       << FTI.RefQualifierIsLValueRef
6872       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6873     D.setInvalidType();
6874   }
6875 
6876   // Make sure we don't have any parameters.
6877   if (FTIHasNonVoidParameters(FTI)) {
6878     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6879 
6880     // Delete the parameters.
6881     FTI.freeParams();
6882     D.setInvalidType();
6883   }
6884 
6885   // Make sure the destructor isn't variadic.
6886   if (FTI.isVariadic) {
6887     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
6888     D.setInvalidType();
6889   }
6890 
6891   // Rebuild the function type "R" without any type qualifiers or
6892   // parameters (in case any of the errors above fired) and with
6893   // "void" as the return type, since destructors don't have return
6894   // types.
6895   if (!D.isInvalidType())
6896     return R;
6897 
6898   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6899   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6900   EPI.Variadic = false;
6901   EPI.TypeQuals = 0;
6902   EPI.RefQualifier = RQ_None;
6903   return Context.getFunctionType(Context.VoidTy, None, EPI);
6904 }
6905 
6906 static void extendLeft(SourceRange &R, SourceRange Before) {
6907   if (Before.isInvalid())
6908     return;
6909   R.setBegin(Before.getBegin());
6910   if (R.getEnd().isInvalid())
6911     R.setEnd(Before.getEnd());
6912 }
6913 
6914 static void extendRight(SourceRange &R, SourceRange After) {
6915   if (After.isInvalid())
6916     return;
6917   if (R.getBegin().isInvalid())
6918     R.setBegin(After.getBegin());
6919   R.setEnd(After.getEnd());
6920 }
6921 
6922 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6923 /// well-formednes of the conversion function declarator @p D with
6924 /// type @p R. If there are any errors in the declarator, this routine
6925 /// will emit diagnostics and return true. Otherwise, it will return
6926 /// false. Either way, the type @p R will be updated to reflect a
6927 /// well-formed type for the conversion operator.
6928 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
6929                                      StorageClass& SC) {
6930   // C++ [class.conv.fct]p1:
6931   //   Neither parameter types nor return type can be specified. The
6932   //   type of a conversion function (8.3.5) is "function taking no
6933   //   parameter returning conversion-type-id."
6934   if (SC == SC_Static) {
6935     if (!D.isInvalidType())
6936       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
6937         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6938         << D.getName().getSourceRange();
6939     D.setInvalidType();
6940     SC = SC_None;
6941   }
6942 
6943   TypeSourceInfo *ConvTSI = nullptr;
6944   QualType ConvType =
6945       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
6946 
6947   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
6948     // Conversion functions don't have return types, but the parser will
6949     // happily parse something like:
6950     //
6951     //   class X {
6952     //     float operator bool();
6953     //   };
6954     //
6955     // The return type will be changed later anyway.
6956     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6957       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6958       << SourceRange(D.getIdentifierLoc());
6959     D.setInvalidType();
6960   }
6961 
6962   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6963 
6964   // Make sure we don't have any parameters.
6965   if (Proto->getNumParams() > 0) {
6966     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6967 
6968     // Delete the parameters.
6969     D.getFunctionTypeInfo().freeParams();
6970     D.setInvalidType();
6971   } else if (Proto->isVariadic()) {
6972     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
6973     D.setInvalidType();
6974   }
6975 
6976   // Diagnose "&operator bool()" and other such nonsense.  This
6977   // is actually a gcc extension which we don't support.
6978   if (Proto->getReturnType() != ConvType) {
6979     bool NeedsTypedef = false;
6980     SourceRange Before, After;
6981 
6982     // Walk the chunks and extract information on them for our diagnostic.
6983     bool PastFunctionChunk = false;
6984     for (auto &Chunk : D.type_objects()) {
6985       switch (Chunk.Kind) {
6986       case DeclaratorChunk::Function:
6987         if (!PastFunctionChunk) {
6988           if (Chunk.Fun.HasTrailingReturnType) {
6989             TypeSourceInfo *TRT = nullptr;
6990             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
6991             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
6992           }
6993           PastFunctionChunk = true;
6994           break;
6995         }
6996         // Fall through.
6997       case DeclaratorChunk::Array:
6998         NeedsTypedef = true;
6999         extendRight(After, Chunk.getSourceRange());
7000         break;
7001 
7002       case DeclaratorChunk::Pointer:
7003       case DeclaratorChunk::BlockPointer:
7004       case DeclaratorChunk::Reference:
7005       case DeclaratorChunk::MemberPointer:
7006       case DeclaratorChunk::Pipe:
7007         extendLeft(Before, Chunk.getSourceRange());
7008         break;
7009 
7010       case DeclaratorChunk::Paren:
7011         extendLeft(Before, Chunk.Loc);
7012         extendRight(After, Chunk.EndLoc);
7013         break;
7014       }
7015     }
7016 
7017     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
7018                          After.isValid()  ? After.getBegin() :
7019                                             D.getIdentifierLoc();
7020     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
7021     DB << Before << After;
7022 
7023     if (!NeedsTypedef) {
7024       DB << /*don't need a typedef*/0;
7025 
7026       // If we can provide a correct fix-it hint, do so.
7027       if (After.isInvalid() && ConvTSI) {
7028         SourceLocation InsertLoc =
7029             getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
7030         DB << FixItHint::CreateInsertion(InsertLoc, " ")
7031            << FixItHint::CreateInsertionFromRange(
7032                   InsertLoc, CharSourceRange::getTokenRange(Before))
7033            << FixItHint::CreateRemoval(Before);
7034       }
7035     } else if (!Proto->getReturnType()->isDependentType()) {
7036       DB << /*typedef*/1 << Proto->getReturnType();
7037     } else if (getLangOpts().CPlusPlus11) {
7038       DB << /*alias template*/2 << Proto->getReturnType();
7039     } else {
7040       DB << /*might not be fixable*/3;
7041     }
7042 
7043     // Recover by incorporating the other type chunks into the result type.
7044     // Note, this does *not* change the name of the function. This is compatible
7045     // with the GCC extension:
7046     //   struct S { &operator int(); } s;
7047     //   int &r = s.operator int(); // ok in GCC
7048     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
7049     ConvType = Proto->getReturnType();
7050   }
7051 
7052   // C++ [class.conv.fct]p4:
7053   //   The conversion-type-id shall not represent a function type nor
7054   //   an array type.
7055   if (ConvType->isArrayType()) {
7056     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
7057     ConvType = Context.getPointerType(ConvType);
7058     D.setInvalidType();
7059   } else if (ConvType->isFunctionType()) {
7060     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
7061     ConvType = Context.getPointerType(ConvType);
7062     D.setInvalidType();
7063   }
7064 
7065   // Rebuild the function type "R" without any parameters (in case any
7066   // of the errors above fired) and with the conversion type as the
7067   // return type.
7068   if (D.isInvalidType())
7069     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
7070 
7071   // C++0x explicit conversion operators.
7072   if (D.getDeclSpec().isExplicitSpecified())
7073     Diag(D.getDeclSpec().getExplicitSpecLoc(),
7074          getLangOpts().CPlusPlus11 ?
7075            diag::warn_cxx98_compat_explicit_conversion_functions :
7076            diag::ext_explicit_conversion_functions)
7077       << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
7078 }
7079 
7080 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
7081 /// the declaration of the given C++ conversion function. This routine
7082 /// is responsible for recording the conversion function in the C++
7083 /// class, if possible.
7084 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
7085   assert(Conversion && "Expected to receive a conversion function declaration");
7086 
7087   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
7088 
7089   // Make sure we aren't redeclaring the conversion function.
7090   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
7091 
7092   // C++ [class.conv.fct]p1:
7093   //   [...] A conversion function is never used to convert a
7094   //   (possibly cv-qualified) object to the (possibly cv-qualified)
7095   //   same object type (or a reference to it), to a (possibly
7096   //   cv-qualified) base class of that type (or a reference to it),
7097   //   or to (possibly cv-qualified) void.
7098   // FIXME: Suppress this warning if the conversion function ends up being a
7099   // virtual function that overrides a virtual function in a base class.
7100   QualType ClassType
7101     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
7102   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
7103     ConvType = ConvTypeRef->getPointeeType();
7104   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
7105       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
7106     /* Suppress diagnostics for instantiations. */;
7107   else if (ConvType->isRecordType()) {
7108     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
7109     if (ConvType == ClassType)
7110       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
7111         << ClassType;
7112     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
7113       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
7114         <<  ClassType << ConvType;
7115   } else if (ConvType->isVoidType()) {
7116     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
7117       << ClassType << ConvType;
7118   }
7119 
7120   if (FunctionTemplateDecl *ConversionTemplate
7121                                 = Conversion->getDescribedFunctionTemplate())
7122     return ConversionTemplate;
7123 
7124   return Conversion;
7125 }
7126 
7127 //===----------------------------------------------------------------------===//
7128 // Namespace Handling
7129 //===----------------------------------------------------------------------===//
7130 
7131 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
7132 /// reopened.
7133 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
7134                                             SourceLocation Loc,
7135                                             IdentifierInfo *II, bool *IsInline,
7136                                             NamespaceDecl *PrevNS) {
7137   assert(*IsInline != PrevNS->isInline());
7138 
7139   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
7140   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
7141   // inline namespaces, with the intention of bringing names into namespace std.
7142   //
7143   // We support this just well enough to get that case working; this is not
7144   // sufficient to support reopening namespaces as inline in general.
7145   if (*IsInline && II && II->getName().startswith("__atomic") &&
7146       S.getSourceManager().isInSystemHeader(Loc)) {
7147     // Mark all prior declarations of the namespace as inline.
7148     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
7149          NS = NS->getPreviousDecl())
7150       NS->setInline(*IsInline);
7151     // Patch up the lookup table for the containing namespace. This isn't really
7152     // correct, but it's good enough for this particular case.
7153     for (auto *I : PrevNS->decls())
7154       if (auto *ND = dyn_cast<NamedDecl>(I))
7155         PrevNS->getParent()->makeDeclVisibleInContext(ND);
7156     return;
7157   }
7158 
7159   if (PrevNS->isInline())
7160     // The user probably just forgot the 'inline', so suggest that it
7161     // be added back.
7162     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
7163       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
7164   else
7165     S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
7166 
7167   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
7168   *IsInline = PrevNS->isInline();
7169 }
7170 
7171 /// ActOnStartNamespaceDef - This is called at the start of a namespace
7172 /// definition.
7173 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
7174                                    SourceLocation InlineLoc,
7175                                    SourceLocation NamespaceLoc,
7176                                    SourceLocation IdentLoc,
7177                                    IdentifierInfo *II,
7178                                    SourceLocation LBrace,
7179                                    AttributeList *AttrList,
7180                                    UsingDirectiveDecl *&UD) {
7181   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
7182   // For anonymous namespace, take the location of the left brace.
7183   SourceLocation Loc = II ? IdentLoc : LBrace;
7184   bool IsInline = InlineLoc.isValid();
7185   bool IsInvalid = false;
7186   bool IsStd = false;
7187   bool AddToKnown = false;
7188   Scope *DeclRegionScope = NamespcScope->getParent();
7189 
7190   NamespaceDecl *PrevNS = nullptr;
7191   if (II) {
7192     // C++ [namespace.def]p2:
7193     //   The identifier in an original-namespace-definition shall not
7194     //   have been previously defined in the declarative region in
7195     //   which the original-namespace-definition appears. The
7196     //   identifier in an original-namespace-definition is the name of
7197     //   the namespace. Subsequently in that declarative region, it is
7198     //   treated as an original-namespace-name.
7199     //
7200     // Since namespace names are unique in their scope, and we don't
7201     // look through using directives, just look for any ordinary names
7202     // as if by qualified name lookup.
7203     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, ForRedeclaration);
7204     LookupQualifiedName(R, CurContext->getRedeclContext());
7205     NamedDecl *PrevDecl =
7206         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
7207     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
7208 
7209     if (PrevNS) {
7210       // This is an extended namespace definition.
7211       if (IsInline != PrevNS->isInline())
7212         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
7213                                         &IsInline, PrevNS);
7214     } else if (PrevDecl) {
7215       // This is an invalid name redefinition.
7216       Diag(Loc, diag::err_redefinition_different_kind)
7217         << II;
7218       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
7219       IsInvalid = true;
7220       // Continue on to push Namespc as current DeclContext and return it.
7221     } else if (II->isStr("std") &&
7222                CurContext->getRedeclContext()->isTranslationUnit()) {
7223       // This is the first "real" definition of the namespace "std", so update
7224       // our cache of the "std" namespace to point at this definition.
7225       PrevNS = getStdNamespace();
7226       IsStd = true;
7227       AddToKnown = !IsInline;
7228     } else {
7229       // We've seen this namespace for the first time.
7230       AddToKnown = !IsInline;
7231     }
7232   } else {
7233     // Anonymous namespaces.
7234 
7235     // Determine whether the parent already has an anonymous namespace.
7236     DeclContext *Parent = CurContext->getRedeclContext();
7237     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7238       PrevNS = TU->getAnonymousNamespace();
7239     } else {
7240       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
7241       PrevNS = ND->getAnonymousNamespace();
7242     }
7243 
7244     if (PrevNS && IsInline != PrevNS->isInline())
7245       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
7246                                       &IsInline, PrevNS);
7247   }
7248 
7249   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
7250                                                  StartLoc, Loc, II, PrevNS);
7251   if (IsInvalid)
7252     Namespc->setInvalidDecl();
7253 
7254   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
7255 
7256   // FIXME: Should we be merging attributes?
7257   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
7258     PushNamespaceVisibilityAttr(Attr, Loc);
7259 
7260   if (IsStd)
7261     StdNamespace = Namespc;
7262   if (AddToKnown)
7263     KnownNamespaces[Namespc] = false;
7264 
7265   if (II) {
7266     PushOnScopeChains(Namespc, DeclRegionScope);
7267   } else {
7268     // Link the anonymous namespace into its parent.
7269     DeclContext *Parent = CurContext->getRedeclContext();
7270     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7271       TU->setAnonymousNamespace(Namespc);
7272     } else {
7273       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
7274     }
7275 
7276     CurContext->addDecl(Namespc);
7277 
7278     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
7279     //   behaves as if it were replaced by
7280     //     namespace unique { /* empty body */ }
7281     //     using namespace unique;
7282     //     namespace unique { namespace-body }
7283     //   where all occurrences of 'unique' in a translation unit are
7284     //   replaced by the same identifier and this identifier differs
7285     //   from all other identifiers in the entire program.
7286 
7287     // We just create the namespace with an empty name and then add an
7288     // implicit using declaration, just like the standard suggests.
7289     //
7290     // CodeGen enforces the "universally unique" aspect by giving all
7291     // declarations semantically contained within an anonymous
7292     // namespace internal linkage.
7293 
7294     if (!PrevNS) {
7295       UD = 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.getFoundDecl());
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->isTemplateParamScope())
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.getRepresentativeDecl();
7588     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
7589     assert(NS && "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     DeclContext *CommonAncestor = cast<DeclContext>(NS);
7607     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7608       CommonAncestor = CommonAncestor->getParent();
7609 
7610     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
7611                                       SS.getWithLocInContext(Context),
7612                                       IdentLoc, Named, CommonAncestor);
7613 
7614     if (IsUsingDirectiveInToplevelContext(CurContext) &&
7615         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
7616       Diag(IdentLoc, diag::warn_using_directive_in_header);
7617     }
7618 
7619     PushUsingDirective(S, UDir);
7620   } else {
7621     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
7622   }
7623 
7624   if (UDir)
7625     ProcessDeclAttributeList(S, UDir, AttrList);
7626 
7627   return UDir;
7628 }
7629 
7630 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
7631   // If the scope has an associated entity and the using directive is at
7632   // namespace or translation unit scope, add the UsingDirectiveDecl into
7633   // its lookup structure so qualified name lookup can find it.
7634   DeclContext *Ctx = S->getEntity();
7635   if (Ctx && !Ctx->isFunctionOrMethod())
7636     Ctx->addDecl(UDir);
7637   else
7638     // Otherwise, it is at block scope. The using-directives will affect lookup
7639     // only to the end of the scope.
7640     S->PushUsingDirective(UDir);
7641 }
7642 
7643 
7644 Decl *Sema::ActOnUsingDeclaration(Scope *S,
7645                                   AccessSpecifier AS,
7646                                   bool HasUsingKeyword,
7647                                   SourceLocation UsingLoc,
7648                                   CXXScopeSpec &SS,
7649                                   UnqualifiedId &Name,
7650                                   AttributeList *AttrList,
7651                                   bool HasTypenameKeyword,
7652                                   SourceLocation TypenameLoc) {
7653   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7654 
7655   switch (Name.getKind()) {
7656   case UnqualifiedId::IK_ImplicitSelfParam:
7657   case UnqualifiedId::IK_Identifier:
7658   case UnqualifiedId::IK_OperatorFunctionId:
7659   case UnqualifiedId::IK_LiteralOperatorId:
7660   case UnqualifiedId::IK_ConversionFunctionId:
7661     break;
7662 
7663   case UnqualifiedId::IK_ConstructorName:
7664   case UnqualifiedId::IK_ConstructorTemplateId:
7665     // C++11 inheriting constructors.
7666     Diag(Name.getLocStart(),
7667          getLangOpts().CPlusPlus11 ?
7668            diag::warn_cxx98_compat_using_decl_constructor :
7669            diag::err_using_decl_constructor)
7670       << SS.getRange();
7671 
7672     if (getLangOpts().CPlusPlus11) break;
7673 
7674     return nullptr;
7675 
7676   case UnqualifiedId::IK_DestructorName:
7677     Diag(Name.getLocStart(), diag::err_using_decl_destructor)
7678       << SS.getRange();
7679     return nullptr;
7680 
7681   case UnqualifiedId::IK_TemplateId:
7682     Diag(Name.getLocStart(), diag::err_using_decl_template_id)
7683       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
7684     return nullptr;
7685   }
7686 
7687   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7688   DeclarationName TargetName = TargetNameInfo.getName();
7689   if (!TargetName)
7690     return nullptr;
7691 
7692   // Warn about access declarations.
7693   if (!HasUsingKeyword) {
7694     Diag(Name.getLocStart(),
7695          getLangOpts().CPlusPlus11 ? diag::err_access_decl
7696                                    : diag::warn_access_decl_deprecated)
7697       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
7698   }
7699 
7700   if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7701       DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7702     return nullptr;
7703 
7704   NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
7705                                         TargetNameInfo, AttrList,
7706                                         /* IsInstantiation */ false,
7707                                         HasTypenameKeyword, TypenameLoc);
7708   if (UD)
7709     PushOnScopeChains(UD, S, /*AddToContext*/ false);
7710 
7711   return UD;
7712 }
7713 
7714 /// \brief Determine whether a using declaration considers the given
7715 /// declarations as "equivalent", e.g., if they are redeclarations of
7716 /// the same entity or are both typedefs of the same type.
7717 static bool
7718 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7719   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
7720     return true;
7721 
7722   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
7723     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
7724       return Context.hasSameType(TD1->getUnderlyingType(),
7725                                  TD2->getUnderlyingType());
7726 
7727   return false;
7728 }
7729 
7730 
7731 /// Determines whether to create a using shadow decl for a particular
7732 /// decl, given the set of decls existing prior to this using lookup.
7733 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
7734                                 const LookupResult &Previous,
7735                                 UsingShadowDecl *&PrevShadow) {
7736   // Diagnose finding a decl which is not from a base class of the
7737   // current class.  We do this now because there are cases where this
7738   // function will silently decide not to build a shadow decl, which
7739   // will pre-empt further diagnostics.
7740   //
7741   // We don't need to do this in C++0x because we do the check once on
7742   // the qualifier.
7743   //
7744   // FIXME: diagnose the following if we care enough:
7745   //   struct A { int foo; };
7746   //   struct B : A { using A::foo; };
7747   //   template <class T> struct C : A {};
7748   //   template <class T> struct D : C<T> { using B::foo; } // <---
7749   // This is invalid (during instantiation) in C++03 because B::foo
7750   // resolves to the using decl in B, which is not a base class of D<T>.
7751   // We can't diagnose it immediately because C<T> is an unknown
7752   // specialization.  The UsingShadowDecl in D<T> then points directly
7753   // to A::foo, which will look well-formed when we instantiate.
7754   // The right solution is to not collapse the shadow-decl chain.
7755   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
7756     DeclContext *OrigDC = Orig->getDeclContext();
7757 
7758     // Handle enums and anonymous structs.
7759     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7760     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7761     while (OrigRec->isAnonymousStructOrUnion())
7762       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7763 
7764     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7765       if (OrigDC == CurContext) {
7766         Diag(Using->getLocation(),
7767              diag::err_using_decl_nested_name_specifier_is_current_class)
7768           << Using->getQualifierLoc().getSourceRange();
7769         Diag(Orig->getLocation(), diag::note_using_decl_target);
7770         return true;
7771       }
7772 
7773       Diag(Using->getQualifierLoc().getBeginLoc(),
7774            diag::err_using_decl_nested_name_specifier_is_not_base_class)
7775         << Using->getQualifier()
7776         << cast<CXXRecordDecl>(CurContext)
7777         << Using->getQualifierLoc().getSourceRange();
7778       Diag(Orig->getLocation(), diag::note_using_decl_target);
7779       return true;
7780     }
7781   }
7782 
7783   if (Previous.empty()) return false;
7784 
7785   NamedDecl *Target = Orig;
7786   if (isa<UsingShadowDecl>(Target))
7787     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7788 
7789   // If the target happens to be one of the previous declarations, we
7790   // don't have a conflict.
7791   //
7792   // FIXME: but we might be increasing its access, in which case we
7793   // should redeclare it.
7794   NamedDecl *NonTag = nullptr, *Tag = nullptr;
7795   bool FoundEquivalentDecl = false;
7796   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7797          I != E; ++I) {
7798     NamedDecl *D = (*I)->getUnderlyingDecl();
7799     // We can have UsingDecls in our Previous results because we use the same
7800     // LookupResult for checking whether the UsingDecl itself is a valid
7801     // redeclaration.
7802     if (isa<UsingDecl>(D))
7803       continue;
7804 
7805     if (IsEquivalentForUsingDecl(Context, D, Target)) {
7806       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7807         PrevShadow = Shadow;
7808       FoundEquivalentDecl = true;
7809     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
7810       // We don't conflict with an existing using shadow decl of an equivalent
7811       // declaration, but we're not a redeclaration of it.
7812       FoundEquivalentDecl = true;
7813     }
7814 
7815     if (isVisible(D))
7816       (isa<TagDecl>(D) ? Tag : NonTag) = D;
7817   }
7818 
7819   if (FoundEquivalentDecl)
7820     return false;
7821 
7822   if (FunctionDecl *FD = Target->getAsFunction()) {
7823     NamedDecl *OldDecl = nullptr;
7824     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7825                           /*IsForUsingDecl*/ true)) {
7826     case Ovl_Overload:
7827       return false;
7828 
7829     case Ovl_NonFunction:
7830       Diag(Using->getLocation(), diag::err_using_decl_conflict);
7831       break;
7832 
7833     // We found a decl with the exact signature.
7834     case Ovl_Match:
7835       // If we're in a record, we want to hide the target, so we
7836       // return true (without a diagnostic) to tell the caller not to
7837       // build a shadow decl.
7838       if (CurContext->isRecord())
7839         return true;
7840 
7841       // If we're not in a record, this is an error.
7842       Diag(Using->getLocation(), diag::err_using_decl_conflict);
7843       break;
7844     }
7845 
7846     Diag(Target->getLocation(), diag::note_using_decl_target);
7847     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7848     return true;
7849   }
7850 
7851   // Target is not a function.
7852 
7853   if (isa<TagDecl>(Target)) {
7854     // No conflict between a tag and a non-tag.
7855     if (!Tag) return false;
7856 
7857     Diag(Using->getLocation(), diag::err_using_decl_conflict);
7858     Diag(Target->getLocation(), diag::note_using_decl_target);
7859     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7860     return true;
7861   }
7862 
7863   // No conflict between a tag and a non-tag.
7864   if (!NonTag) return false;
7865 
7866   Diag(Using->getLocation(), diag::err_using_decl_conflict);
7867   Diag(Target->getLocation(), diag::note_using_decl_target);
7868   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7869   return true;
7870 }
7871 
7872 /// Builds a shadow declaration corresponding to a 'using' declaration.
7873 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
7874                                             UsingDecl *UD,
7875                                             NamedDecl *Orig,
7876                                             UsingShadowDecl *PrevDecl) {
7877 
7878   // If we resolved to another shadow declaration, just coalesce them.
7879   NamedDecl *Target = Orig;
7880   if (isa<UsingShadowDecl>(Target)) {
7881     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7882     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
7883   }
7884 
7885   UsingShadowDecl *Shadow
7886     = UsingShadowDecl::Create(Context, CurContext,
7887                               UD->getLocation(), UD, Target);
7888   UD->addShadowDecl(Shadow);
7889 
7890   Shadow->setAccess(UD->getAccess());
7891   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7892     Shadow->setInvalidDecl();
7893 
7894   Shadow->setPreviousDecl(PrevDecl);
7895 
7896   if (S)
7897     PushOnScopeChains(Shadow, S);
7898   else
7899     CurContext->addDecl(Shadow);
7900 
7901 
7902   return Shadow;
7903 }
7904 
7905 /// Hides a using shadow declaration.  This is required by the current
7906 /// using-decl implementation when a resolvable using declaration in a
7907 /// class is followed by a declaration which would hide or override
7908 /// one or more of the using decl's targets; for example:
7909 ///
7910 ///   struct Base { void foo(int); };
7911 ///   struct Derived : Base {
7912 ///     using Base::foo;
7913 ///     void foo(int);
7914 ///   };
7915 ///
7916 /// The governing language is C++03 [namespace.udecl]p12:
7917 ///
7918 ///   When a using-declaration brings names from a base class into a
7919 ///   derived class scope, member functions in the derived class
7920 ///   override and/or hide member functions with the same name and
7921 ///   parameter types in a base class (rather than conflicting).
7922 ///
7923 /// There are two ways to implement this:
7924 ///   (1) optimistically create shadow decls when they're not hidden
7925 ///       by existing declarations, or
7926 ///   (2) don't create any shadow decls (or at least don't make them
7927 ///       visible) until we've fully parsed/instantiated the class.
7928 /// The problem with (1) is that we might have to retroactively remove
7929 /// a shadow decl, which requires several O(n) operations because the
7930 /// decl structures are (very reasonably) not designed for removal.
7931 /// (2) avoids this but is very fiddly and phase-dependent.
7932 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
7933   if (Shadow->getDeclName().getNameKind() ==
7934         DeclarationName::CXXConversionFunctionName)
7935     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7936 
7937   // Remove it from the DeclContext...
7938   Shadow->getDeclContext()->removeDecl(Shadow);
7939 
7940   // ...and the scope, if applicable...
7941   if (S) {
7942     S->RemoveDecl(Shadow);
7943     IdResolver.RemoveDecl(Shadow);
7944   }
7945 
7946   // ...and the using decl.
7947   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7948 
7949   // TODO: complain somehow if Shadow was used.  It shouldn't
7950   // be possible for this to happen, because...?
7951 }
7952 
7953 /// Find the base specifier for a base class with the given type.
7954 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7955                                                 QualType DesiredBase,
7956                                                 bool &AnyDependentBases) {
7957   // Check whether the named type is a direct base class.
7958   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7959   for (auto &Base : Derived->bases()) {
7960     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7961     if (CanonicalDesiredBase == BaseType)
7962       return &Base;
7963     if (BaseType->isDependentType())
7964       AnyDependentBases = true;
7965   }
7966   return nullptr;
7967 }
7968 
7969 namespace {
7970 class UsingValidatorCCC : public CorrectionCandidateCallback {
7971 public:
7972   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
7973                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
7974       : HasTypenameKeyword(HasTypenameKeyword),
7975         IsInstantiation(IsInstantiation), OldNNS(NNS),
7976         RequireMemberOf(RequireMemberOf) {}
7977 
7978   bool ValidateCandidate(const TypoCorrection &Candidate) override {
7979     NamedDecl *ND = Candidate.getCorrectionDecl();
7980 
7981     // Keywords are not valid here.
7982     if (!ND || isa<NamespaceDecl>(ND))
7983       return false;
7984 
7985     // Completely unqualified names are invalid for a 'using' declaration.
7986     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7987       return false;
7988 
7989     if (RequireMemberOf) {
7990       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
7991       if (FoundRecord && FoundRecord->isInjectedClassName()) {
7992         // No-one ever wants a using-declaration to name an injected-class-name
7993         // of a base class, unless they're declaring an inheriting constructor.
7994         ASTContext &Ctx = ND->getASTContext();
7995         if (!Ctx.getLangOpts().CPlusPlus11)
7996           return false;
7997         QualType FoundType = Ctx.getRecordType(FoundRecord);
7998 
7999         // Check that the injected-class-name is named as a member of its own
8000         // type; we don't want to suggest 'using Derived::Base;', since that
8001         // means something else.
8002         NestedNameSpecifier *Specifier =
8003             Candidate.WillReplaceSpecifier()
8004                 ? Candidate.getCorrectionSpecifier()
8005                 : OldNNS;
8006         if (!Specifier->getAsType() ||
8007             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
8008           return false;
8009 
8010         // Check that this inheriting constructor declaration actually names a
8011         // direct base class of the current class.
8012         bool AnyDependentBases = false;
8013         if (!findDirectBaseWithType(RequireMemberOf,
8014                                     Ctx.getRecordType(FoundRecord),
8015                                     AnyDependentBases) &&
8016             !AnyDependentBases)
8017           return false;
8018       } else {
8019         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
8020         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
8021           return false;
8022 
8023         // FIXME: Check that the base class member is accessible?
8024       }
8025     } else {
8026       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
8027       if (FoundRecord && FoundRecord->isInjectedClassName())
8028         return false;
8029     }
8030 
8031     if (isa<TypeDecl>(ND))
8032       return HasTypenameKeyword || !IsInstantiation;
8033 
8034     return !HasTypenameKeyword;
8035   }
8036 
8037 private:
8038   bool HasTypenameKeyword;
8039   bool IsInstantiation;
8040   NestedNameSpecifier *OldNNS;
8041   CXXRecordDecl *RequireMemberOf;
8042 };
8043 } // end anonymous namespace
8044 
8045 /// Builds a using declaration.
8046 ///
8047 /// \param IsInstantiation - Whether this call arises from an
8048 ///   instantiation of an unresolved using declaration.  We treat
8049 ///   the lookup differently for these declarations.
8050 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
8051                                        SourceLocation UsingLoc,
8052                                        CXXScopeSpec &SS,
8053                                        DeclarationNameInfo NameInfo,
8054                                        AttributeList *AttrList,
8055                                        bool IsInstantiation,
8056                                        bool HasTypenameKeyword,
8057                                        SourceLocation TypenameLoc) {
8058   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
8059   SourceLocation IdentLoc = NameInfo.getLoc();
8060   assert(IdentLoc.isValid() && "Invalid TargetName location.");
8061 
8062   // FIXME: We ignore attributes for now.
8063 
8064   if (SS.isEmpty()) {
8065     Diag(IdentLoc, diag::err_using_requires_qualname);
8066     return nullptr;
8067   }
8068 
8069   // Do the redeclaration lookup in the current scope.
8070   LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
8071                         ForRedeclaration);
8072   Previous.setHideTags(false);
8073   if (S) {
8074     LookupName(Previous, S);
8075 
8076     // It is really dumb that we have to do this.
8077     LookupResult::Filter F = Previous.makeFilter();
8078     while (F.hasNext()) {
8079       NamedDecl *D = F.next();
8080       if (!isDeclInScope(D, CurContext, S))
8081         F.erase();
8082       // If we found a local extern declaration that's not ordinarily visible,
8083       // and this declaration is being added to a non-block scope, ignore it.
8084       // We're only checking for scope conflicts here, not also for violations
8085       // of the linkage rules.
8086       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
8087                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
8088         F.erase();
8089     }
8090     F.done();
8091   } else {
8092     assert(IsInstantiation && "no scope in non-instantiation");
8093     assert(CurContext->isRecord() && "scope not record in instantiation");
8094     LookupQualifiedName(Previous, CurContext);
8095   }
8096 
8097   // Check for invalid redeclarations.
8098   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
8099                                   SS, IdentLoc, Previous))
8100     return nullptr;
8101 
8102   // Check for bad qualifiers.
8103   if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
8104     return nullptr;
8105 
8106   DeclContext *LookupContext = computeDeclContext(SS);
8107   NamedDecl *D;
8108   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
8109   if (!LookupContext) {
8110     if (HasTypenameKeyword) {
8111       // FIXME: not all declaration name kinds are legal here
8112       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
8113                                               UsingLoc, TypenameLoc,
8114                                               QualifierLoc,
8115                                               IdentLoc, NameInfo.getName());
8116     } else {
8117       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
8118                                            QualifierLoc, NameInfo);
8119     }
8120     D->setAccess(AS);
8121     CurContext->addDecl(D);
8122     return D;
8123   }
8124 
8125   auto Build = [&](bool Invalid) {
8126     UsingDecl *UD =
8127         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
8128                           HasTypenameKeyword);
8129     UD->setAccess(AS);
8130     CurContext->addDecl(UD);
8131     UD->setInvalidDecl(Invalid);
8132     return UD;
8133   };
8134   auto BuildInvalid = [&]{ return Build(true); };
8135   auto BuildValid = [&]{ return Build(false); };
8136 
8137   if (RequireCompleteDeclContext(SS, LookupContext))
8138     return BuildInvalid();
8139 
8140   // Look up the target name.
8141   LookupResult R(*this, NameInfo, LookupOrdinaryName);
8142 
8143   // Unlike most lookups, we don't always want to hide tag
8144   // declarations: tag names are visible through the using declaration
8145   // even if hidden by ordinary names, *except* in a dependent context
8146   // where it's important for the sanity of two-phase lookup.
8147   if (!IsInstantiation)
8148     R.setHideTags(false);
8149 
8150   // For the purposes of this lookup, we have a base object type
8151   // equal to that of the current context.
8152   if (CurContext->isRecord()) {
8153     R.setBaseObjectType(
8154                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
8155   }
8156 
8157   LookupQualifiedName(R, LookupContext);
8158 
8159   // Try to correct typos if possible. If constructor name lookup finds no
8160   // results, that means the named class has no explicit constructors, and we
8161   // suppressed declaring implicit ones (probably because it's dependent or
8162   // invalid).
8163   if (R.empty() &&
8164       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
8165     if (TypoCorrection Corrected = CorrectTypo(
8166             R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
8167             llvm::make_unique<UsingValidatorCCC>(
8168                 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
8169                 dyn_cast<CXXRecordDecl>(CurContext)),
8170             CTK_ErrorRecovery)) {
8171       // We reject any correction for which ND would be NULL.
8172       NamedDecl *ND = Corrected.getCorrectionDecl();
8173 
8174       // We reject candidates where DroppedSpecifier == true, hence the
8175       // literal '0' below.
8176       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
8177                                 << NameInfo.getName() << LookupContext << 0
8178                                 << SS.getRange());
8179 
8180       // If we corrected to an inheriting constructor, handle it as one.
8181       auto *RD = dyn_cast<CXXRecordDecl>(ND);
8182       if (RD && RD->isInjectedClassName()) {
8183         // Fix up the information we'll use to build the using declaration.
8184         if (Corrected.WillReplaceSpecifier()) {
8185           NestedNameSpecifierLocBuilder Builder;
8186           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
8187                               QualifierLoc.getSourceRange());
8188           QualifierLoc = Builder.getWithLocInContext(Context);
8189         }
8190 
8191         NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
8192             Context.getCanonicalType(Context.getRecordType(RD))));
8193         NameInfo.setNamedTypeInfo(nullptr);
8194         for (auto *Ctor : LookupConstructors(RD))
8195           R.addDecl(Ctor);
8196       } else {
8197         // FIXME: Pick up all the declarations if we found an overloaded function.
8198         R.addDecl(ND);
8199       }
8200     } else {
8201       Diag(IdentLoc, diag::err_no_member)
8202         << NameInfo.getName() << LookupContext << SS.getRange();
8203       return BuildInvalid();
8204     }
8205   }
8206 
8207   if (R.isAmbiguous())
8208     return BuildInvalid();
8209 
8210   if (HasTypenameKeyword) {
8211     // If we asked for a typename and got a non-type decl, error out.
8212     if (!R.getAsSingle<TypeDecl>()) {
8213       Diag(IdentLoc, diag::err_using_typename_non_type);
8214       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8215         Diag((*I)->getUnderlyingDecl()->getLocation(),
8216              diag::note_using_decl_target);
8217       return BuildInvalid();
8218     }
8219   } else {
8220     // If we asked for a non-typename and we got a type, error out,
8221     // but only if this is an instantiation of an unresolved using
8222     // decl.  Otherwise just silently find the type name.
8223     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
8224       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
8225       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
8226       return BuildInvalid();
8227     }
8228   }
8229 
8230   // C++0x N2914 [namespace.udecl]p6:
8231   // A using-declaration shall not name a namespace.
8232   if (R.getAsSingle<NamespaceDecl>()) {
8233     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
8234       << SS.getRange();
8235     return BuildInvalid();
8236   }
8237 
8238   UsingDecl *UD = BuildValid();
8239 
8240   // The normal rules do not apply to inheriting constructor declarations.
8241   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
8242     // Suppress access diagnostics; the access check is instead performed at the
8243     // point of use for an inheriting constructor.
8244     R.suppressDiagnostics();
8245     CheckInheritingConstructorUsingDecl(UD);
8246     return UD;
8247   }
8248 
8249   // Otherwise, look up the target name.
8250 
8251   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8252     UsingShadowDecl *PrevDecl = nullptr;
8253     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
8254       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
8255   }
8256 
8257   return UD;
8258 }
8259 
8260 /// Additional checks for a using declaration referring to a constructor name.
8261 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
8262   assert(!UD->hasTypename() && "expecting a constructor name");
8263 
8264   const Type *SourceType = UD->getQualifier()->getAsType();
8265   assert(SourceType &&
8266          "Using decl naming constructor doesn't have type in scope spec.");
8267   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
8268 
8269   // Check whether the named type is a direct base class.
8270   bool AnyDependentBases = false;
8271   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
8272                                       AnyDependentBases);
8273   if (!Base && !AnyDependentBases) {
8274     Diag(UD->getUsingLoc(),
8275          diag::err_using_decl_constructor_not_in_direct_base)
8276       << UD->getNameInfo().getSourceRange()
8277       << QualType(SourceType, 0) << TargetClass;
8278     UD->setInvalidDecl();
8279     return true;
8280   }
8281 
8282   if (Base)
8283     Base->setInheritConstructors();
8284 
8285   return false;
8286 }
8287 
8288 /// Checks that the given using declaration is not an invalid
8289 /// redeclaration.  Note that this is checking only for the using decl
8290 /// itself, not for any ill-formedness among the UsingShadowDecls.
8291 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
8292                                        bool HasTypenameKeyword,
8293                                        const CXXScopeSpec &SS,
8294                                        SourceLocation NameLoc,
8295                                        const LookupResult &Prev) {
8296   // C++03 [namespace.udecl]p8:
8297   // C++0x [namespace.udecl]p10:
8298   //   A using-declaration is a declaration and can therefore be used
8299   //   repeatedly where (and only where) multiple declarations are
8300   //   allowed.
8301   //
8302   // That's in non-member contexts.
8303   if (!CurContext->getRedeclContext()->isRecord())
8304     return false;
8305 
8306   NestedNameSpecifier *Qual = SS.getScopeRep();
8307 
8308   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
8309     NamedDecl *D = *I;
8310 
8311     bool DTypename;
8312     NestedNameSpecifier *DQual;
8313     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
8314       DTypename = UD->hasTypename();
8315       DQual = UD->getQualifier();
8316     } else if (UnresolvedUsingValueDecl *UD
8317                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
8318       DTypename = false;
8319       DQual = UD->getQualifier();
8320     } else if (UnresolvedUsingTypenameDecl *UD
8321                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
8322       DTypename = true;
8323       DQual = UD->getQualifier();
8324     } else continue;
8325 
8326     // using decls differ if one says 'typename' and the other doesn't.
8327     // FIXME: non-dependent using decls?
8328     if (HasTypenameKeyword != DTypename) continue;
8329 
8330     // using decls differ if they name different scopes (but note that
8331     // template instantiation can cause this check to trigger when it
8332     // didn't before instantiation).
8333     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
8334         Context.getCanonicalNestedNameSpecifier(DQual))
8335       continue;
8336 
8337     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
8338     Diag(D->getLocation(), diag::note_using_decl) << 1;
8339     return true;
8340   }
8341 
8342   return false;
8343 }
8344 
8345 
8346 /// Checks that the given nested-name qualifier used in a using decl
8347 /// in the current context is appropriately related to the current
8348 /// scope.  If an error is found, diagnoses it and returns true.
8349 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
8350                                    const CXXScopeSpec &SS,
8351                                    const DeclarationNameInfo &NameInfo,
8352                                    SourceLocation NameLoc) {
8353   DeclContext *NamedContext = computeDeclContext(SS);
8354 
8355   if (!CurContext->isRecord()) {
8356     // C++03 [namespace.udecl]p3:
8357     // C++0x [namespace.udecl]p8:
8358     //   A using-declaration for a class member shall be a member-declaration.
8359 
8360     // If we weren't able to compute a valid scope, it must be a
8361     // dependent class scope.
8362     if (!NamedContext || NamedContext->isRecord()) {
8363       auto *RD = dyn_cast_or_null<CXXRecordDecl>(NamedContext);
8364       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
8365         RD = nullptr;
8366 
8367       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
8368         << SS.getRange();
8369 
8370       // If we have a complete, non-dependent source type, try to suggest a
8371       // way to get the same effect.
8372       if (!RD)
8373         return true;
8374 
8375       // Find what this using-declaration was referring to.
8376       LookupResult R(*this, NameInfo, LookupOrdinaryName);
8377       R.setHideTags(false);
8378       R.suppressDiagnostics();
8379       LookupQualifiedName(R, RD);
8380 
8381       if (R.getAsSingle<TypeDecl>()) {
8382         if (getLangOpts().CPlusPlus11) {
8383           // Convert 'using X::Y;' to 'using Y = X::Y;'.
8384           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
8385             << 0 // alias declaration
8386             << FixItHint::CreateInsertion(SS.getBeginLoc(),
8387                                           NameInfo.getName().getAsString() +
8388                                               " = ");
8389         } else {
8390           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
8391           SourceLocation InsertLoc =
8392               getLocForEndOfToken(NameInfo.getLocEnd());
8393           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
8394             << 1 // typedef declaration
8395             << FixItHint::CreateReplacement(UsingLoc, "typedef")
8396             << FixItHint::CreateInsertion(
8397                    InsertLoc, " " + NameInfo.getName().getAsString());
8398         }
8399       } else if (R.getAsSingle<VarDecl>()) {
8400         // Don't provide a fixit outside C++11 mode; we don't want to suggest
8401         // repeating the type of the static data member here.
8402         FixItHint FixIt;
8403         if (getLangOpts().CPlusPlus11) {
8404           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
8405           FixIt = FixItHint::CreateReplacement(
8406               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
8407         }
8408 
8409         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
8410           << 2 // reference declaration
8411           << FixIt;
8412       }
8413       return true;
8414     }
8415 
8416     // Otherwise, everything is known to be fine.
8417     return false;
8418   }
8419 
8420   // The current scope is a record.
8421 
8422   // If the named context is dependent, we can't decide much.
8423   if (!NamedContext) {
8424     // FIXME: in C++0x, we can diagnose if we can prove that the
8425     // nested-name-specifier does not refer to a base class, which is
8426     // still possible in some cases.
8427 
8428     // Otherwise we have to conservatively report that things might be
8429     // okay.
8430     return false;
8431   }
8432 
8433   if (!NamedContext->isRecord()) {
8434     // Ideally this would point at the last name in the specifier,
8435     // but we don't have that level of source info.
8436     Diag(SS.getRange().getBegin(),
8437          diag::err_using_decl_nested_name_specifier_is_not_class)
8438       << SS.getScopeRep() << SS.getRange();
8439     return true;
8440   }
8441 
8442   if (!NamedContext->isDependentContext() &&
8443       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
8444     return true;
8445 
8446   if (getLangOpts().CPlusPlus11) {
8447     // C++0x [namespace.udecl]p3:
8448     //   In a using-declaration used as a member-declaration, the
8449     //   nested-name-specifier shall name a base class of the class
8450     //   being defined.
8451 
8452     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
8453                                  cast<CXXRecordDecl>(NamedContext))) {
8454       if (CurContext == NamedContext) {
8455         Diag(NameLoc,
8456              diag::err_using_decl_nested_name_specifier_is_current_class)
8457           << SS.getRange();
8458         return true;
8459       }
8460 
8461       Diag(SS.getRange().getBegin(),
8462            diag::err_using_decl_nested_name_specifier_is_not_base_class)
8463         << SS.getScopeRep()
8464         << cast<CXXRecordDecl>(CurContext)
8465         << SS.getRange();
8466       return true;
8467     }
8468 
8469     return false;
8470   }
8471 
8472   // C++03 [namespace.udecl]p4:
8473   //   A using-declaration used as a member-declaration shall refer
8474   //   to a member of a base class of the class being defined [etc.].
8475 
8476   // Salient point: SS doesn't have to name a base class as long as
8477   // lookup only finds members from base classes.  Therefore we can
8478   // diagnose here only if we can prove that that can't happen,
8479   // i.e. if the class hierarchies provably don't intersect.
8480 
8481   // TODO: it would be nice if "definitely valid" results were cached
8482   // in the UsingDecl and UsingShadowDecl so that these checks didn't
8483   // need to be repeated.
8484 
8485   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
8486   auto Collect = [&Bases](const CXXRecordDecl *Base) {
8487     Bases.insert(Base);
8488     return true;
8489   };
8490 
8491   // Collect all bases. Return false if we find a dependent base.
8492   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
8493     return false;
8494 
8495   // Returns true if the base is dependent or is one of the accumulated base
8496   // classes.
8497   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
8498     return !Bases.count(Base);
8499   };
8500 
8501   // Return false if the class has a dependent base or if it or one
8502   // of its bases is present in the base set of the current context.
8503   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
8504       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
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->isTemplateParamScope())
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     // Check that we can declare a template here.
8589     if (CheckTemplateDeclScope(S, TemplateParams))
8590       return nullptr;
8591 
8592     // Only consider previous declarations in the same scope.
8593     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8594                          /*ExplicitInstantiationOrSpecialization*/false);
8595     if (!Previous.empty()) {
8596       Redeclaration = true;
8597 
8598       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8599       if (!OldDecl && !Invalid) {
8600         Diag(UsingLoc, diag::err_redefinition_different_kind)
8601           << Name.Identifier;
8602 
8603         NamedDecl *OldD = Previous.getRepresentativeDecl();
8604         if (OldD->getLocation().isValid())
8605           Diag(OldD->getLocation(), diag::note_previous_definition);
8606 
8607         Invalid = true;
8608       }
8609 
8610       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8611         if (TemplateParameterListsAreEqual(TemplateParams,
8612                                            OldDecl->getTemplateParameters(),
8613                                            /*Complain=*/true,
8614                                            TPL_TemplateMatch))
8615           OldTemplateParams = OldDecl->getTemplateParameters();
8616         else
8617           Invalid = true;
8618 
8619         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8620         if (!Invalid &&
8621             !Context.hasSameType(OldTD->getUnderlyingType(),
8622                                  NewTD->getUnderlyingType())) {
8623           // FIXME: The C++0x standard does not clearly say this is ill-formed,
8624           // but we can't reasonably accept it.
8625           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8626             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8627           if (OldTD->getLocation().isValid())
8628             Diag(OldTD->getLocation(), diag::note_previous_definition);
8629           Invalid = true;
8630         }
8631       }
8632     }
8633 
8634     // Merge any previous default template arguments into our parameters,
8635     // and check the parameter list.
8636     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8637                                    TPC_TypeAliasTemplate))
8638       return nullptr;
8639 
8640     TypeAliasTemplateDecl *NewDecl =
8641       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8642                                     Name.Identifier, TemplateParams,
8643                                     NewTD);
8644     NewTD->setDescribedAliasTemplate(NewDecl);
8645 
8646     NewDecl->setAccess(AS);
8647 
8648     if (Invalid)
8649       NewDecl->setInvalidDecl();
8650     else if (OldDecl)
8651       NewDecl->setPreviousDecl(OldDecl);
8652 
8653     NewND = NewDecl;
8654   } else {
8655     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
8656       setTagNameForLinkagePurposes(TD, NewTD);
8657       handleTagNumbering(TD, S);
8658     }
8659     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8660     NewND = NewTD;
8661   }
8662 
8663   if (!Redeclaration)
8664     PushOnScopeChains(NewND, S);
8665 
8666   ActOnDocumentableDecl(NewND);
8667   return NewND;
8668 }
8669 
8670 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
8671                                    SourceLocation AliasLoc,
8672                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
8673                                    SourceLocation IdentLoc,
8674                                    IdentifierInfo *Ident) {
8675 
8676   // Lookup the namespace name.
8677   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8678   LookupParsedName(R, S, &SS);
8679 
8680   if (R.isAmbiguous())
8681     return nullptr;
8682 
8683   if (R.empty()) {
8684     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
8685       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
8686       return nullptr;
8687     }
8688   }
8689   assert(!R.isAmbiguous() && !R.empty());
8690   NamedDecl *ND = R.getRepresentativeDecl();
8691 
8692   // Check if we have a previous declaration with the same name.
8693   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
8694                      ForRedeclaration);
8695   LookupName(PrevR, S);
8696 
8697   // Check we're not shadowing a template parameter.
8698   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
8699     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
8700     PrevR.clear();
8701   }
8702 
8703   // Filter out any other lookup result from an enclosing scope.
8704   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
8705                        /*AllowInlineNamespace*/false);
8706 
8707   // Find the previous declaration and check that we can redeclare it.
8708   NamespaceAliasDecl *Prev = nullptr;
8709   if (PrevR.isSingleResult()) {
8710     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
8711     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
8712       // We already have an alias with the same name that points to the same
8713       // namespace; check that it matches.
8714       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
8715         Prev = AD;
8716       } else if (isVisible(PrevDecl)) {
8717         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
8718           << Alias;
8719         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
8720           << AD->getNamespace();
8721         return nullptr;
8722       }
8723     } else if (isVisible(PrevDecl)) {
8724       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
8725                             ? diag::err_redefinition
8726                             : diag::err_redefinition_different_kind;
8727       Diag(AliasLoc, DiagID) << Alias;
8728       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8729       return nullptr;
8730     }
8731   }
8732 
8733   // The use of a nested name specifier may trigger deprecation warnings.
8734   DiagnoseUseOfDecl(ND, IdentLoc);
8735 
8736   NamespaceAliasDecl *AliasDecl =
8737     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
8738                                Alias, SS.getWithLocInContext(Context),
8739                                IdentLoc, ND);
8740   if (Prev)
8741     AliasDecl->setPreviousDecl(Prev);
8742 
8743   PushOnScopeChains(AliasDecl, S);
8744   return AliasDecl;
8745 }
8746 
8747 Sema::ImplicitExceptionSpecification
8748 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8749                                                CXXMethodDecl *MD) {
8750   CXXRecordDecl *ClassDecl = MD->getParent();
8751 
8752   // C++ [except.spec]p14:
8753   //   An implicitly declared special member function (Clause 12) shall have an
8754   //   exception-specification. [...]
8755   ImplicitExceptionSpecification ExceptSpec(*this);
8756   if (ClassDecl->isInvalidDecl())
8757     return ExceptSpec;
8758 
8759   // Direct base-class constructors.
8760   for (const auto &B : ClassDecl->bases()) {
8761     if (B.isVirtual()) // Handled below.
8762       continue;
8763 
8764     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8765       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8766       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8767       // If this is a deleted function, add it anyway. This might be conformant
8768       // with the standard. This might not. I'm not sure. It might not matter.
8769       if (Constructor)
8770         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8771     }
8772   }
8773 
8774   // Virtual base-class constructors.
8775   for (const auto &B : ClassDecl->vbases()) {
8776     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8777       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8778       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8779       // If this is a deleted function, add it anyway. This might be conformant
8780       // with the standard. This might not. I'm not sure. It might not matter.
8781       if (Constructor)
8782         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8783     }
8784   }
8785 
8786   // Field constructors.
8787   for (const auto *F : ClassDecl->fields()) {
8788     if (F->hasInClassInitializer()) {
8789       if (Expr *E = F->getInClassInitializer())
8790         ExceptSpec.CalledExpr(E);
8791     } else if (const RecordType *RecordTy
8792               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8793       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8794       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8795       // If this is a deleted function, add it anyway. This might be conformant
8796       // with the standard. This might not. I'm not sure. It might not matter.
8797       // In particular, the problem is that this function never gets called. It
8798       // might just be ill-formed because this function attempts to refer to
8799       // a deleted function here.
8800       if (Constructor)
8801         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8802     }
8803   }
8804 
8805   return ExceptSpec;
8806 }
8807 
8808 Sema::ImplicitExceptionSpecification
8809 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8810   CXXRecordDecl *ClassDecl = CD->getParent();
8811 
8812   // C++ [except.spec]p14:
8813   //   An inheriting constructor [...] shall have an exception-specification. [...]
8814   ImplicitExceptionSpecification ExceptSpec(*this);
8815   if (ClassDecl->isInvalidDecl())
8816     return ExceptSpec;
8817 
8818   // Inherited constructor.
8819   const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8820   const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8821   // FIXME: Copying or moving the parameters could add extra exceptions to the
8822   // set, as could the default arguments for the inherited constructor. This
8823   // will be addressed when we implement the resolution of core issue 1351.
8824   ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8825 
8826   // Direct base-class constructors.
8827   for (const auto &B : ClassDecl->bases()) {
8828     if (B.isVirtual()) // Handled below.
8829       continue;
8830 
8831     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8832       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8833       if (BaseClassDecl == InheritedDecl)
8834         continue;
8835       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8836       if (Constructor)
8837         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8838     }
8839   }
8840 
8841   // Virtual base-class constructors.
8842   for (const auto &B : ClassDecl->vbases()) {
8843     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8844       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8845       if (BaseClassDecl == InheritedDecl)
8846         continue;
8847       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8848       if (Constructor)
8849         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8850     }
8851   }
8852 
8853   // Field constructors.
8854   for (const auto *F : ClassDecl->fields()) {
8855     if (F->hasInClassInitializer()) {
8856       if (Expr *E = F->getInClassInitializer())
8857         ExceptSpec.CalledExpr(E);
8858     } else if (const RecordType *RecordTy
8859               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8860       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8861       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8862       if (Constructor)
8863         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8864     }
8865   }
8866 
8867   return ExceptSpec;
8868 }
8869 
8870 namespace {
8871 /// RAII object to register a special member as being currently declared.
8872 struct DeclaringSpecialMember {
8873   Sema &S;
8874   Sema::SpecialMemberDecl D;
8875   bool WasAlreadyBeingDeclared;
8876 
8877   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8878     : S(S), D(RD, CSM) {
8879     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
8880     if (WasAlreadyBeingDeclared)
8881       // This almost never happens, but if it does, ensure that our cache
8882       // doesn't contain a stale result.
8883       S.SpecialMemberCache.clear();
8884 
8885     // FIXME: Register a note to be produced if we encounter an error while
8886     // declaring the special member.
8887   }
8888   ~DeclaringSpecialMember() {
8889     if (!WasAlreadyBeingDeclared)
8890       S.SpecialMembersBeingDeclared.erase(D);
8891   }
8892 
8893   /// \brief Are we already trying to declare this special member?
8894   bool isAlreadyBeingDeclared() const {
8895     return WasAlreadyBeingDeclared;
8896   }
8897 };
8898 }
8899 
8900 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8901                                                      CXXRecordDecl *ClassDecl) {
8902   // C++ [class.ctor]p5:
8903   //   A default constructor for a class X is a constructor of class X
8904   //   that can be called without an argument. If there is no
8905   //   user-declared constructor for class X, a default constructor is
8906   //   implicitly declared. An implicitly-declared default constructor
8907   //   is an inline public member of its class.
8908   assert(ClassDecl->needsImplicitDefaultConstructor() &&
8909          "Should not build implicit default constructor!");
8910 
8911   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8912   if (DSM.isAlreadyBeingDeclared())
8913     return nullptr;
8914 
8915   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8916                                                      CXXDefaultConstructor,
8917                                                      false);
8918 
8919   // Create the actual constructor declaration.
8920   CanQualType ClassType
8921     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8922   SourceLocation ClassLoc = ClassDecl->getLocation();
8923   DeclarationName Name
8924     = Context.DeclarationNames.getCXXConstructorName(ClassType);
8925   DeclarationNameInfo NameInfo(Name, ClassLoc);
8926   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
8927       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8928       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8929       /*isImplicitlyDeclared=*/true, Constexpr);
8930   DefaultCon->setAccess(AS_public);
8931   DefaultCon->setDefaulted();
8932 
8933   if (getLangOpts().CUDA) {
8934     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
8935                                             DefaultCon,
8936                                             /* ConstRHS */ false,
8937                                             /* Diagnose */ false);
8938   }
8939 
8940   // Build an exception specification pointing back at this constructor.
8941   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
8942   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8943 
8944   // We don't need to use SpecialMemberIsTrivial here; triviality for default
8945   // constructors is easy to compute.
8946   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8947 
8948   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
8949     SetDeclDeleted(DefaultCon, ClassLoc);
8950 
8951   // Note that we have declared this constructor.
8952   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
8953 
8954   if (Scope *S = getScopeForContext(ClassDecl))
8955     PushOnScopeChains(DefaultCon, S, false);
8956   ClassDecl->addDecl(DefaultCon);
8957 
8958   return DefaultCon;
8959 }
8960 
8961 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8962                                             CXXConstructorDecl *Constructor) {
8963   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
8964           !Constructor->doesThisDeclarationHaveABody() &&
8965           !Constructor->isDeleted()) &&
8966     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
8967 
8968   CXXRecordDecl *ClassDecl = Constructor->getParent();
8969   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
8970 
8971   SynthesizedFunctionScope Scope(*this, Constructor);
8972   DiagnosticErrorTrap Trap(Diags);
8973   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8974       Trap.hasErrorOccurred()) {
8975     Diag(CurrentLocation, diag::note_member_synthesized_at)
8976       << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
8977     Constructor->setInvalidDecl();
8978     return;
8979   }
8980 
8981   // The exception specification is needed because we are defining the
8982   // function.
8983   ResolveExceptionSpec(CurrentLocation,
8984                        Constructor->getType()->castAs<FunctionProtoType>());
8985 
8986   SourceLocation Loc = Constructor->getLocEnd().isValid()
8987                            ? Constructor->getLocEnd()
8988                            : Constructor->getLocation();
8989   Constructor->setBody(new (Context) CompoundStmt(Loc));
8990 
8991   Constructor->markUsed(Context);
8992   MarkVTableUsed(CurrentLocation, ClassDecl);
8993 
8994   if (ASTMutationListener *L = getASTMutationListener()) {
8995     L->CompletedImplicitDefinition(Constructor);
8996   }
8997 
8998   DiagnoseUninitializedFields(*this, Constructor);
8999 }
9000 
9001 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
9002   // Perform any delayed checks on exception specifications.
9003   CheckDelayedMemberExceptionSpecs();
9004 }
9005 
9006 namespace {
9007 /// Information on inheriting constructors to declare.
9008 class InheritingConstructorInfo {
9009 public:
9010   InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
9011       : SemaRef(SemaRef), Derived(Derived) {
9012     // Mark the constructors that we already have in the derived class.
9013     //
9014     // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
9015     //   unless there is a user-declared constructor with the same signature in
9016     //   the class where the using-declaration appears.
9017     visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
9018   }
9019 
9020   void inheritAll(CXXRecordDecl *RD) {
9021     visitAll(RD, &InheritingConstructorInfo::inherit);
9022   }
9023 
9024 private:
9025   /// Information about an inheriting constructor.
9026   struct InheritingConstructor {
9027     InheritingConstructor()
9028       : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
9029 
9030     /// If \c true, a constructor with this signature is already declared
9031     /// in the derived class.
9032     bool DeclaredInDerived;
9033 
9034     /// The constructor which is inherited.
9035     const CXXConstructorDecl *BaseCtor;
9036 
9037     /// The derived constructor we declared.
9038     CXXConstructorDecl *DerivedCtor;
9039   };
9040 
9041   /// Inheriting constructors with a given canonical type. There can be at
9042   /// most one such non-template constructor, and any number of templated
9043   /// constructors.
9044   struct InheritingConstructorsForType {
9045     InheritingConstructor NonTemplate;
9046     SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
9047         Templates;
9048 
9049     InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
9050       if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
9051         TemplateParameterList *ParamList = FTD->getTemplateParameters();
9052         for (unsigned I = 0, N = Templates.size(); I != N; ++I)
9053           if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
9054                                                false, S.TPL_TemplateMatch))
9055             return Templates[I].second;
9056         Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
9057         return Templates.back().second;
9058       }
9059 
9060       return NonTemplate;
9061     }
9062   };
9063 
9064   /// Get or create the inheriting constructor record for a constructor.
9065   InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
9066                                   QualType CtorType) {
9067     return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
9068         .getEntry(SemaRef, Ctor);
9069   }
9070 
9071   typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
9072 
9073   /// Process all constructors for a class.
9074   void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
9075     for (const auto *Ctor : RD->ctors())
9076       (this->*Callback)(Ctor);
9077     for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
9078              I(RD->decls_begin()), E(RD->decls_end());
9079          I != E; ++I) {
9080       const FunctionDecl *FD = (*I)->getTemplatedDecl();
9081       if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
9082         (this->*Callback)(CD);
9083     }
9084   }
9085 
9086   /// Note that a constructor (or constructor template) was declared in Derived.
9087   void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
9088     getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
9089   }
9090 
9091   /// Inherit a single constructor.
9092   void inherit(const CXXConstructorDecl *Ctor) {
9093     const FunctionProtoType *CtorType =
9094         Ctor->getType()->castAs<FunctionProtoType>();
9095     ArrayRef<QualType> ArgTypes = CtorType->getParamTypes();
9096     FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
9097 
9098     SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
9099 
9100     // Core issue (no number yet): the ellipsis is always discarded.
9101     if (EPI.Variadic) {
9102       SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
9103       SemaRef.Diag(Ctor->getLocation(),
9104                    diag::note_using_decl_constructor_ellipsis);
9105       EPI.Variadic = false;
9106     }
9107 
9108     // Declare a constructor for each number of parameters.
9109     //
9110     // C++11 [class.inhctor]p1:
9111     //   The candidate set of inherited constructors from the class X named in
9112     //   the using-declaration consists of [... modulo defects ...] for each
9113     //   constructor or constructor template of X, the set of constructors or
9114     //   constructor templates that results from omitting any ellipsis parameter
9115     //   specification and successively omitting parameters with a default
9116     //   argument from the end of the parameter-type-list
9117     unsigned MinParams = minParamsToInherit(Ctor);
9118     unsigned Params = Ctor->getNumParams();
9119     if (Params >= MinParams) {
9120       do
9121         declareCtor(UsingLoc, Ctor,
9122                     SemaRef.Context.getFunctionType(
9123                         Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
9124       while (Params > MinParams &&
9125              Ctor->getParamDecl(--Params)->hasDefaultArg());
9126     }
9127   }
9128 
9129   /// Find the using-declaration which specified that we should inherit the
9130   /// constructors of \p Base.
9131   SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
9132     // No fancy lookup required; just look for the base constructor name
9133     // directly within the derived class.
9134     ASTContext &Context = SemaRef.Context;
9135     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9136         Context.getCanonicalType(Context.getRecordType(Base)));
9137     DeclContext::lookup_result Decls = Derived->lookup(Name);
9138     return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
9139   }
9140 
9141   unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
9142     // C++11 [class.inhctor]p3:
9143     //   [F]or each constructor template in the candidate set of inherited
9144     //   constructors, a constructor template is implicitly declared
9145     if (Ctor->getDescribedFunctionTemplate())
9146       return 0;
9147 
9148     //   For each non-template constructor in the candidate set of inherited
9149     //   constructors other than a constructor having no parameters or a
9150     //   copy/move constructor having a single parameter, a constructor is
9151     //   implicitly declared [...]
9152     if (Ctor->getNumParams() == 0)
9153       return 1;
9154     if (Ctor->isCopyOrMoveConstructor())
9155       return 2;
9156 
9157     // Per discussion on core reflector, never inherit a constructor which
9158     // would become a default, copy, or move constructor of Derived either.
9159     const ParmVarDecl *PD = Ctor->getParamDecl(0);
9160     const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
9161     return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
9162   }
9163 
9164   /// Declare a single inheriting constructor, inheriting the specified
9165   /// constructor, with the given type.
9166   void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
9167                    QualType DerivedType) {
9168     InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
9169 
9170     // C++11 [class.inhctor]p3:
9171     //   ... a constructor is implicitly declared with the same constructor
9172     //   characteristics unless there is a user-declared constructor with
9173     //   the same signature in the class where the using-declaration appears
9174     if (Entry.DeclaredInDerived)
9175       return;
9176 
9177     // C++11 [class.inhctor]p7:
9178     //   If two using-declarations declare inheriting constructors with the
9179     //   same signature, the program is ill-formed
9180     if (Entry.DerivedCtor) {
9181       if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
9182         // Only diagnose this once per constructor.
9183         if (Entry.DerivedCtor->isInvalidDecl())
9184           return;
9185         Entry.DerivedCtor->setInvalidDecl();
9186 
9187         SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
9188         SemaRef.Diag(BaseCtor->getLocation(),
9189                      diag::note_using_decl_constructor_conflict_current_ctor);
9190         SemaRef.Diag(Entry.BaseCtor->getLocation(),
9191                      diag::note_using_decl_constructor_conflict_previous_ctor);
9192         SemaRef.Diag(Entry.DerivedCtor->getLocation(),
9193                      diag::note_using_decl_constructor_conflict_previous_using);
9194       } else {
9195         // Core issue (no number): if the same inheriting constructor is
9196         // produced by multiple base class constructors from the same base
9197         // class, the inheriting constructor is defined as deleted.
9198         SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
9199       }
9200 
9201       return;
9202     }
9203 
9204     ASTContext &Context = SemaRef.Context;
9205     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9206         Context.getCanonicalType(Context.getRecordType(Derived)));
9207     DeclarationNameInfo NameInfo(Name, UsingLoc);
9208 
9209     TemplateParameterList *TemplateParams = nullptr;
9210     if (const FunctionTemplateDecl *FTD =
9211             BaseCtor->getDescribedFunctionTemplate()) {
9212       TemplateParams = FTD->getTemplateParameters();
9213       // We're reusing template parameters from a different DeclContext. This
9214       // is questionable at best, but works out because the template depth in
9215       // both places is guaranteed to be 0.
9216       // FIXME: Rebuild the template parameters in the new context, and
9217       // transform the function type to refer to them.
9218     }
9219 
9220     // Build type source info pointing at the using-declaration. This is
9221     // required by template instantiation.
9222     TypeSourceInfo *TInfo =
9223         Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
9224     FunctionProtoTypeLoc ProtoLoc =
9225         TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
9226 
9227     CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
9228         Context, Derived, UsingLoc, NameInfo, DerivedType,
9229         TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
9230         /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
9231 
9232     // Build an unevaluated exception specification for this constructor.
9233     const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
9234     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9235     EPI.ExceptionSpec.Type = EST_Unevaluated;
9236     EPI.ExceptionSpec.SourceDecl = DerivedCtor;
9237     DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
9238                                                  FPT->getParamTypes(), EPI));
9239 
9240     // Build the parameter declarations.
9241     SmallVector<ParmVarDecl *, 16> ParamDecls;
9242     for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
9243       TypeSourceInfo *TInfo =
9244           Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
9245       ParmVarDecl *PD = ParmVarDecl::Create(
9246           Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
9247           FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
9248       PD->setScopeInfo(0, I);
9249       PD->setImplicit();
9250       ParamDecls.push_back(PD);
9251       ProtoLoc.setParam(I, PD);
9252     }
9253 
9254     // Set up the new constructor.
9255     DerivedCtor->setAccess(BaseCtor->getAccess());
9256     DerivedCtor->setParams(ParamDecls);
9257     DerivedCtor->setInheritedConstructor(BaseCtor);
9258     if (BaseCtor->isDeleted())
9259       SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
9260 
9261     // If this is a constructor template, build the template declaration.
9262     if (TemplateParams) {
9263       FunctionTemplateDecl *DerivedTemplate =
9264           FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
9265                                        TemplateParams, DerivedCtor);
9266       DerivedTemplate->setAccess(BaseCtor->getAccess());
9267       DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
9268       Derived->addDecl(DerivedTemplate);
9269     } else {
9270       Derived->addDecl(DerivedCtor);
9271     }
9272 
9273     Entry.BaseCtor = BaseCtor;
9274     Entry.DerivedCtor = DerivedCtor;
9275   }
9276 
9277   Sema &SemaRef;
9278   CXXRecordDecl *Derived;
9279   typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
9280   MapType Map;
9281 };
9282 }
9283 
9284 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
9285   // Defer declaring the inheriting constructors until the class is
9286   // instantiated.
9287   if (ClassDecl->isDependentContext())
9288     return;
9289 
9290   // Find base classes from which we might inherit constructors.
9291   SmallVector<CXXRecordDecl*, 4> InheritedBases;
9292   for (const auto &BaseIt : ClassDecl->bases())
9293     if (BaseIt.getInheritConstructors())
9294       InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
9295 
9296   // Go no further if we're not inheriting any constructors.
9297   if (InheritedBases.empty())
9298     return;
9299 
9300   // Declare the inherited constructors.
9301   InheritingConstructorInfo ICI(*this, ClassDecl);
9302   for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
9303     ICI.inheritAll(InheritedBases[I]);
9304 }
9305 
9306 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
9307                                        CXXConstructorDecl *Constructor) {
9308   CXXRecordDecl *ClassDecl = Constructor->getParent();
9309   assert(Constructor->getInheritedConstructor() &&
9310          !Constructor->doesThisDeclarationHaveABody() &&
9311          !Constructor->isDeleted());
9312 
9313   SynthesizedFunctionScope Scope(*this, Constructor);
9314   DiagnosticErrorTrap Trap(Diags);
9315   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
9316       Trap.hasErrorOccurred()) {
9317     Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
9318       << Context.getTagDeclType(ClassDecl);
9319     Constructor->setInvalidDecl();
9320     return;
9321   }
9322 
9323   SourceLocation Loc = Constructor->getLocation();
9324   Constructor->setBody(new (Context) CompoundStmt(Loc));
9325 
9326   Constructor->markUsed(Context);
9327   MarkVTableUsed(CurrentLocation, ClassDecl);
9328 
9329   if (ASTMutationListener *L = getASTMutationListener()) {
9330     L->CompletedImplicitDefinition(Constructor);
9331   }
9332 }
9333 
9334 
9335 Sema::ImplicitExceptionSpecification
9336 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
9337   CXXRecordDecl *ClassDecl = MD->getParent();
9338 
9339   // C++ [except.spec]p14:
9340   //   An implicitly declared special member function (Clause 12) shall have
9341   //   an exception-specification.
9342   ImplicitExceptionSpecification ExceptSpec(*this);
9343   if (ClassDecl->isInvalidDecl())
9344     return ExceptSpec;
9345 
9346   // Direct base-class destructors.
9347   for (const auto &B : ClassDecl->bases()) {
9348     if (B.isVirtual()) // Handled below.
9349       continue;
9350 
9351     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9352       ExceptSpec.CalledDecl(B.getLocStart(),
9353                    LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
9354   }
9355 
9356   // Virtual base-class destructors.
9357   for (const auto &B : ClassDecl->vbases()) {
9358     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9359       ExceptSpec.CalledDecl(B.getLocStart(),
9360                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
9361   }
9362 
9363   // Field destructors.
9364   for (const auto *F : ClassDecl->fields()) {
9365     if (const RecordType *RecordTy
9366         = Context.getBaseElementType(F->getType())->getAs<RecordType>())
9367       ExceptSpec.CalledDecl(F->getLocation(),
9368                   LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
9369   }
9370 
9371   return ExceptSpec;
9372 }
9373 
9374 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
9375   // C++ [class.dtor]p2:
9376   //   If a class has no user-declared destructor, a destructor is
9377   //   declared implicitly. An implicitly-declared destructor is an
9378   //   inline public member of its class.
9379   assert(ClassDecl->needsImplicitDestructor());
9380 
9381   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
9382   if (DSM.isAlreadyBeingDeclared())
9383     return nullptr;
9384 
9385   // Create the actual destructor declaration.
9386   CanQualType ClassType
9387     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
9388   SourceLocation ClassLoc = ClassDecl->getLocation();
9389   DeclarationName Name
9390     = Context.DeclarationNames.getCXXDestructorName(ClassType);
9391   DeclarationNameInfo NameInfo(Name, ClassLoc);
9392   CXXDestructorDecl *Destructor
9393       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
9394                                   QualType(), nullptr, /*isInline=*/true,
9395                                   /*isImplicitlyDeclared=*/true);
9396   Destructor->setAccess(AS_public);
9397   Destructor->setDefaulted();
9398 
9399   if (getLangOpts().CUDA) {
9400     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
9401                                             Destructor,
9402                                             /* ConstRHS */ false,
9403                                             /* Diagnose */ false);
9404   }
9405 
9406   // Build an exception specification pointing back at this destructor.
9407   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
9408   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9409 
9410   AddOverriddenMethods(ClassDecl, Destructor);
9411 
9412   // We don't need to use SpecialMemberIsTrivial here; triviality for
9413   // destructors is easy to compute.
9414   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
9415 
9416   if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
9417     SetDeclDeleted(Destructor, ClassLoc);
9418 
9419   // Note that we have declared this destructor.
9420   ++ASTContext::NumImplicitDestructorsDeclared;
9421 
9422   // Introduce this destructor into its scope.
9423   if (Scope *S = getScopeForContext(ClassDecl))
9424     PushOnScopeChains(Destructor, S, false);
9425   ClassDecl->addDecl(Destructor);
9426 
9427   return Destructor;
9428 }
9429 
9430 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
9431                                     CXXDestructorDecl *Destructor) {
9432   assert((Destructor->isDefaulted() &&
9433           !Destructor->doesThisDeclarationHaveABody() &&
9434           !Destructor->isDeleted()) &&
9435          "DefineImplicitDestructor - call it for implicit default dtor");
9436   CXXRecordDecl *ClassDecl = Destructor->getParent();
9437   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
9438 
9439   if (Destructor->isInvalidDecl())
9440     return;
9441 
9442   SynthesizedFunctionScope Scope(*this, Destructor);
9443 
9444   DiagnosticErrorTrap Trap(Diags);
9445   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9446                                          Destructor->getParent());
9447 
9448   if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
9449     Diag(CurrentLocation, diag::note_member_synthesized_at)
9450       << CXXDestructor << Context.getTagDeclType(ClassDecl);
9451 
9452     Destructor->setInvalidDecl();
9453     return;
9454   }
9455 
9456   // The exception specification is needed because we are defining the
9457   // function.
9458   ResolveExceptionSpec(CurrentLocation,
9459                        Destructor->getType()->castAs<FunctionProtoType>());
9460 
9461   SourceLocation Loc = Destructor->getLocEnd().isValid()
9462                            ? Destructor->getLocEnd()
9463                            : Destructor->getLocation();
9464   Destructor->setBody(new (Context) CompoundStmt(Loc));
9465   Destructor->markUsed(Context);
9466   MarkVTableUsed(CurrentLocation, ClassDecl);
9467 
9468   if (ASTMutationListener *L = getASTMutationListener()) {
9469     L->CompletedImplicitDefinition(Destructor);
9470   }
9471 }
9472 
9473 /// \brief Perform any semantic analysis which needs to be delayed until all
9474 /// pending class member declarations have been parsed.
9475 void Sema::ActOnFinishCXXMemberDecls() {
9476   // If the context is an invalid C++ class, just suppress these checks.
9477   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
9478     if (Record->isInvalidDecl()) {
9479       DelayedDefaultedMemberExceptionSpecs.clear();
9480       DelayedExceptionSpecChecks.clear();
9481       return;
9482     }
9483   }
9484 }
9485 
9486 static void getDefaultArgExprsForConstructors(Sema &S, CXXRecordDecl *Class) {
9487   // Don't do anything for template patterns.
9488   if (Class->getDescribedClassTemplate())
9489     return;
9490 
9491   CallingConv ExpectedCallingConv = S.Context.getDefaultCallingConvention(
9492       /*IsVariadic=*/false, /*IsCXXMethod=*/true);
9493 
9494   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
9495   for (Decl *Member : Class->decls()) {
9496     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
9497     if (!CD) {
9498       // Recurse on nested classes.
9499       if (auto *NestedRD = dyn_cast<CXXRecordDecl>(Member))
9500         getDefaultArgExprsForConstructors(S, NestedRD);
9501       continue;
9502     } else if (!CD->isDefaultConstructor() || !CD->hasAttr<DLLExportAttr>()) {
9503       continue;
9504     }
9505 
9506     CallingConv ActualCallingConv =
9507         CD->getType()->getAs<FunctionProtoType>()->getCallConv();
9508 
9509     // Skip default constructors with typical calling conventions and no default
9510     // arguments.
9511     unsigned NumParams = CD->getNumParams();
9512     if (ExpectedCallingConv == ActualCallingConv && NumParams == 0)
9513       continue;
9514 
9515     if (LastExportedDefaultCtor) {
9516       S.Diag(LastExportedDefaultCtor->getLocation(),
9517              diag::err_attribute_dll_ambiguous_default_ctor) << Class;
9518       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
9519           << CD->getDeclName();
9520       return;
9521     }
9522     LastExportedDefaultCtor = CD;
9523 
9524     for (unsigned I = 0; I != NumParams; ++I) {
9525       // Skip any default arguments that we've already instantiated.
9526       if (S.Context.getDefaultArgExprForConstructor(CD, I))
9527         continue;
9528 
9529       Expr *DefaultArg = S.BuildCXXDefaultArgExpr(Class->getLocation(), CD,
9530                                                   CD->getParamDecl(I)).get();
9531       S.DiscardCleanupsInEvaluationContext();
9532       S.Context.addDefaultArgExprForConstructor(CD, I, DefaultArg);
9533     }
9534   }
9535 }
9536 
9537 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
9538   auto *RD = dyn_cast<CXXRecordDecl>(D);
9539 
9540   // Default constructors that are annotated with __declspec(dllexport) which
9541   // have default arguments or don't use the standard calling convention are
9542   // wrapped with a thunk called the default constructor closure.
9543   if (RD && Context.getTargetInfo().getCXXABI().isMicrosoft())
9544     getDefaultArgExprsForConstructors(*this, RD);
9545 
9546   referenceDLLExportedClassMethods();
9547 }
9548 
9549 void Sema::referenceDLLExportedClassMethods() {
9550   if (!DelayedDllExportClasses.empty()) {
9551     // Calling ReferenceDllExportedMethods might cause the current function to
9552     // be called again, so use a local copy of DelayedDllExportClasses.
9553     SmallVector<CXXRecordDecl *, 4> WorkList;
9554     std::swap(DelayedDllExportClasses, WorkList);
9555     for (CXXRecordDecl *Class : WorkList)
9556       ReferenceDllExportedMethods(*this, Class);
9557   }
9558 }
9559 
9560 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
9561                                          CXXDestructorDecl *Destructor) {
9562   assert(getLangOpts().CPlusPlus11 &&
9563          "adjusting dtor exception specs was introduced in c++11");
9564 
9565   // C++11 [class.dtor]p3:
9566   //   A declaration of a destructor that does not have an exception-
9567   //   specification is implicitly considered to have the same exception-
9568   //   specification as an implicit declaration.
9569   const FunctionProtoType *DtorType = Destructor->getType()->
9570                                         getAs<FunctionProtoType>();
9571   if (DtorType->hasExceptionSpec())
9572     return;
9573 
9574   // Replace the destructor's type, building off the existing one. Fortunately,
9575   // the only thing of interest in the destructor type is its extended info.
9576   // The return and arguments are fixed.
9577   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
9578   EPI.ExceptionSpec.Type = EST_Unevaluated;
9579   EPI.ExceptionSpec.SourceDecl = Destructor;
9580   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9581 
9582   // FIXME: If the destructor has a body that could throw, and the newly created
9583   // spec doesn't allow exceptions, we should emit a warning, because this
9584   // change in behavior can break conforming C++03 programs at runtime.
9585   // However, we don't have a body or an exception specification yet, so it
9586   // needs to be done somewhere else.
9587 }
9588 
9589 namespace {
9590 /// \brief An abstract base class for all helper classes used in building the
9591 //  copy/move operators. These classes serve as factory functions and help us
9592 //  avoid using the same Expr* in the AST twice.
9593 class ExprBuilder {
9594   ExprBuilder(const ExprBuilder&) = delete;
9595   ExprBuilder &operator=(const ExprBuilder&) = delete;
9596 
9597 protected:
9598   static Expr *assertNotNull(Expr *E) {
9599     assert(E && "Expression construction must not fail.");
9600     return E;
9601   }
9602 
9603 public:
9604   ExprBuilder() {}
9605   virtual ~ExprBuilder() {}
9606 
9607   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
9608 };
9609 
9610 class RefBuilder: public ExprBuilder {
9611   VarDecl *Var;
9612   QualType VarType;
9613 
9614 public:
9615   Expr *build(Sema &S, SourceLocation Loc) const override {
9616     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
9617   }
9618 
9619   RefBuilder(VarDecl *Var, QualType VarType)
9620       : Var(Var), VarType(VarType) {}
9621 };
9622 
9623 class ThisBuilder: public ExprBuilder {
9624 public:
9625   Expr *build(Sema &S, SourceLocation Loc) const override {
9626     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
9627   }
9628 };
9629 
9630 class CastBuilder: public ExprBuilder {
9631   const ExprBuilder &Builder;
9632   QualType Type;
9633   ExprValueKind Kind;
9634   const CXXCastPath &Path;
9635 
9636 public:
9637   Expr *build(Sema &S, SourceLocation Loc) const override {
9638     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
9639                                              CK_UncheckedDerivedToBase, Kind,
9640                                              &Path).get());
9641   }
9642 
9643   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
9644               const CXXCastPath &Path)
9645       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
9646 };
9647 
9648 class DerefBuilder: public ExprBuilder {
9649   const ExprBuilder &Builder;
9650 
9651 public:
9652   Expr *build(Sema &S, SourceLocation Loc) const override {
9653     return assertNotNull(
9654         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
9655   }
9656 
9657   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9658 };
9659 
9660 class MemberBuilder: public ExprBuilder {
9661   const ExprBuilder &Builder;
9662   QualType Type;
9663   CXXScopeSpec SS;
9664   bool IsArrow;
9665   LookupResult &MemberLookup;
9666 
9667 public:
9668   Expr *build(Sema &S, SourceLocation Loc) const override {
9669     return assertNotNull(S.BuildMemberReferenceExpr(
9670         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
9671         nullptr, MemberLookup, nullptr, nullptr).get());
9672   }
9673 
9674   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9675                 LookupResult &MemberLookup)
9676       : Builder(Builder), Type(Type), IsArrow(IsArrow),
9677         MemberLookup(MemberLookup) {}
9678 };
9679 
9680 class MoveCastBuilder: public ExprBuilder {
9681   const ExprBuilder &Builder;
9682 
9683 public:
9684   Expr *build(Sema &S, SourceLocation Loc) const override {
9685     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9686   }
9687 
9688   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9689 };
9690 
9691 class LvalueConvBuilder: public ExprBuilder {
9692   const ExprBuilder &Builder;
9693 
9694 public:
9695   Expr *build(Sema &S, SourceLocation Loc) const override {
9696     return assertNotNull(
9697         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
9698   }
9699 
9700   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9701 };
9702 
9703 class SubscriptBuilder: public ExprBuilder {
9704   const ExprBuilder &Base;
9705   const ExprBuilder &Index;
9706 
9707 public:
9708   Expr *build(Sema &S, SourceLocation Loc) const override {
9709     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
9710         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
9711   }
9712 
9713   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9714       : Base(Base), Index(Index) {}
9715 };
9716 
9717 } // end anonymous namespace
9718 
9719 /// When generating a defaulted copy or move assignment operator, if a field
9720 /// should be copied with __builtin_memcpy rather than via explicit assignments,
9721 /// do so. This optimization only applies for arrays of scalars, and for arrays
9722 /// of class type where the selected copy/move-assignment operator is trivial.
9723 static StmtResult
9724 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
9725                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
9726   // Compute the size of the memory buffer to be copied.
9727   QualType SizeType = S.Context.getSizeType();
9728   llvm::APInt Size(S.Context.getTypeSize(SizeType),
9729                    S.Context.getTypeSizeInChars(T).getQuantity());
9730 
9731   // Take the address of the field references for "from" and "to". We
9732   // directly construct UnaryOperators here because semantic analysis
9733   // does not permit us to take the address of an xvalue.
9734   Expr *From = FromB.build(S, Loc);
9735   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9736                          S.Context.getPointerType(From->getType()),
9737                          VK_RValue, OK_Ordinary, Loc);
9738   Expr *To = ToB.build(S, Loc);
9739   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9740                        S.Context.getPointerType(To->getType()),
9741                        VK_RValue, OK_Ordinary, Loc);
9742 
9743   const Type *E = T->getBaseElementTypeUnsafe();
9744   bool NeedsCollectableMemCpy =
9745     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9746 
9747   // Create a reference to the __builtin_objc_memmove_collectable function
9748   StringRef MemCpyName = NeedsCollectableMemCpy ?
9749     "__builtin_objc_memmove_collectable" :
9750     "__builtin_memcpy";
9751   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9752                  Sema::LookupOrdinaryName);
9753   S.LookupName(R, S.TUScope, true);
9754 
9755   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9756   if (!MemCpy)
9757     // Something went horribly wrong earlier, and we will have complained
9758     // about it.
9759     return StmtError();
9760 
9761   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
9762                                             VK_RValue, Loc, nullptr);
9763   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9764 
9765   Expr *CallArgs[] = {
9766     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9767   };
9768   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
9769                                     Loc, CallArgs, Loc);
9770 
9771   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
9772   return Call.getAs<Stmt>();
9773 }
9774 
9775 /// \brief Builds a statement that copies/moves the given entity from \p From to
9776 /// \c To.
9777 ///
9778 /// This routine is used to copy/move the members of a class with an
9779 /// implicitly-declared copy/move assignment operator. When the entities being
9780 /// copied are arrays, this routine builds for loops to copy them.
9781 ///
9782 /// \param S The Sema object used for type-checking.
9783 ///
9784 /// \param Loc The location where the implicit copy/move is being generated.
9785 ///
9786 /// \param T The type of the expressions being copied/moved. Both expressions
9787 /// must have this type.
9788 ///
9789 /// \param To The expression we are copying/moving to.
9790 ///
9791 /// \param From The expression we are copying/moving from.
9792 ///
9793 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
9794 /// Otherwise, it's a non-static member subobject.
9795 ///
9796 /// \param Copying Whether we're copying or moving.
9797 ///
9798 /// \param Depth Internal parameter recording the depth of the recursion.
9799 ///
9800 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9801 /// if a memcpy should be used instead.
9802 static StmtResult
9803 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
9804                                  const ExprBuilder &To, const ExprBuilder &From,
9805                                  bool CopyingBaseSubobject, bool Copying,
9806                                  unsigned Depth = 0) {
9807   // C++11 [class.copy]p28:
9808   //   Each subobject is assigned in the manner appropriate to its type:
9809   //
9810   //     - if the subobject is of class type, as if by a call to operator= with
9811   //       the subobject as the object expression and the corresponding
9812   //       subobject of x as a single function argument (as if by explicit
9813   //       qualification; that is, ignoring any possible virtual overriding
9814   //       functions in more derived classes);
9815   //
9816   // C++03 [class.copy]p13:
9817   //     - if the subobject is of class type, the copy assignment operator for
9818   //       the class is used (as if by explicit qualification; that is,
9819   //       ignoring any possible virtual overriding functions in more derived
9820   //       classes);
9821   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9822     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9823 
9824     // Look for operator=.
9825     DeclarationName Name
9826       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9827     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9828     S.LookupQualifiedName(OpLookup, ClassDecl, false);
9829 
9830     // Prior to C++11, filter out any result that isn't a copy/move-assignment
9831     // operator.
9832     if (!S.getLangOpts().CPlusPlus11) {
9833       LookupResult::Filter F = OpLookup.makeFilter();
9834       while (F.hasNext()) {
9835         NamedDecl *D = F.next();
9836         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9837           if (Method->isCopyAssignmentOperator() ||
9838               (!Copying && Method->isMoveAssignmentOperator()))
9839             continue;
9840 
9841         F.erase();
9842       }
9843       F.done();
9844     }
9845 
9846     // Suppress the protected check (C++ [class.protected]) for each of the
9847     // assignment operators we found. This strange dance is required when
9848     // we're assigning via a base classes's copy-assignment operator. To
9849     // ensure that we're getting the right base class subobject (without
9850     // ambiguities), we need to cast "this" to that subobject type; to
9851     // ensure that we don't go through the virtual call mechanism, we need
9852     // to qualify the operator= name with the base class (see below). However,
9853     // this means that if the base class has a protected copy assignment
9854     // operator, the protected member access check will fail. So, we
9855     // rewrite "protected" access to "public" access in this case, since we
9856     // know by construction that we're calling from a derived class.
9857     if (CopyingBaseSubobject) {
9858       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9859            L != LEnd; ++L) {
9860         if (L.getAccess() == AS_protected)
9861           L.setAccess(AS_public);
9862       }
9863     }
9864 
9865     // Create the nested-name-specifier that will be used to qualify the
9866     // reference to operator=; this is required to suppress the virtual
9867     // call mechanism.
9868     CXXScopeSpec SS;
9869     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
9870     SS.MakeTrivial(S.Context,
9871                    NestedNameSpecifier::Create(S.Context, nullptr, false,
9872                                                CanonicalT),
9873                    Loc);
9874 
9875     // Create the reference to operator=.
9876     ExprResult OpEqualRef
9877       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9878                                    SS, /*TemplateKWLoc=*/SourceLocation(),
9879                                    /*FirstQualifierInScope=*/nullptr,
9880                                    OpLookup,
9881                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
9882                                    /*SuppressQualifierCheck=*/true);
9883     if (OpEqualRef.isInvalid())
9884       return StmtError();
9885 
9886     // Build the call to the assignment operator.
9887 
9888     Expr *FromInst = From.build(S, Loc);
9889     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
9890                                                   OpEqualRef.getAs<Expr>(),
9891                                                   Loc, FromInst, Loc);
9892     if (Call.isInvalid())
9893       return StmtError();
9894 
9895     // If we built a call to a trivial 'operator=' while copying an array,
9896     // bail out. We'll replace the whole shebang with a memcpy.
9897     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9898     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9899       return StmtResult((Stmt*)nullptr);
9900 
9901     // Convert to an expression-statement, and clean up any produced
9902     // temporaries.
9903     return S.ActOnExprStmt(Call);
9904   }
9905 
9906   //     - if the subobject is of scalar type, the built-in assignment
9907   //       operator is used.
9908   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
9909   if (!ArrayTy) {
9910     ExprResult Assignment = S.CreateBuiltinBinOp(
9911         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
9912     if (Assignment.isInvalid())
9913       return StmtError();
9914     return S.ActOnExprStmt(Assignment);
9915   }
9916 
9917   //     - if the subobject is an array, each element is assigned, in the
9918   //       manner appropriate to the element type;
9919 
9920   // Construct a loop over the array bounds, e.g.,
9921   //
9922   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9923   //
9924   // that will copy each of the array elements.
9925   QualType SizeType = S.Context.getSizeType();
9926 
9927   // Create the iteration variable.
9928   IdentifierInfo *IterationVarName = nullptr;
9929   {
9930     SmallString<8> Str;
9931     llvm::raw_svector_ostream OS(Str);
9932     OS << "__i" << Depth;
9933     IterationVarName = &S.Context.Idents.get(OS.str());
9934   }
9935   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
9936                                           IterationVarName, SizeType,
9937                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
9938                                           SC_None);
9939 
9940   // Initialize the iteration variable to zero.
9941   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
9942   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
9943 
9944   // Creates a reference to the iteration variable.
9945   RefBuilder IterationVarRef(IterationVar, SizeType);
9946   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
9947 
9948   // Create the DeclStmt that holds the iteration variable.
9949   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
9950 
9951   // Subscript the "from" and "to" expressions with the iteration variable.
9952   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9953   MoveCastBuilder FromIndexMove(FromIndexCopy);
9954   const ExprBuilder *FromIndex;
9955   if (Copying)
9956     FromIndex = &FromIndexCopy;
9957   else
9958     FromIndex = &FromIndexMove;
9959 
9960   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
9961 
9962   // Build the copy/move for an individual element of the array.
9963   StmtResult Copy =
9964     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
9965                                      ToIndex, *FromIndex, CopyingBaseSubobject,
9966                                      Copying, Depth + 1);
9967   // Bail out if copying fails or if we determined that we should use memcpy.
9968   if (Copy.isInvalid() || !Copy.get())
9969     return Copy;
9970 
9971   // Create the comparison against the array bound.
9972   llvm::APInt Upper
9973     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9974   Expr *Comparison
9975     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
9976                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9977                                      BO_NE, S.Context.BoolTy,
9978                                      VK_RValue, OK_Ordinary, Loc, false);
9979 
9980   // Create the pre-increment of the iteration variable.
9981   Expr *Increment
9982     = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9983                                     SizeType, VK_LValue, OK_Ordinary, Loc);
9984 
9985   // Construct the loop that copies all elements of this array.
9986   return S.ActOnForStmt(Loc, Loc, InitStmt,
9987                         S.MakeFullExpr(Comparison),
9988                         nullptr, S.MakeFullDiscardedValueExpr(Increment),
9989                         Loc, Copy.get());
9990 }
9991 
9992 static StmtResult
9993 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
9994                       const ExprBuilder &To, const ExprBuilder &From,
9995                       bool CopyingBaseSubobject, bool Copying) {
9996   // Maybe we should use a memcpy?
9997   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9998       T.isTriviallyCopyableType(S.Context))
9999     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
10000 
10001   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
10002                                                      CopyingBaseSubobject,
10003                                                      Copying, 0));
10004 
10005   // If we ended up picking a trivial assignment operator for an array of a
10006   // non-trivially-copyable class type, just emit a memcpy.
10007   if (!Result.isInvalid() && !Result.get())
10008     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
10009 
10010   return Result;
10011 }
10012 
10013 Sema::ImplicitExceptionSpecification
10014 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
10015   CXXRecordDecl *ClassDecl = MD->getParent();
10016 
10017   ImplicitExceptionSpecification ExceptSpec(*this);
10018   if (ClassDecl->isInvalidDecl())
10019     return ExceptSpec;
10020 
10021   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
10022   assert(T->getNumParams() == 1 && "not a copy assignment op");
10023   unsigned ArgQuals =
10024       T->getParamType(0).getNonReferenceType().getCVRQualifiers();
10025 
10026   // C++ [except.spec]p14:
10027   //   An implicitly declared special member function (Clause 12) shall have an
10028   //   exception-specification. [...]
10029 
10030   // It is unspecified whether or not an implicit copy assignment operator
10031   // attempts to deduplicate calls to assignment operators of virtual bases are
10032   // made. As such, this exception specification is effectively unspecified.
10033   // Based on a similar decision made for constness in C++0x, we're erring on
10034   // the side of assuming such calls to be made regardless of whether they
10035   // actually happen.
10036   for (const auto &Base : ClassDecl->bases()) {
10037     if (Base.isVirtual())
10038       continue;
10039 
10040     CXXRecordDecl *BaseClassDecl
10041       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10042     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
10043                                                             ArgQuals, false, 0))
10044       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
10045   }
10046 
10047   for (const auto &Base : ClassDecl->vbases()) {
10048     CXXRecordDecl *BaseClassDecl
10049       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10050     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
10051                                                             ArgQuals, false, 0))
10052       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
10053   }
10054 
10055   for (const auto *Field : ClassDecl->fields()) {
10056     QualType FieldType = Context.getBaseElementType(Field->getType());
10057     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10058       if (CXXMethodDecl *CopyAssign =
10059           LookupCopyingAssignment(FieldClassDecl,
10060                                   ArgQuals | FieldType.getCVRQualifiers(),
10061                                   false, 0))
10062         ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
10063     }
10064   }
10065 
10066   return ExceptSpec;
10067 }
10068 
10069 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
10070   // Note: The following rules are largely analoguous to the copy
10071   // constructor rules. Note that virtual bases are not taken into account
10072   // for determining the argument type of the operator. Note also that
10073   // operators taking an object instead of a reference are allowed.
10074   assert(ClassDecl->needsImplicitCopyAssignment());
10075 
10076   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
10077   if (DSM.isAlreadyBeingDeclared())
10078     return nullptr;
10079 
10080   QualType ArgType = Context.getTypeDeclType(ClassDecl);
10081   QualType RetType = Context.getLValueReferenceType(ArgType);
10082   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
10083   if (Const)
10084     ArgType = ArgType.withConst();
10085   ArgType = Context.getLValueReferenceType(ArgType);
10086 
10087   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10088                                                      CXXCopyAssignment,
10089                                                      Const);
10090 
10091   //   An implicitly-declared copy assignment operator is an inline public
10092   //   member of its class.
10093   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10094   SourceLocation ClassLoc = ClassDecl->getLocation();
10095   DeclarationNameInfo NameInfo(Name, ClassLoc);
10096   CXXMethodDecl *CopyAssignment =
10097       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
10098                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10099                             /*isInline=*/true, Constexpr, SourceLocation());
10100   CopyAssignment->setAccess(AS_public);
10101   CopyAssignment->setDefaulted();
10102   CopyAssignment->setImplicit();
10103 
10104   if (getLangOpts().CUDA) {
10105     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
10106                                             CopyAssignment,
10107                                             /* ConstRHS */ Const,
10108                                             /* Diagnose */ false);
10109   }
10110 
10111   // Build an exception specification pointing back at this member.
10112   FunctionProtoType::ExtProtoInfo EPI =
10113       getImplicitMethodEPI(*this, CopyAssignment);
10114   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
10115 
10116   // Add the parameter to the operator.
10117   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
10118                                                ClassLoc, ClassLoc,
10119                                                /*Id=*/nullptr, ArgType,
10120                                                /*TInfo=*/nullptr, SC_None,
10121                                                nullptr);
10122   CopyAssignment->setParams(FromParam);
10123 
10124   AddOverriddenMethods(ClassDecl, CopyAssignment);
10125 
10126   CopyAssignment->setTrivial(
10127     ClassDecl->needsOverloadResolutionForCopyAssignment()
10128       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
10129       : ClassDecl->hasTrivialCopyAssignment());
10130 
10131   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
10132     SetDeclDeleted(CopyAssignment, ClassLoc);
10133 
10134   // Note that we have added this copy-assignment operator.
10135   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
10136 
10137   if (Scope *S = getScopeForContext(ClassDecl))
10138     PushOnScopeChains(CopyAssignment, S, false);
10139   ClassDecl->addDecl(CopyAssignment);
10140 
10141   return CopyAssignment;
10142 }
10143 
10144 /// Diagnose an implicit copy operation for a class which is odr-used, but
10145 /// which is deprecated because the class has a user-declared copy constructor,
10146 /// copy assignment operator, or destructor.
10147 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
10148                                             SourceLocation UseLoc) {
10149   assert(CopyOp->isImplicit());
10150 
10151   CXXRecordDecl *RD = CopyOp->getParent();
10152   CXXMethodDecl *UserDeclaredOperation = nullptr;
10153 
10154   // In Microsoft mode, assignment operations don't affect constructors and
10155   // vice versa.
10156   if (RD->hasUserDeclaredDestructor()) {
10157     UserDeclaredOperation = RD->getDestructor();
10158   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
10159              RD->hasUserDeclaredCopyConstructor() &&
10160              !S.getLangOpts().MSVCCompat) {
10161     // Find any user-declared copy constructor.
10162     for (auto *I : RD->ctors()) {
10163       if (I->isCopyConstructor()) {
10164         UserDeclaredOperation = I;
10165         break;
10166       }
10167     }
10168     assert(UserDeclaredOperation);
10169   } else if (isa<CXXConstructorDecl>(CopyOp) &&
10170              RD->hasUserDeclaredCopyAssignment() &&
10171              !S.getLangOpts().MSVCCompat) {
10172     // Find any user-declared move assignment operator.
10173     for (auto *I : RD->methods()) {
10174       if (I->isCopyAssignmentOperator()) {
10175         UserDeclaredOperation = I;
10176         break;
10177       }
10178     }
10179     assert(UserDeclaredOperation);
10180   }
10181 
10182   if (UserDeclaredOperation) {
10183     S.Diag(UserDeclaredOperation->getLocation(),
10184          diag::warn_deprecated_copy_operation)
10185       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
10186       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
10187     S.Diag(UseLoc, diag::note_member_synthesized_at)
10188       << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
10189                                           : Sema::CXXCopyAssignment)
10190       << RD;
10191   }
10192 }
10193 
10194 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
10195                                         CXXMethodDecl *CopyAssignOperator) {
10196   assert((CopyAssignOperator->isDefaulted() &&
10197           CopyAssignOperator->isOverloadedOperator() &&
10198           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
10199           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
10200           !CopyAssignOperator->isDeleted()) &&
10201          "DefineImplicitCopyAssignment called for wrong function");
10202 
10203   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
10204 
10205   if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
10206     CopyAssignOperator->setInvalidDecl();
10207     return;
10208   }
10209 
10210   // C++11 [class.copy]p18:
10211   //   The [definition of an implicitly declared copy assignment operator] is
10212   //   deprecated if the class has a user-declared copy constructor or a
10213   //   user-declared destructor.
10214   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
10215     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
10216 
10217   CopyAssignOperator->markUsed(Context);
10218 
10219   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
10220   DiagnosticErrorTrap Trap(Diags);
10221 
10222   // C++0x [class.copy]p30:
10223   //   The implicitly-defined or explicitly-defaulted copy assignment operator
10224   //   for a non-union class X performs memberwise copy assignment of its
10225   //   subobjects. The direct base classes of X are assigned first, in the
10226   //   order of their declaration in the base-specifier-list, and then the
10227   //   immediate non-static data members of X are assigned, in the order in
10228   //   which they were declared in the class definition.
10229 
10230   // The statements that form the synthesized function body.
10231   SmallVector<Stmt*, 8> Statements;
10232 
10233   // The parameter for the "other" object, which we are copying from.
10234   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
10235   Qualifiers OtherQuals = Other->getType().getQualifiers();
10236   QualType OtherRefType = Other->getType();
10237   if (const LValueReferenceType *OtherRef
10238                                 = OtherRefType->getAs<LValueReferenceType>()) {
10239     OtherRefType = OtherRef->getPointeeType();
10240     OtherQuals = OtherRefType.getQualifiers();
10241   }
10242 
10243   // Our location for everything implicitly-generated.
10244   SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
10245                            ? CopyAssignOperator->getLocEnd()
10246                            : CopyAssignOperator->getLocation();
10247 
10248   // Builds a DeclRefExpr for the "other" object.
10249   RefBuilder OtherRef(Other, OtherRefType);
10250 
10251   // Builds the "this" pointer.
10252   ThisBuilder This;
10253 
10254   // Assign base classes.
10255   bool Invalid = false;
10256   for (auto &Base : ClassDecl->bases()) {
10257     // Form the assignment:
10258     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
10259     QualType BaseType = Base.getType().getUnqualifiedType();
10260     if (!BaseType->isRecordType()) {
10261       Invalid = true;
10262       continue;
10263     }
10264 
10265     CXXCastPath BasePath;
10266     BasePath.push_back(&Base);
10267 
10268     // Construct the "from" expression, which is an implicit cast to the
10269     // appropriately-qualified base type.
10270     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
10271                      VK_LValue, BasePath);
10272 
10273     // Dereference "this".
10274     DerefBuilder DerefThis(This);
10275     CastBuilder To(DerefThis,
10276                    Context.getCVRQualifiedType(
10277                        BaseType, CopyAssignOperator->getTypeQualifiers()),
10278                    VK_LValue, BasePath);
10279 
10280     // Build the copy.
10281     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
10282                                             To, From,
10283                                             /*CopyingBaseSubobject=*/true,
10284                                             /*Copying=*/true);
10285     if (Copy.isInvalid()) {
10286       Diag(CurrentLocation, diag::note_member_synthesized_at)
10287         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10288       CopyAssignOperator->setInvalidDecl();
10289       return;
10290     }
10291 
10292     // Success! Record the copy.
10293     Statements.push_back(Copy.getAs<Expr>());
10294   }
10295 
10296   // Assign non-static members.
10297   for (auto *Field : ClassDecl->fields()) {
10298     // FIXME: We should form some kind of AST representation for the implied
10299     // memcpy in a union copy operation.
10300     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
10301       continue;
10302 
10303     if (Field->isInvalidDecl()) {
10304       Invalid = true;
10305       continue;
10306     }
10307 
10308     // Check for members of reference type; we can't copy those.
10309     if (Field->getType()->isReferenceType()) {
10310       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10311         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10312       Diag(Field->getLocation(), diag::note_declared_at);
10313       Diag(CurrentLocation, diag::note_member_synthesized_at)
10314         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10315       Invalid = true;
10316       continue;
10317     }
10318 
10319     // Check for members of const-qualified, non-class type.
10320     QualType BaseType = Context.getBaseElementType(Field->getType());
10321     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10322       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10323         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10324       Diag(Field->getLocation(), diag::note_declared_at);
10325       Diag(CurrentLocation, diag::note_member_synthesized_at)
10326         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10327       Invalid = true;
10328       continue;
10329     }
10330 
10331     // Suppress assigning zero-width bitfields.
10332     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10333       continue;
10334 
10335     QualType FieldType = Field->getType().getNonReferenceType();
10336     if (FieldType->isIncompleteArrayType()) {
10337       assert(ClassDecl->hasFlexibleArrayMember() &&
10338              "Incomplete array type is not valid");
10339       continue;
10340     }
10341 
10342     // Build references to the field in the object we're copying from and to.
10343     CXXScopeSpec SS; // Intentionally empty
10344     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10345                               LookupMemberName);
10346     MemberLookup.addDecl(Field);
10347     MemberLookup.resolveKind();
10348 
10349     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
10350 
10351     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
10352 
10353     // Build the copy of this field.
10354     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
10355                                             To, From,
10356                                             /*CopyingBaseSubobject=*/false,
10357                                             /*Copying=*/true);
10358     if (Copy.isInvalid()) {
10359       Diag(CurrentLocation, diag::note_member_synthesized_at)
10360         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10361       CopyAssignOperator->setInvalidDecl();
10362       return;
10363     }
10364 
10365     // Success! Record the copy.
10366     Statements.push_back(Copy.getAs<Stmt>());
10367   }
10368 
10369   if (!Invalid) {
10370     // Add a "return *this;"
10371     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10372 
10373     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
10374     if (Return.isInvalid())
10375       Invalid = true;
10376     else {
10377       Statements.push_back(Return.getAs<Stmt>());
10378 
10379       if (Trap.hasErrorOccurred()) {
10380         Diag(CurrentLocation, diag::note_member_synthesized_at)
10381           << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10382         Invalid = true;
10383       }
10384     }
10385   }
10386 
10387   // The exception specification is needed because we are defining the
10388   // function.
10389   ResolveExceptionSpec(CurrentLocation,
10390                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
10391 
10392   if (Invalid) {
10393     CopyAssignOperator->setInvalidDecl();
10394     return;
10395   }
10396 
10397   StmtResult Body;
10398   {
10399     CompoundScopeRAII CompoundScope(*this);
10400     Body = ActOnCompoundStmt(Loc, Loc, Statements,
10401                              /*isStmtExpr=*/false);
10402     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10403   }
10404   CopyAssignOperator->setBody(Body.getAs<Stmt>());
10405 
10406   if (ASTMutationListener *L = getASTMutationListener()) {
10407     L->CompletedImplicitDefinition(CopyAssignOperator);
10408   }
10409 }
10410 
10411 Sema::ImplicitExceptionSpecification
10412 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
10413   CXXRecordDecl *ClassDecl = MD->getParent();
10414 
10415   ImplicitExceptionSpecification ExceptSpec(*this);
10416   if (ClassDecl->isInvalidDecl())
10417     return ExceptSpec;
10418 
10419   // C++0x [except.spec]p14:
10420   //   An implicitly declared special member function (Clause 12) shall have an
10421   //   exception-specification. [...]
10422 
10423   // It is unspecified whether or not an implicit move assignment operator
10424   // attempts to deduplicate calls to assignment operators of virtual bases are
10425   // made. As such, this exception specification is effectively unspecified.
10426   // Based on a similar decision made for constness in C++0x, we're erring on
10427   // the side of assuming such calls to be made regardless of whether they
10428   // actually happen.
10429   // Note that a move constructor is not implicitly declared when there are
10430   // virtual bases, but it can still be user-declared and explicitly defaulted.
10431   for (const auto &Base : ClassDecl->bases()) {
10432     if (Base.isVirtual())
10433       continue;
10434 
10435     CXXRecordDecl *BaseClassDecl
10436       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10437     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
10438                                                            0, false, 0))
10439       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
10440   }
10441 
10442   for (const auto &Base : ClassDecl->vbases()) {
10443     CXXRecordDecl *BaseClassDecl
10444       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10445     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
10446                                                            0, false, 0))
10447       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
10448   }
10449 
10450   for (const auto *Field : ClassDecl->fields()) {
10451     QualType FieldType = Context.getBaseElementType(Field->getType());
10452     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10453       if (CXXMethodDecl *MoveAssign =
10454               LookupMovingAssignment(FieldClassDecl,
10455                                      FieldType.getCVRQualifiers(),
10456                                      false, 0))
10457         ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
10458     }
10459   }
10460 
10461   return ExceptSpec;
10462 }
10463 
10464 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
10465   assert(ClassDecl->needsImplicitMoveAssignment());
10466 
10467   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
10468   if (DSM.isAlreadyBeingDeclared())
10469     return nullptr;
10470 
10471   // Note: The following rules are largely analoguous to the move
10472   // constructor rules.
10473 
10474   QualType ArgType = Context.getTypeDeclType(ClassDecl);
10475   QualType RetType = Context.getLValueReferenceType(ArgType);
10476   ArgType = Context.getRValueReferenceType(ArgType);
10477 
10478   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10479                                                      CXXMoveAssignment,
10480                                                      false);
10481 
10482   //   An implicitly-declared move assignment operator is an inline public
10483   //   member of its class.
10484   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10485   SourceLocation ClassLoc = ClassDecl->getLocation();
10486   DeclarationNameInfo NameInfo(Name, ClassLoc);
10487   CXXMethodDecl *MoveAssignment =
10488       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
10489                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10490                             /*isInline=*/true, Constexpr, SourceLocation());
10491   MoveAssignment->setAccess(AS_public);
10492   MoveAssignment->setDefaulted();
10493   MoveAssignment->setImplicit();
10494 
10495   if (getLangOpts().CUDA) {
10496     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
10497                                             MoveAssignment,
10498                                             /* ConstRHS */ false,
10499                                             /* Diagnose */ false);
10500   }
10501 
10502   // Build an exception specification pointing back at this member.
10503   FunctionProtoType::ExtProtoInfo EPI =
10504       getImplicitMethodEPI(*this, MoveAssignment);
10505   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
10506 
10507   // Add the parameter to the operator.
10508   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
10509                                                ClassLoc, ClassLoc,
10510                                                /*Id=*/nullptr, ArgType,
10511                                                /*TInfo=*/nullptr, SC_None,
10512                                                nullptr);
10513   MoveAssignment->setParams(FromParam);
10514 
10515   AddOverriddenMethods(ClassDecl, MoveAssignment);
10516 
10517   MoveAssignment->setTrivial(
10518     ClassDecl->needsOverloadResolutionForMoveAssignment()
10519       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
10520       : ClassDecl->hasTrivialMoveAssignment());
10521 
10522   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
10523     ClassDecl->setImplicitMoveAssignmentIsDeleted();
10524     SetDeclDeleted(MoveAssignment, ClassLoc);
10525   }
10526 
10527   // Note that we have added this copy-assignment operator.
10528   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
10529 
10530   if (Scope *S = getScopeForContext(ClassDecl))
10531     PushOnScopeChains(MoveAssignment, S, false);
10532   ClassDecl->addDecl(MoveAssignment);
10533 
10534   return MoveAssignment;
10535 }
10536 
10537 /// Check if we're implicitly defining a move assignment operator for a class
10538 /// with virtual bases. Such a move assignment might move-assign the virtual
10539 /// base multiple times.
10540 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
10541                                                SourceLocation CurrentLocation) {
10542   assert(!Class->isDependentContext() && "should not define dependent move");
10543 
10544   // Only a virtual base could get implicitly move-assigned multiple times.
10545   // Only a non-trivial move assignment can observe this. We only want to
10546   // diagnose if we implicitly define an assignment operator that assigns
10547   // two base classes, both of which move-assign the same virtual base.
10548   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
10549       Class->getNumBases() < 2)
10550     return;
10551 
10552   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
10553   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
10554   VBaseMap VBases;
10555 
10556   for (auto &BI : Class->bases()) {
10557     Worklist.push_back(&BI);
10558     while (!Worklist.empty()) {
10559       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
10560       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
10561 
10562       // If the base has no non-trivial move assignment operators,
10563       // we don't care about moves from it.
10564       if (!Base->hasNonTrivialMoveAssignment())
10565         continue;
10566 
10567       // If there's nothing virtual here, skip it.
10568       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
10569         continue;
10570 
10571       // If we're not actually going to call a move assignment for this base,
10572       // or the selected move assignment is trivial, skip it.
10573       Sema::SpecialMemberOverloadResult *SMOR =
10574         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
10575                               /*ConstArg*/false, /*VolatileArg*/false,
10576                               /*RValueThis*/true, /*ConstThis*/false,
10577                               /*VolatileThis*/false);
10578       if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
10579           !SMOR->getMethod()->isMoveAssignmentOperator())
10580         continue;
10581 
10582       if (BaseSpec->isVirtual()) {
10583         // We're going to move-assign this virtual base, and its move
10584         // assignment operator is not trivial. If this can happen for
10585         // multiple distinct direct bases of Class, diagnose it. (If it
10586         // only happens in one base, we'll diagnose it when synthesizing
10587         // that base class's move assignment operator.)
10588         CXXBaseSpecifier *&Existing =
10589             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
10590                 .first->second;
10591         if (Existing && Existing != &BI) {
10592           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
10593             << Class << Base;
10594           S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
10595             << (Base->getCanonicalDecl() ==
10596                 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10597             << Base << Existing->getType() << Existing->getSourceRange();
10598           S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
10599             << (Base->getCanonicalDecl() ==
10600                 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10601             << Base << BI.getType() << BaseSpec->getSourceRange();
10602 
10603           // Only diagnose each vbase once.
10604           Existing = nullptr;
10605         }
10606       } else {
10607         // Only walk over bases that have defaulted move assignment operators.
10608         // We assume that any user-provided move assignment operator handles
10609         // the multiple-moves-of-vbase case itself somehow.
10610         if (!SMOR->getMethod()->isDefaulted())
10611           continue;
10612 
10613         // We're going to move the base classes of Base. Add them to the list.
10614         for (auto &BI : Base->bases())
10615           Worklist.push_back(&BI);
10616       }
10617     }
10618   }
10619 }
10620 
10621 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
10622                                         CXXMethodDecl *MoveAssignOperator) {
10623   assert((MoveAssignOperator->isDefaulted() &&
10624           MoveAssignOperator->isOverloadedOperator() &&
10625           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
10626           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
10627           !MoveAssignOperator->isDeleted()) &&
10628          "DefineImplicitMoveAssignment called for wrong function");
10629 
10630   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
10631 
10632   if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
10633     MoveAssignOperator->setInvalidDecl();
10634     return;
10635   }
10636 
10637   MoveAssignOperator->markUsed(Context);
10638 
10639   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
10640   DiagnosticErrorTrap Trap(Diags);
10641 
10642   // C++0x [class.copy]p28:
10643   //   The implicitly-defined or move assignment operator for a non-union class
10644   //   X performs memberwise move assignment of its subobjects. The direct base
10645   //   classes of X are assigned first, in the order of their declaration in the
10646   //   base-specifier-list, and then the immediate non-static data members of X
10647   //   are assigned, in the order in which they were declared in the class
10648   //   definition.
10649 
10650   // Issue a warning if our implicit move assignment operator will move
10651   // from a virtual base more than once.
10652   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
10653 
10654   // The statements that form the synthesized function body.
10655   SmallVector<Stmt*, 8> Statements;
10656 
10657   // The parameter for the "other" object, which we are move from.
10658   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
10659   QualType OtherRefType = Other->getType()->
10660       getAs<RValueReferenceType>()->getPointeeType();
10661   assert(!OtherRefType.getQualifiers() &&
10662          "Bad argument type of defaulted move assignment");
10663 
10664   // Our location for everything implicitly-generated.
10665   SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
10666                            ? MoveAssignOperator->getLocEnd()
10667                            : MoveAssignOperator->getLocation();
10668 
10669   // Builds a reference to the "other" object.
10670   RefBuilder OtherRef(Other, OtherRefType);
10671   // Cast to rvalue.
10672   MoveCastBuilder MoveOther(OtherRef);
10673 
10674   // Builds the "this" pointer.
10675   ThisBuilder This;
10676 
10677   // Assign base classes.
10678   bool Invalid = false;
10679   for (auto &Base : ClassDecl->bases()) {
10680     // C++11 [class.copy]p28:
10681     //   It is unspecified whether subobjects representing virtual base classes
10682     //   are assigned more than once by the implicitly-defined copy assignment
10683     //   operator.
10684     // FIXME: Do not assign to a vbase that will be assigned by some other base
10685     // class. For a move-assignment, this can result in the vbase being moved
10686     // multiple times.
10687 
10688     // Form the assignment:
10689     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
10690     QualType BaseType = Base.getType().getUnqualifiedType();
10691     if (!BaseType->isRecordType()) {
10692       Invalid = true;
10693       continue;
10694     }
10695 
10696     CXXCastPath BasePath;
10697     BasePath.push_back(&Base);
10698 
10699     // Construct the "from" expression, which is an implicit cast to the
10700     // appropriately-qualified base type.
10701     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
10702 
10703     // Dereference "this".
10704     DerefBuilder DerefThis(This);
10705 
10706     // Implicitly cast "this" to the appropriately-qualified base type.
10707     CastBuilder To(DerefThis,
10708                    Context.getCVRQualifiedType(
10709                        BaseType, MoveAssignOperator->getTypeQualifiers()),
10710                    VK_LValue, BasePath);
10711 
10712     // Build the move.
10713     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
10714                                             To, From,
10715                                             /*CopyingBaseSubobject=*/true,
10716                                             /*Copying=*/false);
10717     if (Move.isInvalid()) {
10718       Diag(CurrentLocation, diag::note_member_synthesized_at)
10719         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10720       MoveAssignOperator->setInvalidDecl();
10721       return;
10722     }
10723 
10724     // Success! Record the move.
10725     Statements.push_back(Move.getAs<Expr>());
10726   }
10727 
10728   // Assign non-static members.
10729   for (auto *Field : ClassDecl->fields()) {
10730     // FIXME: We should form some kind of AST representation for the implied
10731     // memcpy in a union copy operation.
10732     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
10733       continue;
10734 
10735     if (Field->isInvalidDecl()) {
10736       Invalid = true;
10737       continue;
10738     }
10739 
10740     // Check for members of reference type; we can't move those.
10741     if (Field->getType()->isReferenceType()) {
10742       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10743         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10744       Diag(Field->getLocation(), diag::note_declared_at);
10745       Diag(CurrentLocation, diag::note_member_synthesized_at)
10746         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10747       Invalid = true;
10748       continue;
10749     }
10750 
10751     // Check for members of const-qualified, non-class type.
10752     QualType BaseType = Context.getBaseElementType(Field->getType());
10753     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10754       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10755         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10756       Diag(Field->getLocation(), diag::note_declared_at);
10757       Diag(CurrentLocation, diag::note_member_synthesized_at)
10758         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10759       Invalid = true;
10760       continue;
10761     }
10762 
10763     // Suppress assigning zero-width bitfields.
10764     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10765       continue;
10766 
10767     QualType FieldType = Field->getType().getNonReferenceType();
10768     if (FieldType->isIncompleteArrayType()) {
10769       assert(ClassDecl->hasFlexibleArrayMember() &&
10770              "Incomplete array type is not valid");
10771       continue;
10772     }
10773 
10774     // Build references to the field in the object we're copying from and to.
10775     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10776                               LookupMemberName);
10777     MemberLookup.addDecl(Field);
10778     MemberLookup.resolveKind();
10779     MemberBuilder From(MoveOther, OtherRefType,
10780                        /*IsArrow=*/false, MemberLookup);
10781     MemberBuilder To(This, getCurrentThisType(),
10782                      /*IsArrow=*/true, MemberLookup);
10783 
10784     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
10785         "Member reference with rvalue base must be rvalue except for reference "
10786         "members, which aren't allowed for move assignment.");
10787 
10788     // Build the move of this field.
10789     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
10790                                             To, From,
10791                                             /*CopyingBaseSubobject=*/false,
10792                                             /*Copying=*/false);
10793     if (Move.isInvalid()) {
10794       Diag(CurrentLocation, diag::note_member_synthesized_at)
10795         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10796       MoveAssignOperator->setInvalidDecl();
10797       return;
10798     }
10799 
10800     // Success! Record the copy.
10801     Statements.push_back(Move.getAs<Stmt>());
10802   }
10803 
10804   if (!Invalid) {
10805     // Add a "return *this;"
10806     ExprResult ThisObj =
10807         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10808 
10809     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
10810     if (Return.isInvalid())
10811       Invalid = true;
10812     else {
10813       Statements.push_back(Return.getAs<Stmt>());
10814 
10815       if (Trap.hasErrorOccurred()) {
10816         Diag(CurrentLocation, diag::note_member_synthesized_at)
10817           << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10818         Invalid = true;
10819       }
10820     }
10821   }
10822 
10823   // The exception specification is needed because we are defining the
10824   // function.
10825   ResolveExceptionSpec(CurrentLocation,
10826                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
10827 
10828   if (Invalid) {
10829     MoveAssignOperator->setInvalidDecl();
10830     return;
10831   }
10832 
10833   StmtResult Body;
10834   {
10835     CompoundScopeRAII CompoundScope(*this);
10836     Body = ActOnCompoundStmt(Loc, Loc, Statements,
10837                              /*isStmtExpr=*/false);
10838     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10839   }
10840   MoveAssignOperator->setBody(Body.getAs<Stmt>());
10841 
10842   if (ASTMutationListener *L = getASTMutationListener()) {
10843     L->CompletedImplicitDefinition(MoveAssignOperator);
10844   }
10845 }
10846 
10847 Sema::ImplicitExceptionSpecification
10848 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10849   CXXRecordDecl *ClassDecl = MD->getParent();
10850 
10851   ImplicitExceptionSpecification ExceptSpec(*this);
10852   if (ClassDecl->isInvalidDecl())
10853     return ExceptSpec;
10854 
10855   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
10856   assert(T->getNumParams() >= 1 && "not a copy ctor");
10857   unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
10858 
10859   // C++ [except.spec]p14:
10860   //   An implicitly declared special member function (Clause 12) shall have an
10861   //   exception-specification. [...]
10862   for (const auto &Base : ClassDecl->bases()) {
10863     // Virtual bases are handled below.
10864     if (Base.isVirtual())
10865       continue;
10866 
10867     CXXRecordDecl *BaseClassDecl
10868       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10869     if (CXXConstructorDecl *CopyConstructor =
10870           LookupCopyingConstructor(BaseClassDecl, Quals))
10871       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10872   }
10873   for (const auto &Base : ClassDecl->vbases()) {
10874     CXXRecordDecl *BaseClassDecl
10875       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10876     if (CXXConstructorDecl *CopyConstructor =
10877           LookupCopyingConstructor(BaseClassDecl, Quals))
10878       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10879   }
10880   for (const auto *Field : ClassDecl->fields()) {
10881     QualType FieldType = Context.getBaseElementType(Field->getType());
10882     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10883       if (CXXConstructorDecl *CopyConstructor =
10884               LookupCopyingConstructor(FieldClassDecl,
10885                                        Quals | FieldType.getCVRQualifiers()))
10886       ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
10887     }
10888   }
10889 
10890   return ExceptSpec;
10891 }
10892 
10893 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10894                                                     CXXRecordDecl *ClassDecl) {
10895   // C++ [class.copy]p4:
10896   //   If the class definition does not explicitly declare a copy
10897   //   constructor, one is declared implicitly.
10898   assert(ClassDecl->needsImplicitCopyConstructor());
10899 
10900   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10901   if (DSM.isAlreadyBeingDeclared())
10902     return nullptr;
10903 
10904   QualType ClassType = Context.getTypeDeclType(ClassDecl);
10905   QualType ArgType = ClassType;
10906   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
10907   if (Const)
10908     ArgType = ArgType.withConst();
10909   ArgType = Context.getLValueReferenceType(ArgType);
10910 
10911   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10912                                                      CXXCopyConstructor,
10913                                                      Const);
10914 
10915   DeclarationName Name
10916     = Context.DeclarationNames.getCXXConstructorName(
10917                                            Context.getCanonicalType(ClassType));
10918   SourceLocation ClassLoc = ClassDecl->getLocation();
10919   DeclarationNameInfo NameInfo(Name, ClassLoc);
10920 
10921   //   An implicitly-declared copy constructor is an inline public
10922   //   member of its class.
10923   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
10924       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
10925       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10926       Constexpr);
10927   CopyConstructor->setAccess(AS_public);
10928   CopyConstructor->setDefaulted();
10929 
10930   if (getLangOpts().CUDA) {
10931     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
10932                                             CopyConstructor,
10933                                             /* ConstRHS */ Const,
10934                                             /* Diagnose */ false);
10935   }
10936 
10937   // Build an exception specification pointing back at this member.
10938   FunctionProtoType::ExtProtoInfo EPI =
10939       getImplicitMethodEPI(*this, CopyConstructor);
10940   CopyConstructor->setType(
10941       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10942 
10943   // Add the parameter to the constructor.
10944   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
10945                                                ClassLoc, ClassLoc,
10946                                                /*IdentifierInfo=*/nullptr,
10947                                                ArgType, /*TInfo=*/nullptr,
10948                                                SC_None, nullptr);
10949   CopyConstructor->setParams(FromParam);
10950 
10951   CopyConstructor->setTrivial(
10952     ClassDecl->needsOverloadResolutionForCopyConstructor()
10953       ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10954       : ClassDecl->hasTrivialCopyConstructor());
10955 
10956   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
10957     SetDeclDeleted(CopyConstructor, ClassLoc);
10958 
10959   // Note that we have declared this constructor.
10960   ++ASTContext::NumImplicitCopyConstructorsDeclared;
10961 
10962   if (Scope *S = getScopeForContext(ClassDecl))
10963     PushOnScopeChains(CopyConstructor, S, false);
10964   ClassDecl->addDecl(CopyConstructor);
10965 
10966   return CopyConstructor;
10967 }
10968 
10969 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
10970                                    CXXConstructorDecl *CopyConstructor) {
10971   assert((CopyConstructor->isDefaulted() &&
10972           CopyConstructor->isCopyConstructor() &&
10973           !CopyConstructor->doesThisDeclarationHaveABody() &&
10974           !CopyConstructor->isDeleted()) &&
10975          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
10976 
10977   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
10978   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
10979 
10980   // C++11 [class.copy]p7:
10981   //   The [definition of an implicitly declared copy constructor] is
10982   //   deprecated if the class has a user-declared copy assignment operator
10983   //   or a user-declared destructor.
10984   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10985     diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10986 
10987   SynthesizedFunctionScope Scope(*this, CopyConstructor);
10988   DiagnosticErrorTrap Trap(Diags);
10989 
10990   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
10991       Trap.hasErrorOccurred()) {
10992     Diag(CurrentLocation, diag::note_member_synthesized_at)
10993       << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
10994     CopyConstructor->setInvalidDecl();
10995   }  else {
10996     SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
10997                              ? CopyConstructor->getLocEnd()
10998                              : CopyConstructor->getLocation();
10999     Sema::CompoundScopeRAII CompoundScope(*this);
11000     CopyConstructor->setBody(
11001         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
11002   }
11003 
11004   // The exception specification is needed because we are defining the
11005   // function.
11006   ResolveExceptionSpec(CurrentLocation,
11007                        CopyConstructor->getType()->castAs<FunctionProtoType>());
11008 
11009   CopyConstructor->markUsed(Context);
11010   MarkVTableUsed(CurrentLocation, ClassDecl);
11011 
11012   if (ASTMutationListener *L = getASTMutationListener()) {
11013     L->CompletedImplicitDefinition(CopyConstructor);
11014   }
11015 }
11016 
11017 Sema::ImplicitExceptionSpecification
11018 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
11019   CXXRecordDecl *ClassDecl = MD->getParent();
11020 
11021   // C++ [except.spec]p14:
11022   //   An implicitly declared special member function (Clause 12) shall have an
11023   //   exception-specification. [...]
11024   ImplicitExceptionSpecification ExceptSpec(*this);
11025   if (ClassDecl->isInvalidDecl())
11026     return ExceptSpec;
11027 
11028   // Direct base-class constructors.
11029   for (const auto &B : ClassDecl->bases()) {
11030     if (B.isVirtual()) // Handled below.
11031       continue;
11032 
11033     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
11034       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
11035       CXXConstructorDecl *Constructor =
11036           LookupMovingConstructor(BaseClassDecl, 0);
11037       // If this is a deleted function, add it anyway. This might be conformant
11038       // with the standard. This might not. I'm not sure. It might not matter.
11039       if (Constructor)
11040         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
11041     }
11042   }
11043 
11044   // Virtual base-class constructors.
11045   for (const auto &B : ClassDecl->vbases()) {
11046     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
11047       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
11048       CXXConstructorDecl *Constructor =
11049           LookupMovingConstructor(BaseClassDecl, 0);
11050       // If this is a deleted function, add it anyway. This might be conformant
11051       // with the standard. This might not. I'm not sure. It might not matter.
11052       if (Constructor)
11053         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
11054     }
11055   }
11056 
11057   // Field constructors.
11058   for (const auto *F : ClassDecl->fields()) {
11059     QualType FieldType = Context.getBaseElementType(F->getType());
11060     if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
11061       CXXConstructorDecl *Constructor =
11062           LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
11063       // If this is a deleted function, add it anyway. This might be conformant
11064       // with the standard. This might not. I'm not sure. It might not matter.
11065       // In particular, the problem is that this function never gets called. It
11066       // might just be ill-formed because this function attempts to refer to
11067       // a deleted function here.
11068       if (Constructor)
11069         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
11070     }
11071   }
11072 
11073   return ExceptSpec;
11074 }
11075 
11076 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
11077                                                     CXXRecordDecl *ClassDecl) {
11078   assert(ClassDecl->needsImplicitMoveConstructor());
11079 
11080   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
11081   if (DSM.isAlreadyBeingDeclared())
11082     return nullptr;
11083 
11084   QualType ClassType = Context.getTypeDeclType(ClassDecl);
11085   QualType ArgType = Context.getRValueReferenceType(ClassType);
11086 
11087   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11088                                                      CXXMoveConstructor,
11089                                                      false);
11090 
11091   DeclarationName Name
11092     = Context.DeclarationNames.getCXXConstructorName(
11093                                            Context.getCanonicalType(ClassType));
11094   SourceLocation ClassLoc = ClassDecl->getLocation();
11095   DeclarationNameInfo NameInfo(Name, ClassLoc);
11096 
11097   // C++11 [class.copy]p11:
11098   //   An implicitly-declared copy/move constructor is an inline public
11099   //   member of its class.
11100   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
11101       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
11102       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
11103       Constexpr);
11104   MoveConstructor->setAccess(AS_public);
11105   MoveConstructor->setDefaulted();
11106 
11107   if (getLangOpts().CUDA) {
11108     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
11109                                             MoveConstructor,
11110                                             /* ConstRHS */ false,
11111                                             /* Diagnose */ false);
11112   }
11113 
11114   // Build an exception specification pointing back at this member.
11115   FunctionProtoType::ExtProtoInfo EPI =
11116       getImplicitMethodEPI(*this, MoveConstructor);
11117   MoveConstructor->setType(
11118       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
11119 
11120   // Add the parameter to the constructor.
11121   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
11122                                                ClassLoc, ClassLoc,
11123                                                /*IdentifierInfo=*/nullptr,
11124                                                ArgType, /*TInfo=*/nullptr,
11125                                                SC_None, nullptr);
11126   MoveConstructor->setParams(FromParam);
11127 
11128   MoveConstructor->setTrivial(
11129     ClassDecl->needsOverloadResolutionForMoveConstructor()
11130       ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
11131       : ClassDecl->hasTrivialMoveConstructor());
11132 
11133   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
11134     ClassDecl->setImplicitMoveConstructorIsDeleted();
11135     SetDeclDeleted(MoveConstructor, ClassLoc);
11136   }
11137 
11138   // Note that we have declared this constructor.
11139   ++ASTContext::NumImplicitMoveConstructorsDeclared;
11140 
11141   if (Scope *S = getScopeForContext(ClassDecl))
11142     PushOnScopeChains(MoveConstructor, S, false);
11143   ClassDecl->addDecl(MoveConstructor);
11144 
11145   return MoveConstructor;
11146 }
11147 
11148 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
11149                                    CXXConstructorDecl *MoveConstructor) {
11150   assert((MoveConstructor->isDefaulted() &&
11151           MoveConstructor->isMoveConstructor() &&
11152           !MoveConstructor->doesThisDeclarationHaveABody() &&
11153           !MoveConstructor->isDeleted()) &&
11154          "DefineImplicitMoveConstructor - call it for implicit move ctor");
11155 
11156   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
11157   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
11158 
11159   SynthesizedFunctionScope Scope(*this, MoveConstructor);
11160   DiagnosticErrorTrap Trap(Diags);
11161 
11162   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
11163       Trap.hasErrorOccurred()) {
11164     Diag(CurrentLocation, diag::note_member_synthesized_at)
11165       << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
11166     MoveConstructor->setInvalidDecl();
11167   }  else {
11168     SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
11169                              ? MoveConstructor->getLocEnd()
11170                              : MoveConstructor->getLocation();
11171     Sema::CompoundScopeRAII CompoundScope(*this);
11172     MoveConstructor->setBody(ActOnCompoundStmt(
11173         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
11174   }
11175 
11176   // The exception specification is needed because we are defining the
11177   // function.
11178   ResolveExceptionSpec(CurrentLocation,
11179                        MoveConstructor->getType()->castAs<FunctionProtoType>());
11180 
11181   MoveConstructor->markUsed(Context);
11182   MarkVTableUsed(CurrentLocation, ClassDecl);
11183 
11184   if (ASTMutationListener *L = getASTMutationListener()) {
11185     L->CompletedImplicitDefinition(MoveConstructor);
11186   }
11187 }
11188 
11189 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
11190   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
11191 }
11192 
11193 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
11194                             SourceLocation CurrentLocation,
11195                             CXXConversionDecl *Conv) {
11196   CXXRecordDecl *Lambda = Conv->getParent();
11197   CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
11198   // If we are defining a specialization of a conversion to function-ptr
11199   // cache the deduced template arguments for this specialization
11200   // so that we can use them to retrieve the corresponding call-operator
11201   // and static-invoker.
11202   const TemplateArgumentList *DeducedTemplateArgs = nullptr;
11203 
11204   // Retrieve the corresponding call-operator specialization.
11205   if (Lambda->isGenericLambda()) {
11206     assert(Conv->isFunctionTemplateSpecialization());
11207     FunctionTemplateDecl *CallOpTemplate =
11208         CallOp->getDescribedFunctionTemplate();
11209     DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
11210     void *InsertPos = nullptr;
11211     FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
11212                                                 DeducedTemplateArgs->asArray(),
11213                                                 InsertPos);
11214     assert(CallOpSpec &&
11215           "Conversion operator must have a corresponding call operator");
11216     CallOp = cast<CXXMethodDecl>(CallOpSpec);
11217   }
11218   // Mark the call operator referenced (and add to pending instantiations
11219   // if necessary).
11220   // For both the conversion and static-invoker template specializations
11221   // we construct their body's in this function, so no need to add them
11222   // to the PendingInstantiations.
11223   MarkFunctionReferenced(CurrentLocation, CallOp);
11224 
11225   SynthesizedFunctionScope Scope(*this, Conv);
11226   DiagnosticErrorTrap Trap(Diags);
11227 
11228   // Retrieve the static invoker...
11229   CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
11230   // ... and get the corresponding specialization for a generic lambda.
11231   if (Lambda->isGenericLambda()) {
11232     assert(DeducedTemplateArgs &&
11233       "Must have deduced template arguments from Conversion Operator");
11234     FunctionTemplateDecl *InvokeTemplate =
11235                           Invoker->getDescribedFunctionTemplate();
11236     void *InsertPos = nullptr;
11237     FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
11238                                                 DeducedTemplateArgs->asArray(),
11239                                                 InsertPos);
11240     assert(InvokeSpec &&
11241       "Must have a corresponding static invoker specialization");
11242     Invoker = cast<CXXMethodDecl>(InvokeSpec);
11243   }
11244   // Construct the body of the conversion function { return __invoke; }.
11245   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
11246                                         VK_LValue, Conv->getLocation()).get();
11247    assert(FunctionRef && "Can't refer to __invoke function?");
11248    Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
11249    Conv->setBody(new (Context) CompoundStmt(Context, Return,
11250                                             Conv->getLocation(),
11251                                             Conv->getLocation()));
11252 
11253   Conv->markUsed(Context);
11254   Conv->setReferenced();
11255 
11256   // Fill in the __invoke function with a dummy implementation. IR generation
11257   // will fill in the actual details.
11258   Invoker->markUsed(Context);
11259   Invoker->setReferenced();
11260   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
11261 
11262   if (ASTMutationListener *L = getASTMutationListener()) {
11263     L->CompletedImplicitDefinition(Conv);
11264     L->CompletedImplicitDefinition(Invoker);
11265    }
11266 }
11267 
11268 
11269 
11270 void Sema::DefineImplicitLambdaToBlockPointerConversion(
11271        SourceLocation CurrentLocation,
11272        CXXConversionDecl *Conv)
11273 {
11274   assert(!Conv->getParent()->isGenericLambda());
11275 
11276   Conv->markUsed(Context);
11277 
11278   SynthesizedFunctionScope Scope(*this, Conv);
11279   DiagnosticErrorTrap Trap(Diags);
11280 
11281   // Copy-initialize the lambda object as needed to capture it.
11282   Expr *This = ActOnCXXThis(CurrentLocation).get();
11283   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
11284 
11285   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
11286                                                         Conv->getLocation(),
11287                                                         Conv, DerefThis);
11288 
11289   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
11290   // behavior.  Note that only the general conversion function does this
11291   // (since it's unusable otherwise); in the case where we inline the
11292   // block literal, it has block literal lifetime semantics.
11293   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
11294     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
11295                                           CK_CopyAndAutoreleaseBlockObject,
11296                                           BuildBlock.get(), nullptr, VK_RValue);
11297 
11298   if (BuildBlock.isInvalid()) {
11299     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11300     Conv->setInvalidDecl();
11301     return;
11302   }
11303 
11304   // Create the return statement that returns the block from the conversion
11305   // function.
11306   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
11307   if (Return.isInvalid()) {
11308     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11309     Conv->setInvalidDecl();
11310     return;
11311   }
11312 
11313   // Set the body of the conversion function.
11314   Stmt *ReturnS = Return.get();
11315   Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
11316                                            Conv->getLocation(),
11317                                            Conv->getLocation()));
11318 
11319   // We're done; notify the mutation listener, if any.
11320   if (ASTMutationListener *L = getASTMutationListener()) {
11321     L->CompletedImplicitDefinition(Conv);
11322   }
11323 }
11324 
11325 /// \brief Determine whether the given list arguments contains exactly one
11326 /// "real" (non-default) argument.
11327 static bool hasOneRealArgument(MultiExprArg Args) {
11328   switch (Args.size()) {
11329   case 0:
11330     return false;
11331 
11332   default:
11333     if (!Args[1]->isDefaultArgument())
11334       return false;
11335 
11336     // fall through
11337   case 1:
11338     return !Args[0]->isDefaultArgument();
11339   }
11340 
11341   return false;
11342 }
11343 
11344 ExprResult
11345 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11346                             CXXConstructorDecl *Constructor,
11347                             MultiExprArg ExprArgs,
11348                             bool HadMultipleCandidates,
11349                             bool IsListInitialization,
11350                             bool IsStdInitListInitialization,
11351                             bool RequiresZeroInit,
11352                             unsigned ConstructKind,
11353                             SourceRange ParenRange) {
11354   bool Elidable = false;
11355 
11356   // C++0x [class.copy]p34:
11357   //   When certain criteria are met, an implementation is allowed to
11358   //   omit the copy/move construction of a class object, even if the
11359   //   copy/move constructor and/or destructor for the object have
11360   //   side effects. [...]
11361   //     - when a temporary class object that has not been bound to a
11362   //       reference (12.2) would be copied/moved to a class object
11363   //       with the same cv-unqualified type, the copy/move operation
11364   //       can be omitted by constructing the temporary object
11365   //       directly into the target of the omitted copy/move
11366   if (ConstructKind == CXXConstructExpr::CK_Complete &&
11367       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
11368     Expr *SubExpr = ExprArgs[0];
11369     Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
11370   }
11371 
11372   return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
11373                                Elidable, ExprArgs, HadMultipleCandidates,
11374                                IsListInitialization,
11375                                IsStdInitListInitialization, RequiresZeroInit,
11376                                ConstructKind, ParenRange);
11377 }
11378 
11379 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
11380 /// including handling of its default argument expressions.
11381 ExprResult
11382 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11383                             CXXConstructorDecl *Constructor, bool Elidable,
11384                             MultiExprArg ExprArgs,
11385                             bool HadMultipleCandidates,
11386                             bool IsListInitialization,
11387                             bool IsStdInitListInitialization,
11388                             bool RequiresZeroInit,
11389                             unsigned ConstructKind,
11390                             SourceRange ParenRange) {
11391   MarkFunctionReferenced(ConstructLoc, Constructor);
11392   return CXXConstructExpr::Create(
11393       Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
11394       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
11395       RequiresZeroInit,
11396       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
11397       ParenRange);
11398 }
11399 
11400 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
11401   assert(Field->hasInClassInitializer());
11402 
11403   // If we already have the in-class initializer nothing needs to be done.
11404   if (Field->getInClassInitializer())
11405     return CXXDefaultInitExpr::Create(Context, Loc, Field);
11406 
11407   // Maybe we haven't instantiated the in-class initializer. Go check the
11408   // pattern FieldDecl to see if it has one.
11409   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
11410 
11411   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
11412     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
11413     DeclContext::lookup_result Lookup =
11414         ClassPattern->lookup(Field->getDeclName());
11415 
11416     // Lookup can return at most two results: the pattern for the field, or the
11417     // injected class name of the parent record. No other member can have the
11418     // same name as the field.
11419     assert(!Lookup.empty() && Lookup.size() <= 2 &&
11420            "more than two lookup results for field name");
11421     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
11422     if (!Pattern) {
11423       assert(isa<CXXRecordDecl>(Lookup[0]) &&
11424              "cannot have other non-field member with same name");
11425       Pattern = cast<FieldDecl>(Lookup[1]);
11426     }
11427 
11428     if (InstantiateInClassInitializer(Loc, Field, Pattern,
11429                                       getTemplateInstantiationArgs(Field)))
11430       return ExprError();
11431     return CXXDefaultInitExpr::Create(Context, Loc, Field);
11432   }
11433 
11434   // DR1351:
11435   //   If the brace-or-equal-initializer of a non-static data member
11436   //   invokes a defaulted default constructor of its class or of an
11437   //   enclosing class in a potentially evaluated subexpression, the
11438   //   program is ill-formed.
11439   //
11440   // This resolution is unworkable: the exception specification of the
11441   // default constructor can be needed in an unevaluated context, in
11442   // particular, in the operand of a noexcept-expression, and we can be
11443   // unable to compute an exception specification for an enclosed class.
11444   //
11445   // Any attempt to resolve the exception specification of a defaulted default
11446   // constructor before the initializer is lexically complete will ultimately
11447   // come here at which point we can diagnose it.
11448   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
11449   if (OutermostClass == ParentRD) {
11450     Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
11451         << ParentRD << Field;
11452   } else {
11453     Diag(Field->getLocEnd(),
11454          diag::err_in_class_initializer_not_yet_parsed_outer_class)
11455         << ParentRD << OutermostClass << Field;
11456   }
11457 
11458   return ExprError();
11459 }
11460 
11461 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
11462   if (VD->isInvalidDecl()) return;
11463 
11464   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
11465   if (ClassDecl->isInvalidDecl()) return;
11466   if (ClassDecl->hasIrrelevantDestructor()) return;
11467   if (ClassDecl->isDependentContext()) return;
11468 
11469   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
11470   MarkFunctionReferenced(VD->getLocation(), Destructor);
11471   CheckDestructorAccess(VD->getLocation(), Destructor,
11472                         PDiag(diag::err_access_dtor_var)
11473                         << VD->getDeclName()
11474                         << VD->getType());
11475   DiagnoseUseOfDecl(Destructor, VD->getLocation());
11476 
11477   if (Destructor->isTrivial()) return;
11478   if (!VD->hasGlobalStorage()) return;
11479 
11480   // Emit warning for non-trivial dtor in global scope (a real global,
11481   // class-static, function-static).
11482   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
11483 
11484   // TODO: this should be re-enabled for static locals by !CXAAtExit
11485   if (!VD->isStaticLocal())
11486     Diag(VD->getLocation(), diag::warn_global_destructor);
11487 }
11488 
11489 /// \brief Given a constructor and the set of arguments provided for the
11490 /// constructor, convert the arguments and add any required default arguments
11491 /// to form a proper call to this constructor.
11492 ///
11493 /// \returns true if an error occurred, false otherwise.
11494 bool
11495 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
11496                               MultiExprArg ArgsPtr,
11497                               SourceLocation Loc,
11498                               SmallVectorImpl<Expr*> &ConvertedArgs,
11499                               bool AllowExplicit,
11500                               bool IsListInitialization) {
11501   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
11502   unsigned NumArgs = ArgsPtr.size();
11503   Expr **Args = ArgsPtr.data();
11504 
11505   const FunctionProtoType *Proto
11506     = Constructor->getType()->getAs<FunctionProtoType>();
11507   assert(Proto && "Constructor without a prototype?");
11508   unsigned NumParams = Proto->getNumParams();
11509 
11510   // If too few arguments are available, we'll fill in the rest with defaults.
11511   if (NumArgs < NumParams)
11512     ConvertedArgs.reserve(NumParams);
11513   else
11514     ConvertedArgs.reserve(NumArgs);
11515 
11516   VariadicCallType CallType =
11517     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
11518   SmallVector<Expr *, 8> AllArgs;
11519   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
11520                                         Proto, 0,
11521                                         llvm::makeArrayRef(Args, NumArgs),
11522                                         AllArgs,
11523                                         CallType, AllowExplicit,
11524                                         IsListInitialization);
11525   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
11526 
11527   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
11528 
11529   CheckConstructorCall(Constructor,
11530                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
11531                        Proto, Loc);
11532 
11533   return Invalid;
11534 }
11535 
11536 static inline bool
11537 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
11538                                        const FunctionDecl *FnDecl) {
11539   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
11540   if (isa<NamespaceDecl>(DC)) {
11541     return SemaRef.Diag(FnDecl->getLocation(),
11542                         diag::err_operator_new_delete_declared_in_namespace)
11543       << FnDecl->getDeclName();
11544   }
11545 
11546   if (isa<TranslationUnitDecl>(DC) &&
11547       FnDecl->getStorageClass() == SC_Static) {
11548     return SemaRef.Diag(FnDecl->getLocation(),
11549                         diag::err_operator_new_delete_declared_static)
11550       << FnDecl->getDeclName();
11551   }
11552 
11553   return false;
11554 }
11555 
11556 static inline bool
11557 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
11558                             CanQualType ExpectedResultType,
11559                             CanQualType ExpectedFirstParamType,
11560                             unsigned DependentParamTypeDiag,
11561                             unsigned InvalidParamTypeDiag) {
11562   QualType ResultType =
11563       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
11564 
11565   // Check that the result type is not dependent.
11566   if (ResultType->isDependentType())
11567     return SemaRef.Diag(FnDecl->getLocation(),
11568                         diag::err_operator_new_delete_dependent_result_type)
11569     << FnDecl->getDeclName() << ExpectedResultType;
11570 
11571   // Check that the result type is what we expect.
11572   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
11573     return SemaRef.Diag(FnDecl->getLocation(),
11574                         diag::err_operator_new_delete_invalid_result_type)
11575     << FnDecl->getDeclName() << ExpectedResultType;
11576 
11577   // A function template must have at least 2 parameters.
11578   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
11579     return SemaRef.Diag(FnDecl->getLocation(),
11580                       diag::err_operator_new_delete_template_too_few_parameters)
11581         << FnDecl->getDeclName();
11582 
11583   // The function decl must have at least 1 parameter.
11584   if (FnDecl->getNumParams() == 0)
11585     return SemaRef.Diag(FnDecl->getLocation(),
11586                         diag::err_operator_new_delete_too_few_parameters)
11587       << FnDecl->getDeclName();
11588 
11589   // Check the first parameter type is not dependent.
11590   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
11591   if (FirstParamType->isDependentType())
11592     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
11593       << FnDecl->getDeclName() << ExpectedFirstParamType;
11594 
11595   // Check that the first parameter type is what we expect.
11596   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
11597       ExpectedFirstParamType)
11598     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
11599     << FnDecl->getDeclName() << ExpectedFirstParamType;
11600 
11601   return false;
11602 }
11603 
11604 static bool
11605 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
11606   // C++ [basic.stc.dynamic.allocation]p1:
11607   //   A program is ill-formed if an allocation function is declared in a
11608   //   namespace scope other than global scope or declared static in global
11609   //   scope.
11610   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11611     return true;
11612 
11613   CanQualType SizeTy =
11614     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
11615 
11616   // C++ [basic.stc.dynamic.allocation]p1:
11617   //  The return type shall be void*. The first parameter shall have type
11618   //  std::size_t.
11619   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
11620                                   SizeTy,
11621                                   diag::err_operator_new_dependent_param_type,
11622                                   diag::err_operator_new_param_type))
11623     return true;
11624 
11625   // C++ [basic.stc.dynamic.allocation]p1:
11626   //  The first parameter shall not have an associated default argument.
11627   if (FnDecl->getParamDecl(0)->hasDefaultArg())
11628     return SemaRef.Diag(FnDecl->getLocation(),
11629                         diag::err_operator_new_default_arg)
11630       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
11631 
11632   return false;
11633 }
11634 
11635 static bool
11636 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
11637   // C++ [basic.stc.dynamic.deallocation]p1:
11638   //   A program is ill-formed if deallocation functions are declared in a
11639   //   namespace scope other than global scope or declared static in global
11640   //   scope.
11641   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11642     return true;
11643 
11644   // C++ [basic.stc.dynamic.deallocation]p2:
11645   //   Each deallocation function shall return void and its first parameter
11646   //   shall be void*.
11647   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
11648                                   SemaRef.Context.VoidPtrTy,
11649                                  diag::err_operator_delete_dependent_param_type,
11650                                  diag::err_operator_delete_param_type))
11651     return true;
11652 
11653   return false;
11654 }
11655 
11656 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
11657 /// of this overloaded operator is well-formed. If so, returns false;
11658 /// otherwise, emits appropriate diagnostics and returns true.
11659 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
11660   assert(FnDecl && FnDecl->isOverloadedOperator() &&
11661          "Expected an overloaded operator declaration");
11662 
11663   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
11664 
11665   // C++ [over.oper]p5:
11666   //   The allocation and deallocation functions, operator new,
11667   //   operator new[], operator delete and operator delete[], are
11668   //   described completely in 3.7.3. The attributes and restrictions
11669   //   found in the rest of this subclause do not apply to them unless
11670   //   explicitly stated in 3.7.3.
11671   if (Op == OO_Delete || Op == OO_Array_Delete)
11672     return CheckOperatorDeleteDeclaration(*this, FnDecl);
11673 
11674   if (Op == OO_New || Op == OO_Array_New)
11675     return CheckOperatorNewDeclaration(*this, FnDecl);
11676 
11677   // C++ [over.oper]p6:
11678   //   An operator function shall either be a non-static member
11679   //   function or be a non-member function and have at least one
11680   //   parameter whose type is a class, a reference to a class, an
11681   //   enumeration, or a reference to an enumeration.
11682   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
11683     if (MethodDecl->isStatic())
11684       return Diag(FnDecl->getLocation(),
11685                   diag::err_operator_overload_static) << FnDecl->getDeclName();
11686   } else {
11687     bool ClassOrEnumParam = false;
11688     for (auto Param : FnDecl->params()) {
11689       QualType ParamType = Param->getType().getNonReferenceType();
11690       if (ParamType->isDependentType() || ParamType->isRecordType() ||
11691           ParamType->isEnumeralType()) {
11692         ClassOrEnumParam = true;
11693         break;
11694       }
11695     }
11696 
11697     if (!ClassOrEnumParam)
11698       return Diag(FnDecl->getLocation(),
11699                   diag::err_operator_overload_needs_class_or_enum)
11700         << FnDecl->getDeclName();
11701   }
11702 
11703   // C++ [over.oper]p8:
11704   //   An operator function cannot have default arguments (8.3.6),
11705   //   except where explicitly stated below.
11706   //
11707   // Only the function-call operator allows default arguments
11708   // (C++ [over.call]p1).
11709   if (Op != OO_Call) {
11710     for (auto Param : FnDecl->params()) {
11711       if (Param->hasDefaultArg())
11712         return Diag(Param->getLocation(),
11713                     diag::err_operator_overload_default_arg)
11714           << FnDecl->getDeclName() << Param->getDefaultArgRange();
11715     }
11716   }
11717 
11718   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
11719     { false, false, false }
11720 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11721     , { Unary, Binary, MemberOnly }
11722 #include "clang/Basic/OperatorKinds.def"
11723   };
11724 
11725   bool CanBeUnaryOperator = OperatorUses[Op][0];
11726   bool CanBeBinaryOperator = OperatorUses[Op][1];
11727   bool MustBeMemberOperator = OperatorUses[Op][2];
11728 
11729   // C++ [over.oper]p8:
11730   //   [...] Operator functions cannot have more or fewer parameters
11731   //   than the number required for the corresponding operator, as
11732   //   described in the rest of this subclause.
11733   unsigned NumParams = FnDecl->getNumParams()
11734                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
11735   if (Op != OO_Call &&
11736       ((NumParams == 1 && !CanBeUnaryOperator) ||
11737        (NumParams == 2 && !CanBeBinaryOperator) ||
11738        (NumParams < 1) || (NumParams > 2))) {
11739     // We have the wrong number of parameters.
11740     unsigned ErrorKind;
11741     if (CanBeUnaryOperator && CanBeBinaryOperator) {
11742       ErrorKind = 2;  // 2 -> unary or binary.
11743     } else if (CanBeUnaryOperator) {
11744       ErrorKind = 0;  // 0 -> unary
11745     } else {
11746       assert(CanBeBinaryOperator &&
11747              "All non-call overloaded operators are unary or binary!");
11748       ErrorKind = 1;  // 1 -> binary
11749     }
11750 
11751     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
11752       << FnDecl->getDeclName() << NumParams << ErrorKind;
11753   }
11754 
11755   // Overloaded operators other than operator() cannot be variadic.
11756   if (Op != OO_Call &&
11757       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
11758     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
11759       << FnDecl->getDeclName();
11760   }
11761 
11762   // Some operators must be non-static member functions.
11763   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
11764     return Diag(FnDecl->getLocation(),
11765                 diag::err_operator_overload_must_be_member)
11766       << FnDecl->getDeclName();
11767   }
11768 
11769   // C++ [over.inc]p1:
11770   //   The user-defined function called operator++ implements the
11771   //   prefix and postfix ++ operator. If this function is a member
11772   //   function with no parameters, or a non-member function with one
11773   //   parameter of class or enumeration type, it defines the prefix
11774   //   increment operator ++ for objects of that type. If the function
11775   //   is a member function with one parameter (which shall be of type
11776   //   int) or a non-member function with two parameters (the second
11777   //   of which shall be of type int), it defines the postfix
11778   //   increment operator ++ for objects of that type.
11779   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11780     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
11781     QualType ParamType = LastParam->getType();
11782 
11783     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11784         !ParamType->isDependentType())
11785       return Diag(LastParam->getLocation(),
11786                   diag::err_operator_overload_post_incdec_must_be_int)
11787         << LastParam->getType() << (Op == OO_MinusMinus);
11788   }
11789 
11790   return false;
11791 }
11792 
11793 static bool
11794 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
11795                                           FunctionTemplateDecl *TpDecl) {
11796   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
11797 
11798   // Must have one or two template parameters.
11799   if (TemplateParams->size() == 1) {
11800     NonTypeTemplateParmDecl *PmDecl =
11801         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
11802 
11803     // The template parameter must be a char parameter pack.
11804     if (PmDecl && PmDecl->isTemplateParameterPack() &&
11805         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
11806       return false;
11807 
11808   } else if (TemplateParams->size() == 2) {
11809     TemplateTypeParmDecl *PmType =
11810         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
11811     NonTypeTemplateParmDecl *PmArgs =
11812         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
11813 
11814     // The second template parameter must be a parameter pack with the
11815     // first template parameter as its type.
11816     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
11817         PmArgs->isTemplateParameterPack()) {
11818       const TemplateTypeParmType *TArgs =
11819           PmArgs->getType()->getAs<TemplateTypeParmType>();
11820       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11821           TArgs->getIndex() == PmType->getIndex()) {
11822         if (SemaRef.ActiveTemplateInstantiations.empty())
11823           SemaRef.Diag(TpDecl->getLocation(),
11824                        diag::ext_string_literal_operator_template);
11825         return false;
11826       }
11827     }
11828   }
11829 
11830   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
11831                diag::err_literal_operator_template)
11832       << TpDecl->getTemplateParameters()->getSourceRange();
11833   return true;
11834 }
11835 
11836 /// CheckLiteralOperatorDeclaration - Check whether the declaration
11837 /// of this literal operator function is well-formed. If so, returns
11838 /// false; otherwise, emits appropriate diagnostics and returns true.
11839 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
11840   if (isa<CXXMethodDecl>(FnDecl)) {
11841     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11842       << FnDecl->getDeclName();
11843     return true;
11844   }
11845 
11846   if (FnDecl->isExternC()) {
11847     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11848     return true;
11849   }
11850 
11851   // This might be the definition of a literal operator template.
11852   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11853 
11854   // This might be a specialization of a literal operator template.
11855   if (!TpDecl)
11856     TpDecl = FnDecl->getPrimaryTemplate();
11857 
11858   // template <char...> type operator "" name() and
11859   // template <class T, T...> type operator "" name() are the only valid
11860   // template signatures, and the only valid signatures with no parameters.
11861   if (TpDecl) {
11862     if (FnDecl->param_size() != 0) {
11863       Diag(FnDecl->getLocation(),
11864            diag::err_literal_operator_template_with_params);
11865       return true;
11866     }
11867 
11868     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
11869       return true;
11870 
11871   } else if (FnDecl->param_size() == 1) {
11872     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
11873 
11874     QualType ParamType = Param->getType().getUnqualifiedType();
11875 
11876     // Only unsigned long long int, long double, any character type, and const
11877     // char * are allowed as the only parameters.
11878     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
11879         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
11880         Context.hasSameType(ParamType, Context.CharTy) ||
11881         Context.hasSameType(ParamType, Context.WideCharTy) ||
11882         Context.hasSameType(ParamType, Context.Char16Ty) ||
11883         Context.hasSameType(ParamType, Context.Char32Ty)) {
11884     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
11885       QualType InnerType = Ptr->getPointeeType();
11886 
11887       // Pointer parameter must be a const char *.
11888       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
11889                                 Context.CharTy) &&
11890             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
11891         Diag(Param->getSourceRange().getBegin(),
11892              diag::err_literal_operator_param)
11893             << ParamType << "'const char *'" << Param->getSourceRange();
11894         return true;
11895       }
11896 
11897     } else if (ParamType->isRealFloatingType()) {
11898       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
11899           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
11900       return true;
11901 
11902     } else if (ParamType->isIntegerType()) {
11903       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
11904           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
11905       return true;
11906 
11907     } else {
11908       Diag(Param->getSourceRange().getBegin(),
11909            diag::err_literal_operator_invalid_param)
11910           << ParamType << Param->getSourceRange();
11911       return true;
11912     }
11913 
11914   } else if (FnDecl->param_size() == 2) {
11915     FunctionDecl::param_iterator Param = FnDecl->param_begin();
11916 
11917     // First, verify that the first parameter is correct.
11918 
11919     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
11920 
11921     // Two parameter function must have a pointer to const as a
11922     // first parameter; let's strip those qualifiers.
11923     const PointerType *PT = FirstParamType->getAs<PointerType>();
11924 
11925     if (!PT) {
11926       Diag((*Param)->getSourceRange().getBegin(),
11927            diag::err_literal_operator_param)
11928           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
11929       return true;
11930     }
11931 
11932     QualType PointeeType = PT->getPointeeType();
11933     // First parameter must be const
11934     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
11935       Diag((*Param)->getSourceRange().getBegin(),
11936            diag::err_literal_operator_param)
11937           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
11938       return true;
11939     }
11940 
11941     QualType InnerType = PointeeType.getUnqualifiedType();
11942     // Only const char *, const wchar_t*, const char16_t*, and const char32_t*
11943     // are allowed as the first parameter to a two-parameter function
11944     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
11945           Context.hasSameType(InnerType, Context.WideCharTy) ||
11946           Context.hasSameType(InnerType, Context.Char16Ty) ||
11947           Context.hasSameType(InnerType, Context.Char32Ty))) {
11948       Diag((*Param)->getSourceRange().getBegin(),
11949            diag::err_literal_operator_param)
11950           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
11951       return true;
11952     }
11953 
11954     // Move on to the second and final parameter.
11955     ++Param;
11956 
11957     // The second parameter must be a std::size_t.
11958     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
11959     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
11960       Diag((*Param)->getSourceRange().getBegin(),
11961            diag::err_literal_operator_param)
11962           << SecondParamType << Context.getSizeType()
11963           << (*Param)->getSourceRange();
11964       return true;
11965     }
11966   } else {
11967     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
11968     return true;
11969   }
11970 
11971   // Parameters are good.
11972 
11973   // A parameter-declaration-clause containing a default argument is not
11974   // equivalent to any of the permitted forms.
11975   for (auto Param : FnDecl->params()) {
11976     if (Param->hasDefaultArg()) {
11977       Diag(Param->getDefaultArgRange().getBegin(),
11978            diag::err_literal_operator_default_argument)
11979         << Param->getDefaultArgRange();
11980       break;
11981     }
11982   }
11983 
11984   StringRef LiteralName
11985     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11986   if (LiteralName[0] != '_') {
11987     // C++11 [usrlit.suffix]p1:
11988     //   Literal suffix identifiers that do not start with an underscore
11989     //   are reserved for future standardization.
11990     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11991       << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
11992   }
11993 
11994   return false;
11995 }
11996 
11997 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11998 /// linkage specification, including the language and (if present)
11999 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
12000 /// language string literal. LBraceLoc, if valid, provides the location of
12001 /// the '{' brace. Otherwise, this linkage specification does not
12002 /// have any braces.
12003 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
12004                                            Expr *LangStr,
12005                                            SourceLocation LBraceLoc) {
12006   StringLiteral *Lit = cast<StringLiteral>(LangStr);
12007   if (!Lit->isAscii()) {
12008     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
12009       << LangStr->getSourceRange();
12010     return nullptr;
12011   }
12012 
12013   StringRef Lang = Lit->getString();
12014   LinkageSpecDecl::LanguageIDs Language;
12015   if (Lang == "C")
12016     Language = LinkageSpecDecl::lang_c;
12017   else if (Lang == "C++")
12018     Language = LinkageSpecDecl::lang_cxx;
12019   else {
12020     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
12021       << LangStr->getSourceRange();
12022     return nullptr;
12023   }
12024 
12025   // FIXME: Add all the various semantics of linkage specifications
12026 
12027   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
12028                                                LangStr->getExprLoc(), Language,
12029                                                LBraceLoc.isValid());
12030   CurContext->addDecl(D);
12031   PushDeclContext(S, D);
12032   return D;
12033 }
12034 
12035 /// ActOnFinishLinkageSpecification - Complete the definition of
12036 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
12037 /// valid, it's the position of the closing '}' brace in a linkage
12038 /// specification that uses braces.
12039 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
12040                                             Decl *LinkageSpec,
12041                                             SourceLocation RBraceLoc) {
12042   if (RBraceLoc.isValid()) {
12043     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
12044     LSDecl->setRBraceLoc(RBraceLoc);
12045   }
12046   PopDeclContext();
12047   return LinkageSpec;
12048 }
12049 
12050 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
12051                                   AttributeList *AttrList,
12052                                   SourceLocation SemiLoc) {
12053   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
12054   // Attribute declarations appertain to empty declaration so we handle
12055   // them here.
12056   if (AttrList)
12057     ProcessDeclAttributeList(S, ED, AttrList);
12058 
12059   CurContext->addDecl(ED);
12060   return ED;
12061 }
12062 
12063 /// \brief Perform semantic analysis for the variable declaration that
12064 /// occurs within a C++ catch clause, returning the newly-created
12065 /// variable.
12066 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
12067                                          TypeSourceInfo *TInfo,
12068                                          SourceLocation StartLoc,
12069                                          SourceLocation Loc,
12070                                          IdentifierInfo *Name) {
12071   bool Invalid = false;
12072   QualType ExDeclType = TInfo->getType();
12073 
12074   // Arrays and functions decay.
12075   if (ExDeclType->isArrayType())
12076     ExDeclType = Context.getArrayDecayedType(ExDeclType);
12077   else if (ExDeclType->isFunctionType())
12078     ExDeclType = Context.getPointerType(ExDeclType);
12079 
12080   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
12081   // The exception-declaration shall not denote a pointer or reference to an
12082   // incomplete type, other than [cv] void*.
12083   // N2844 forbids rvalue references.
12084   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
12085     Diag(Loc, diag::err_catch_rvalue_ref);
12086     Invalid = true;
12087   }
12088 
12089   QualType BaseType = ExDeclType;
12090   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
12091   unsigned DK = diag::err_catch_incomplete;
12092   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
12093     BaseType = Ptr->getPointeeType();
12094     Mode = 1;
12095     DK = diag::err_catch_incomplete_ptr;
12096   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
12097     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
12098     BaseType = Ref->getPointeeType();
12099     Mode = 2;
12100     DK = diag::err_catch_incomplete_ref;
12101   }
12102   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
12103       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
12104     Invalid = true;
12105 
12106   if (!Invalid && !ExDeclType->isDependentType() &&
12107       RequireNonAbstractType(Loc, ExDeclType,
12108                              diag::err_abstract_type_in_decl,
12109                              AbstractVariableType))
12110     Invalid = true;
12111 
12112   // Only the non-fragile NeXT runtime currently supports C++ catches
12113   // of ObjC types, and no runtime supports catching ObjC types by value.
12114   if (!Invalid && getLangOpts().ObjC1) {
12115     QualType T = ExDeclType;
12116     if (const ReferenceType *RT = T->getAs<ReferenceType>())
12117       T = RT->getPointeeType();
12118 
12119     if (T->isObjCObjectType()) {
12120       Diag(Loc, diag::err_objc_object_catch);
12121       Invalid = true;
12122     } else if (T->isObjCObjectPointerType()) {
12123       // FIXME: should this be a test for macosx-fragile specifically?
12124       if (getLangOpts().ObjCRuntime.isFragile())
12125         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
12126     }
12127   }
12128 
12129   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
12130                                     ExDeclType, TInfo, SC_None);
12131   ExDecl->setExceptionVariable(true);
12132 
12133   // In ARC, infer 'retaining' for variables of retainable type.
12134   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
12135     Invalid = true;
12136 
12137   if (!Invalid && !ExDeclType->isDependentType()) {
12138     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
12139       // Insulate this from anything else we might currently be parsing.
12140       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
12141 
12142       // C++ [except.handle]p16:
12143       //   The object declared in an exception-declaration or, if the
12144       //   exception-declaration does not specify a name, a temporary (12.2) is
12145       //   copy-initialized (8.5) from the exception object. [...]
12146       //   The object is destroyed when the handler exits, after the destruction
12147       //   of any automatic objects initialized within the handler.
12148       //
12149       // We just pretend to initialize the object with itself, then make sure
12150       // it can be destroyed later.
12151       QualType initType = Context.getExceptionObjectType(ExDeclType);
12152 
12153       InitializedEntity entity =
12154         InitializedEntity::InitializeVariable(ExDecl);
12155       InitializationKind initKind =
12156         InitializationKind::CreateCopy(Loc, SourceLocation());
12157 
12158       Expr *opaqueValue =
12159         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
12160       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
12161       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
12162       if (result.isInvalid())
12163         Invalid = true;
12164       else {
12165         // If the constructor used was non-trivial, set this as the
12166         // "initializer".
12167         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
12168         if (!construct->getConstructor()->isTrivial()) {
12169           Expr *init = MaybeCreateExprWithCleanups(construct);
12170           ExDecl->setInit(init);
12171         }
12172 
12173         // And make sure it's destructable.
12174         FinalizeVarWithDestructor(ExDecl, recordType);
12175       }
12176     }
12177   }
12178 
12179   if (Invalid)
12180     ExDecl->setInvalidDecl();
12181 
12182   return ExDecl;
12183 }
12184 
12185 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
12186 /// handler.
12187 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
12188   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12189   bool Invalid = D.isInvalidType();
12190 
12191   // Check for unexpanded parameter packs.
12192   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12193                                       UPPC_ExceptionType)) {
12194     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12195                                              D.getIdentifierLoc());
12196     Invalid = true;
12197   }
12198 
12199   IdentifierInfo *II = D.getIdentifier();
12200   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
12201                                              LookupOrdinaryName,
12202                                              ForRedeclaration)) {
12203     // The scope should be freshly made just for us. There is just no way
12204     // it contains any previous declaration, except for function parameters in
12205     // a function-try-block's catch statement.
12206     assert(!S->isDeclScope(PrevDecl));
12207     if (isDeclInScope(PrevDecl, CurContext, S)) {
12208       Diag(D.getIdentifierLoc(), diag::err_redefinition)
12209         << D.getIdentifier();
12210       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12211       Invalid = true;
12212     } else if (PrevDecl->isTemplateParameter())
12213       // Maybe we will complain about the shadowed template parameter.
12214       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12215   }
12216 
12217   if (D.getCXXScopeSpec().isSet() && !Invalid) {
12218     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
12219       << D.getCXXScopeSpec().getRange();
12220     Invalid = true;
12221   }
12222 
12223   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
12224                                               D.getLocStart(),
12225                                               D.getIdentifierLoc(),
12226                                               D.getIdentifier());
12227   if (Invalid)
12228     ExDecl->setInvalidDecl();
12229 
12230   // Add the exception declaration into this scope.
12231   if (II)
12232     PushOnScopeChains(ExDecl, S);
12233   else
12234     CurContext->addDecl(ExDecl);
12235 
12236   ProcessDeclAttributes(S, ExDecl, D);
12237   return ExDecl;
12238 }
12239 
12240 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
12241                                          Expr *AssertExpr,
12242                                          Expr *AssertMessageExpr,
12243                                          SourceLocation RParenLoc) {
12244   StringLiteral *AssertMessage =
12245       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
12246 
12247   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
12248     return nullptr;
12249 
12250   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
12251                                       AssertMessage, RParenLoc, false);
12252 }
12253 
12254 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
12255                                          Expr *AssertExpr,
12256                                          StringLiteral *AssertMessage,
12257                                          SourceLocation RParenLoc,
12258                                          bool Failed) {
12259   assert(AssertExpr != nullptr && "Expected non-null condition");
12260   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
12261       !Failed) {
12262     // In a static_assert-declaration, the constant-expression shall be a
12263     // constant expression that can be contextually converted to bool.
12264     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
12265     if (Converted.isInvalid())
12266       Failed = true;
12267 
12268     llvm::APSInt Cond;
12269     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
12270           diag::err_static_assert_expression_is_not_constant,
12271           /*AllowFold=*/false).isInvalid())
12272       Failed = true;
12273 
12274     if (!Failed && !Cond) {
12275       SmallString<256> MsgBuffer;
12276       llvm::raw_svector_ostream Msg(MsgBuffer);
12277       if (AssertMessage)
12278         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
12279       Diag(StaticAssertLoc, diag::err_static_assert_failed)
12280         << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
12281       Failed = true;
12282     }
12283   }
12284 
12285   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
12286                                         AssertExpr, AssertMessage, RParenLoc,
12287                                         Failed);
12288 
12289   CurContext->addDecl(Decl);
12290   return Decl;
12291 }
12292 
12293 /// \brief Perform semantic analysis of the given friend type declaration.
12294 ///
12295 /// \returns A friend declaration that.
12296 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
12297                                       SourceLocation FriendLoc,
12298                                       TypeSourceInfo *TSInfo) {
12299   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
12300 
12301   QualType T = TSInfo->getType();
12302   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
12303 
12304   // C++03 [class.friend]p2:
12305   //   An elaborated-type-specifier shall be used in a friend declaration
12306   //   for a class.*
12307   //
12308   //   * The class-key of the elaborated-type-specifier is required.
12309   if (!ActiveTemplateInstantiations.empty()) {
12310     // Do not complain about the form of friend template types during
12311     // template instantiation; we will already have complained when the
12312     // template was declared.
12313   } else {
12314     if (!T->isElaboratedTypeSpecifier()) {
12315       // If we evaluated the type to a record type, suggest putting
12316       // a tag in front.
12317       if (const RecordType *RT = T->getAs<RecordType>()) {
12318         RecordDecl *RD = RT->getDecl();
12319 
12320         SmallString<16> InsertionText(" ");
12321         InsertionText += RD->getKindName();
12322 
12323         Diag(TypeRange.getBegin(),
12324              getLangOpts().CPlusPlus11 ?
12325                diag::warn_cxx98_compat_unelaborated_friend_type :
12326                diag::ext_unelaborated_friend_type)
12327           << (unsigned) RD->getTagKind()
12328           << T
12329           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
12330                                         InsertionText);
12331       } else {
12332         Diag(FriendLoc,
12333              getLangOpts().CPlusPlus11 ?
12334                diag::warn_cxx98_compat_nonclass_type_friend :
12335                diag::ext_nonclass_type_friend)
12336           << T
12337           << TypeRange;
12338       }
12339     } else if (T->getAs<EnumType>()) {
12340       Diag(FriendLoc,
12341            getLangOpts().CPlusPlus11 ?
12342              diag::warn_cxx98_compat_enum_friend :
12343              diag::ext_enum_friend)
12344         << T
12345         << TypeRange;
12346     }
12347 
12348     // C++11 [class.friend]p3:
12349     //   A friend declaration that does not declare a function shall have one
12350     //   of the following forms:
12351     //     friend elaborated-type-specifier ;
12352     //     friend simple-type-specifier ;
12353     //     friend typename-specifier ;
12354     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
12355       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
12356   }
12357 
12358   //   If the type specifier in a friend declaration designates a (possibly
12359   //   cv-qualified) class type, that class is declared as a friend; otherwise,
12360   //   the friend declaration is ignored.
12361   return FriendDecl::Create(Context, CurContext,
12362                             TSInfo->getTypeLoc().getLocStart(), TSInfo,
12363                             FriendLoc);
12364 }
12365 
12366 /// Handle a friend tag declaration where the scope specifier was
12367 /// templated.
12368 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
12369                                     unsigned TagSpec, SourceLocation TagLoc,
12370                                     CXXScopeSpec &SS,
12371                                     IdentifierInfo *Name,
12372                                     SourceLocation NameLoc,
12373                                     AttributeList *Attr,
12374                                     MultiTemplateParamsArg TempParamLists) {
12375   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12376 
12377   bool isExplicitSpecialization = false;
12378   bool Invalid = false;
12379 
12380   if (TemplateParameterList *TemplateParams =
12381           MatchTemplateParametersToScopeSpecifier(
12382               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
12383               isExplicitSpecialization, Invalid)) {
12384     if (TemplateParams->size() > 0) {
12385       // This is a declaration of a class template.
12386       if (Invalid)
12387         return nullptr;
12388 
12389       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
12390                                 NameLoc, Attr, TemplateParams, AS_public,
12391                                 /*ModulePrivateLoc=*/SourceLocation(),
12392                                 FriendLoc, TempParamLists.size() - 1,
12393                                 TempParamLists.data()).get();
12394     } else {
12395       // The "template<>" header is extraneous.
12396       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12397         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12398       isExplicitSpecialization = true;
12399     }
12400   }
12401 
12402   if (Invalid) return nullptr;
12403 
12404   bool isAllExplicitSpecializations = true;
12405   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
12406     if (TempParamLists[I]->size()) {
12407       isAllExplicitSpecializations = false;
12408       break;
12409     }
12410   }
12411 
12412   // FIXME: don't ignore attributes.
12413 
12414   // If it's explicit specializations all the way down, just forget
12415   // about the template header and build an appropriate non-templated
12416   // friend.  TODO: for source fidelity, remember the headers.
12417   if (isAllExplicitSpecializations) {
12418     if (SS.isEmpty()) {
12419       bool Owned = false;
12420       bool IsDependent = false;
12421       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
12422                       Attr, AS_public,
12423                       /*ModulePrivateLoc=*/SourceLocation(),
12424                       MultiTemplateParamsArg(), Owned, IsDependent,
12425                       /*ScopedEnumKWLoc=*/SourceLocation(),
12426                       /*ScopedEnumUsesClassTag=*/false,
12427                       /*UnderlyingType=*/TypeResult(),
12428                       /*IsTypeSpecifier=*/false);
12429     }
12430 
12431     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12432     ElaboratedTypeKeyword Keyword
12433       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12434     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
12435                                    *Name, NameLoc);
12436     if (T.isNull())
12437       return nullptr;
12438 
12439     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12440     if (isa<DependentNameType>(T)) {
12441       DependentNameTypeLoc TL =
12442           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
12443       TL.setElaboratedKeywordLoc(TagLoc);
12444       TL.setQualifierLoc(QualifierLoc);
12445       TL.setNameLoc(NameLoc);
12446     } else {
12447       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
12448       TL.setElaboratedKeywordLoc(TagLoc);
12449       TL.setQualifierLoc(QualifierLoc);
12450       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
12451     }
12452 
12453     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
12454                                             TSI, FriendLoc, TempParamLists);
12455     Friend->setAccess(AS_public);
12456     CurContext->addDecl(Friend);
12457     return Friend;
12458   }
12459 
12460   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
12461 
12462 
12463 
12464   // Handle the case of a templated-scope friend class.  e.g.
12465   //   template <class T> class A<T>::B;
12466   // FIXME: we don't support these right now.
12467   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
12468     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
12469   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12470   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
12471   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12472   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
12473   TL.setElaboratedKeywordLoc(TagLoc);
12474   TL.setQualifierLoc(SS.getWithLocInContext(Context));
12475   TL.setNameLoc(NameLoc);
12476 
12477   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
12478                                           TSI, FriendLoc, TempParamLists);
12479   Friend->setAccess(AS_public);
12480   Friend->setUnsupportedFriend(true);
12481   CurContext->addDecl(Friend);
12482   return Friend;
12483 }
12484 
12485 
12486 /// Handle a friend type declaration.  This works in tandem with
12487 /// ActOnTag.
12488 ///
12489 /// Notes on friend class templates:
12490 ///
12491 /// We generally treat friend class declarations as if they were
12492 /// declaring a class.  So, for example, the elaborated type specifier
12493 /// in a friend declaration is required to obey the restrictions of a
12494 /// class-head (i.e. no typedefs in the scope chain), template
12495 /// parameters are required to match up with simple template-ids, &c.
12496 /// However, unlike when declaring a template specialization, it's
12497 /// okay to refer to a template specialization without an empty
12498 /// template parameter declaration, e.g.
12499 ///   friend class A<T>::B<unsigned>;
12500 /// We permit this as a special case; if there are any template
12501 /// parameters present at all, require proper matching, i.e.
12502 ///   template <> template \<class T> friend class A<int>::B;
12503 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
12504                                 MultiTemplateParamsArg TempParams) {
12505   SourceLocation Loc = DS.getLocStart();
12506 
12507   assert(DS.isFriendSpecified());
12508   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12509 
12510   // Try to convert the decl specifier to a type.  This works for
12511   // friend templates because ActOnTag never produces a ClassTemplateDecl
12512   // for a TUK_Friend.
12513   Declarator TheDeclarator(DS, Declarator::MemberContext);
12514   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
12515   QualType T = TSI->getType();
12516   if (TheDeclarator.isInvalidType())
12517     return nullptr;
12518 
12519   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
12520     return nullptr;
12521 
12522   // This is definitely an error in C++98.  It's probably meant to
12523   // be forbidden in C++0x, too, but the specification is just
12524   // poorly written.
12525   //
12526   // The problem is with declarations like the following:
12527   //   template <T> friend A<T>::foo;
12528   // where deciding whether a class C is a friend or not now hinges
12529   // on whether there exists an instantiation of A that causes
12530   // 'foo' to equal C.  There are restrictions on class-heads
12531   // (which we declare (by fiat) elaborated friend declarations to
12532   // be) that makes this tractable.
12533   //
12534   // FIXME: handle "template <> friend class A<T>;", which
12535   // is possibly well-formed?  Who even knows?
12536   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
12537     Diag(Loc, diag::err_tagless_friend_type_template)
12538       << DS.getSourceRange();
12539     return nullptr;
12540   }
12541 
12542   // C++98 [class.friend]p1: A friend of a class is a function
12543   //   or class that is not a member of the class . . .
12544   // This is fixed in DR77, which just barely didn't make the C++03
12545   // deadline.  It's also a very silly restriction that seriously
12546   // affects inner classes and which nobody else seems to implement;
12547   // thus we never diagnose it, not even in -pedantic.
12548   //
12549   // But note that we could warn about it: it's always useless to
12550   // friend one of your own members (it's not, however, worthless to
12551   // friend a member of an arbitrary specialization of your template).
12552 
12553   Decl *D;
12554   if (unsigned NumTempParamLists = TempParams.size())
12555     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
12556                                    NumTempParamLists,
12557                                    TempParams.data(),
12558                                    TSI,
12559                                    DS.getFriendSpecLoc());
12560   else
12561     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
12562 
12563   if (!D)
12564     return nullptr;
12565 
12566   D->setAccess(AS_public);
12567   CurContext->addDecl(D);
12568 
12569   return D;
12570 }
12571 
12572 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
12573                                         MultiTemplateParamsArg TemplateParams) {
12574   const DeclSpec &DS = D.getDeclSpec();
12575 
12576   assert(DS.isFriendSpecified());
12577   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12578 
12579   SourceLocation Loc = D.getIdentifierLoc();
12580   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12581 
12582   // C++ [class.friend]p1
12583   //   A friend of a class is a function or class....
12584   // Note that this sees through typedefs, which is intended.
12585   // It *doesn't* see through dependent types, which is correct
12586   // according to [temp.arg.type]p3:
12587   //   If a declaration acquires a function type through a
12588   //   type dependent on a template-parameter and this causes
12589   //   a declaration that does not use the syntactic form of a
12590   //   function declarator to have a function type, the program
12591   //   is ill-formed.
12592   if (!TInfo->getType()->isFunctionType()) {
12593     Diag(Loc, diag::err_unexpected_friend);
12594 
12595     // It might be worthwhile to try to recover by creating an
12596     // appropriate declaration.
12597     return nullptr;
12598   }
12599 
12600   // C++ [namespace.memdef]p3
12601   //  - If a friend declaration in a non-local class first declares a
12602   //    class or function, the friend class or function is a member
12603   //    of the innermost enclosing namespace.
12604   //  - The name of the friend is not found by simple name lookup
12605   //    until a matching declaration is provided in that namespace
12606   //    scope (either before or after the class declaration granting
12607   //    friendship).
12608   //  - If a friend function is called, its name may be found by the
12609   //    name lookup that considers functions from namespaces and
12610   //    classes associated with the types of the function arguments.
12611   //  - When looking for a prior declaration of a class or a function
12612   //    declared as a friend, scopes outside the innermost enclosing
12613   //    namespace scope are not considered.
12614 
12615   CXXScopeSpec &SS = D.getCXXScopeSpec();
12616   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
12617   DeclarationName Name = NameInfo.getName();
12618   assert(Name);
12619 
12620   // Check for unexpanded parameter packs.
12621   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
12622       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
12623       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
12624     return nullptr;
12625 
12626   // The context we found the declaration in, or in which we should
12627   // create the declaration.
12628   DeclContext *DC;
12629   Scope *DCScope = S;
12630   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12631                         ForRedeclaration);
12632 
12633   // There are five cases here.
12634   //   - There's no scope specifier and we're in a local class. Only look
12635   //     for functions declared in the immediately-enclosing block scope.
12636   // We recover from invalid scope qualifiers as if they just weren't there.
12637   FunctionDecl *FunctionContainingLocalClass = nullptr;
12638   if ((SS.isInvalid() || !SS.isSet()) &&
12639       (FunctionContainingLocalClass =
12640            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
12641     // C++11 [class.friend]p11:
12642     //   If a friend declaration appears in a local class and the name
12643     //   specified is an unqualified name, a prior declaration is
12644     //   looked up without considering scopes that are outside the
12645     //   innermost enclosing non-class scope. For a friend function
12646     //   declaration, if there is no prior declaration, the program is
12647     //   ill-formed.
12648 
12649     // Find the innermost enclosing non-class scope. This is the block
12650     // scope containing the local class definition (or for a nested class,
12651     // the outer local class).
12652     DCScope = S->getFnParent();
12653 
12654     // Look up the function name in the scope.
12655     Previous.clear(LookupLocalFriendName);
12656     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
12657 
12658     if (!Previous.empty()) {
12659       // All possible previous declarations must have the same context:
12660       // either they were declared at block scope or they are members of
12661       // one of the enclosing local classes.
12662       DC = Previous.getRepresentativeDecl()->getDeclContext();
12663     } else {
12664       // This is ill-formed, but provide the context that we would have
12665       // declared the function in, if we were permitted to, for error recovery.
12666       DC = FunctionContainingLocalClass;
12667     }
12668     adjustContextForLocalExternDecl(DC);
12669 
12670     // C++ [class.friend]p6:
12671     //   A function can be defined in a friend declaration of a class if and
12672     //   only if the class is a non-local class (9.8), the function name is
12673     //   unqualified, and the function has namespace scope.
12674     if (D.isFunctionDefinition()) {
12675       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
12676     }
12677 
12678   //   - There's no scope specifier, in which case we just go to the
12679   //     appropriate scope and look for a function or function template
12680   //     there as appropriate.
12681   } else if (SS.isInvalid() || !SS.isSet()) {
12682     // C++11 [namespace.memdef]p3:
12683     //   If the name in a friend declaration is neither qualified nor
12684     //   a template-id and the declaration is a function or an
12685     //   elaborated-type-specifier, the lookup to determine whether
12686     //   the entity has been previously declared shall not consider
12687     //   any scopes outside the innermost enclosing namespace.
12688     bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
12689 
12690     // Find the appropriate context according to the above.
12691     DC = CurContext;
12692 
12693     // Skip class contexts.  If someone can cite chapter and verse
12694     // for this behavior, that would be nice --- it's what GCC and
12695     // EDG do, and it seems like a reasonable intent, but the spec
12696     // really only says that checks for unqualified existing
12697     // declarations should stop at the nearest enclosing namespace,
12698     // not that they should only consider the nearest enclosing
12699     // namespace.
12700     while (DC->isRecord())
12701       DC = DC->getParent();
12702 
12703     DeclContext *LookupDC = DC;
12704     while (LookupDC->isTransparentContext())
12705       LookupDC = LookupDC->getParent();
12706 
12707     while (true) {
12708       LookupQualifiedName(Previous, LookupDC);
12709 
12710       if (!Previous.empty()) {
12711         DC = LookupDC;
12712         break;
12713       }
12714 
12715       if (isTemplateId) {
12716         if (isa<TranslationUnitDecl>(LookupDC)) break;
12717       } else {
12718         if (LookupDC->isFileContext()) break;
12719       }
12720       LookupDC = LookupDC->getParent();
12721     }
12722 
12723     DCScope = getScopeForDeclContext(S, DC);
12724 
12725   //   - There's a non-dependent scope specifier, in which case we
12726   //     compute it and do a previous lookup there for a function
12727   //     or function template.
12728   } else if (!SS.getScopeRep()->isDependent()) {
12729     DC = computeDeclContext(SS);
12730     if (!DC) return nullptr;
12731 
12732     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
12733 
12734     LookupQualifiedName(Previous, DC);
12735 
12736     // Ignore things found implicitly in the wrong scope.
12737     // TODO: better diagnostics for this case.  Suggesting the right
12738     // qualified scope would be nice...
12739     LookupResult::Filter F = Previous.makeFilter();
12740     while (F.hasNext()) {
12741       NamedDecl *D = F.next();
12742       if (!DC->InEnclosingNamespaceSetOf(
12743               D->getDeclContext()->getRedeclContext()))
12744         F.erase();
12745     }
12746     F.done();
12747 
12748     if (Previous.empty()) {
12749       D.setInvalidType();
12750       Diag(Loc, diag::err_qualified_friend_not_found)
12751           << Name << TInfo->getType();
12752       return nullptr;
12753     }
12754 
12755     // C++ [class.friend]p1: A friend of a class is a function or
12756     //   class that is not a member of the class . . .
12757     if (DC->Equals(CurContext))
12758       Diag(DS.getFriendSpecLoc(),
12759            getLangOpts().CPlusPlus11 ?
12760              diag::warn_cxx98_compat_friend_is_member :
12761              diag::err_friend_is_member);
12762 
12763     if (D.isFunctionDefinition()) {
12764       // C++ [class.friend]p6:
12765       //   A function can be defined in a friend declaration of a class if and
12766       //   only if the class is a non-local class (9.8), the function name is
12767       //   unqualified, and the function has namespace scope.
12768       SemaDiagnosticBuilder DB
12769         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
12770 
12771       DB << SS.getScopeRep();
12772       if (DC->isFileContext())
12773         DB << FixItHint::CreateRemoval(SS.getRange());
12774       SS.clear();
12775     }
12776 
12777   //   - There's a scope specifier that does not match any template
12778   //     parameter lists, in which case we use some arbitrary context,
12779   //     create a method or method template, and wait for instantiation.
12780   //   - There's a scope specifier that does match some template
12781   //     parameter lists, which we don't handle right now.
12782   } else {
12783     if (D.isFunctionDefinition()) {
12784       // C++ [class.friend]p6:
12785       //   A function can be defined in a friend declaration of a class if and
12786       //   only if the class is a non-local class (9.8), the function name is
12787       //   unqualified, and the function has namespace scope.
12788       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
12789         << SS.getScopeRep();
12790     }
12791 
12792     DC = CurContext;
12793     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
12794   }
12795 
12796   if (!DC->isRecord()) {
12797     int DiagArg = -1;
12798     switch (D.getName().getKind()) {
12799     case UnqualifiedId::IK_ConstructorTemplateId:
12800     case UnqualifiedId::IK_ConstructorName:
12801       DiagArg = 0;
12802       break;
12803     case UnqualifiedId::IK_DestructorName:
12804       DiagArg = 1;
12805       break;
12806     case UnqualifiedId::IK_ConversionFunctionId:
12807       DiagArg = 2;
12808       break;
12809     case UnqualifiedId::IK_Identifier:
12810     case UnqualifiedId::IK_ImplicitSelfParam:
12811     case UnqualifiedId::IK_LiteralOperatorId:
12812     case UnqualifiedId::IK_OperatorFunctionId:
12813     case UnqualifiedId::IK_TemplateId:
12814       break;
12815     }
12816     // This implies that it has to be an operator or function.
12817     if (DiagArg >= 0) {
12818       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
12819       return nullptr;
12820     }
12821   }
12822 
12823   // FIXME: This is an egregious hack to cope with cases where the scope stack
12824   // does not contain the declaration context, i.e., in an out-of-line
12825   // definition of a class.
12826   Scope FakeDCScope(S, Scope::DeclScope, Diags);
12827   if (!DCScope) {
12828     FakeDCScope.setEntity(DC);
12829     DCScope = &FakeDCScope;
12830   }
12831 
12832   bool AddToScope = true;
12833   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
12834                                           TemplateParams, AddToScope);
12835   if (!ND) return nullptr;
12836 
12837   assert(ND->getLexicalDeclContext() == CurContext);
12838 
12839   // If we performed typo correction, we might have added a scope specifier
12840   // and changed the decl context.
12841   DC = ND->getDeclContext();
12842 
12843   // Add the function declaration to the appropriate lookup tables,
12844   // adjusting the redeclarations list as necessary.  We don't
12845   // want to do this yet if the friending class is dependent.
12846   //
12847   // Also update the scope-based lookup if the target context's
12848   // lookup context is in lexical scope.
12849   if (!CurContext->isDependentContext()) {
12850     DC = DC->getRedeclContext();
12851     DC->makeDeclVisibleInContext(ND);
12852     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
12853       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
12854   }
12855 
12856   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
12857                                        D.getIdentifierLoc(), ND,
12858                                        DS.getFriendSpecLoc());
12859   FrD->setAccess(AS_public);
12860   CurContext->addDecl(FrD);
12861 
12862   if (ND->isInvalidDecl()) {
12863     FrD->setInvalidDecl();
12864   } else {
12865     if (DC->isRecord()) CheckFriendAccess(ND);
12866 
12867     FunctionDecl *FD;
12868     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12869       FD = FTD->getTemplatedDecl();
12870     else
12871       FD = cast<FunctionDecl>(ND);
12872 
12873     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12874     // default argument expression, that declaration shall be a definition
12875     // and shall be the only declaration of the function or function
12876     // template in the translation unit.
12877     if (functionDeclHasDefaultArgument(FD)) {
12878       if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12879         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12880         Diag(OldFD->getLocation(), diag::note_previous_declaration);
12881       } else if (!D.isFunctionDefinition())
12882         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12883     }
12884 
12885     // Mark templated-scope function declarations as unsupported.
12886     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
12887       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
12888         << SS.getScopeRep() << SS.getRange()
12889         << cast<CXXRecordDecl>(CurContext);
12890       FrD->setUnsupportedFriend(true);
12891     }
12892   }
12893 
12894   return ND;
12895 }
12896 
12897 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12898   AdjustDeclIfTemplate(Dcl);
12899 
12900   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
12901   if (!Fn) {
12902     Diag(DelLoc, diag::err_deleted_non_function);
12903     return;
12904   }
12905 
12906   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
12907     // Don't consider the implicit declaration we generate for explicit
12908     // specializations. FIXME: Do not generate these implicit declarations.
12909     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12910          Prev->getPreviousDecl()) &&
12911         !Prev->isDefined()) {
12912       Diag(DelLoc, diag::err_deleted_decl_not_first);
12913       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12914            Prev->isImplicit() ? diag::note_previous_implicit_declaration
12915                               : diag::note_previous_declaration);
12916     }
12917     // If the declaration wasn't the first, we delete the function anyway for
12918     // recovery.
12919     Fn = Fn->getCanonicalDecl();
12920   }
12921 
12922   // dllimport/dllexport cannot be deleted.
12923   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12924     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12925     Fn->setInvalidDecl();
12926   }
12927 
12928   if (Fn->isDeleted())
12929     return;
12930 
12931   // See if we're deleting a function which is already known to override a
12932   // non-deleted virtual function.
12933   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
12934     bool IssuedDiagnostic = false;
12935     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
12936                                         E = MD->end_overridden_methods();
12937          I != E; ++I) {
12938       if (!(*MD->begin_overridden_methods())->isDeleted()) {
12939         if (!IssuedDiagnostic) {
12940           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
12941           IssuedDiagnostic = true;
12942         }
12943         Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
12944       }
12945     }
12946   }
12947 
12948   // C++11 [basic.start.main]p3:
12949   //   A program that defines main as deleted [...] is ill-formed.
12950   if (Fn->isMain())
12951     Diag(DelLoc, diag::err_deleted_main);
12952 
12953   Fn->setDeletedAsWritten();
12954 }
12955 
12956 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
12957   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
12958 
12959   if (MD) {
12960     if (MD->getParent()->isDependentType()) {
12961       MD->setDefaulted();
12962       MD->setExplicitlyDefaulted();
12963       return;
12964     }
12965 
12966     CXXSpecialMember Member = getSpecialMember(MD);
12967     if (Member == CXXInvalid) {
12968       if (!MD->isInvalidDecl())
12969         Diag(DefaultLoc, diag::err_default_special_members);
12970       return;
12971     }
12972 
12973     MD->setDefaulted();
12974     MD->setExplicitlyDefaulted();
12975 
12976     // If this definition appears within the record, do the checking when
12977     // the record is complete.
12978     const FunctionDecl *Primary = MD;
12979     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
12980       // Find the uninstantiated declaration that actually had the '= default'
12981       // on it.
12982       Pattern->isDefined(Primary);
12983 
12984     // If the method was defaulted on its first declaration, we will have
12985     // already performed the checking in CheckCompletedCXXClass. Such a
12986     // declaration doesn't trigger an implicit definition.
12987     if (Primary == Primary->getCanonicalDecl())
12988       return;
12989 
12990     CheckExplicitlyDefaultedSpecialMember(MD);
12991 
12992     if (MD->isInvalidDecl())
12993       return;
12994 
12995     switch (Member) {
12996     case CXXDefaultConstructor:
12997       DefineImplicitDefaultConstructor(DefaultLoc,
12998                                        cast<CXXConstructorDecl>(MD));
12999       break;
13000     case CXXCopyConstructor:
13001       DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
13002       break;
13003     case CXXCopyAssignment:
13004       DefineImplicitCopyAssignment(DefaultLoc, MD);
13005       break;
13006     case CXXDestructor:
13007       DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
13008       break;
13009     case CXXMoveConstructor:
13010       DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
13011       break;
13012     case CXXMoveAssignment:
13013       DefineImplicitMoveAssignment(DefaultLoc, MD);
13014       break;
13015     case CXXInvalid:
13016       llvm_unreachable("Invalid special member.");
13017     }
13018   } else {
13019     Diag(DefaultLoc, diag::err_default_special_members);
13020   }
13021 }
13022 
13023 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
13024   for (Stmt *SubStmt : S->children()) {
13025     if (!SubStmt)
13026       continue;
13027     if (isa<ReturnStmt>(SubStmt))
13028       Self.Diag(SubStmt->getLocStart(),
13029            diag::err_return_in_constructor_handler);
13030     if (!isa<Expr>(SubStmt))
13031       SearchForReturnInStmt(Self, SubStmt);
13032   }
13033 }
13034 
13035 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
13036   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
13037     CXXCatchStmt *Handler = TryBlock->getHandler(I);
13038     SearchForReturnInStmt(*this, Handler);
13039   }
13040 }
13041 
13042 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
13043                                              const CXXMethodDecl *Old) {
13044   const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
13045   const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
13046 
13047   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
13048 
13049   // If the calling conventions match, everything is fine
13050   if (NewCC == OldCC)
13051     return false;
13052 
13053   // If the calling conventions mismatch because the new function is static,
13054   // suppress the calling convention mismatch error; the error about static
13055   // function override (err_static_overrides_virtual from
13056   // Sema::CheckFunctionDeclaration) is more clear.
13057   if (New->getStorageClass() == SC_Static)
13058     return false;
13059 
13060   Diag(New->getLocation(),
13061        diag::err_conflicting_overriding_cc_attributes)
13062     << New->getDeclName() << New->getType() << Old->getType();
13063   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
13064   return true;
13065 }
13066 
13067 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
13068                                              const CXXMethodDecl *Old) {
13069   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
13070   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
13071 
13072   if (Context.hasSameType(NewTy, OldTy) ||
13073       NewTy->isDependentType() || OldTy->isDependentType())
13074     return false;
13075 
13076   // Check if the return types are covariant
13077   QualType NewClassTy, OldClassTy;
13078 
13079   /// Both types must be pointers or references to classes.
13080   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
13081     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
13082       NewClassTy = NewPT->getPointeeType();
13083       OldClassTy = OldPT->getPointeeType();
13084     }
13085   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
13086     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
13087       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
13088         NewClassTy = NewRT->getPointeeType();
13089         OldClassTy = OldRT->getPointeeType();
13090       }
13091     }
13092   }
13093 
13094   // The return types aren't either both pointers or references to a class type.
13095   if (NewClassTy.isNull()) {
13096     Diag(New->getLocation(),
13097          diag::err_different_return_type_for_overriding_virtual_function)
13098         << New->getDeclName() << NewTy << OldTy
13099         << New->getReturnTypeSourceRange();
13100     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13101         << Old->getReturnTypeSourceRange();
13102 
13103     return true;
13104   }
13105 
13106   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
13107     // C++14 [class.virtual]p8:
13108     //   If the class type in the covariant return type of D::f differs from
13109     //   that of B::f, the class type in the return type of D::f shall be
13110     //   complete at the point of declaration of D::f or shall be the class
13111     //   type D.
13112     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
13113       if (!RT->isBeingDefined() &&
13114           RequireCompleteType(New->getLocation(), NewClassTy,
13115                               diag::err_covariant_return_incomplete,
13116                               New->getDeclName()))
13117         return true;
13118     }
13119 
13120     // Check if the new class derives from the old class.
13121     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
13122       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
13123           << New->getDeclName() << NewTy << OldTy
13124           << New->getReturnTypeSourceRange();
13125       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13126           << Old->getReturnTypeSourceRange();
13127       return true;
13128     }
13129 
13130     // Check if we the conversion from derived to base is valid.
13131     if (CheckDerivedToBaseConversion(
13132             NewClassTy, OldClassTy,
13133             diag::err_covariant_return_inaccessible_base,
13134             diag::err_covariant_return_ambiguous_derived_to_base_conv,
13135             New->getLocation(), New->getReturnTypeSourceRange(),
13136             New->getDeclName(), nullptr)) {
13137       // FIXME: this note won't trigger for delayed access control
13138       // diagnostics, and it's impossible to get an undelayed error
13139       // here from access control during the original parse because
13140       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
13141       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13142           << Old->getReturnTypeSourceRange();
13143       return true;
13144     }
13145   }
13146 
13147   // The qualifiers of the return types must be the same.
13148   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
13149     Diag(New->getLocation(),
13150          diag::err_covariant_return_type_different_qualifications)
13151         << New->getDeclName() << NewTy << OldTy
13152         << New->getReturnTypeSourceRange();
13153     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13154         << Old->getReturnTypeSourceRange();
13155     return true;
13156   }
13157 
13158 
13159   // The new class type must have the same or less qualifiers as the old type.
13160   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
13161     Diag(New->getLocation(),
13162          diag::err_covariant_return_type_class_type_more_qualified)
13163         << New->getDeclName() << NewTy << OldTy
13164         << New->getReturnTypeSourceRange();
13165     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13166         << Old->getReturnTypeSourceRange();
13167     return true;
13168   }
13169 
13170   return false;
13171 }
13172 
13173 /// \brief Mark the given method pure.
13174 ///
13175 /// \param Method the method to be marked pure.
13176 ///
13177 /// \param InitRange the source range that covers the "0" initializer.
13178 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
13179   SourceLocation EndLoc = InitRange.getEnd();
13180   if (EndLoc.isValid())
13181     Method->setRangeEnd(EndLoc);
13182 
13183   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
13184     Method->setPure();
13185     return false;
13186   }
13187 
13188   if (!Method->isInvalidDecl())
13189     Diag(Method->getLocation(), diag::err_non_virtual_pure)
13190       << Method->getDeclName() << InitRange;
13191   return true;
13192 }
13193 
13194 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
13195   if (D->getFriendObjectKind())
13196     Diag(D->getLocation(), diag::err_pure_friend);
13197   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
13198     CheckPureMethod(M, ZeroLoc);
13199   else
13200     Diag(D->getLocation(), diag::err_illegal_initializer);
13201 }
13202 
13203 /// \brief Determine whether the given declaration is a static data member.
13204 static bool isStaticDataMember(const Decl *D) {
13205   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
13206     return Var->isStaticDataMember();
13207 
13208   return false;
13209 }
13210 
13211 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
13212 /// an initializer for the out-of-line declaration 'Dcl'.  The scope
13213 /// is a fresh scope pushed for just this purpose.
13214 ///
13215 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
13216 /// static data member of class X, names should be looked up in the scope of
13217 /// class X.
13218 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
13219   // If there is no declaration, there was an error parsing it.
13220   if (!D || D->isInvalidDecl())
13221     return;
13222 
13223   // We will always have a nested name specifier here, but this declaration
13224   // might not be out of line if the specifier names the current namespace:
13225   //   extern int n;
13226   //   int ::n = 0;
13227   if (D->isOutOfLine())
13228     EnterDeclaratorContext(S, D->getDeclContext());
13229 
13230   // If we are parsing the initializer for a static data member, push a
13231   // new expression evaluation context that is associated with this static
13232   // data member.
13233   if (isStaticDataMember(D))
13234     PushExpressionEvaluationContext(PotentiallyEvaluated, D);
13235 }
13236 
13237 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
13238 /// initializer for the out-of-line declaration 'D'.
13239 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
13240   // If there is no declaration, there was an error parsing it.
13241   if (!D || D->isInvalidDecl())
13242     return;
13243 
13244   if (isStaticDataMember(D))
13245     PopExpressionEvaluationContext();
13246 
13247   if (D->isOutOfLine())
13248     ExitDeclaratorContext(S);
13249 }
13250 
13251 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
13252 /// C++ if/switch/while/for statement.
13253 /// e.g: "if (int x = f()) {...}"
13254 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
13255   // C++ 6.4p2:
13256   // The declarator shall not specify a function or an array.
13257   // The type-specifier-seq shall not contain typedef and shall not declare a
13258   // new class or enumeration.
13259   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
13260          "Parser allowed 'typedef' as storage class of condition decl.");
13261 
13262   Decl *Dcl = ActOnDeclarator(S, D);
13263   if (!Dcl)
13264     return true;
13265 
13266   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
13267     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
13268       << D.getSourceRange();
13269     return true;
13270   }
13271 
13272   return Dcl;
13273 }
13274 
13275 void Sema::LoadExternalVTableUses() {
13276   if (!ExternalSource)
13277     return;
13278 
13279   SmallVector<ExternalVTableUse, 4> VTables;
13280   ExternalSource->ReadUsedVTables(VTables);
13281   SmallVector<VTableUse, 4> NewUses;
13282   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
13283     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
13284       = VTablesUsed.find(VTables[I].Record);
13285     // Even if a definition wasn't required before, it may be required now.
13286     if (Pos != VTablesUsed.end()) {
13287       if (!Pos->second && VTables[I].DefinitionRequired)
13288         Pos->second = true;
13289       continue;
13290     }
13291 
13292     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
13293     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
13294   }
13295 
13296   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
13297 }
13298 
13299 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
13300                           bool DefinitionRequired) {
13301   // Ignore any vtable uses in unevaluated operands or for classes that do
13302   // not have a vtable.
13303   if (!Class->isDynamicClass() || Class->isDependentContext() ||
13304       CurContext->isDependentContext() || isUnevaluatedContext())
13305     return;
13306 
13307   // Try to insert this class into the map.
13308   LoadExternalVTableUses();
13309   Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13310   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
13311     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
13312   if (!Pos.second) {
13313     // If we already had an entry, check to see if we are promoting this vtable
13314     // to require a definition. If so, we need to reappend to the VTableUses
13315     // list, since we may have already processed the first entry.
13316     if (DefinitionRequired && !Pos.first->second) {
13317       Pos.first->second = true;
13318     } else {
13319       // Otherwise, we can early exit.
13320       return;
13321     }
13322   } else {
13323     // The Microsoft ABI requires that we perform the destructor body
13324     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
13325     // the deleting destructor is emitted with the vtable, not with the
13326     // destructor definition as in the Itanium ABI.
13327     // If it has a definition, we do the check at that point instead.
13328     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13329       if (Class->hasUserDeclaredDestructor() &&
13330           !Class->getDestructor()->isDefined() &&
13331           !Class->getDestructor()->isDeleted()) {
13332         CXXDestructorDecl *DD = Class->getDestructor();
13333         ContextRAII SavedContext(*this, DD);
13334         CheckDestructor(DD);
13335       } else if (Class->hasAttr<DLLImportAttr>()) {
13336         // We always synthesize vtables on the import side. To make sure
13337         // CheckDestructor gets called, mark the destructor referenced.
13338         assert(Class->getDestructor() &&
13339                "The destructor has always been declared on a dllimport class");
13340         MarkFunctionReferenced(Loc, Class->getDestructor());
13341       }
13342     }
13343   }
13344 
13345   // Local classes need to have their virtual members marked
13346   // immediately. For all other classes, we mark their virtual members
13347   // at the end of the translation unit.
13348   if (Class->isLocalClass())
13349     MarkVirtualMembersReferenced(Loc, Class);
13350   else
13351     VTableUses.push_back(std::make_pair(Class, Loc));
13352 }
13353 
13354 bool Sema::DefineUsedVTables() {
13355   LoadExternalVTableUses();
13356   if (VTableUses.empty())
13357     return false;
13358 
13359   // Note: The VTableUses vector could grow as a result of marking
13360   // the members of a class as "used", so we check the size each
13361   // time through the loop and prefer indices (which are stable) to
13362   // iterators (which are not).
13363   bool DefinedAnything = false;
13364   for (unsigned I = 0; I != VTableUses.size(); ++I) {
13365     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
13366     if (!Class)
13367       continue;
13368 
13369     SourceLocation Loc = VTableUses[I].second;
13370 
13371     bool DefineVTable = true;
13372 
13373     // If this class has a key function, but that key function is
13374     // defined in another translation unit, we don't need to emit the
13375     // vtable even though we're using it.
13376     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
13377     if (KeyFunction && !KeyFunction->hasBody()) {
13378       // The key function is in another translation unit.
13379       DefineVTable = false;
13380       TemplateSpecializationKind TSK =
13381           KeyFunction->getTemplateSpecializationKind();
13382       assert(TSK != TSK_ExplicitInstantiationDefinition &&
13383              TSK != TSK_ImplicitInstantiation &&
13384              "Instantiations don't have key functions");
13385       (void)TSK;
13386     } else if (!KeyFunction) {
13387       // If we have a class with no key function that is the subject
13388       // of an explicit instantiation declaration, suppress the
13389       // vtable; it will live with the explicit instantiation
13390       // definition.
13391       bool IsExplicitInstantiationDeclaration
13392         = Class->getTemplateSpecializationKind()
13393                                       == TSK_ExplicitInstantiationDeclaration;
13394       for (auto R : Class->redecls()) {
13395         TemplateSpecializationKind TSK
13396           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
13397         if (TSK == TSK_ExplicitInstantiationDeclaration)
13398           IsExplicitInstantiationDeclaration = true;
13399         else if (TSK == TSK_ExplicitInstantiationDefinition) {
13400           IsExplicitInstantiationDeclaration = false;
13401           break;
13402         }
13403       }
13404 
13405       if (IsExplicitInstantiationDeclaration)
13406         DefineVTable = false;
13407     }
13408 
13409     // The exception specifications for all virtual members may be needed even
13410     // if we are not providing an authoritative form of the vtable in this TU.
13411     // We may choose to emit it available_externally anyway.
13412     if (!DefineVTable) {
13413       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
13414       continue;
13415     }
13416 
13417     // Mark all of the virtual members of this class as referenced, so
13418     // that we can build a vtable. Then, tell the AST consumer that a
13419     // vtable for this class is required.
13420     DefinedAnything = true;
13421     MarkVirtualMembersReferenced(Loc, Class);
13422     CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13423     if (VTablesUsed[Canonical])
13424       Consumer.HandleVTable(Class);
13425 
13426     // Optionally warn if we're emitting a weak vtable.
13427     if (Class->isExternallyVisible() &&
13428         Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
13429       const FunctionDecl *KeyFunctionDef = nullptr;
13430       if (!KeyFunction ||
13431           (KeyFunction->hasBody(KeyFunctionDef) &&
13432            KeyFunctionDef->isInlined()))
13433         Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
13434              TSK_ExplicitInstantiationDefinition
13435              ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
13436           << Class;
13437     }
13438   }
13439   VTableUses.clear();
13440 
13441   return DefinedAnything;
13442 }
13443 
13444 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
13445                                                  const CXXRecordDecl *RD) {
13446   for (const auto *I : RD->methods())
13447     if (I->isVirtual() && !I->isPure())
13448       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
13449 }
13450 
13451 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
13452                                         const CXXRecordDecl *RD) {
13453   // Mark all functions which will appear in RD's vtable as used.
13454   CXXFinalOverriderMap FinalOverriders;
13455   RD->getFinalOverriders(FinalOverriders);
13456   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
13457                                             E = FinalOverriders.end();
13458        I != E; ++I) {
13459     for (OverridingMethods::const_iterator OI = I->second.begin(),
13460                                            OE = I->second.end();
13461          OI != OE; ++OI) {
13462       assert(OI->second.size() > 0 && "no final overrider");
13463       CXXMethodDecl *Overrider = OI->second.front().Method;
13464 
13465       // C++ [basic.def.odr]p2:
13466       //   [...] A virtual member function is used if it is not pure. [...]
13467       if (!Overrider->isPure())
13468         MarkFunctionReferenced(Loc, Overrider);
13469     }
13470   }
13471 
13472   // Only classes that have virtual bases need a VTT.
13473   if (RD->getNumVBases() == 0)
13474     return;
13475 
13476   for (const auto &I : RD->bases()) {
13477     const CXXRecordDecl *Base =
13478         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
13479     if (Base->getNumVBases() == 0)
13480       continue;
13481     MarkVirtualMembersReferenced(Loc, Base);
13482   }
13483 }
13484 
13485 /// SetIvarInitializers - This routine builds initialization ASTs for the
13486 /// Objective-C implementation whose ivars need be initialized.
13487 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
13488   if (!getLangOpts().CPlusPlus)
13489     return;
13490   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
13491     SmallVector<ObjCIvarDecl*, 8> ivars;
13492     CollectIvarsToConstructOrDestruct(OID, ivars);
13493     if (ivars.empty())
13494       return;
13495     SmallVector<CXXCtorInitializer*, 32> AllToInit;
13496     for (unsigned i = 0; i < ivars.size(); i++) {
13497       FieldDecl *Field = ivars[i];
13498       if (Field->isInvalidDecl())
13499         continue;
13500 
13501       CXXCtorInitializer *Member;
13502       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
13503       InitializationKind InitKind =
13504         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
13505 
13506       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
13507       ExprResult MemberInit =
13508         InitSeq.Perform(*this, InitEntity, InitKind, None);
13509       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
13510       // Note, MemberInit could actually come back empty if no initialization
13511       // is required (e.g., because it would call a trivial default constructor)
13512       if (!MemberInit.get() || MemberInit.isInvalid())
13513         continue;
13514 
13515       Member =
13516         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
13517                                          SourceLocation(),
13518                                          MemberInit.getAs<Expr>(),
13519                                          SourceLocation());
13520       AllToInit.push_back(Member);
13521 
13522       // Be sure that the destructor is accessible and is marked as referenced.
13523       if (const RecordType *RecordTy =
13524               Context.getBaseElementType(Field->getType())
13525                   ->getAs<RecordType>()) {
13526         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
13527         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
13528           MarkFunctionReferenced(Field->getLocation(), Destructor);
13529           CheckDestructorAccess(Field->getLocation(), Destructor,
13530                             PDiag(diag::err_access_dtor_ivar)
13531                               << Context.getBaseElementType(Field->getType()));
13532         }
13533       }
13534     }
13535     ObjCImplementation->setIvarInitializers(Context,
13536                                             AllToInit.data(), AllToInit.size());
13537   }
13538 }
13539 
13540 static
13541 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
13542                            llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
13543                            llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
13544                            llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
13545                            Sema &S) {
13546   if (Ctor->isInvalidDecl())
13547     return;
13548 
13549   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
13550 
13551   // Target may not be determinable yet, for instance if this is a dependent
13552   // call in an uninstantiated template.
13553   if (Target) {
13554     const FunctionDecl *FNTarget = nullptr;
13555     (void)Target->hasBody(FNTarget);
13556     Target = const_cast<CXXConstructorDecl*>(
13557       cast_or_null<CXXConstructorDecl>(FNTarget));
13558   }
13559 
13560   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
13561                      // Avoid dereferencing a null pointer here.
13562                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
13563 
13564   if (!Current.insert(Canonical).second)
13565     return;
13566 
13567   // We know that beyond here, we aren't chaining into a cycle.
13568   if (!Target || !Target->isDelegatingConstructor() ||
13569       Target->isInvalidDecl() || Valid.count(TCanonical)) {
13570     Valid.insert(Current.begin(), Current.end());
13571     Current.clear();
13572   // We've hit a cycle.
13573   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
13574              Current.count(TCanonical)) {
13575     // If we haven't diagnosed this cycle yet, do so now.
13576     if (!Invalid.count(TCanonical)) {
13577       S.Diag((*Ctor->init_begin())->getSourceLocation(),
13578              diag::warn_delegating_ctor_cycle)
13579         << Ctor;
13580 
13581       // Don't add a note for a function delegating directly to itself.
13582       if (TCanonical != Canonical)
13583         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
13584 
13585       CXXConstructorDecl *C = Target;
13586       while (C->getCanonicalDecl() != Canonical) {
13587         const FunctionDecl *FNTarget = nullptr;
13588         (void)C->getTargetConstructor()->hasBody(FNTarget);
13589         assert(FNTarget && "Ctor cycle through bodiless function");
13590 
13591         C = const_cast<CXXConstructorDecl*>(
13592           cast<CXXConstructorDecl>(FNTarget));
13593         S.Diag(C->getLocation(), diag::note_which_delegates_to);
13594       }
13595     }
13596 
13597     Invalid.insert(Current.begin(), Current.end());
13598     Current.clear();
13599   } else {
13600     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
13601   }
13602 }
13603 
13604 
13605 void Sema::CheckDelegatingCtorCycles() {
13606   llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
13607 
13608   for (DelegatingCtorDeclsType::iterator
13609          I = DelegatingCtorDecls.begin(ExternalSource),
13610          E = DelegatingCtorDecls.end();
13611        I != E; ++I)
13612     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
13613 
13614   for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
13615                                                          CE = Invalid.end();
13616        CI != CE; ++CI)
13617     (*CI)->setInvalidDecl();
13618 }
13619 
13620 namespace {
13621   /// \brief AST visitor that finds references to the 'this' expression.
13622   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
13623     Sema &S;
13624 
13625   public:
13626     explicit FindCXXThisExpr(Sema &S) : S(S) { }
13627 
13628     bool VisitCXXThisExpr(CXXThisExpr *E) {
13629       S.Diag(E->getLocation(), diag::err_this_static_member_func)
13630         << E->isImplicit();
13631       return false;
13632     }
13633   };
13634 }
13635 
13636 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
13637   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13638   if (!TSInfo)
13639     return false;
13640 
13641   TypeLoc TL = TSInfo->getTypeLoc();
13642   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
13643   if (!ProtoTL)
13644     return false;
13645 
13646   // C++11 [expr.prim.general]p3:
13647   //   [The expression this] shall not appear before the optional
13648   //   cv-qualifier-seq and it shall not appear within the declaration of a
13649   //   static member function (although its type and value category are defined
13650   //   within a static member function as they are within a non-static member
13651   //   function). [ Note: this is because declaration matching does not occur
13652   //  until the complete declarator is known. - end note ]
13653   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
13654   FindCXXThisExpr Finder(*this);
13655 
13656   // If the return type came after the cv-qualifier-seq, check it now.
13657   if (Proto->hasTrailingReturn() &&
13658       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
13659     return true;
13660 
13661   // Check the exception specification.
13662   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
13663     return true;
13664 
13665   return checkThisInStaticMemberFunctionAttributes(Method);
13666 }
13667 
13668 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
13669   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13670   if (!TSInfo)
13671     return false;
13672 
13673   TypeLoc TL = TSInfo->getTypeLoc();
13674   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
13675   if (!ProtoTL)
13676     return false;
13677 
13678   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
13679   FindCXXThisExpr Finder(*this);
13680 
13681   switch (Proto->getExceptionSpecType()) {
13682   case EST_Unparsed:
13683   case EST_Uninstantiated:
13684   case EST_Unevaluated:
13685   case EST_BasicNoexcept:
13686   case EST_DynamicNone:
13687   case EST_MSAny:
13688   case EST_None:
13689     break;
13690 
13691   case EST_ComputedNoexcept:
13692     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
13693       return true;
13694 
13695   case EST_Dynamic:
13696     for (const auto &E : Proto->exceptions()) {
13697       if (!Finder.TraverseType(E))
13698         return true;
13699     }
13700     break;
13701   }
13702 
13703   return false;
13704 }
13705 
13706 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
13707   FindCXXThisExpr Finder(*this);
13708 
13709   // Check attributes.
13710   for (const auto *A : Method->attrs()) {
13711     // FIXME: This should be emitted by tblgen.
13712     Expr *Arg = nullptr;
13713     ArrayRef<Expr *> Args;
13714     if (const auto *G = dyn_cast<GuardedByAttr>(A))
13715       Arg = G->getArg();
13716     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
13717       Arg = G->getArg();
13718     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
13719       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
13720     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
13721       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
13722     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
13723       Arg = ETLF->getSuccessValue();
13724       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
13725     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
13726       Arg = STLF->getSuccessValue();
13727       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
13728     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
13729       Arg = LR->getArg();
13730     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
13731       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
13732     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
13733       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
13734     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
13735       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
13736     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
13737       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
13738     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
13739       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
13740 
13741     if (Arg && !Finder.TraverseStmt(Arg))
13742       return true;
13743 
13744     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
13745       if (!Finder.TraverseStmt(Args[I]))
13746         return true;
13747     }
13748   }
13749 
13750   return false;
13751 }
13752 
13753 void Sema::checkExceptionSpecification(
13754     bool IsTopLevel, ExceptionSpecificationType EST,
13755     ArrayRef<ParsedType> DynamicExceptions,
13756     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
13757     SmallVectorImpl<QualType> &Exceptions,
13758     FunctionProtoType::ExceptionSpecInfo &ESI) {
13759   Exceptions.clear();
13760   ESI.Type = EST;
13761   if (EST == EST_Dynamic) {
13762     Exceptions.reserve(DynamicExceptions.size());
13763     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
13764       // FIXME: Preserve type source info.
13765       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
13766 
13767       if (IsTopLevel) {
13768         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13769         collectUnexpandedParameterPacks(ET, Unexpanded);
13770         if (!Unexpanded.empty()) {
13771           DiagnoseUnexpandedParameterPacks(
13772               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
13773               Unexpanded);
13774           continue;
13775         }
13776       }
13777 
13778       // Check that the type is valid for an exception spec, and
13779       // drop it if not.
13780       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
13781         Exceptions.push_back(ET);
13782     }
13783     ESI.Exceptions = Exceptions;
13784     return;
13785   }
13786 
13787   if (EST == EST_ComputedNoexcept) {
13788     // If an error occurred, there's no expression here.
13789     if (NoexceptExpr) {
13790       assert((NoexceptExpr->isTypeDependent() ||
13791               NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
13792               Context.BoolTy) &&
13793              "Parser should have made sure that the expression is boolean");
13794       if (IsTopLevel && NoexceptExpr &&
13795           DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
13796         ESI.Type = EST_BasicNoexcept;
13797         return;
13798       }
13799 
13800       if (!NoexceptExpr->isValueDependent())
13801         NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
13802                          diag::err_noexcept_needs_constant_expression,
13803                          /*AllowFold*/ false).get();
13804       ESI.NoexceptExpr = NoexceptExpr;
13805     }
13806     return;
13807   }
13808 }
13809 
13810 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
13811              ExceptionSpecificationType EST,
13812              SourceRange SpecificationRange,
13813              ArrayRef<ParsedType> DynamicExceptions,
13814              ArrayRef<SourceRange> DynamicExceptionRanges,
13815              Expr *NoexceptExpr) {
13816   if (!MethodD)
13817     return;
13818 
13819   // Dig out the method we're referring to.
13820   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
13821     MethodD = FunTmpl->getTemplatedDecl();
13822 
13823   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
13824   if (!Method)
13825     return;
13826 
13827   // Check the exception specification.
13828   llvm::SmallVector<QualType, 4> Exceptions;
13829   FunctionProtoType::ExceptionSpecInfo ESI;
13830   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
13831                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
13832                               ESI);
13833 
13834   // Update the exception specification on the function type.
13835   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
13836 
13837   if (Method->isStatic())
13838     checkThisInStaticMemberFunctionExceptionSpec(Method);
13839 
13840   if (Method->isVirtual()) {
13841     // Check overrides, which we previously had to delay.
13842     for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
13843                                      OEnd = Method->end_overridden_methods();
13844          O != OEnd; ++O)
13845       CheckOverridingFunctionExceptionSpec(Method, *O);
13846   }
13847 }
13848 
13849 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
13850 ///
13851 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
13852                                        SourceLocation DeclStart,
13853                                        Declarator &D, Expr *BitWidth,
13854                                        InClassInitStyle InitStyle,
13855                                        AccessSpecifier AS,
13856                                        AttributeList *MSPropertyAttr) {
13857   IdentifierInfo *II = D.getIdentifier();
13858   if (!II) {
13859     Diag(DeclStart, diag::err_anonymous_property);
13860     return nullptr;
13861   }
13862   SourceLocation Loc = D.getIdentifierLoc();
13863 
13864   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13865   QualType T = TInfo->getType();
13866   if (getLangOpts().CPlusPlus) {
13867     CheckExtraCXXDefaultArguments(D);
13868 
13869     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13870                                         UPPC_DataMemberType)) {
13871       D.setInvalidType();
13872       T = Context.IntTy;
13873       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13874     }
13875   }
13876 
13877   DiagnoseFunctionSpecifiers(D.getDeclSpec());
13878 
13879   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13880     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13881          diag::err_invalid_thread)
13882       << DeclSpec::getSpecifierName(TSCS);
13883 
13884   // Check to see if this name was declared as a member previously
13885   NamedDecl *PrevDecl = nullptr;
13886   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13887   LookupName(Previous, S);
13888   switch (Previous.getResultKind()) {
13889   case LookupResult::Found:
13890   case LookupResult::FoundUnresolvedValue:
13891     PrevDecl = Previous.getAsSingle<NamedDecl>();
13892     break;
13893 
13894   case LookupResult::FoundOverloaded:
13895     PrevDecl = Previous.getRepresentativeDecl();
13896     break;
13897 
13898   case LookupResult::NotFound:
13899   case LookupResult::NotFoundInCurrentInstantiation:
13900   case LookupResult::Ambiguous:
13901     break;
13902   }
13903 
13904   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13905     // Maybe we will complain about the shadowed template parameter.
13906     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13907     // Just pretend that we didn't see the previous declaration.
13908     PrevDecl = nullptr;
13909   }
13910 
13911   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13912     PrevDecl = nullptr;
13913 
13914   SourceLocation TSSL = D.getLocStart();
13915   const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
13916   MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13917       Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
13918   ProcessDeclAttributes(TUScope, NewPD, D);
13919   NewPD->setAccess(AS);
13920 
13921   if (NewPD->isInvalidDecl())
13922     Record->setInvalidDecl();
13923 
13924   if (D.getDeclSpec().isModulePrivateSpecified())
13925     NewPD->setModulePrivate();
13926 
13927   if (NewPD->isInvalidDecl() && PrevDecl) {
13928     // Don't introduce NewFD into scope; there's already something
13929     // with the same name in the same scope.
13930   } else if (II) {
13931     PushOnScopeChains(NewPD, S);
13932   } else
13933     Record->addDecl(NewPD);
13934 
13935   return NewPD;
13936 }
13937