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 "llvm/ADT/STLExtras.h"
40 #include "llvm/ADT/SmallString.h"
41 #include <map>
42 #include <set>
43 
44 using namespace clang;
45 
46 //===----------------------------------------------------------------------===//
47 // CheckDefaultArgumentVisitor
48 //===----------------------------------------------------------------------===//
49 
50 namespace {
51   /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
52   /// the default argument of a parameter to determine whether it
53   /// contains any ill-formed subexpressions. For example, this will
54   /// diagnose the use of local variables or parameters within the
55   /// default argument expression.
56   class CheckDefaultArgumentVisitor
57     : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
58     Expr *DefaultArg;
59     Sema *S;
60 
61   public:
62     CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
63       : DefaultArg(defarg), S(s) {}
64 
65     bool VisitExpr(Expr *Node);
66     bool VisitDeclRefExpr(DeclRefExpr *DRE);
67     bool VisitCXXThisExpr(CXXThisExpr *ThisE);
68     bool VisitLambdaExpr(LambdaExpr *Lambda);
69     bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
70   };
71 
72   /// VisitExpr - Visit all of the children of this expression.
73   bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
74     bool IsInvalid = false;
75     for (Stmt::child_range I = Node->children(); I; ++I)
76       IsInvalid |= Visit(*I);
77     return IsInvalid;
78   }
79 
80   /// VisitDeclRefExpr - Visit a reference to a declaration, to
81   /// determine whether this declaration can be used in the default
82   /// argument expression.
83   bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
84     NamedDecl *Decl = DRE->getDecl();
85     if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
86       // C++ [dcl.fct.default]p9
87       //   Default arguments are evaluated each time the function is
88       //   called. The order of evaluation of function arguments is
89       //   unspecified. Consequently, parameters of a function shall not
90       //   be used in default argument expressions, even if they are not
91       //   evaluated. Parameters of a function declared before a default
92       //   argument expression are in scope and can hide namespace and
93       //   class member names.
94       return S->Diag(DRE->getLocStart(),
95                      diag::err_param_default_argument_references_param)
96          << Param->getDeclName() << DefaultArg->getSourceRange();
97     } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
98       // C++ [dcl.fct.default]p7
99       //   Local variables shall not be used in default argument
100       //   expressions.
101       if (VDecl->isLocalVarDecl())
102         return S->Diag(DRE->getLocStart(),
103                        diag::err_param_default_argument_references_local)
104           << VDecl->getDeclName() << DefaultArg->getSourceRange();
105     }
106 
107     return false;
108   }
109 
110   /// VisitCXXThisExpr - Visit a C++ "this" expression.
111   bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
112     // C++ [dcl.fct.default]p8:
113     //   The keyword this shall not be used in a default argument of a
114     //   member function.
115     return S->Diag(ThisE->getLocStart(),
116                    diag::err_param_default_argument_references_this)
117                << ThisE->getSourceRange();
118   }
119 
120   bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
121     bool Invalid = false;
122     for (PseudoObjectExpr::semantics_iterator
123            i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
124       Expr *E = *i;
125 
126       // Look through bindings.
127       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
128         E = OVE->getSourceExpr();
129         assert(E && "pseudo-object binding without source expression?");
130       }
131 
132       Invalid |= Visit(E);
133     }
134     return Invalid;
135   }
136 
137   bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
138     // C++11 [expr.lambda.prim]p13:
139     //   A lambda-expression appearing in a default argument shall not
140     //   implicitly or explicitly capture any entity.
141     if (Lambda->capture_begin() == Lambda->capture_end())
142       return false;
143 
144     return S->Diag(Lambda->getLocStart(),
145                    diag::err_lambda_capture_default_arg);
146   }
147 }
148 
149 void
150 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
151                                                  const CXXMethodDecl *Method) {
152   // If we have an MSAny spec already, don't bother.
153   if (!Method || ComputedEST == EST_MSAny)
154     return;
155 
156   const FunctionProtoType *Proto
157     = Method->getType()->getAs<FunctionProtoType>();
158   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
159   if (!Proto)
160     return;
161 
162   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
163 
164   // If this function can throw any exceptions, make a note of that.
165   if (EST == EST_MSAny || EST == EST_None) {
166     ClearExceptions();
167     ComputedEST = EST;
168     return;
169   }
170 
171   // FIXME: If the call to this decl is using any of its default arguments, we
172   // need to search them for potentially-throwing calls.
173 
174   // If this function has a basic noexcept, it doesn't affect the outcome.
175   if (EST == EST_BasicNoexcept)
176     return;
177 
178   // If we have a throw-all spec at this point, ignore the function.
179   if (ComputedEST == EST_None)
180     return;
181 
182   // If we're still at noexcept(true) and there's a nothrow() callee,
183   // change to that specification.
184   if (EST == EST_DynamicNone) {
185     if (ComputedEST == EST_BasicNoexcept)
186       ComputedEST = EST_DynamicNone;
187     return;
188   }
189 
190   // Check out noexcept specs.
191   if (EST == EST_ComputedNoexcept) {
192     FunctionProtoType::NoexceptResult NR =
193         Proto->getNoexceptSpec(Self->Context);
194     assert(NR != FunctionProtoType::NR_NoNoexcept &&
195            "Must have noexcept result for EST_ComputedNoexcept.");
196     assert(NR != FunctionProtoType::NR_Dependent &&
197            "Should not generate implicit declarations for dependent cases, "
198            "and don't know how to handle them anyway.");
199 
200     // noexcept(false) -> no spec on the new function
201     if (NR == FunctionProtoType::NR_Throw) {
202       ClearExceptions();
203       ComputedEST = EST_None;
204     }
205     // noexcept(true) won't change anything either.
206     return;
207   }
208 
209   assert(EST == EST_Dynamic && "EST case not considered earlier.");
210   assert(ComputedEST != EST_None &&
211          "Shouldn't collect exceptions when throw-all is guaranteed.");
212   ComputedEST = EST_Dynamic;
213   // Record the exceptions in this function's exception specification.
214   for (const auto &E : Proto->exceptions())
215     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)))
216       Exceptions.push_back(E);
217 }
218 
219 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
220   if (!E || ComputedEST == EST_MSAny)
221     return;
222 
223   // FIXME:
224   //
225   // C++0x [except.spec]p14:
226   //   [An] implicit exception-specification specifies the type-id T if and
227   // only if T is allowed by the exception-specification of a function directly
228   // invoked by f's implicit definition; f shall allow all exceptions if any
229   // function it directly invokes allows all exceptions, and f shall allow no
230   // exceptions if every function it directly invokes allows no exceptions.
231   //
232   // Note in particular that if an implicit exception-specification is generated
233   // for a function containing a throw-expression, that specification can still
234   // be noexcept(true).
235   //
236   // Note also that 'directly invoked' is not defined in the standard, and there
237   // is no indication that we should only consider potentially-evaluated calls.
238   //
239   // Ultimately we should implement the intent of the standard: the exception
240   // specification should be the set of exceptions which can be thrown by the
241   // implicit definition. For now, we assume that any non-nothrow expression can
242   // throw any exception.
243 
244   if (Self->canThrow(E))
245     ComputedEST = EST_None;
246 }
247 
248 bool
249 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
250                               SourceLocation EqualLoc) {
251   if (RequireCompleteType(Param->getLocation(), Param->getType(),
252                           diag::err_typecheck_decl_incomplete_type)) {
253     Param->setInvalidDecl();
254     return true;
255   }
256 
257   // C++ [dcl.fct.default]p5
258   //   A default argument expression is implicitly converted (clause
259   //   4) to the parameter type. The default argument expression has
260   //   the same semantic constraints as the initializer expression in
261   //   a declaration of a variable of the parameter type, using the
262   //   copy-initialization semantics (8.5).
263   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
264                                                                     Param);
265   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
266                                                            EqualLoc);
267   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
268   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
269   if (Result.isInvalid())
270     return true;
271   Arg = Result.getAs<Expr>();
272 
273   CheckCompletedExpr(Arg, EqualLoc);
274   Arg = MaybeCreateExprWithCleanups(Arg);
275 
276   // Okay: add the default argument to the parameter
277   Param->setDefaultArg(Arg);
278 
279   // We have already instantiated this parameter; provide each of the
280   // instantiations with the uninstantiated default argument.
281   UnparsedDefaultArgInstantiationsMap::iterator InstPos
282     = UnparsedDefaultArgInstantiations.find(Param);
283   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
284     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
285       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
286 
287     // We're done tracking this parameter's instantiations.
288     UnparsedDefaultArgInstantiations.erase(InstPos);
289   }
290 
291   return false;
292 }
293 
294 /// ActOnParamDefaultArgument - Check whether the default argument
295 /// provided for a function parameter is well-formed. If so, attach it
296 /// to the parameter declaration.
297 void
298 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
299                                 Expr *DefaultArg) {
300   if (!param || !DefaultArg)
301     return;
302 
303   ParmVarDecl *Param = cast<ParmVarDecl>(param);
304   UnparsedDefaultArgLocs.erase(Param);
305 
306   // Default arguments are only permitted in C++
307   if (!getLangOpts().CPlusPlus) {
308     Diag(EqualLoc, diag::err_param_default_argument)
309       << DefaultArg->getSourceRange();
310     Param->setInvalidDecl();
311     return;
312   }
313 
314   // Check for unexpanded parameter packs.
315   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
316     Param->setInvalidDecl();
317     return;
318   }
319 
320   // Check that the default argument is well-formed
321   CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
322   if (DefaultArgChecker.Visit(DefaultArg)) {
323     Param->setInvalidDecl();
324     return;
325   }
326 
327   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
328 }
329 
330 /// ActOnParamUnparsedDefaultArgument - We've seen a default
331 /// argument for a function parameter, but we can't parse it yet
332 /// because we're inside a class definition. Note that this default
333 /// argument will be parsed later.
334 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
335                                              SourceLocation EqualLoc,
336                                              SourceLocation ArgLoc) {
337   if (!param)
338     return;
339 
340   ParmVarDecl *Param = cast<ParmVarDecl>(param);
341   Param->setUnparsedDefaultArg();
342   UnparsedDefaultArgLocs[Param] = ArgLoc;
343 }
344 
345 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
346 /// the default argument for the parameter param failed.
347 void Sema::ActOnParamDefaultArgumentError(Decl *param,
348                                           SourceLocation EqualLoc) {
349   if (!param)
350     return;
351 
352   ParmVarDecl *Param = cast<ParmVarDecl>(param);
353   Param->setInvalidDecl();
354   UnparsedDefaultArgLocs.erase(Param);
355   Param->setDefaultArg(new(Context)
356                        OpaqueValueExpr(EqualLoc, Param->getType(), VK_RValue));
357 }
358 
359 /// CheckExtraCXXDefaultArguments - Check for any extra default
360 /// arguments in the declarator, which is not a function declaration
361 /// or definition and therefore is not permitted to have default
362 /// arguments. This routine should be invoked for every declarator
363 /// that is not a function declaration or definition.
364 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
365   // C++ [dcl.fct.default]p3
366   //   A default argument expression shall be specified only in the
367   //   parameter-declaration-clause of a function declaration or in a
368   //   template-parameter (14.1). It shall not be specified for a
369   //   parameter pack. If it is specified in a
370   //   parameter-declaration-clause, it shall not occur within a
371   //   declarator or abstract-declarator of a parameter-declaration.
372   bool MightBeFunction = D.isFunctionDeclarationContext();
373   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
374     DeclaratorChunk &chunk = D.getTypeObject(i);
375     if (chunk.Kind == DeclaratorChunk::Function) {
376       if (MightBeFunction) {
377         // This is a function declaration. It can have default arguments, but
378         // keep looking in case its return type is a function type with default
379         // arguments.
380         MightBeFunction = false;
381         continue;
382       }
383       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
384            ++argIdx) {
385         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
386         if (Param->hasUnparsedDefaultArg()) {
387           CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
388           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
389             << SourceRange((*Toks)[1].getLocation(),
390                            Toks->back().getLocation());
391           delete Toks;
392           chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
393         } else if (Param->getDefaultArg()) {
394           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
395             << Param->getDefaultArg()->getSourceRange();
396           Param->setDefaultArg(nullptr);
397         }
398       }
399     } else if (chunk.Kind != DeclaratorChunk::Paren) {
400       MightBeFunction = false;
401     }
402   }
403 }
404 
405 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
406   for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
407     const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
408     if (!PVD->hasDefaultArg())
409       return false;
410     if (!PVD->hasInheritedDefaultArg())
411       return true;
412   }
413   return false;
414 }
415 
416 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
417 /// function, once we already know that they have the same
418 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
419 /// error, false otherwise.
420 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
421                                 Scope *S) {
422   bool Invalid = false;
423 
424   // C++ [dcl.fct.default]p4:
425   //   For non-template functions, default arguments can be added in
426   //   later declarations of a function in the same
427   //   scope. Declarations in different scopes have completely
428   //   distinct sets of default arguments. That is, declarations in
429   //   inner scopes do not acquire default arguments from
430   //   declarations in outer scopes, and vice versa. In a given
431   //   function declaration, all parameters subsequent to a
432   //   parameter with a default argument shall have default
433   //   arguments supplied in this or previous declarations. A
434   //   default argument shall not be redefined by a later
435   //   declaration (not even to the same value).
436   //
437   // C++ [dcl.fct.default]p6:
438   //   Except for member functions of class templates, the default arguments
439   //   in a member function definition that appears outside of the class
440   //   definition are added to the set of default arguments provided by the
441   //   member function declaration in the class definition.
442   for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
443     ParmVarDecl *OldParam = Old->getParamDecl(p);
444     ParmVarDecl *NewParam = New->getParamDecl(p);
445 
446     bool OldParamHasDfl = OldParam->hasDefaultArg();
447     bool NewParamHasDfl = NewParam->hasDefaultArg();
448 
449     NamedDecl *ND = Old;
450 
451     // The declaration context corresponding to the scope is the semantic
452     // parent, unless this is a local function declaration, in which case
453     // it is that surrounding function.
454     DeclContext *ScopeDC = New->getLexicalDeclContext();
455     if (!ScopeDC->isFunctionOrMethod())
456       ScopeDC = New->getDeclContext();
457     if (S && !isDeclInScope(ND, ScopeDC, S) &&
458         !New->getDeclContext()->isRecord())
459       // Ignore default parameters of old decl if they are not in
460       // the same scope and this is not an out-of-line definition of
461       // a member function.
462       OldParamHasDfl = false;
463 
464     if (OldParamHasDfl && NewParamHasDfl) {
465 
466       unsigned DiagDefaultParamID =
467         diag::err_param_default_argument_redefinition;
468 
469       // MSVC accepts that default parameters be redefined for member functions
470       // of template class. The new default parameter's value is ignored.
471       Invalid = true;
472       if (getLangOpts().MicrosoftExt) {
473         CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
474         if (MD && MD->getParent()->getDescribedClassTemplate()) {
475           // Merge the old default argument into the new parameter.
476           NewParam->setHasInheritedDefaultArg();
477           if (OldParam->hasUninstantiatedDefaultArg())
478             NewParam->setUninstantiatedDefaultArg(
479                                       OldParam->getUninstantiatedDefaultArg());
480           else
481             NewParam->setDefaultArg(OldParam->getInit());
482           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
483           Invalid = false;
484         }
485       }
486 
487       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
488       // hint here. Alternatively, we could walk the type-source information
489       // for NewParam to find the last source location in the type... but it
490       // isn't worth the effort right now. This is the kind of test case that
491       // is hard to get right:
492       //   int f(int);
493       //   void g(int (*fp)(int) = f);
494       //   void g(int (*fp)(int) = &f);
495       Diag(NewParam->getLocation(), DiagDefaultParamID)
496         << NewParam->getDefaultArgRange();
497 
498       // Look for the function declaration where the default argument was
499       // actually written, which may be a declaration prior to Old.
500       for (FunctionDecl *Older = Old->getPreviousDecl();
501            Older; Older = Older->getPreviousDecl()) {
502         if (!Older->getParamDecl(p)->hasDefaultArg())
503           break;
504 
505         OldParam = Older->getParamDecl(p);
506       }
507 
508       Diag(OldParam->getLocation(), diag::note_previous_definition)
509         << OldParam->getDefaultArgRange();
510     } else if (OldParamHasDfl) {
511       // Merge the old default argument into the new parameter.
512       // It's important to use getInit() here;  getDefaultArg()
513       // strips off any top-level ExprWithCleanups.
514       NewParam->setHasInheritedDefaultArg();
515       if (OldParam->hasUninstantiatedDefaultArg())
516         NewParam->setUninstantiatedDefaultArg(
517                                       OldParam->getUninstantiatedDefaultArg());
518       else
519         NewParam->setDefaultArg(OldParam->getInit());
520     } else if (NewParamHasDfl) {
521       if (New->getDescribedFunctionTemplate()) {
522         // Paragraph 4, quoted above, only applies to non-template functions.
523         Diag(NewParam->getLocation(),
524              diag::err_param_default_argument_template_redecl)
525           << NewParam->getDefaultArgRange();
526         Diag(Old->getLocation(), diag::note_template_prev_declaration)
527           << false;
528       } else if (New->getTemplateSpecializationKind()
529                    != TSK_ImplicitInstantiation &&
530                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
531         // C++ [temp.expr.spec]p21:
532         //   Default function arguments shall not be specified in a declaration
533         //   or a definition for one of the following explicit specializations:
534         //     - the explicit specialization of a function template;
535         //     - the explicit specialization of a member function template;
536         //     - the explicit specialization of a member function of a class
537         //       template where the class template specialization to which the
538         //       member function specialization belongs is implicitly
539         //       instantiated.
540         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
541           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
542           << New->getDeclName()
543           << NewParam->getDefaultArgRange();
544       } else if (New->getDeclContext()->isDependentContext()) {
545         // C++ [dcl.fct.default]p6 (DR217):
546         //   Default arguments for a member function of a class template shall
547         //   be specified on the initial declaration of the member function
548         //   within the class template.
549         //
550         // Reading the tea leaves a bit in DR217 and its reference to DR205
551         // leads me to the conclusion that one cannot add default function
552         // arguments for an out-of-line definition of a member function of a
553         // dependent type.
554         int WhichKind = 2;
555         if (CXXRecordDecl *Record
556               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
557           if (Record->getDescribedClassTemplate())
558             WhichKind = 0;
559           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
560             WhichKind = 1;
561           else
562             WhichKind = 2;
563         }
564 
565         Diag(NewParam->getLocation(),
566              diag::err_param_default_argument_member_template_redecl)
567           << WhichKind
568           << NewParam->getDefaultArgRange();
569       }
570     }
571   }
572 
573   // DR1344: If a default argument is added outside a class definition and that
574   // default argument makes the function a special member function, the program
575   // is ill-formed. This can only happen for constructors.
576   if (isa<CXXConstructorDecl>(New) &&
577       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
578     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
579                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
580     if (NewSM != OldSM) {
581       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
582       assert(NewParam->hasDefaultArg());
583       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
584         << NewParam->getDefaultArgRange() << NewSM;
585       Diag(Old->getLocation(), diag::note_previous_declaration);
586     }
587   }
588 
589   const FunctionDecl *Def;
590   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
591   // template has a constexpr specifier then all its declarations shall
592   // contain the constexpr specifier.
593   if (New->isConstexpr() != Old->isConstexpr()) {
594     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
595       << New << New->isConstexpr();
596     Diag(Old->getLocation(), diag::note_previous_declaration);
597     Invalid = true;
598   } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) {
599     // C++11 [dcl.fcn.spec]p4:
600     //   If the definition of a function appears in a translation unit before its
601     //   first declaration as inline, the program is ill-formed.
602     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
603     Diag(Def->getLocation(), diag::note_previous_definition);
604     Invalid = true;
605   }
606 
607   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
608   // argument expression, that declaration shall be a definition and shall be
609   // the only declaration of the function or function template in the
610   // translation unit.
611   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
612       functionDeclHasDefaultArgument(Old)) {
613     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
614     Diag(Old->getLocation(), diag::note_previous_declaration);
615     Invalid = true;
616   }
617 
618   if (CheckEquivalentExceptionSpec(Old, New))
619     Invalid = true;
620 
621   return Invalid;
622 }
623 
624 /// \brief Merge the exception specifications of two variable declarations.
625 ///
626 /// This is called when there's a redeclaration of a VarDecl. The function
627 /// checks if the redeclaration might have an exception specification and
628 /// validates compatibility and merges the specs if necessary.
629 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
630   // Shortcut if exceptions are disabled.
631   if (!getLangOpts().CXXExceptions)
632     return;
633 
634   assert(Context.hasSameType(New->getType(), Old->getType()) &&
635          "Should only be called if types are otherwise the same.");
636 
637   QualType NewType = New->getType();
638   QualType OldType = Old->getType();
639 
640   // We're only interested in pointers and references to functions, as well
641   // as pointers to member functions.
642   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
643     NewType = R->getPointeeType();
644     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
645   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
646     NewType = P->getPointeeType();
647     OldType = OldType->getAs<PointerType>()->getPointeeType();
648   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
649     NewType = M->getPointeeType();
650     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
651   }
652 
653   if (!NewType->isFunctionProtoType())
654     return;
655 
656   // There's lots of special cases for functions. For function pointers, system
657   // libraries are hopefully not as broken so that we don't need these
658   // workarounds.
659   if (CheckEquivalentExceptionSpec(
660         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
661         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
662     New->setInvalidDecl();
663   }
664 }
665 
666 /// CheckCXXDefaultArguments - Verify that the default arguments for a
667 /// function declaration are well-formed according to C++
668 /// [dcl.fct.default].
669 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
670   unsigned NumParams = FD->getNumParams();
671   unsigned p;
672 
673   // Find first parameter with a default argument
674   for (p = 0; p < NumParams; ++p) {
675     ParmVarDecl *Param = FD->getParamDecl(p);
676     if (Param->hasDefaultArg())
677       break;
678   }
679 
680   // C++ [dcl.fct.default]p4:
681   //   In a given function declaration, all parameters
682   //   subsequent to a parameter with a default argument shall
683   //   have default arguments supplied in this or previous
684   //   declarations. A default argument shall not be redefined
685   //   by a later declaration (not even to the same value).
686   unsigned LastMissingDefaultArg = 0;
687   for (; p < NumParams; ++p) {
688     ParmVarDecl *Param = FD->getParamDecl(p);
689     if (!Param->hasDefaultArg()) {
690       if (Param->isInvalidDecl())
691         /* We already complained about this parameter. */;
692       else if (Param->getIdentifier())
693         Diag(Param->getLocation(),
694              diag::err_param_default_argument_missing_name)
695           << Param->getIdentifier();
696       else
697         Diag(Param->getLocation(),
698              diag::err_param_default_argument_missing);
699 
700       LastMissingDefaultArg = p;
701     }
702   }
703 
704   if (LastMissingDefaultArg > 0) {
705     // Some default arguments were missing. Clear out all of the
706     // default arguments up to (and including) the last missing
707     // default argument, so that we leave the function parameters
708     // in a semantically valid state.
709     for (p = 0; p <= LastMissingDefaultArg; ++p) {
710       ParmVarDecl *Param = FD->getParamDecl(p);
711       if (Param->hasDefaultArg()) {
712         Param->setDefaultArg(nullptr);
713       }
714     }
715   }
716 }
717 
718 // CheckConstexprParameterTypes - Check whether a function's parameter types
719 // are all literal types. If so, return true. If not, produce a suitable
720 // diagnostic and return false.
721 static bool CheckConstexprParameterTypes(Sema &SemaRef,
722                                          const FunctionDecl *FD) {
723   unsigned ArgIndex = 0;
724   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
725   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
726                                               e = FT->param_type_end();
727        i != e; ++i, ++ArgIndex) {
728     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
729     SourceLocation ParamLoc = PD->getLocation();
730     if (!(*i)->isDependentType() &&
731         SemaRef.RequireLiteralType(ParamLoc, *i,
732                                    diag::err_constexpr_non_literal_param,
733                                    ArgIndex+1, PD->getSourceRange(),
734                                    isa<CXXConstructorDecl>(FD)))
735       return false;
736   }
737   return true;
738 }
739 
740 /// \brief Get diagnostic %select index for tag kind for
741 /// record diagnostic message.
742 /// WARNING: Indexes apply to particular diagnostics only!
743 ///
744 /// \returns diagnostic %select index.
745 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
746   switch (Tag) {
747   case TTK_Struct: return 0;
748   case TTK_Interface: return 1;
749   case TTK_Class:  return 2;
750   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
751   }
752 }
753 
754 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
755 // the requirements of a constexpr function definition or a constexpr
756 // constructor definition. If so, return true. If not, produce appropriate
757 // diagnostics and return false.
758 //
759 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
760 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
761   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
762   if (MD && MD->isInstance()) {
763     // C++11 [dcl.constexpr]p4:
764     //  The definition of a constexpr constructor shall satisfy the following
765     //  constraints:
766     //  - the class shall not have any virtual base classes;
767     const CXXRecordDecl *RD = MD->getParent();
768     if (RD->getNumVBases()) {
769       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
770         << isa<CXXConstructorDecl>(NewFD)
771         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
772       for (const auto &I : RD->vbases())
773         Diag(I.getLocStart(),
774              diag::note_constexpr_virtual_base_here) << I.getSourceRange();
775       return false;
776     }
777   }
778 
779   if (!isa<CXXConstructorDecl>(NewFD)) {
780     // C++11 [dcl.constexpr]p3:
781     //  The definition of a constexpr function shall satisfy the following
782     //  constraints:
783     // - it shall not be virtual;
784     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
785     if (Method && Method->isVirtual()) {
786       Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
787 
788       // If it's not obvious why this function is virtual, find an overridden
789       // function which uses the 'virtual' keyword.
790       const CXXMethodDecl *WrittenVirtual = Method;
791       while (!WrittenVirtual->isVirtualAsWritten())
792         WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
793       if (WrittenVirtual != Method)
794         Diag(WrittenVirtual->getLocation(),
795              diag::note_overridden_virtual_function);
796       return false;
797     }
798 
799     // - its return type shall be a literal type;
800     QualType RT = NewFD->getReturnType();
801     if (!RT->isDependentType() &&
802         RequireLiteralType(NewFD->getLocation(), RT,
803                            diag::err_constexpr_non_literal_return))
804       return false;
805   }
806 
807   // - each of its parameter types shall be a literal type;
808   if (!CheckConstexprParameterTypes(*this, NewFD))
809     return false;
810 
811   return true;
812 }
813 
814 /// Check the given declaration statement is legal within a constexpr function
815 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
816 ///
817 /// \return true if the body is OK (maybe only as an extension), false if we
818 ///         have diagnosed a problem.
819 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
820                                    DeclStmt *DS, SourceLocation &Cxx1yLoc) {
821   // C++11 [dcl.constexpr]p3 and p4:
822   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
823   //  contain only
824   for (const auto *DclIt : DS->decls()) {
825     switch (DclIt->getKind()) {
826     case Decl::StaticAssert:
827     case Decl::Using:
828     case Decl::UsingShadow:
829     case Decl::UsingDirective:
830     case Decl::UnresolvedUsingTypename:
831     case Decl::UnresolvedUsingValue:
832       //   - static_assert-declarations
833       //   - using-declarations,
834       //   - using-directives,
835       continue;
836 
837     case Decl::Typedef:
838     case Decl::TypeAlias: {
839       //   - typedef declarations and alias-declarations that do not define
840       //     classes or enumerations,
841       const auto *TN = cast<TypedefNameDecl>(DclIt);
842       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
843         // Don't allow variably-modified types in constexpr functions.
844         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
845         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
846           << TL.getSourceRange() << TL.getType()
847           << isa<CXXConstructorDecl>(Dcl);
848         return false;
849       }
850       continue;
851     }
852 
853     case Decl::Enum:
854     case Decl::CXXRecord:
855       // C++1y allows types to be defined, not just declared.
856       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
857         SemaRef.Diag(DS->getLocStart(),
858                      SemaRef.getLangOpts().CPlusPlus14
859                        ? diag::warn_cxx11_compat_constexpr_type_definition
860                        : diag::ext_constexpr_type_definition)
861           << isa<CXXConstructorDecl>(Dcl);
862       continue;
863 
864     case Decl::EnumConstant:
865     case Decl::IndirectField:
866     case Decl::ParmVar:
867       // These can only appear with other declarations which are banned in
868       // C++11 and permitted in C++1y, so ignore them.
869       continue;
870 
871     case Decl::Var: {
872       // C++1y [dcl.constexpr]p3 allows anything except:
873       //   a definition of a variable of non-literal type or of static or
874       //   thread storage duration or for which no initialization is performed.
875       const auto *VD = cast<VarDecl>(DclIt);
876       if (VD->isThisDeclarationADefinition()) {
877         if (VD->isStaticLocal()) {
878           SemaRef.Diag(VD->getLocation(),
879                        diag::err_constexpr_local_var_static)
880             << isa<CXXConstructorDecl>(Dcl)
881             << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
882           return false;
883         }
884         if (!VD->getType()->isDependentType() &&
885             SemaRef.RequireLiteralType(
886               VD->getLocation(), VD->getType(),
887               diag::err_constexpr_local_var_non_literal_type,
888               isa<CXXConstructorDecl>(Dcl)))
889           return false;
890         if (!VD->getType()->isDependentType() &&
891             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
892           SemaRef.Diag(VD->getLocation(),
893                        diag::err_constexpr_local_var_no_init)
894             << isa<CXXConstructorDecl>(Dcl);
895           return false;
896         }
897       }
898       SemaRef.Diag(VD->getLocation(),
899                    SemaRef.getLangOpts().CPlusPlus14
900                     ? diag::warn_cxx11_compat_constexpr_local_var
901                     : diag::ext_constexpr_local_var)
902         << isa<CXXConstructorDecl>(Dcl);
903       continue;
904     }
905 
906     case Decl::NamespaceAlias:
907     case Decl::Function:
908       // These are disallowed in C++11 and permitted in C++1y. Allow them
909       // everywhere as an extension.
910       if (!Cxx1yLoc.isValid())
911         Cxx1yLoc = DS->getLocStart();
912       continue;
913 
914     default:
915       SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
916         << isa<CXXConstructorDecl>(Dcl);
917       return false;
918     }
919   }
920 
921   return true;
922 }
923 
924 /// Check that the given field is initialized within a constexpr constructor.
925 ///
926 /// \param Dcl The constexpr constructor being checked.
927 /// \param Field The field being checked. This may be a member of an anonymous
928 ///        struct or union nested within the class being checked.
929 /// \param Inits All declarations, including anonymous struct/union members and
930 ///        indirect members, for which any initialization was provided.
931 /// \param Diagnosed Set to true if an error is produced.
932 static void CheckConstexprCtorInitializer(Sema &SemaRef,
933                                           const FunctionDecl *Dcl,
934                                           FieldDecl *Field,
935                                           llvm::SmallSet<Decl*, 16> &Inits,
936                                           bool &Diagnosed) {
937   if (Field->isInvalidDecl())
938     return;
939 
940   if (Field->isUnnamedBitfield())
941     return;
942 
943   // Anonymous unions with no variant members and empty anonymous structs do not
944   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
945   // indirect fields don't need initializing.
946   if (Field->isAnonymousStructOrUnion() &&
947       (Field->getType()->isUnionType()
948            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
949            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
950     return;
951 
952   if (!Inits.count(Field)) {
953     if (!Diagnosed) {
954       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
955       Diagnosed = true;
956     }
957     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
958   } else if (Field->isAnonymousStructOrUnion()) {
959     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
960     for (auto *I : RD->fields())
961       // If an anonymous union contains an anonymous struct of which any member
962       // is initialized, all members must be initialized.
963       if (!RD->isUnion() || Inits.count(I))
964         CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
965   }
966 }
967 
968 /// Check the provided statement is allowed in a constexpr function
969 /// definition.
970 static bool
971 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
972                            SmallVectorImpl<SourceLocation> &ReturnStmts,
973                            SourceLocation &Cxx1yLoc) {
974   // - its function-body shall be [...] a compound-statement that contains only
975   switch (S->getStmtClass()) {
976   case Stmt::NullStmtClass:
977     //   - null statements,
978     return true;
979 
980   case Stmt::DeclStmtClass:
981     //   - static_assert-declarations
982     //   - using-declarations,
983     //   - using-directives,
984     //   - typedef declarations and alias-declarations that do not define
985     //     classes or enumerations,
986     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
987       return false;
988     return true;
989 
990   case Stmt::ReturnStmtClass:
991     //   - and exactly one return statement;
992     if (isa<CXXConstructorDecl>(Dcl)) {
993       // C++1y allows return statements in constexpr constructors.
994       if (!Cxx1yLoc.isValid())
995         Cxx1yLoc = S->getLocStart();
996       return true;
997     }
998 
999     ReturnStmts.push_back(S->getLocStart());
1000     return true;
1001 
1002   case Stmt::CompoundStmtClass: {
1003     // C++1y allows compound-statements.
1004     if (!Cxx1yLoc.isValid())
1005       Cxx1yLoc = S->getLocStart();
1006 
1007     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1008     for (auto *BodyIt : CompStmt->body()) {
1009       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1010                                       Cxx1yLoc))
1011         return false;
1012     }
1013     return true;
1014   }
1015 
1016   case Stmt::AttributedStmtClass:
1017     if (!Cxx1yLoc.isValid())
1018       Cxx1yLoc = S->getLocStart();
1019     return true;
1020 
1021   case Stmt::IfStmtClass: {
1022     // C++1y allows if-statements.
1023     if (!Cxx1yLoc.isValid())
1024       Cxx1yLoc = S->getLocStart();
1025 
1026     IfStmt *If = cast<IfStmt>(S);
1027     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1028                                     Cxx1yLoc))
1029       return false;
1030     if (If->getElse() &&
1031         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1032                                     Cxx1yLoc))
1033       return false;
1034     return true;
1035   }
1036 
1037   case Stmt::WhileStmtClass:
1038   case Stmt::DoStmtClass:
1039   case Stmt::ForStmtClass:
1040   case Stmt::CXXForRangeStmtClass:
1041   case Stmt::ContinueStmtClass:
1042     // C++1y allows all of these. We don't allow them as extensions in C++11,
1043     // because they don't make sense without variable mutation.
1044     if (!SemaRef.getLangOpts().CPlusPlus14)
1045       break;
1046     if (!Cxx1yLoc.isValid())
1047       Cxx1yLoc = S->getLocStart();
1048     for (Stmt::child_range Children = S->children(); Children; ++Children)
1049       if (*Children &&
1050           !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1051                                       Cxx1yLoc))
1052         return false;
1053     return true;
1054 
1055   case Stmt::SwitchStmtClass:
1056   case Stmt::CaseStmtClass:
1057   case Stmt::DefaultStmtClass:
1058   case Stmt::BreakStmtClass:
1059     // C++1y allows switch-statements, and since they don't need variable
1060     // mutation, we can reasonably allow them in C++11 as an extension.
1061     if (!Cxx1yLoc.isValid())
1062       Cxx1yLoc = S->getLocStart();
1063     for (Stmt::child_range Children = S->children(); Children; ++Children)
1064       if (*Children &&
1065           !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1066                                       Cxx1yLoc))
1067         return false;
1068     return true;
1069 
1070   default:
1071     if (!isa<Expr>(S))
1072       break;
1073 
1074     // C++1y allows expression-statements.
1075     if (!Cxx1yLoc.isValid())
1076       Cxx1yLoc = S->getLocStart();
1077     return true;
1078   }
1079 
1080   SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1081     << isa<CXXConstructorDecl>(Dcl);
1082   return false;
1083 }
1084 
1085 /// Check the body for the given constexpr function declaration only contains
1086 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1087 ///
1088 /// \return true if the body is OK, false if we have diagnosed a problem.
1089 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1090   if (isa<CXXTryStmt>(Body)) {
1091     // C++11 [dcl.constexpr]p3:
1092     //  The definition of a constexpr function shall satisfy the following
1093     //  constraints: [...]
1094     // - its function-body shall be = delete, = default, or a
1095     //   compound-statement
1096     //
1097     // C++11 [dcl.constexpr]p4:
1098     //  In the definition of a constexpr constructor, [...]
1099     // - its function-body shall not be a function-try-block;
1100     Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1101       << isa<CXXConstructorDecl>(Dcl);
1102     return false;
1103   }
1104 
1105   SmallVector<SourceLocation, 4> ReturnStmts;
1106 
1107   // - its function-body shall be [...] a compound-statement that contains only
1108   //   [... list of cases ...]
1109   CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1110   SourceLocation Cxx1yLoc;
1111   for (auto *BodyIt : CompBody->body()) {
1112     if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
1113       return false;
1114   }
1115 
1116   if (Cxx1yLoc.isValid())
1117     Diag(Cxx1yLoc,
1118          getLangOpts().CPlusPlus14
1119            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1120            : diag::ext_constexpr_body_invalid_stmt)
1121       << isa<CXXConstructorDecl>(Dcl);
1122 
1123   if (const CXXConstructorDecl *Constructor
1124         = dyn_cast<CXXConstructorDecl>(Dcl)) {
1125     const CXXRecordDecl *RD = Constructor->getParent();
1126     // DR1359:
1127     // - every non-variant non-static data member and base class sub-object
1128     //   shall be initialized;
1129     // DR1460:
1130     // - if the class is a union having variant members, exactly one of them
1131     //   shall be initialized;
1132     if (RD->isUnion()) {
1133       if (Constructor->getNumCtorInitializers() == 0 &&
1134           RD->hasVariantMembers()) {
1135         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1136         return false;
1137       }
1138     } else if (!Constructor->isDependentContext() &&
1139                !Constructor->isDelegatingConstructor()) {
1140       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1141 
1142       // Skip detailed checking if we have enough initializers, and we would
1143       // allow at most one initializer per member.
1144       bool AnyAnonStructUnionMembers = false;
1145       unsigned Fields = 0;
1146       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1147            E = RD->field_end(); I != E; ++I, ++Fields) {
1148         if (I->isAnonymousStructOrUnion()) {
1149           AnyAnonStructUnionMembers = true;
1150           break;
1151         }
1152       }
1153       // DR1460:
1154       // - if the class is a union-like class, but is not a union, for each of
1155       //   its anonymous union members having variant members, exactly one of
1156       //   them shall be initialized;
1157       if (AnyAnonStructUnionMembers ||
1158           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1159         // Check initialization of non-static data members. Base classes are
1160         // always initialized so do not need to be checked. Dependent bases
1161         // might not have initializers in the member initializer list.
1162         llvm::SmallSet<Decl*, 16> Inits;
1163         for (const auto *I: Constructor->inits()) {
1164           if (FieldDecl *FD = I->getMember())
1165             Inits.insert(FD);
1166           else if (IndirectFieldDecl *ID = I->getIndirectMember())
1167             Inits.insert(ID->chain_begin(), ID->chain_end());
1168         }
1169 
1170         bool Diagnosed = false;
1171         for (auto *I : RD->fields())
1172           CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
1173         if (Diagnosed)
1174           return false;
1175       }
1176     }
1177   } else {
1178     if (ReturnStmts.empty()) {
1179       // C++1y doesn't require constexpr functions to contain a 'return'
1180       // statement. We still do, unless the return type might be void, because
1181       // otherwise if there's no return statement, the function cannot
1182       // be used in a core constant expression.
1183       bool OK = getLangOpts().CPlusPlus14 &&
1184                 (Dcl->getReturnType()->isVoidType() ||
1185                  Dcl->getReturnType()->isDependentType());
1186       Diag(Dcl->getLocation(),
1187            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1188               : diag::err_constexpr_body_no_return);
1189       return OK;
1190     }
1191     if (ReturnStmts.size() > 1) {
1192       Diag(ReturnStmts.back(),
1193            getLangOpts().CPlusPlus14
1194              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1195              : diag::ext_constexpr_body_multiple_return);
1196       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1197         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
1198     }
1199   }
1200 
1201   // C++11 [dcl.constexpr]p5:
1202   //   if no function argument values exist such that the function invocation
1203   //   substitution would produce a constant expression, the program is
1204   //   ill-formed; no diagnostic required.
1205   // C++11 [dcl.constexpr]p3:
1206   //   - every constructor call and implicit conversion used in initializing the
1207   //     return value shall be one of those allowed in a constant expression.
1208   // C++11 [dcl.constexpr]p4:
1209   //   - every constructor involved in initializing non-static data members and
1210   //     base class sub-objects shall be a constexpr constructor.
1211   SmallVector<PartialDiagnosticAt, 8> Diags;
1212   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
1213     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
1214       << isa<CXXConstructorDecl>(Dcl);
1215     for (size_t I = 0, N = Diags.size(); I != N; ++I)
1216       Diag(Diags[I].first, Diags[I].second);
1217     // Don't return false here: we allow this for compatibility in
1218     // system headers.
1219   }
1220 
1221   return true;
1222 }
1223 
1224 /// isCurrentClassName - Determine whether the identifier II is the
1225 /// name of the class type currently being defined. In the case of
1226 /// nested classes, this will only return true if II is the name of
1227 /// the innermost class.
1228 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1229                               const CXXScopeSpec *SS) {
1230   assert(getLangOpts().CPlusPlus && "No class names in C!");
1231 
1232   CXXRecordDecl *CurDecl;
1233   if (SS && SS->isSet() && !SS->isInvalid()) {
1234     DeclContext *DC = computeDeclContext(*SS, true);
1235     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1236   } else
1237     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1238 
1239   if (CurDecl && CurDecl->getIdentifier())
1240     return &II == CurDecl->getIdentifier();
1241   return false;
1242 }
1243 
1244 /// \brief Determine whether the identifier II is a typo for the name of
1245 /// the class type currently being defined. If so, update it to the identifier
1246 /// that should have been used.
1247 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1248   assert(getLangOpts().CPlusPlus && "No class names in C!");
1249 
1250   if (!getLangOpts().SpellChecking)
1251     return false;
1252 
1253   CXXRecordDecl *CurDecl;
1254   if (SS && SS->isSet() && !SS->isInvalid()) {
1255     DeclContext *DC = computeDeclContext(*SS, true);
1256     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1257   } else
1258     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1259 
1260   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1261       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1262           < II->getLength()) {
1263     II = CurDecl->getIdentifier();
1264     return true;
1265   }
1266 
1267   return false;
1268 }
1269 
1270 /// \brief Determine whether the given class is a base class of the given
1271 /// class, including looking at dependent bases.
1272 static bool findCircularInheritance(const CXXRecordDecl *Class,
1273                                     const CXXRecordDecl *Current) {
1274   SmallVector<const CXXRecordDecl*, 8> Queue;
1275 
1276   Class = Class->getCanonicalDecl();
1277   while (true) {
1278     for (const auto &I : Current->bases()) {
1279       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
1280       if (!Base)
1281         continue;
1282 
1283       Base = Base->getDefinition();
1284       if (!Base)
1285         continue;
1286 
1287       if (Base->getCanonicalDecl() == Class)
1288         return true;
1289 
1290       Queue.push_back(Base);
1291     }
1292 
1293     if (Queue.empty())
1294       return false;
1295 
1296     Current = Queue.pop_back_val();
1297   }
1298 
1299   return false;
1300 }
1301 
1302 /// \brief Perform propagation of DLL attributes from a derived class to a
1303 /// templated base class for MS compatibility.
1304 static void propagateDLLAttrToBaseClassTemplate(
1305     Sema &S, CXXRecordDecl *Class, Attr *ClassAttr,
1306     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
1307   if (getDLLAttr(
1308           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
1309     // If the base class template has a DLL attribute, don't try to change it.
1310     return;
1311   }
1312 
1313   if (BaseTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
1314     // If the base class is not already specialized, we can do the propagation.
1315     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
1316     NewAttr->setInherited(true);
1317     BaseTemplateSpec->addAttr(NewAttr);
1318     return;
1319   }
1320 
1321   bool DifferentAttribute = false;
1322   if (Attr *SpecializationAttr = getDLLAttr(BaseTemplateSpec)) {
1323     if (!SpecializationAttr->isInherited()) {
1324       // The template has previously been specialized or instantiated with an
1325       // explicit attribute. We should not try to change it.
1326       return;
1327     }
1328     if (SpecializationAttr->getKind() == ClassAttr->getKind()) {
1329       // The specialization already has the right attribute.
1330       return;
1331     }
1332     DifferentAttribute = true;
1333   }
1334 
1335   // The template was previously instantiated or explicitly specialized without
1336   // a dll attribute, or the template was previously instantiated with a
1337   // different inherited attribute. It's too late for us to change the
1338   // attribute, so warn that this is unsupported.
1339   S.Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
1340       << BaseTemplateSpec->isExplicitSpecialization() << DifferentAttribute;
1341   S.Diag(ClassAttr->getLocation(), diag::note_attribute);
1342   if (BaseTemplateSpec->isExplicitSpecialization()) {
1343     S.Diag(BaseTemplateSpec->getLocation(),
1344            diag::note_template_class_explicit_specialization_was_here)
1345         << BaseTemplateSpec;
1346   } else {
1347     S.Diag(BaseTemplateSpec->getPointOfInstantiation(),
1348            diag::note_template_class_instantiation_was_here)
1349         << BaseTemplateSpec;
1350   }
1351 }
1352 
1353 /// \brief Check the validity of a C++ base class specifier.
1354 ///
1355 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1356 /// and returns NULL otherwise.
1357 CXXBaseSpecifier *
1358 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1359                          SourceRange SpecifierRange,
1360                          bool Virtual, AccessSpecifier Access,
1361                          TypeSourceInfo *TInfo,
1362                          SourceLocation EllipsisLoc) {
1363   QualType BaseType = TInfo->getType();
1364 
1365   // C++ [class.union]p1:
1366   //   A union shall not have base classes.
1367   if (Class->isUnion()) {
1368     Diag(Class->getLocation(), diag::err_base_clause_on_union)
1369       << SpecifierRange;
1370     return nullptr;
1371   }
1372 
1373   if (EllipsisLoc.isValid() &&
1374       !TInfo->getType()->containsUnexpandedParameterPack()) {
1375     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1376       << TInfo->getTypeLoc().getSourceRange();
1377     EllipsisLoc = SourceLocation();
1378   }
1379 
1380   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1381 
1382   if (BaseType->isDependentType()) {
1383     // Make sure that we don't have circular inheritance among our dependent
1384     // bases. For non-dependent bases, the check for completeness below handles
1385     // this.
1386     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1387       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1388           ((BaseDecl = BaseDecl->getDefinition()) &&
1389            findCircularInheritance(Class, BaseDecl))) {
1390         Diag(BaseLoc, diag::err_circular_inheritance)
1391           << BaseType << Context.getTypeDeclType(Class);
1392 
1393         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1394           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1395             << BaseType;
1396 
1397         return nullptr;
1398       }
1399     }
1400 
1401     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1402                                           Class->getTagKind() == TTK_Class,
1403                                           Access, TInfo, EllipsisLoc);
1404   }
1405 
1406   // Base specifiers must be record types.
1407   if (!BaseType->isRecordType()) {
1408     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1409     return nullptr;
1410   }
1411 
1412   // C++ [class.union]p1:
1413   //   A union shall not be used as a base class.
1414   if (BaseType->isUnionType()) {
1415     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1416     return nullptr;
1417   }
1418 
1419   // For the MS ABI, propagate DLL attributes to base class templates.
1420   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1421     if (Attr *ClassAttr = getDLLAttr(Class)) {
1422       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1423               BaseType->getAsCXXRecordDecl())) {
1424         propagateDLLAttrToBaseClassTemplate(*this, Class, ClassAttr,
1425                                             BaseTemplate, BaseLoc);
1426       }
1427     }
1428   }
1429 
1430   // C++ [class.derived]p2:
1431   //   The class-name in a base-specifier shall not be an incompletely
1432   //   defined class.
1433   if (RequireCompleteType(BaseLoc, BaseType,
1434                           diag::err_incomplete_base_class, SpecifierRange)) {
1435     Class->setInvalidDecl();
1436     return nullptr;
1437   }
1438 
1439   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1440   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1441   assert(BaseDecl && "Record type has no declaration");
1442   BaseDecl = BaseDecl->getDefinition();
1443   assert(BaseDecl && "Base type is not incomplete, but has no definition");
1444   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1445   assert(CXXBaseDecl && "Base type is not a C++ type");
1446 
1447   // A class which contains a flexible array member is not suitable for use as a
1448   // base class:
1449   //   - If the layout determines that a base comes before another base,
1450   //     the flexible array member would index into the subsequent base.
1451   //   - If the layout determines that base comes before the derived class,
1452   //     the flexible array member would index into the derived class.
1453   if (CXXBaseDecl->hasFlexibleArrayMember()) {
1454     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1455       << CXXBaseDecl->getDeclName();
1456     return nullptr;
1457   }
1458 
1459   // C++ [class]p3:
1460   //   If a class is marked final and it appears as a base-type-specifier in
1461   //   base-clause, the program is ill-formed.
1462   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
1463     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1464       << CXXBaseDecl->getDeclName()
1465       << FA->isSpelledAsSealed();
1466     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
1467         << CXXBaseDecl->getDeclName() << FA->getRange();
1468     return nullptr;
1469   }
1470 
1471   if (BaseDecl->isInvalidDecl())
1472     Class->setInvalidDecl();
1473 
1474   // Create the base specifier.
1475   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1476                                         Class->getTagKind() == TTK_Class,
1477                                         Access, TInfo, EllipsisLoc);
1478 }
1479 
1480 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1481 /// one entry in the base class list of a class specifier, for
1482 /// example:
1483 ///    class foo : public bar, virtual private baz {
1484 /// 'public bar' and 'virtual private baz' are each base-specifiers.
1485 BaseResult
1486 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1487                          ParsedAttributes &Attributes,
1488                          bool Virtual, AccessSpecifier Access,
1489                          ParsedType basetype, SourceLocation BaseLoc,
1490                          SourceLocation EllipsisLoc) {
1491   if (!classdecl)
1492     return true;
1493 
1494   AdjustDeclIfTemplate(classdecl);
1495   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1496   if (!Class)
1497     return true;
1498 
1499   // We haven't yet attached the base specifiers.
1500   Class->setIsParsingBaseSpecifiers();
1501 
1502   // We do not support any C++11 attributes on base-specifiers yet.
1503   // Diagnose any attributes we see.
1504   if (!Attributes.empty()) {
1505     for (AttributeList *Attr = Attributes.getList(); Attr;
1506          Attr = Attr->getNext()) {
1507       if (Attr->isInvalid() ||
1508           Attr->getKind() == AttributeList::IgnoredAttribute)
1509         continue;
1510       Diag(Attr->getLoc(),
1511            Attr->getKind() == AttributeList::UnknownAttribute
1512              ? diag::warn_unknown_attribute_ignored
1513              : diag::err_base_specifier_attribute)
1514         << Attr->getName();
1515     }
1516   }
1517 
1518   TypeSourceInfo *TInfo = nullptr;
1519   GetTypeFromParser(basetype, &TInfo);
1520 
1521   if (EllipsisLoc.isInvalid() &&
1522       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1523                                       UPPC_BaseType))
1524     return true;
1525 
1526   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1527                                                       Virtual, Access, TInfo,
1528                                                       EllipsisLoc))
1529     return BaseSpec;
1530   else
1531     Class->setInvalidDecl();
1532 
1533   return true;
1534 }
1535 
1536 /// \brief Performs the actual work of attaching the given base class
1537 /// specifiers to a C++ class.
1538 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1539                                 unsigned NumBases) {
1540  if (NumBases == 0)
1541     return false;
1542 
1543   // Used to keep track of which base types we have already seen, so
1544   // that we can properly diagnose redundant direct base types. Note
1545   // that the key is always the unqualified canonical type of the base
1546   // class.
1547   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1548 
1549   // Copy non-redundant base specifiers into permanent storage.
1550   unsigned NumGoodBases = 0;
1551   bool Invalid = false;
1552   for (unsigned idx = 0; idx < NumBases; ++idx) {
1553     QualType NewBaseType
1554       = Context.getCanonicalType(Bases[idx]->getType());
1555     NewBaseType = NewBaseType.getLocalUnqualifiedType();
1556 
1557     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1558     if (KnownBase) {
1559       // C++ [class.mi]p3:
1560       //   A class shall not be specified as a direct base class of a
1561       //   derived class more than once.
1562       Diag(Bases[idx]->getLocStart(),
1563            diag::err_duplicate_base_class)
1564         << KnownBase->getType()
1565         << Bases[idx]->getSourceRange();
1566 
1567       // Delete the duplicate base class specifier; we're going to
1568       // overwrite its pointer later.
1569       Context.Deallocate(Bases[idx]);
1570 
1571       Invalid = true;
1572     } else {
1573       // Okay, add this new base class.
1574       KnownBase = Bases[idx];
1575       Bases[NumGoodBases++] = Bases[idx];
1576       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1577         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1578         if (Class->isInterface() &&
1579               (!RD->isInterface() ||
1580                KnownBase->getAccessSpecifier() != AS_public)) {
1581           // The Microsoft extension __interface does not permit bases that
1582           // are not themselves public interfaces.
1583           Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1584             << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1585             << RD->getSourceRange();
1586           Invalid = true;
1587         }
1588         if (RD->hasAttr<WeakAttr>())
1589           Class->addAttr(WeakAttr::CreateImplicit(Context));
1590       }
1591     }
1592   }
1593 
1594   // Attach the remaining base class specifiers to the derived class.
1595   Class->setBases(Bases, NumGoodBases);
1596 
1597   // Delete the remaining (good) base class specifiers, since their
1598   // data has been copied into the CXXRecordDecl.
1599   for (unsigned idx = 0; idx < NumGoodBases; ++idx)
1600     Context.Deallocate(Bases[idx]);
1601 
1602   return Invalid;
1603 }
1604 
1605 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
1606 /// class, after checking whether there are any duplicate base
1607 /// classes.
1608 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
1609                                unsigned NumBases) {
1610   if (!ClassDecl || !Bases || !NumBases)
1611     return;
1612 
1613   AdjustDeclIfTemplate(ClassDecl);
1614   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
1615 }
1616 
1617 /// \brief Determine whether the type \p Derived is a C++ class that is
1618 /// derived from the type \p Base.
1619 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1620   if (!getLangOpts().CPlusPlus)
1621     return false;
1622 
1623   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1624   if (!DerivedRD)
1625     return false;
1626 
1627   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1628   if (!BaseRD)
1629     return false;
1630 
1631   // If either the base or the derived type is invalid, don't try to
1632   // check whether one is derived from the other.
1633   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1634     return false;
1635 
1636   // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
1637   return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
1638 }
1639 
1640 /// \brief Determine whether the type \p Derived is a C++ class that is
1641 /// derived from the type \p Base.
1642 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1643   if (!getLangOpts().CPlusPlus)
1644     return false;
1645 
1646   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1647   if (!DerivedRD)
1648     return false;
1649 
1650   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1651   if (!BaseRD)
1652     return false;
1653 
1654   return DerivedRD->isDerivedFrom(BaseRD, Paths);
1655 }
1656 
1657 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1658                               CXXCastPath &BasePathArray) {
1659   assert(BasePathArray.empty() && "Base path array must be empty!");
1660   assert(Paths.isRecordingPaths() && "Must record paths!");
1661 
1662   const CXXBasePath &Path = Paths.front();
1663 
1664   // We first go backward and check if we have a virtual base.
1665   // FIXME: It would be better if CXXBasePath had the base specifier for
1666   // the nearest virtual base.
1667   unsigned Start = 0;
1668   for (unsigned I = Path.size(); I != 0; --I) {
1669     if (Path[I - 1].Base->isVirtual()) {
1670       Start = I - 1;
1671       break;
1672     }
1673   }
1674 
1675   // Now add all bases.
1676   for (unsigned I = Start, E = Path.size(); I != E; ++I)
1677     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1678 }
1679 
1680 /// \brief Determine whether the given base path includes a virtual
1681 /// base class.
1682 bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1683   for (CXXCastPath::const_iterator B = BasePath.begin(),
1684                                 BEnd = BasePath.end();
1685        B != BEnd; ++B)
1686     if ((*B)->isVirtual())
1687       return true;
1688 
1689   return false;
1690 }
1691 
1692 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1693 /// conversion (where Derived and Base are class types) is
1694 /// well-formed, meaning that the conversion is unambiguous (and
1695 /// that all of the base classes are accessible). Returns true
1696 /// and emits a diagnostic if the code is ill-formed, returns false
1697 /// otherwise. Loc is the location where this routine should point to
1698 /// if there is an error, and Range is the source range to highlight
1699 /// if there is an error.
1700 bool
1701 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1702                                    unsigned InaccessibleBaseID,
1703                                    unsigned AmbigiousBaseConvID,
1704                                    SourceLocation Loc, SourceRange Range,
1705                                    DeclarationName Name,
1706                                    CXXCastPath *BasePath) {
1707   // First, determine whether the path from Derived to Base is
1708   // ambiguous. This is slightly more expensive than checking whether
1709   // the Derived to Base conversion exists, because here we need to
1710   // explore multiple paths to determine if there is an ambiguity.
1711   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1712                      /*DetectVirtual=*/false);
1713   bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1714   assert(DerivationOkay &&
1715          "Can only be used with a derived-to-base conversion");
1716   (void)DerivationOkay;
1717 
1718   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1719     if (InaccessibleBaseID) {
1720       // Check that the base class can be accessed.
1721       switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1722                                    InaccessibleBaseID)) {
1723         case AR_inaccessible:
1724           return true;
1725         case AR_accessible:
1726         case AR_dependent:
1727         case AR_delayed:
1728           break;
1729       }
1730     }
1731 
1732     // Build a base path if necessary.
1733     if (BasePath)
1734       BuildBasePathArray(Paths, *BasePath);
1735     return false;
1736   }
1737 
1738   if (AmbigiousBaseConvID) {
1739     // We know that the derived-to-base conversion is ambiguous, and
1740     // we're going to produce a diagnostic. Perform the derived-to-base
1741     // search just one more time to compute all of the possible paths so
1742     // that we can print them out. This is more expensive than any of
1743     // the previous derived-to-base checks we've done, but at this point
1744     // performance isn't as much of an issue.
1745     Paths.clear();
1746     Paths.setRecordingPaths(true);
1747     bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1748     assert(StillOkay && "Can only be used with a derived-to-base conversion");
1749     (void)StillOkay;
1750 
1751     // Build up a textual representation of the ambiguous paths, e.g.,
1752     // D -> B -> A, that will be used to illustrate the ambiguous
1753     // conversions in the diagnostic. We only print one of the paths
1754     // to each base class subobject.
1755     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1756 
1757     Diag(Loc, AmbigiousBaseConvID)
1758     << Derived << Base << PathDisplayStr << Range << Name;
1759   }
1760   return true;
1761 }
1762 
1763 bool
1764 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1765                                    SourceLocation Loc, SourceRange Range,
1766                                    CXXCastPath *BasePath,
1767                                    bool IgnoreAccess) {
1768   return CheckDerivedToBaseConversion(Derived, Base,
1769                                       IgnoreAccess ? 0
1770                                        : diag::err_upcast_to_inaccessible_base,
1771                                       diag::err_ambiguous_derived_to_base_conv,
1772                                       Loc, Range, DeclarationName(),
1773                                       BasePath);
1774 }
1775 
1776 
1777 /// @brief Builds a string representing ambiguous paths from a
1778 /// specific derived class to different subobjects of the same base
1779 /// class.
1780 ///
1781 /// This function builds a string that can be used in error messages
1782 /// to show the different paths that one can take through the
1783 /// inheritance hierarchy to go from the derived class to different
1784 /// subobjects of a base class. The result looks something like this:
1785 /// @code
1786 /// struct D -> struct B -> struct A
1787 /// struct D -> struct C -> struct A
1788 /// @endcode
1789 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1790   std::string PathDisplayStr;
1791   std::set<unsigned> DisplayedPaths;
1792   for (CXXBasePaths::paths_iterator Path = Paths.begin();
1793        Path != Paths.end(); ++Path) {
1794     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1795       // We haven't displayed a path to this particular base
1796       // class subobject yet.
1797       PathDisplayStr += "\n    ";
1798       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1799       for (CXXBasePath::const_iterator Element = Path->begin();
1800            Element != Path->end(); ++Element)
1801         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1802     }
1803   }
1804 
1805   return PathDisplayStr;
1806 }
1807 
1808 //===----------------------------------------------------------------------===//
1809 // C++ class member Handling
1810 //===----------------------------------------------------------------------===//
1811 
1812 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1813 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1814                                 SourceLocation ASLoc,
1815                                 SourceLocation ColonLoc,
1816                                 AttributeList *Attrs) {
1817   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1818   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1819                                                   ASLoc, ColonLoc);
1820   CurContext->addHiddenDecl(ASDecl);
1821   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1822 }
1823 
1824 /// CheckOverrideControl - Check C++11 override control semantics.
1825 void Sema::CheckOverrideControl(NamedDecl *D) {
1826   if (D->isInvalidDecl())
1827     return;
1828 
1829   // We only care about "override" and "final" declarations.
1830   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1831     return;
1832 
1833   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1834 
1835   // We can't check dependent instance methods.
1836   if (MD && MD->isInstance() &&
1837       (MD->getParent()->hasAnyDependentBases() ||
1838        MD->getType()->isDependentType()))
1839     return;
1840 
1841   if (MD && !MD->isVirtual()) {
1842     // If we have a non-virtual method, check if if hides a virtual method.
1843     // (In that case, it's most likely the method has the wrong type.)
1844     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1845     FindHiddenVirtualMethods(MD, OverloadedMethods);
1846 
1847     if (!OverloadedMethods.empty()) {
1848       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1849         Diag(OA->getLocation(),
1850              diag::override_keyword_hides_virtual_member_function)
1851           << "override" << (OverloadedMethods.size() > 1);
1852       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1853         Diag(FA->getLocation(),
1854              diag::override_keyword_hides_virtual_member_function)
1855           << (FA->isSpelledAsSealed() ? "sealed" : "final")
1856           << (OverloadedMethods.size() > 1);
1857       }
1858       NoteHiddenVirtualMethods(MD, OverloadedMethods);
1859       MD->setInvalidDecl();
1860       return;
1861     }
1862     // Fall through into the general case diagnostic.
1863     // FIXME: We might want to attempt typo correction here.
1864   }
1865 
1866   if (!MD || !MD->isVirtual()) {
1867     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1868       Diag(OA->getLocation(),
1869            diag::override_keyword_only_allowed_on_virtual_member_functions)
1870         << "override" << FixItHint::CreateRemoval(OA->getLocation());
1871       D->dropAttr<OverrideAttr>();
1872     }
1873     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1874       Diag(FA->getLocation(),
1875            diag::override_keyword_only_allowed_on_virtual_member_functions)
1876         << (FA->isSpelledAsSealed() ? "sealed" : "final")
1877         << FixItHint::CreateRemoval(FA->getLocation());
1878       D->dropAttr<FinalAttr>();
1879     }
1880     return;
1881   }
1882 
1883   // C++11 [class.virtual]p5:
1884   //   If a virtual function is marked with the virt-specifier override and
1885   //   does not override a member function of a base class, the program is
1886   //   ill-formed.
1887   bool HasOverriddenMethods =
1888     MD->begin_overridden_methods() != MD->end_overridden_methods();
1889   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1890     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1891       << MD->getDeclName();
1892 }
1893 
1894 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1895 /// function overrides a virtual member function marked 'final', according to
1896 /// C++11 [class.virtual]p4.
1897 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1898                                                   const CXXMethodDecl *Old) {
1899   FinalAttr *FA = Old->getAttr<FinalAttr>();
1900   if (!FA)
1901     return false;
1902 
1903   Diag(New->getLocation(), diag::err_final_function_overridden)
1904     << New->getDeclName()
1905     << FA->isSpelledAsSealed();
1906   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1907   return true;
1908 }
1909 
1910 static bool InitializationHasSideEffects(const FieldDecl &FD) {
1911   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1912   // FIXME: Destruction of ObjC lifetime types has side-effects.
1913   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1914     return !RD->isCompleteDefinition() ||
1915            !RD->hasTrivialDefaultConstructor() ||
1916            !RD->hasTrivialDestructor();
1917   return false;
1918 }
1919 
1920 static AttributeList *getMSPropertyAttr(AttributeList *list) {
1921   for (AttributeList *it = list; it != nullptr; it = it->getNext())
1922     if (it->isDeclspecPropertyAttribute())
1923       return it;
1924   return nullptr;
1925 }
1926 
1927 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1928 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1929 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
1930 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1931 /// present (but parsing it has been deferred).
1932 NamedDecl *
1933 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1934                                MultiTemplateParamsArg TemplateParameterLists,
1935                                Expr *BW, const VirtSpecifiers &VS,
1936                                InClassInitStyle InitStyle) {
1937   const DeclSpec &DS = D.getDeclSpec();
1938   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1939   DeclarationName Name = NameInfo.getName();
1940   SourceLocation Loc = NameInfo.getLoc();
1941 
1942   // For anonymous bitfields, the location should point to the type.
1943   if (Loc.isInvalid())
1944     Loc = D.getLocStart();
1945 
1946   Expr *BitWidth = static_cast<Expr*>(BW);
1947 
1948   assert(isa<CXXRecordDecl>(CurContext));
1949   assert(!DS.isFriendSpecified());
1950 
1951   bool isFunc = D.isDeclarationOfFunction();
1952 
1953   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1954     // The Microsoft extension __interface only permits public member functions
1955     // and prohibits constructors, destructors, operators, non-public member
1956     // functions, static methods and data members.
1957     unsigned InvalidDecl;
1958     bool ShowDeclName = true;
1959     if (!isFunc)
1960       InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1961     else if (AS != AS_public)
1962       InvalidDecl = 2;
1963     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1964       InvalidDecl = 3;
1965     else switch (Name.getNameKind()) {
1966       case DeclarationName::CXXConstructorName:
1967         InvalidDecl = 4;
1968         ShowDeclName = false;
1969         break;
1970 
1971       case DeclarationName::CXXDestructorName:
1972         InvalidDecl = 5;
1973         ShowDeclName = false;
1974         break;
1975 
1976       case DeclarationName::CXXOperatorName:
1977       case DeclarationName::CXXConversionFunctionName:
1978         InvalidDecl = 6;
1979         break;
1980 
1981       default:
1982         InvalidDecl = 0;
1983         break;
1984     }
1985 
1986     if (InvalidDecl) {
1987       if (ShowDeclName)
1988         Diag(Loc, diag::err_invalid_member_in_interface)
1989           << (InvalidDecl-1) << Name;
1990       else
1991         Diag(Loc, diag::err_invalid_member_in_interface)
1992           << (InvalidDecl-1) << "";
1993       return nullptr;
1994     }
1995   }
1996 
1997   // C++ 9.2p6: A member shall not be declared to have automatic storage
1998   // duration (auto, register) or with the extern storage-class-specifier.
1999   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2000   // data members and cannot be applied to names declared const or static,
2001   // and cannot be applied to reference members.
2002   switch (DS.getStorageClassSpec()) {
2003   case DeclSpec::SCS_unspecified:
2004   case DeclSpec::SCS_typedef:
2005   case DeclSpec::SCS_static:
2006     break;
2007   case DeclSpec::SCS_mutable:
2008     if (isFunc) {
2009       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2010 
2011       // FIXME: It would be nicer if the keyword was ignored only for this
2012       // declarator. Otherwise we could get follow-up errors.
2013       D.getMutableDeclSpec().ClearStorageClassSpecs();
2014     }
2015     break;
2016   default:
2017     Diag(DS.getStorageClassSpecLoc(),
2018          diag::err_storageclass_invalid_for_member);
2019     D.getMutableDeclSpec().ClearStorageClassSpecs();
2020     break;
2021   }
2022 
2023   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2024                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
2025                       !isFunc);
2026 
2027   if (DS.isConstexprSpecified() && isInstField) {
2028     SemaDiagnosticBuilder B =
2029         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2030     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2031     if (InitStyle == ICIS_NoInit) {
2032       B << 0 << 0;
2033       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2034         B << FixItHint::CreateRemoval(ConstexprLoc);
2035       else {
2036         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2037         D.getMutableDeclSpec().ClearConstexprSpec();
2038         const char *PrevSpec;
2039         unsigned DiagID;
2040         bool Failed = D.getMutableDeclSpec().SetTypeQual(
2041             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2042         (void)Failed;
2043         assert(!Failed && "Making a constexpr member const shouldn't fail");
2044       }
2045     } else {
2046       B << 1;
2047       const char *PrevSpec;
2048       unsigned DiagID;
2049       if (D.getMutableDeclSpec().SetStorageClassSpec(
2050           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2051           Context.getPrintingPolicy())) {
2052         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
2053                "This is the only DeclSpec that should fail to be applied");
2054         B << 1;
2055       } else {
2056         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2057         isInstField = false;
2058       }
2059     }
2060   }
2061 
2062   NamedDecl *Member;
2063   if (isInstField) {
2064     CXXScopeSpec &SS = D.getCXXScopeSpec();
2065 
2066     // Data members must have identifiers for names.
2067     if (!Name.isIdentifier()) {
2068       Diag(Loc, diag::err_bad_variable_name)
2069         << Name;
2070       return nullptr;
2071     }
2072 
2073     IdentifierInfo *II = Name.getAsIdentifierInfo();
2074 
2075     // Member field could not be with "template" keyword.
2076     // So TemplateParameterLists should be empty in this case.
2077     if (TemplateParameterLists.size()) {
2078       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
2079       if (TemplateParams->size()) {
2080         // There is no such thing as a member field template.
2081         Diag(D.getIdentifierLoc(), diag::err_template_member)
2082             << II
2083             << SourceRange(TemplateParams->getTemplateLoc(),
2084                 TemplateParams->getRAngleLoc());
2085       } else {
2086         // There is an extraneous 'template<>' for this member.
2087         Diag(TemplateParams->getTemplateLoc(),
2088             diag::err_template_member_noparams)
2089             << II
2090             << SourceRange(TemplateParams->getTemplateLoc(),
2091                 TemplateParams->getRAngleLoc());
2092       }
2093       return nullptr;
2094     }
2095 
2096     if (SS.isSet() && !SS.isInvalid()) {
2097       // The user provided a superfluous scope specifier inside a class
2098       // definition:
2099       //
2100       // class X {
2101       //   int X::member;
2102       // };
2103       if (DeclContext *DC = computeDeclContext(SS, false))
2104         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
2105       else
2106         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2107           << Name << SS.getRange();
2108 
2109       SS.clear();
2110     }
2111 
2112     AttributeList *MSPropertyAttr =
2113       getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
2114     if (MSPropertyAttr) {
2115       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2116                                 BitWidth, InitStyle, AS, MSPropertyAttr);
2117       if (!Member)
2118         return nullptr;
2119       isInstField = false;
2120     } else {
2121       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2122                                 BitWidth, InitStyle, AS);
2123       assert(Member && "HandleField never returns null");
2124     }
2125   } else {
2126     assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2127 
2128     Member = HandleDeclarator(S, D, TemplateParameterLists);
2129     if (!Member)
2130       return nullptr;
2131 
2132     // Non-instance-fields can't have a bitfield.
2133     if (BitWidth) {
2134       if (Member->isInvalidDecl()) {
2135         // don't emit another diagnostic.
2136       } else if (isa<VarDecl>(Member)) {
2137         // C++ 9.6p3: A bit-field shall not be a static member.
2138         // "static member 'A' cannot be a bit-field"
2139         Diag(Loc, diag::err_static_not_bitfield)
2140           << Name << BitWidth->getSourceRange();
2141       } else if (isa<TypedefDecl>(Member)) {
2142         // "typedef member 'x' cannot be a bit-field"
2143         Diag(Loc, diag::err_typedef_not_bitfield)
2144           << Name << BitWidth->getSourceRange();
2145       } else {
2146         // A function typedef ("typedef int f(); f a;").
2147         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2148         Diag(Loc, diag::err_not_integral_type_bitfield)
2149           << Name << cast<ValueDecl>(Member)->getType()
2150           << BitWidth->getSourceRange();
2151       }
2152 
2153       BitWidth = nullptr;
2154       Member->setInvalidDecl();
2155     }
2156 
2157     Member->setAccess(AS);
2158 
2159     // If we have declared a member function template or static data member
2160     // template, set the access of the templated declaration as well.
2161     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2162       FunTmpl->getTemplatedDecl()->setAccess(AS);
2163     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2164       VarTmpl->getTemplatedDecl()->setAccess(AS);
2165   }
2166 
2167   if (VS.isOverrideSpecified())
2168     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
2169   if (VS.isFinalSpecified())
2170     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2171                                             VS.isFinalSpelledSealed()));
2172 
2173   if (VS.getLastLocation().isValid()) {
2174     // Update the end location of a method that has a virt-specifiers.
2175     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2176       MD->setRangeEnd(VS.getLastLocation());
2177   }
2178 
2179   CheckOverrideControl(Member);
2180 
2181   assert((Name || isInstField) && "No identifier for non-field ?");
2182 
2183   if (isInstField) {
2184     FieldDecl *FD = cast<FieldDecl>(Member);
2185     FieldCollector->Add(FD);
2186 
2187     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
2188       // Remember all explicit private FieldDecls that have a name, no side
2189       // effects and are not part of a dependent type declaration.
2190       if (!FD->isImplicit() && FD->getDeclName() &&
2191           FD->getAccess() == AS_private &&
2192           !FD->hasAttr<UnusedAttr>() &&
2193           !FD->getParent()->isDependentContext() &&
2194           !InitializationHasSideEffects(*FD))
2195         UnusedPrivateFields.insert(FD);
2196     }
2197   }
2198 
2199   return Member;
2200 }
2201 
2202 namespace {
2203   class UninitializedFieldVisitor
2204       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2205     Sema &S;
2206     // List of Decls to generate a warning on.  Also remove Decls that become
2207     // initialized.
2208     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
2209     // If non-null, add a note to the warning pointing back to the constructor.
2210     const CXXConstructorDecl *Constructor;
2211   public:
2212     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2213     UninitializedFieldVisitor(Sema &S,
2214                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
2215                               const CXXConstructorDecl *Constructor)
2216       : Inherited(S.Context), S(S), Decls(Decls),
2217         Constructor(Constructor) { }
2218 
2219     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) {
2220       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2221         return;
2222 
2223       // FieldME is the inner-most MemberExpr that is not an anonymous struct
2224       // or union.
2225       MemberExpr *FieldME = ME;
2226 
2227       Expr *Base = ME;
2228       while (isa<MemberExpr>(Base)) {
2229         ME = cast<MemberExpr>(Base);
2230 
2231         if (isa<VarDecl>(ME->getMemberDecl()))
2232           return;
2233 
2234         if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2235           if (!FD->isAnonymousStructOrUnion())
2236             FieldME = ME;
2237 
2238         Base = ME->getBase();
2239       }
2240 
2241       if (!isa<CXXThisExpr>(Base))
2242         return;
2243 
2244       ValueDecl* FoundVD = FieldME->getMemberDecl();
2245 
2246       if (!Decls.count(FoundVD))
2247         return;
2248 
2249       const bool IsReference = FoundVD->getType()->isReferenceType();
2250 
2251       // Prevent double warnings on use of unbounded references.
2252       if (IsReference != CheckReferenceOnly)
2253         return;
2254 
2255       unsigned diag = IsReference
2256           ? diag::warn_reference_field_is_uninit
2257           : diag::warn_field_is_uninit;
2258       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2259       if (Constructor)
2260         S.Diag(Constructor->getLocation(),
2261                diag::note_uninit_in_this_constructor)
2262           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2263 
2264     }
2265 
2266     void HandleValue(Expr *E) {
2267       E = E->IgnoreParens();
2268 
2269       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2270         HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
2271         return;
2272       }
2273 
2274       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2275         HandleValue(CO->getTrueExpr());
2276         HandleValue(CO->getFalseExpr());
2277         return;
2278       }
2279 
2280       if (BinaryConditionalOperator *BCO =
2281               dyn_cast<BinaryConditionalOperator>(E)) {
2282         HandleValue(BCO->getCommon());
2283         HandleValue(BCO->getFalseExpr());
2284         return;
2285       }
2286 
2287       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2288         switch (BO->getOpcode()) {
2289         default:
2290           return;
2291         case(BO_PtrMemD):
2292         case(BO_PtrMemI):
2293           HandleValue(BO->getLHS());
2294           return;
2295         case(BO_Comma):
2296           HandleValue(BO->getRHS());
2297           return;
2298         }
2299       }
2300     }
2301 
2302     void VisitMemberExpr(MemberExpr *ME) {
2303       // All uses of unbounded reference fields will warn.
2304       HandleMemberExpr(ME, true /*CheckReferenceOnly*/);
2305 
2306       Inherited::VisitMemberExpr(ME);
2307     }
2308 
2309     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2310       if (E->getCastKind() == CK_LValueToRValue)
2311         HandleValue(E->getSubExpr());
2312 
2313       Inherited::VisitImplicitCastExpr(E);
2314     }
2315 
2316     void VisitCXXConstructExpr(CXXConstructExpr *E) {
2317       if (E->getConstructor()->isCopyConstructor()) {
2318         Expr *ArgExpr = E->getArg(0);
2319         if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) {
2320           if (ICE->getCastKind() == CK_NoOp) {
2321             ArgExpr = ICE->getSubExpr();
2322           }
2323         }
2324 
2325         if (MemberExpr *ME = dyn_cast<MemberExpr>(ArgExpr)) {
2326           HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
2327         }
2328       }
2329       Inherited::VisitCXXConstructExpr(E);
2330     }
2331 
2332     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2333       Expr *Callee = E->getCallee();
2334       if (isa<MemberExpr>(Callee))
2335         HandleValue(Callee);
2336 
2337       Inherited::VisitCXXMemberCallExpr(E);
2338     }
2339 
2340     void VisitBinaryOperator(BinaryOperator *E) {
2341       // If a field assignment is detected, remove the field from the
2342       // uninitiailized field set.
2343       if (E->getOpcode() == BO_Assign)
2344         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2345           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2346             if (!FD->getType()->isReferenceType())
2347               Decls.erase(FD);
2348 
2349       Inherited::VisitBinaryOperator(E);
2350     }
2351   };
2352   static void CheckInitExprContainsUninitializedFields(
2353       Sema &S, Expr *E, llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
2354       const CXXConstructorDecl *Constructor) {
2355     if (Decls.size() == 0)
2356       return;
2357 
2358     if (!E)
2359       return;
2360 
2361     if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(E)) {
2362       E = Default->getExpr();
2363       if (!E)
2364         return;
2365       // In class initializers will point to the constructor.
2366       UninitializedFieldVisitor(S, Decls, Constructor).Visit(E);
2367     } else {
2368       UninitializedFieldVisitor(S, Decls, nullptr).Visit(E);
2369     }
2370   }
2371 
2372   // Diagnose value-uses of fields to initialize themselves, e.g.
2373   //   foo(foo)
2374   // where foo is not also a parameter to the constructor.
2375   // Also diagnose across field uninitialized use such as
2376   //   x(y), y(x)
2377   // TODO: implement -Wuninitialized and fold this into that framework.
2378   static void DiagnoseUninitializedFields(
2379       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2380 
2381     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
2382                                            Constructor->getLocation())) {
2383       return;
2384     }
2385 
2386     if (Constructor->isInvalidDecl())
2387       return;
2388 
2389     const CXXRecordDecl *RD = Constructor->getParent();
2390 
2391     // Holds fields that are uninitialized.
2392     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2393 
2394     // At the beginning, all fields are uninitialized.
2395     for (auto *I : RD->decls()) {
2396       if (auto *FD = dyn_cast<FieldDecl>(I)) {
2397         UninitializedFields.insert(FD);
2398       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
2399         UninitializedFields.insert(IFD->getAnonField());
2400       }
2401     }
2402 
2403     for (const auto *FieldInit : Constructor->inits()) {
2404       Expr *InitExpr = FieldInit->getInit();
2405 
2406       CheckInitExprContainsUninitializedFields(
2407           SemaRef, InitExpr, UninitializedFields, Constructor);
2408 
2409       if (FieldDecl *Field = FieldInit->getAnyMember())
2410         UninitializedFields.erase(Field);
2411     }
2412   }
2413 } // namespace
2414 
2415 /// \brief Enter a new C++ default initializer scope. After calling this, the
2416 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2417 /// parsing or instantiating the initializer failed.
2418 void Sema::ActOnStartCXXInClassMemberInitializer() {
2419   // Create a synthetic function scope to represent the call to the constructor
2420   // that notionally surrounds a use of this initializer.
2421   PushFunctionScope();
2422 }
2423 
2424 /// \brief This is invoked after parsing an in-class initializer for a
2425 /// non-static C++ class member, and after instantiating an in-class initializer
2426 /// in a class template. Such actions are deferred until the class is complete.
2427 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2428                                                   SourceLocation InitLoc,
2429                                                   Expr *InitExpr) {
2430   // Pop the notional constructor scope we created earlier.
2431   PopFunctionScopeInfo(nullptr, D);
2432 
2433   FieldDecl *FD = cast<FieldDecl>(D);
2434   assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2435          "must set init style when field is created");
2436 
2437   if (!InitExpr) {
2438     FD->setInvalidDecl();
2439     FD->removeInClassInitializer();
2440     return;
2441   }
2442 
2443   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2444     FD->setInvalidDecl();
2445     FD->removeInClassInitializer();
2446     return;
2447   }
2448 
2449   ExprResult Init = InitExpr;
2450   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
2451     InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
2452     InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
2453         ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
2454         : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
2455     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2456     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
2457     if (Init.isInvalid()) {
2458       FD->setInvalidDecl();
2459       return;
2460     }
2461   }
2462 
2463   // C++11 [class.base.init]p7:
2464   //   The initialization of each base and member constitutes a
2465   //   full-expression.
2466   Init = ActOnFinishFullExpr(Init.get(), InitLoc);
2467   if (Init.isInvalid()) {
2468     FD->setInvalidDecl();
2469     return;
2470   }
2471 
2472   InitExpr = Init.get();
2473 
2474   FD->setInClassInitializer(InitExpr);
2475 }
2476 
2477 /// \brief Find the direct and/or virtual base specifiers that
2478 /// correspond to the given base type, for use in base initialization
2479 /// within a constructor.
2480 static bool FindBaseInitializer(Sema &SemaRef,
2481                                 CXXRecordDecl *ClassDecl,
2482                                 QualType BaseType,
2483                                 const CXXBaseSpecifier *&DirectBaseSpec,
2484                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
2485   // First, check for a direct base class.
2486   DirectBaseSpec = nullptr;
2487   for (const auto &Base : ClassDecl->bases()) {
2488     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
2489       // We found a direct base of this type. That's what we're
2490       // initializing.
2491       DirectBaseSpec = &Base;
2492       break;
2493     }
2494   }
2495 
2496   // Check for a virtual base class.
2497   // FIXME: We might be able to short-circuit this if we know in advance that
2498   // there are no virtual bases.
2499   VirtualBaseSpec = nullptr;
2500   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2501     // We haven't found a base yet; search the class hierarchy for a
2502     // virtual base class.
2503     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2504                        /*DetectVirtual=*/false);
2505     if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2506                               BaseType, Paths)) {
2507       for (CXXBasePaths::paths_iterator Path = Paths.begin();
2508            Path != Paths.end(); ++Path) {
2509         if (Path->back().Base->isVirtual()) {
2510           VirtualBaseSpec = Path->back().Base;
2511           break;
2512         }
2513       }
2514     }
2515   }
2516 
2517   return DirectBaseSpec || VirtualBaseSpec;
2518 }
2519 
2520 /// \brief Handle a C++ member initializer using braced-init-list syntax.
2521 MemInitResult
2522 Sema::ActOnMemInitializer(Decl *ConstructorD,
2523                           Scope *S,
2524                           CXXScopeSpec &SS,
2525                           IdentifierInfo *MemberOrBase,
2526                           ParsedType TemplateTypeTy,
2527                           const DeclSpec &DS,
2528                           SourceLocation IdLoc,
2529                           Expr *InitList,
2530                           SourceLocation EllipsisLoc) {
2531   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2532                              DS, IdLoc, InitList,
2533                              EllipsisLoc);
2534 }
2535 
2536 /// \brief Handle a C++ member initializer using parentheses syntax.
2537 MemInitResult
2538 Sema::ActOnMemInitializer(Decl *ConstructorD,
2539                           Scope *S,
2540                           CXXScopeSpec &SS,
2541                           IdentifierInfo *MemberOrBase,
2542                           ParsedType TemplateTypeTy,
2543                           const DeclSpec &DS,
2544                           SourceLocation IdLoc,
2545                           SourceLocation LParenLoc,
2546                           ArrayRef<Expr *> Args,
2547                           SourceLocation RParenLoc,
2548                           SourceLocation EllipsisLoc) {
2549   Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2550                                            Args, RParenLoc);
2551   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2552                              DS, IdLoc, List, EllipsisLoc);
2553 }
2554 
2555 namespace {
2556 
2557 // Callback to only accept typo corrections that can be a valid C++ member
2558 // intializer: either a non-static field member or a base class.
2559 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2560 public:
2561   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2562       : ClassDecl(ClassDecl) {}
2563 
2564   bool ValidateCandidate(const TypoCorrection &candidate) override {
2565     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2566       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2567         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2568       return isa<TypeDecl>(ND);
2569     }
2570     return false;
2571   }
2572 
2573 private:
2574   CXXRecordDecl *ClassDecl;
2575 };
2576 
2577 }
2578 
2579 /// \brief Handle a C++ member initializer.
2580 MemInitResult
2581 Sema::BuildMemInitializer(Decl *ConstructorD,
2582                           Scope *S,
2583                           CXXScopeSpec &SS,
2584                           IdentifierInfo *MemberOrBase,
2585                           ParsedType TemplateTypeTy,
2586                           const DeclSpec &DS,
2587                           SourceLocation IdLoc,
2588                           Expr *Init,
2589                           SourceLocation EllipsisLoc) {
2590   if (!ConstructorD)
2591     return true;
2592 
2593   AdjustDeclIfTemplate(ConstructorD);
2594 
2595   CXXConstructorDecl *Constructor
2596     = dyn_cast<CXXConstructorDecl>(ConstructorD);
2597   if (!Constructor) {
2598     // The user wrote a constructor initializer on a function that is
2599     // not a C++ constructor. Ignore the error for now, because we may
2600     // have more member initializers coming; we'll diagnose it just
2601     // once in ActOnMemInitializers.
2602     return true;
2603   }
2604 
2605   CXXRecordDecl *ClassDecl = Constructor->getParent();
2606 
2607   // C++ [class.base.init]p2:
2608   //   Names in a mem-initializer-id are looked up in the scope of the
2609   //   constructor's class and, if not found in that scope, are looked
2610   //   up in the scope containing the constructor's definition.
2611   //   [Note: if the constructor's class contains a member with the
2612   //   same name as a direct or virtual base class of the class, a
2613   //   mem-initializer-id naming the member or base class and composed
2614   //   of a single identifier refers to the class member. A
2615   //   mem-initializer-id for the hidden base class may be specified
2616   //   using a qualified name. ]
2617   if (!SS.getScopeRep() && !TemplateTypeTy) {
2618     // Look for a member, first.
2619     DeclContext::lookup_result Result
2620       = ClassDecl->lookup(MemberOrBase);
2621     if (!Result.empty()) {
2622       ValueDecl *Member;
2623       if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2624           (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
2625         if (EllipsisLoc.isValid())
2626           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
2627             << MemberOrBase
2628             << SourceRange(IdLoc, Init->getSourceRange().getEnd());
2629 
2630         return BuildMemberInitializer(Member, Init, IdLoc);
2631       }
2632     }
2633   }
2634   // It didn't name a member, so see if it names a class.
2635   QualType BaseType;
2636   TypeSourceInfo *TInfo = nullptr;
2637 
2638   if (TemplateTypeTy) {
2639     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
2640   } else if (DS.getTypeSpecType() == TST_decltype) {
2641     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
2642   } else {
2643     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2644     LookupParsedName(R, S, &SS);
2645 
2646     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2647     if (!TyD) {
2648       if (R.isAmbiguous()) return true;
2649 
2650       // We don't want access-control diagnostics here.
2651       R.suppressDiagnostics();
2652 
2653       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2654         bool NotUnknownSpecialization = false;
2655         DeclContext *DC = computeDeclContext(SS, false);
2656         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2657           NotUnknownSpecialization = !Record->hasAnyDependentBases();
2658 
2659         if (!NotUnknownSpecialization) {
2660           // When the scope specifier can refer to a member of an unknown
2661           // specialization, we take it as a type name.
2662           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2663                                        SS.getWithLocInContext(Context),
2664                                        *MemberOrBase, IdLoc);
2665           if (BaseType.isNull())
2666             return true;
2667 
2668           R.clear();
2669           R.setLookupName(MemberOrBase);
2670         }
2671       }
2672 
2673       // If no results were found, try to correct typos.
2674       TypoCorrection Corr;
2675       MemInitializerValidatorCCC Validator(ClassDecl);
2676       if (R.empty() && BaseType.isNull() &&
2677           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2678                               Validator, CTK_ErrorRecovery, ClassDecl))) {
2679         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
2680           // We have found a non-static data member with a similar
2681           // name to what was typed; complain and initialize that
2682           // member.
2683           diagnoseTypo(Corr,
2684                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
2685                          << MemberOrBase << true);
2686           return BuildMemberInitializer(Member, Init, IdLoc);
2687         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
2688           const CXXBaseSpecifier *DirectBaseSpec;
2689           const CXXBaseSpecifier *VirtualBaseSpec;
2690           if (FindBaseInitializer(*this, ClassDecl,
2691                                   Context.getTypeDeclType(Type),
2692                                   DirectBaseSpec, VirtualBaseSpec)) {
2693             // We have found a direct or virtual base class with a
2694             // similar name to what was typed; complain and initialize
2695             // that base class.
2696             diagnoseTypo(Corr,
2697                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
2698                            << MemberOrBase << false,
2699                          PDiag() /*Suppress note, we provide our own.*/);
2700 
2701             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2702                                                               : VirtualBaseSpec;
2703             Diag(BaseSpec->getLocStart(),
2704                  diag::note_base_class_specified_here)
2705               << BaseSpec->getType()
2706               << BaseSpec->getSourceRange();
2707 
2708             TyD = Type;
2709           }
2710         }
2711       }
2712 
2713       if (!TyD && BaseType.isNull()) {
2714         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
2715           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
2716         return true;
2717       }
2718     }
2719 
2720     if (BaseType.isNull()) {
2721       BaseType = Context.getTypeDeclType(TyD);
2722       if (SS.isSet())
2723         // FIXME: preserve source range information
2724         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2725                                              BaseType);
2726     }
2727   }
2728 
2729   if (!TInfo)
2730     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
2731 
2732   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
2733 }
2734 
2735 /// Checks a member initializer expression for cases where reference (or
2736 /// pointer) members are bound to by-value parameters (or their addresses).
2737 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2738                                                Expr *Init,
2739                                                SourceLocation IdLoc) {
2740   QualType MemberTy = Member->getType();
2741 
2742   // We only handle pointers and references currently.
2743   // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2744   if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2745     return;
2746 
2747   const bool IsPointer = MemberTy->isPointerType();
2748   if (IsPointer) {
2749     if (const UnaryOperator *Op
2750           = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2751       // The only case we're worried about with pointers requires taking the
2752       // address.
2753       if (Op->getOpcode() != UO_AddrOf)
2754         return;
2755 
2756       Init = Op->getSubExpr();
2757     } else {
2758       // We only handle address-of expression initializers for pointers.
2759       return;
2760     }
2761   }
2762 
2763   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2764     // We only warn when referring to a non-reference parameter declaration.
2765     const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2766     if (!Parameter || Parameter->getType()->isReferenceType())
2767       return;
2768 
2769     S.Diag(Init->getExprLoc(),
2770            IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2771                      : diag::warn_bind_ref_member_to_parameter)
2772       << Member << Parameter << Init->getSourceRange();
2773   } else {
2774     // Other initializers are fine.
2775     return;
2776   }
2777 
2778   S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2779     << (unsigned)IsPointer;
2780 }
2781 
2782 MemInitResult
2783 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
2784                              SourceLocation IdLoc) {
2785   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2786   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2787   assert((DirectMember || IndirectMember) &&
2788          "Member must be a FieldDecl or IndirectFieldDecl");
2789 
2790   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2791     return true;
2792 
2793   if (Member->isInvalidDecl())
2794     return true;
2795 
2796   MultiExprArg Args;
2797   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2798     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2799   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2800     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
2801   } else {
2802     // Template instantiation doesn't reconstruct ParenListExprs for us.
2803     Args = Init;
2804   }
2805 
2806   SourceRange InitRange = Init->getSourceRange();
2807 
2808   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
2809     // Can't check initialization for a member of dependent type or when
2810     // any of the arguments are type-dependent expressions.
2811     DiscardCleanupsInEvaluationContext();
2812   } else {
2813     bool InitList = false;
2814     if (isa<InitListExpr>(Init)) {
2815       InitList = true;
2816       Args = Init;
2817     }
2818 
2819     // Initialize the member.
2820     InitializedEntity MemberEntity =
2821       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
2822                    : InitializedEntity::InitializeMember(IndirectMember,
2823                                                          nullptr);
2824     InitializationKind Kind =
2825       InitList ? InitializationKind::CreateDirectList(IdLoc)
2826                : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2827                                                   InitRange.getEnd());
2828 
2829     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2830     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
2831                                             nullptr);
2832     if (MemberInit.isInvalid())
2833       return true;
2834 
2835     CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2836 
2837     // C++11 [class.base.init]p7:
2838     //   The initialization of each base and member constitutes a
2839     //   full-expression.
2840     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
2841     if (MemberInit.isInvalid())
2842       return true;
2843 
2844     Init = MemberInit.get();
2845   }
2846 
2847   if (DirectMember) {
2848     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2849                                             InitRange.getBegin(), Init,
2850                                             InitRange.getEnd());
2851   } else {
2852     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2853                                             InitRange.getBegin(), Init,
2854                                             InitRange.getEnd());
2855   }
2856 }
2857 
2858 MemInitResult
2859 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
2860                                  CXXRecordDecl *ClassDecl) {
2861   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
2862   if (!LangOpts.CPlusPlus11)
2863     return Diag(NameLoc, diag::err_delegating_ctor)
2864       << TInfo->getTypeLoc().getLocalSourceRange();
2865   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
2866 
2867   bool InitList = true;
2868   MultiExprArg Args = Init;
2869   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2870     InitList = false;
2871     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2872   }
2873 
2874   SourceRange InitRange = Init->getSourceRange();
2875   // Initialize the object.
2876   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2877                                      QualType(ClassDecl->getTypeForDecl(), 0));
2878   InitializationKind Kind =
2879     InitList ? InitializationKind::CreateDirectList(NameLoc)
2880              : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2881                                                 InitRange.getEnd());
2882   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
2883   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2884                                               Args, nullptr);
2885   if (DelegationInit.isInvalid())
2886     return true;
2887 
2888   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2889          "Delegating constructor with no target?");
2890 
2891   // C++11 [class.base.init]p7:
2892   //   The initialization of each base and member constitutes a
2893   //   full-expression.
2894   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2895                                        InitRange.getBegin());
2896   if (DelegationInit.isInvalid())
2897     return true;
2898 
2899   // If we are in a dependent context, template instantiation will
2900   // perform this type-checking again. Just save the arguments that we
2901   // received in a ParenListExpr.
2902   // FIXME: This isn't quite ideal, since our ASTs don't capture all
2903   // of the information that we have about the base
2904   // initializer. However, deconstructing the ASTs is a dicey process,
2905   // and this approach is far more likely to get the corner cases right.
2906   if (CurContext->isDependentContext())
2907     DelegationInit = Init;
2908 
2909   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
2910                                           DelegationInit.getAs<Expr>(),
2911                                           InitRange.getEnd());
2912 }
2913 
2914 MemInitResult
2915 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
2916                            Expr *Init, CXXRecordDecl *ClassDecl,
2917                            SourceLocation EllipsisLoc) {
2918   SourceLocation BaseLoc
2919     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
2920 
2921   if (!BaseType->isDependentType() && !BaseType->isRecordType())
2922     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2923              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2924 
2925   // C++ [class.base.init]p2:
2926   //   [...] Unless the mem-initializer-id names a nonstatic data
2927   //   member of the constructor's class or a direct or virtual base
2928   //   of that class, the mem-initializer is ill-formed. A
2929   //   mem-initializer-list can initialize a base class using any
2930   //   name that denotes that base class type.
2931   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
2932 
2933   SourceRange InitRange = Init->getSourceRange();
2934   if (EllipsisLoc.isValid()) {
2935     // This is a pack expansion.
2936     if (!BaseType->containsUnexpandedParameterPack())  {
2937       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2938         << SourceRange(BaseLoc, InitRange.getEnd());
2939 
2940       EllipsisLoc = SourceLocation();
2941     }
2942   } else {
2943     // Check for any unexpanded parameter packs.
2944     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2945       return true;
2946 
2947     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2948       return true;
2949   }
2950 
2951   // Check for direct and virtual base classes.
2952   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
2953   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
2954   if (!Dependent) {
2955     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2956                                        BaseType))
2957       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
2958 
2959     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2960                         VirtualBaseSpec);
2961 
2962     // C++ [base.class.init]p2:
2963     // Unless the mem-initializer-id names a nonstatic data member of the
2964     // constructor's class or a direct or virtual base of that class, the
2965     // mem-initializer is ill-formed.
2966     if (!DirectBaseSpec && !VirtualBaseSpec) {
2967       // If the class has any dependent bases, then it's possible that
2968       // one of those types will resolve to the same type as
2969       // BaseType. Therefore, just treat this as a dependent base
2970       // class initialization.  FIXME: Should we try to check the
2971       // initialization anyway? It seems odd.
2972       if (ClassDecl->hasAnyDependentBases())
2973         Dependent = true;
2974       else
2975         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2976           << BaseType << Context.getTypeDeclType(ClassDecl)
2977           << BaseTInfo->getTypeLoc().getLocalSourceRange();
2978     }
2979   }
2980 
2981   if (Dependent) {
2982     DiscardCleanupsInEvaluationContext();
2983 
2984     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2985                                             /*IsVirtual=*/false,
2986                                             InitRange.getBegin(), Init,
2987                                             InitRange.getEnd(), EllipsisLoc);
2988   }
2989 
2990   // C++ [base.class.init]p2:
2991   //   If a mem-initializer-id is ambiguous because it designates both
2992   //   a direct non-virtual base class and an inherited virtual base
2993   //   class, the mem-initializer is ill-formed.
2994   if (DirectBaseSpec && VirtualBaseSpec)
2995     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
2996       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2997 
2998   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
2999   if (!BaseSpec)
3000     BaseSpec = VirtualBaseSpec;
3001 
3002   // Initialize the base.
3003   bool InitList = true;
3004   MultiExprArg Args = Init;
3005   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3006     InitList = false;
3007     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3008   }
3009 
3010   InitializedEntity BaseEntity =
3011     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
3012   InitializationKind Kind =
3013     InitList ? InitializationKind::CreateDirectList(BaseLoc)
3014              : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
3015                                                 InitRange.getEnd());
3016   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
3017   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
3018   if (BaseInit.isInvalid())
3019     return true;
3020 
3021   // C++11 [class.base.init]p7:
3022   //   The initialization of each base and member constitutes a
3023   //   full-expression.
3024   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
3025   if (BaseInit.isInvalid())
3026     return true;
3027 
3028   // If we are in a dependent context, template instantiation will
3029   // perform this type-checking again. Just save the arguments that we
3030   // received in a ParenListExpr.
3031   // FIXME: This isn't quite ideal, since our ASTs don't capture all
3032   // of the information that we have about the base
3033   // initializer. However, deconstructing the ASTs is a dicey process,
3034   // and this approach is far more likely to get the corner cases right.
3035   if (CurContext->isDependentContext())
3036     BaseInit = Init;
3037 
3038   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3039                                           BaseSpec->isVirtual(),
3040                                           InitRange.getBegin(),
3041                                           BaseInit.getAs<Expr>(),
3042                                           InitRange.getEnd(), EllipsisLoc);
3043 }
3044 
3045 // Create a static_cast\<T&&>(expr).
3046 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
3047   if (T.isNull()) T = E->getType();
3048   QualType TargetType = SemaRef.BuildReferenceType(
3049       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
3050   SourceLocation ExprLoc = E->getLocStart();
3051   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
3052       TargetType, ExprLoc);
3053 
3054   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
3055                                    SourceRange(ExprLoc, ExprLoc),
3056                                    E->getSourceRange()).get();
3057 }
3058 
3059 /// ImplicitInitializerKind - How an implicit base or member initializer should
3060 /// initialize its base or member.
3061 enum ImplicitInitializerKind {
3062   IIK_Default,
3063   IIK_Copy,
3064   IIK_Move,
3065   IIK_Inherit
3066 };
3067 
3068 static bool
3069 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3070                              ImplicitInitializerKind ImplicitInitKind,
3071                              CXXBaseSpecifier *BaseSpec,
3072                              bool IsInheritedVirtualBase,
3073                              CXXCtorInitializer *&CXXBaseInit) {
3074   InitializedEntity InitEntity
3075     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3076                                         IsInheritedVirtualBase);
3077 
3078   ExprResult BaseInit;
3079 
3080   switch (ImplicitInitKind) {
3081   case IIK_Inherit: {
3082     const CXXRecordDecl *Inherited =
3083         Constructor->getInheritedConstructor()->getParent();
3084     const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3085     if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3086       // C++11 [class.inhctor]p8:
3087       //   Each expression in the expression-list is of the form
3088       //   static_cast<T&&>(p), where p is the name of the corresponding
3089       //   constructor parameter and T is the declared type of p.
3090       SmallVector<Expr*, 16> Args;
3091       for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3092         ParmVarDecl *PD = Constructor->getParamDecl(I);
3093         ExprResult ArgExpr =
3094             SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3095                                      VK_LValue, SourceLocation());
3096         if (ArgExpr.isInvalid())
3097           return true;
3098         Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
3099       }
3100 
3101       InitializationKind InitKind = InitializationKind::CreateDirect(
3102           Constructor->getLocation(), SourceLocation(), SourceLocation());
3103       InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
3104       BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3105       break;
3106     }
3107   }
3108   // Fall through.
3109   case IIK_Default: {
3110     InitializationKind InitKind
3111       = InitializationKind::CreateDefault(Constructor->getLocation());
3112     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3113     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3114     break;
3115   }
3116 
3117   case IIK_Move:
3118   case IIK_Copy: {
3119     bool Moving = ImplicitInitKind == IIK_Move;
3120     ParmVarDecl *Param = Constructor->getParamDecl(0);
3121     QualType ParamType = Param->getType().getNonReferenceType();
3122 
3123     Expr *CopyCtorArg =
3124       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3125                           SourceLocation(), Param, false,
3126                           Constructor->getLocation(), ParamType,
3127                           VK_LValue, nullptr);
3128 
3129     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3130 
3131     // Cast to the base class to avoid ambiguities.
3132     QualType ArgTy =
3133       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3134                                        ParamType.getQualifiers());
3135 
3136     if (Moving) {
3137       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3138     }
3139 
3140     CXXCastPath BasePath;
3141     BasePath.push_back(BaseSpec);
3142     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3143                                             CK_UncheckedDerivedToBase,
3144                                             Moving ? VK_XValue : VK_LValue,
3145                                             &BasePath).get();
3146 
3147     InitializationKind InitKind
3148       = InitializationKind::CreateDirect(Constructor->getLocation(),
3149                                          SourceLocation(), SourceLocation());
3150     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3151     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
3152     break;
3153   }
3154   }
3155 
3156   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
3157   if (BaseInit.isInvalid())
3158     return true;
3159 
3160   CXXBaseInit =
3161     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3162                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3163                                                         SourceLocation()),
3164                                              BaseSpec->isVirtual(),
3165                                              SourceLocation(),
3166                                              BaseInit.getAs<Expr>(),
3167                                              SourceLocation(),
3168                                              SourceLocation());
3169 
3170   return false;
3171 }
3172 
3173 static bool RefersToRValueRef(Expr *MemRef) {
3174   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3175   return Referenced->getType()->isRValueReferenceType();
3176 }
3177 
3178 static bool
3179 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3180                                ImplicitInitializerKind ImplicitInitKind,
3181                                FieldDecl *Field, IndirectFieldDecl *Indirect,
3182                                CXXCtorInitializer *&CXXMemberInit) {
3183   if (Field->isInvalidDecl())
3184     return true;
3185 
3186   SourceLocation Loc = Constructor->getLocation();
3187 
3188   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3189     bool Moving = ImplicitInitKind == IIK_Move;
3190     ParmVarDecl *Param = Constructor->getParamDecl(0);
3191     QualType ParamType = Param->getType().getNonReferenceType();
3192 
3193     // Suppress copying zero-width bitfields.
3194     if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3195       return false;
3196 
3197     Expr *MemberExprBase =
3198       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3199                           SourceLocation(), Param, false,
3200                           Loc, ParamType, VK_LValue, nullptr);
3201 
3202     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3203 
3204     if (Moving) {
3205       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3206     }
3207 
3208     // Build a reference to this field within the parameter.
3209     CXXScopeSpec SS;
3210     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3211                               Sema::LookupMemberName);
3212     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3213                                   : cast<ValueDecl>(Field), AS_public);
3214     MemberLookup.resolveKind();
3215     ExprResult CtorArg
3216       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
3217                                          ParamType, Loc,
3218                                          /*IsArrow=*/false,
3219                                          SS,
3220                                          /*TemplateKWLoc=*/SourceLocation(),
3221                                          /*FirstQualifierInScope=*/nullptr,
3222                                          MemberLookup,
3223                                          /*TemplateArgs=*/nullptr);
3224     if (CtorArg.isInvalid())
3225       return true;
3226 
3227     // C++11 [class.copy]p15:
3228     //   - if a member m has rvalue reference type T&&, it is direct-initialized
3229     //     with static_cast<T&&>(x.m);
3230     if (RefersToRValueRef(CtorArg.get())) {
3231       CtorArg = CastForMoving(SemaRef, CtorArg.get());
3232     }
3233 
3234     // When the field we are copying is an array, create index variables for
3235     // each dimension of the array. We use these index variables to subscript
3236     // the source array, and other clients (e.g., CodeGen) will perform the
3237     // necessary iteration with these index variables.
3238     SmallVector<VarDecl *, 4> IndexVariables;
3239     QualType BaseType = Field->getType();
3240     QualType SizeType = SemaRef.Context.getSizeType();
3241     bool InitializingArray = false;
3242     while (const ConstantArrayType *Array
3243                           = SemaRef.Context.getAsConstantArrayType(BaseType)) {
3244       InitializingArray = true;
3245       // Create the iteration variable for this array index.
3246       IdentifierInfo *IterationVarName = nullptr;
3247       {
3248         SmallString<8> Str;
3249         llvm::raw_svector_ostream OS(Str);
3250         OS << "__i" << IndexVariables.size();
3251         IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3252       }
3253       VarDecl *IterationVar
3254         = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
3255                           IterationVarName, SizeType,
3256                         SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
3257                           SC_None);
3258       IndexVariables.push_back(IterationVar);
3259 
3260       // Create a reference to the iteration variable.
3261       ExprResult IterationVarRef
3262         = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
3263       assert(!IterationVarRef.isInvalid() &&
3264              "Reference to invented variable cannot fail!");
3265       IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
3266       assert(!IterationVarRef.isInvalid() &&
3267              "Conversion of invented variable cannot fail!");
3268 
3269       // Subscript the array with this iteration variable.
3270       CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3271                                                         IterationVarRef.get(),
3272                                                         Loc);
3273       if (CtorArg.isInvalid())
3274         return true;
3275 
3276       BaseType = Array->getElementType();
3277     }
3278 
3279     // The array subscript expression is an lvalue, which is wrong for moving.
3280     if (Moving && InitializingArray)
3281       CtorArg = CastForMoving(SemaRef, CtorArg.get());
3282 
3283     // Construct the entity that we will be initializing. For an array, this
3284     // will be first element in the array, which may require several levels
3285     // of array-subscript entities.
3286     SmallVector<InitializedEntity, 4> Entities;
3287     Entities.reserve(1 + IndexVariables.size());
3288     if (Indirect)
3289       Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3290     else
3291       Entities.push_back(InitializedEntity::InitializeMember(Field));
3292     for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3293       Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3294                                                               0,
3295                                                               Entities.back()));
3296 
3297     // Direct-initialize to use the copy constructor.
3298     InitializationKind InitKind =
3299       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3300 
3301     Expr *CtorArgE = CtorArg.getAs<Expr>();
3302     InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
3303 
3304     ExprResult MemberInit
3305       = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
3306                         MultiExprArg(&CtorArgE, 1));
3307     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3308     if (MemberInit.isInvalid())
3309       return true;
3310 
3311     if (Indirect) {
3312       assert(IndexVariables.size() == 0 &&
3313              "Indirect field improperly initialized");
3314       CXXMemberInit
3315         = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3316                                                    Loc, Loc,
3317                                                    MemberInit.getAs<Expr>(),
3318                                                    Loc);
3319     } else
3320       CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3321                                                  Loc, MemberInit.getAs<Expr>(),
3322                                                  Loc,
3323                                                  IndexVariables.data(),
3324                                                  IndexVariables.size());
3325     return false;
3326   }
3327 
3328   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3329          "Unhandled implicit init kind!");
3330 
3331   QualType FieldBaseElementType =
3332     SemaRef.Context.getBaseElementType(Field->getType());
3333 
3334   if (FieldBaseElementType->isRecordType()) {
3335     InitializedEntity InitEntity
3336       = Indirect? InitializedEntity::InitializeMember(Indirect)
3337                 : InitializedEntity::InitializeMember(Field);
3338     InitializationKind InitKind =
3339       InitializationKind::CreateDefault(Loc);
3340 
3341     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3342     ExprResult MemberInit =
3343       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3344 
3345     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3346     if (MemberInit.isInvalid())
3347       return true;
3348 
3349     if (Indirect)
3350       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3351                                                                Indirect, Loc,
3352                                                                Loc,
3353                                                                MemberInit.get(),
3354                                                                Loc);
3355     else
3356       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3357                                                                Field, Loc, Loc,
3358                                                                MemberInit.get(),
3359                                                                Loc);
3360     return false;
3361   }
3362 
3363   if (!Field->getParent()->isUnion()) {
3364     if (FieldBaseElementType->isReferenceType()) {
3365       SemaRef.Diag(Constructor->getLocation(),
3366                    diag::err_uninitialized_member_in_ctor)
3367       << (int)Constructor->isImplicit()
3368       << SemaRef.Context.getTagDeclType(Constructor->getParent())
3369       << 0 << Field->getDeclName();
3370       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3371       return true;
3372     }
3373 
3374     if (FieldBaseElementType.isConstQualified()) {
3375       SemaRef.Diag(Constructor->getLocation(),
3376                    diag::err_uninitialized_member_in_ctor)
3377       << (int)Constructor->isImplicit()
3378       << SemaRef.Context.getTagDeclType(Constructor->getParent())
3379       << 1 << Field->getDeclName();
3380       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3381       return true;
3382     }
3383   }
3384 
3385   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
3386       FieldBaseElementType->isObjCRetainableType() &&
3387       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3388       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
3389     // ARC:
3390     //   Default-initialize Objective-C pointers to NULL.
3391     CXXMemberInit
3392       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3393                                                  Loc, Loc,
3394                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3395                                                  Loc);
3396     return false;
3397   }
3398 
3399   // Nothing to initialize.
3400   CXXMemberInit = nullptr;
3401   return false;
3402 }
3403 
3404 namespace {
3405 struct BaseAndFieldInfo {
3406   Sema &S;
3407   CXXConstructorDecl *Ctor;
3408   bool AnyErrorsInInits;
3409   ImplicitInitializerKind IIK;
3410   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
3411   SmallVector<CXXCtorInitializer*, 8> AllToInit;
3412   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
3413 
3414   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3415     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
3416     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3417     if (Generated && Ctor->isCopyConstructor())
3418       IIK = IIK_Copy;
3419     else if (Generated && Ctor->isMoveConstructor())
3420       IIK = IIK_Move;
3421     else if (Ctor->getInheritedConstructor())
3422       IIK = IIK_Inherit;
3423     else
3424       IIK = IIK_Default;
3425   }
3426 
3427   bool isImplicitCopyOrMove() const {
3428     switch (IIK) {
3429     case IIK_Copy:
3430     case IIK_Move:
3431       return true;
3432 
3433     case IIK_Default:
3434     case IIK_Inherit:
3435       return false;
3436     }
3437 
3438     llvm_unreachable("Invalid ImplicitInitializerKind!");
3439   }
3440 
3441   bool addFieldInitializer(CXXCtorInitializer *Init) {
3442     AllToInit.push_back(Init);
3443 
3444     // Check whether this initializer makes the field "used".
3445     if (Init->getInit()->HasSideEffects(S.Context))
3446       S.UnusedPrivateFields.remove(Init->getAnyMember());
3447 
3448     return false;
3449   }
3450 
3451   bool isInactiveUnionMember(FieldDecl *Field) {
3452     RecordDecl *Record = Field->getParent();
3453     if (!Record->isUnion())
3454       return false;
3455 
3456     if (FieldDecl *Active =
3457             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
3458       return Active != Field->getCanonicalDecl();
3459 
3460     // In an implicit copy or move constructor, ignore any in-class initializer.
3461     if (isImplicitCopyOrMove())
3462       return true;
3463 
3464     // If there's no explicit initialization, the field is active only if it
3465     // has an in-class initializer...
3466     if (Field->hasInClassInitializer())
3467       return false;
3468     // ... or it's an anonymous struct or union whose class has an in-class
3469     // initializer.
3470     if (!Field->isAnonymousStructOrUnion())
3471       return true;
3472     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3473     return !FieldRD->hasInClassInitializer();
3474   }
3475 
3476   /// \brief Determine whether the given field is, or is within, a union member
3477   /// that is inactive (because there was an initializer given for a different
3478   /// member of the union, or because the union was not initialized at all).
3479   bool isWithinInactiveUnionMember(FieldDecl *Field,
3480                                    IndirectFieldDecl *Indirect) {
3481     if (!Indirect)
3482       return isInactiveUnionMember(Field);
3483 
3484     for (auto *C : Indirect->chain()) {
3485       FieldDecl *Field = dyn_cast<FieldDecl>(C);
3486       if (Field && isInactiveUnionMember(Field))
3487         return true;
3488     }
3489     return false;
3490   }
3491 };
3492 }
3493 
3494 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
3495 /// array type.
3496 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3497   if (T->isIncompleteArrayType())
3498     return true;
3499 
3500   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3501     if (!ArrayT->getSize())
3502       return true;
3503 
3504     T = ArrayT->getElementType();
3505   }
3506 
3507   return false;
3508 }
3509 
3510 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
3511                                     FieldDecl *Field,
3512                                     IndirectFieldDecl *Indirect = nullptr) {
3513   if (Field->isInvalidDecl())
3514     return false;
3515 
3516   // Overwhelmingly common case: we have a direct initializer for this field.
3517   if (CXXCtorInitializer *Init =
3518           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
3519     return Info.addFieldInitializer(Init);
3520 
3521   // C++11 [class.base.init]p8:
3522   //   if the entity is a non-static data member that has a
3523   //   brace-or-equal-initializer and either
3524   //   -- the constructor's class is a union and no other variant member of that
3525   //      union is designated by a mem-initializer-id or
3526   //   -- the constructor's class is not a union, and, if the entity is a member
3527   //      of an anonymous union, no other member of that union is designated by
3528   //      a mem-initializer-id,
3529   //   the entity is initialized as specified in [dcl.init].
3530   //
3531   // We also apply the same rules to handle anonymous structs within anonymous
3532   // unions.
3533   if (Info.isWithinInactiveUnionMember(Field, Indirect))
3534     return false;
3535 
3536   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
3537     Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3538                                            Info.Ctor->getLocation(), Field);
3539     CXXCtorInitializer *Init;
3540     if (Indirect)
3541       Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3542                                                       SourceLocation(),
3543                                                       SourceLocation(), DIE,
3544                                                       SourceLocation());
3545     else
3546       Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3547                                                       SourceLocation(),
3548                                                       SourceLocation(), DIE,
3549                                                       SourceLocation());
3550     return Info.addFieldInitializer(Init);
3551   }
3552 
3553   // Don't initialize incomplete or zero-length arrays.
3554   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3555     return false;
3556 
3557   // Don't try to build an implicit initializer if there were semantic
3558   // errors in any of the initializers (and therefore we might be
3559   // missing some that the user actually wrote).
3560   if (Info.AnyErrorsInInits)
3561     return false;
3562 
3563   CXXCtorInitializer *Init = nullptr;
3564   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3565                                      Indirect, Init))
3566     return true;
3567 
3568   if (!Init)
3569     return false;
3570 
3571   return Info.addFieldInitializer(Init);
3572 }
3573 
3574 bool
3575 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3576                                CXXCtorInitializer *Initializer) {
3577   assert(Initializer->isDelegatingInitializer());
3578   Constructor->setNumCtorInitializers(1);
3579   CXXCtorInitializer **initializer =
3580     new (Context) CXXCtorInitializer*[1];
3581   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3582   Constructor->setCtorInitializers(initializer);
3583 
3584   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
3585     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
3586     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3587   }
3588 
3589   DelegatingCtorDecls.push_back(Constructor);
3590 
3591   return false;
3592 }
3593 
3594 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3595                                ArrayRef<CXXCtorInitializer *> Initializers) {
3596   if (Constructor->isDependentContext()) {
3597     // Just store the initializers as written, they will be checked during
3598     // instantiation.
3599     if (!Initializers.empty()) {
3600       Constructor->setNumCtorInitializers(Initializers.size());
3601       CXXCtorInitializer **baseOrMemberInitializers =
3602         new (Context) CXXCtorInitializer*[Initializers.size()];
3603       memcpy(baseOrMemberInitializers, Initializers.data(),
3604              Initializers.size() * sizeof(CXXCtorInitializer*));
3605       Constructor->setCtorInitializers(baseOrMemberInitializers);
3606     }
3607 
3608     // Let template instantiation know whether we had errors.
3609     if (AnyErrors)
3610       Constructor->setInvalidDecl();
3611 
3612     return false;
3613   }
3614 
3615   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
3616 
3617   // We need to build the initializer AST according to order of construction
3618   // and not what user specified in the Initializers list.
3619   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
3620   if (!ClassDecl)
3621     return true;
3622 
3623   bool HadError = false;
3624 
3625   for (unsigned i = 0; i < Initializers.size(); i++) {
3626     CXXCtorInitializer *Member = Initializers[i];
3627 
3628     if (Member->isBaseInitializer())
3629       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
3630     else {
3631       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
3632 
3633       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
3634         for (auto *C : F->chain()) {
3635           FieldDecl *FD = dyn_cast<FieldDecl>(C);
3636           if (FD && FD->getParent()->isUnion())
3637             Info.ActiveUnionMember.insert(std::make_pair(
3638                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3639         }
3640       } else if (FieldDecl *FD = Member->getMember()) {
3641         if (FD->getParent()->isUnion())
3642           Info.ActiveUnionMember.insert(std::make_pair(
3643               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3644       }
3645     }
3646   }
3647 
3648   // Keep track of the direct virtual bases.
3649   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3650   for (auto &I : ClassDecl->bases()) {
3651     if (I.isVirtual())
3652       DirectVBases.insert(&I);
3653   }
3654 
3655   // Push virtual bases before others.
3656   for (auto &VBase : ClassDecl->vbases()) {
3657     if (CXXCtorInitializer *Value
3658         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
3659       // [class.base.init]p7, per DR257:
3660       //   A mem-initializer where the mem-initializer-id names a virtual base
3661       //   class is ignored during execution of a constructor of any class that
3662       //   is not the most derived class.
3663       if (ClassDecl->isAbstract()) {
3664         // FIXME: Provide a fixit to remove the base specifier. This requires
3665         // tracking the location of the associated comma for a base specifier.
3666         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3667           << VBase.getType() << ClassDecl;
3668         DiagnoseAbstractType(ClassDecl);
3669       }
3670 
3671       Info.AllToInit.push_back(Value);
3672     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3673       // [class.base.init]p8, per DR257:
3674       //   If a given [...] base class is not named by a mem-initializer-id
3675       //   [...] and the entity is not a virtual base class of an abstract
3676       //   class, then [...] the entity is default-initialized.
3677       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
3678       CXXCtorInitializer *CXXBaseInit;
3679       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3680                                        &VBase, IsInheritedVirtualBase,
3681                                        CXXBaseInit)) {
3682         HadError = true;
3683         continue;
3684       }
3685 
3686       Info.AllToInit.push_back(CXXBaseInit);
3687     }
3688   }
3689 
3690   // Non-virtual bases.
3691   for (auto &Base : ClassDecl->bases()) {
3692     // Virtuals are in the virtual base list and already constructed.
3693     if (Base.isVirtual())
3694       continue;
3695 
3696     if (CXXCtorInitializer *Value
3697           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
3698       Info.AllToInit.push_back(Value);
3699     } else if (!AnyErrors) {
3700       CXXCtorInitializer *CXXBaseInit;
3701       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3702                                        &Base, /*IsInheritedVirtualBase=*/false,
3703                                        CXXBaseInit)) {
3704         HadError = true;
3705         continue;
3706       }
3707 
3708       Info.AllToInit.push_back(CXXBaseInit);
3709     }
3710   }
3711 
3712   // Fields.
3713   for (auto *Mem : ClassDecl->decls()) {
3714     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
3715       // C++ [class.bit]p2:
3716       //   A declaration for a bit-field that omits the identifier declares an
3717       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
3718       //   initialized.
3719       if (F->isUnnamedBitfield())
3720         continue;
3721 
3722       // If we're not generating the implicit copy/move constructor, then we'll
3723       // handle anonymous struct/union fields based on their individual
3724       // indirect fields.
3725       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
3726         continue;
3727 
3728       if (CollectFieldInitializer(*this, Info, F))
3729         HadError = true;
3730       continue;
3731     }
3732 
3733     // Beyond this point, we only consider default initialization.
3734     if (Info.isImplicitCopyOrMove())
3735       continue;
3736 
3737     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
3738       if (F->getType()->isIncompleteArrayType()) {
3739         assert(ClassDecl->hasFlexibleArrayMember() &&
3740                "Incomplete array type is not valid");
3741         continue;
3742       }
3743 
3744       // Initialize each field of an anonymous struct individually.
3745       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3746         HadError = true;
3747 
3748       continue;
3749     }
3750   }
3751 
3752   unsigned NumInitializers = Info.AllToInit.size();
3753   if (NumInitializers > 0) {
3754     Constructor->setNumCtorInitializers(NumInitializers);
3755     CXXCtorInitializer **baseOrMemberInitializers =
3756       new (Context) CXXCtorInitializer*[NumInitializers];
3757     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
3758            NumInitializers * sizeof(CXXCtorInitializer*));
3759     Constructor->setCtorInitializers(baseOrMemberInitializers);
3760 
3761     // Constructors implicitly reference the base and member
3762     // destructors.
3763     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3764                                            Constructor->getParent());
3765   }
3766 
3767   return HadError;
3768 }
3769 
3770 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
3771   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
3772     const RecordDecl *RD = RT->getDecl();
3773     if (RD->isAnonymousStructOrUnion()) {
3774       for (auto *Field : RD->fields())
3775         PopulateKeysForFields(Field, IdealInits);
3776       return;
3777     }
3778   }
3779   IdealInits.push_back(Field->getCanonicalDecl());
3780 }
3781 
3782 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3783   return Context.getCanonicalType(BaseType).getTypePtr();
3784 }
3785 
3786 static const void *GetKeyForMember(ASTContext &Context,
3787                                    CXXCtorInitializer *Member) {
3788   if (!Member->isAnyMemberInitializer())
3789     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
3790 
3791   return Member->getAnyMember()->getCanonicalDecl();
3792 }
3793 
3794 static void DiagnoseBaseOrMemInitializerOrder(
3795     Sema &SemaRef, const CXXConstructorDecl *Constructor,
3796     ArrayRef<CXXCtorInitializer *> Inits) {
3797   if (Constructor->getDeclContext()->isDependentContext())
3798     return;
3799 
3800   // Don't check initializers order unless the warning is enabled at the
3801   // location of at least one initializer.
3802   bool ShouldCheckOrder = false;
3803   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3804     CXXCtorInitializer *Init = Inits[InitIndex];
3805     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
3806                                  Init->getSourceLocation())) {
3807       ShouldCheckOrder = true;
3808       break;
3809     }
3810   }
3811   if (!ShouldCheckOrder)
3812     return;
3813 
3814   // Build the list of bases and members in the order that they'll
3815   // actually be initialized.  The explicit initializers should be in
3816   // this same order but may be missing things.
3817   SmallVector<const void*, 32> IdealInitKeys;
3818 
3819   const CXXRecordDecl *ClassDecl = Constructor->getParent();
3820 
3821   // 1. Virtual bases.
3822   for (const auto &VBase : ClassDecl->vbases())
3823     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
3824 
3825   // 2. Non-virtual bases.
3826   for (const auto &Base : ClassDecl->bases()) {
3827     if (Base.isVirtual())
3828       continue;
3829     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
3830   }
3831 
3832   // 3. Direct fields.
3833   for (auto *Field : ClassDecl->fields()) {
3834     if (Field->isUnnamedBitfield())
3835       continue;
3836 
3837     PopulateKeysForFields(Field, IdealInitKeys);
3838   }
3839 
3840   unsigned NumIdealInits = IdealInitKeys.size();
3841   unsigned IdealIndex = 0;
3842 
3843   CXXCtorInitializer *PrevInit = nullptr;
3844   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3845     CXXCtorInitializer *Init = Inits[InitIndex];
3846     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
3847 
3848     // Scan forward to try to find this initializer in the idealized
3849     // initializers list.
3850     for (; IdealIndex != NumIdealInits; ++IdealIndex)
3851       if (InitKey == IdealInitKeys[IdealIndex])
3852         break;
3853 
3854     // If we didn't find this initializer, it must be because we
3855     // scanned past it on a previous iteration.  That can only
3856     // happen if we're out of order;  emit a warning.
3857     if (IdealIndex == NumIdealInits && PrevInit) {
3858       Sema::SemaDiagnosticBuilder D =
3859         SemaRef.Diag(PrevInit->getSourceLocation(),
3860                      diag::warn_initializer_out_of_order);
3861 
3862       if (PrevInit->isAnyMemberInitializer())
3863         D << 0 << PrevInit->getAnyMember()->getDeclName();
3864       else
3865         D << 1 << PrevInit->getTypeSourceInfo()->getType();
3866 
3867       if (Init->isAnyMemberInitializer())
3868         D << 0 << Init->getAnyMember()->getDeclName();
3869       else
3870         D << 1 << Init->getTypeSourceInfo()->getType();
3871 
3872       // Move back to the initializer's location in the ideal list.
3873       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3874         if (InitKey == IdealInitKeys[IdealIndex])
3875           break;
3876 
3877       assert(IdealIndex != NumIdealInits &&
3878              "initializer not found in initializer list");
3879     }
3880 
3881     PrevInit = Init;
3882   }
3883 }
3884 
3885 namespace {
3886 bool CheckRedundantInit(Sema &S,
3887                         CXXCtorInitializer *Init,
3888                         CXXCtorInitializer *&PrevInit) {
3889   if (!PrevInit) {
3890     PrevInit = Init;
3891     return false;
3892   }
3893 
3894   if (FieldDecl *Field = Init->getAnyMember())
3895     S.Diag(Init->getSourceLocation(),
3896            diag::err_multiple_mem_initialization)
3897       << Field->getDeclName()
3898       << Init->getSourceRange();
3899   else {
3900     const Type *BaseClass = Init->getBaseClass();
3901     assert(BaseClass && "neither field nor base");
3902     S.Diag(Init->getSourceLocation(),
3903            diag::err_multiple_base_initialization)
3904       << QualType(BaseClass, 0)
3905       << Init->getSourceRange();
3906   }
3907   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3908     << 0 << PrevInit->getSourceRange();
3909 
3910   return true;
3911 }
3912 
3913 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
3914 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3915 
3916 bool CheckRedundantUnionInit(Sema &S,
3917                              CXXCtorInitializer *Init,
3918                              RedundantUnionMap &Unions) {
3919   FieldDecl *Field = Init->getAnyMember();
3920   RecordDecl *Parent = Field->getParent();
3921   NamedDecl *Child = Field;
3922 
3923   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
3924     if (Parent->isUnion()) {
3925       UnionEntry &En = Unions[Parent];
3926       if (En.first && En.first != Child) {
3927         S.Diag(Init->getSourceLocation(),
3928                diag::err_multiple_mem_union_initialization)
3929           << Field->getDeclName()
3930           << Init->getSourceRange();
3931         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3932           << 0 << En.second->getSourceRange();
3933         return true;
3934       }
3935       if (!En.first) {
3936         En.first = Child;
3937         En.second = Init;
3938       }
3939       if (!Parent->isAnonymousStructOrUnion())
3940         return false;
3941     }
3942 
3943     Child = Parent;
3944     Parent = cast<RecordDecl>(Parent->getDeclContext());
3945   }
3946 
3947   return false;
3948 }
3949 }
3950 
3951 /// ActOnMemInitializers - Handle the member initializers for a constructor.
3952 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
3953                                 SourceLocation ColonLoc,
3954                                 ArrayRef<CXXCtorInitializer*> MemInits,
3955                                 bool AnyErrors) {
3956   if (!ConstructorDecl)
3957     return;
3958 
3959   AdjustDeclIfTemplate(ConstructorDecl);
3960 
3961   CXXConstructorDecl *Constructor
3962     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
3963 
3964   if (!Constructor) {
3965     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3966     return;
3967   }
3968 
3969   // Mapping for the duplicate initializers check.
3970   // For member initializers, this is keyed with a FieldDecl*.
3971   // For base initializers, this is keyed with a Type*.
3972   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
3973 
3974   // Mapping for the inconsistent anonymous-union initializers check.
3975   RedundantUnionMap MemberUnions;
3976 
3977   bool HadError = false;
3978   for (unsigned i = 0; i < MemInits.size(); i++) {
3979     CXXCtorInitializer *Init = MemInits[i];
3980 
3981     // Set the source order index.
3982     Init->setSourceOrder(i);
3983 
3984     if (Init->isAnyMemberInitializer()) {
3985       const void *Key = GetKeyForMember(Context, Init);
3986       if (CheckRedundantInit(*this, Init, Members[Key]) ||
3987           CheckRedundantUnionInit(*this, Init, MemberUnions))
3988         HadError = true;
3989     } else if (Init->isBaseInitializer()) {
3990       const void *Key = GetKeyForMember(Context, Init);
3991       if (CheckRedundantInit(*this, Init, Members[Key]))
3992         HadError = true;
3993     } else {
3994       assert(Init->isDelegatingInitializer());
3995       // This must be the only initializer
3996       if (MemInits.size() != 1) {
3997         Diag(Init->getSourceLocation(),
3998              diag::err_delegating_initializer_alone)
3999           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
4000         // We will treat this as being the only initializer.
4001       }
4002       SetDelegatingInitializer(Constructor, MemInits[i]);
4003       // Return immediately as the initializer is set.
4004       return;
4005     }
4006   }
4007 
4008   if (HadError)
4009     return;
4010 
4011   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
4012 
4013   SetCtorInitializers(Constructor, AnyErrors, MemInits);
4014 
4015   DiagnoseUninitializedFields(*this, Constructor);
4016 }
4017 
4018 void
4019 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
4020                                              CXXRecordDecl *ClassDecl) {
4021   // Ignore dependent contexts. Also ignore unions, since their members never
4022   // have destructors implicitly called.
4023   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
4024     return;
4025 
4026   // FIXME: all the access-control diagnostics are positioned on the
4027   // field/base declaration.  That's probably good; that said, the
4028   // user might reasonably want to know why the destructor is being
4029   // emitted, and we currently don't say.
4030 
4031   // Non-static data members.
4032   for (auto *Field : ClassDecl->fields()) {
4033     if (Field->isInvalidDecl())
4034       continue;
4035 
4036     // Don't destroy incomplete or zero-length arrays.
4037     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
4038       continue;
4039 
4040     QualType FieldType = Context.getBaseElementType(Field->getType());
4041 
4042     const RecordType* RT = FieldType->getAs<RecordType>();
4043     if (!RT)
4044       continue;
4045 
4046     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4047     if (FieldClassDecl->isInvalidDecl())
4048       continue;
4049     if (FieldClassDecl->hasIrrelevantDestructor())
4050       continue;
4051     // The destructor for an implicit anonymous union member is never invoked.
4052     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4053       continue;
4054 
4055     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
4056     assert(Dtor && "No dtor found for FieldClassDecl!");
4057     CheckDestructorAccess(Field->getLocation(), Dtor,
4058                           PDiag(diag::err_access_dtor_field)
4059                             << Field->getDeclName()
4060                             << FieldType);
4061 
4062     MarkFunctionReferenced(Location, Dtor);
4063     DiagnoseUseOfDecl(Dtor, Location);
4064   }
4065 
4066   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4067 
4068   // Bases.
4069   for (const auto &Base : ClassDecl->bases()) {
4070     // Bases are always records in a well-formed non-dependent class.
4071     const RecordType *RT = Base.getType()->getAs<RecordType>();
4072 
4073     // Remember direct virtual bases.
4074     if (Base.isVirtual())
4075       DirectVirtualBases.insert(RT);
4076 
4077     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4078     // If our base class is invalid, we probably can't get its dtor anyway.
4079     if (BaseClassDecl->isInvalidDecl())
4080       continue;
4081     if (BaseClassDecl->hasIrrelevantDestructor())
4082       continue;
4083 
4084     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4085     assert(Dtor && "No dtor found for BaseClassDecl!");
4086 
4087     // FIXME: caret should be on the start of the class name
4088     CheckDestructorAccess(Base.getLocStart(), Dtor,
4089                           PDiag(diag::err_access_dtor_base)
4090                             << Base.getType()
4091                             << Base.getSourceRange(),
4092                           Context.getTypeDeclType(ClassDecl));
4093 
4094     MarkFunctionReferenced(Location, Dtor);
4095     DiagnoseUseOfDecl(Dtor, Location);
4096   }
4097 
4098   // Virtual bases.
4099   for (const auto &VBase : ClassDecl->vbases()) {
4100     // Bases are always records in a well-formed non-dependent class.
4101     const RecordType *RT = VBase.getType()->castAs<RecordType>();
4102 
4103     // Ignore direct virtual bases.
4104     if (DirectVirtualBases.count(RT))
4105       continue;
4106 
4107     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4108     // If our base class is invalid, we probably can't get its dtor anyway.
4109     if (BaseClassDecl->isInvalidDecl())
4110       continue;
4111     if (BaseClassDecl->hasIrrelevantDestructor())
4112       continue;
4113 
4114     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4115     assert(Dtor && "No dtor found for BaseClassDecl!");
4116     if (CheckDestructorAccess(
4117             ClassDecl->getLocation(), Dtor,
4118             PDiag(diag::err_access_dtor_vbase)
4119                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
4120             Context.getTypeDeclType(ClassDecl)) ==
4121         AR_accessible) {
4122       CheckDerivedToBaseConversion(
4123           Context.getTypeDeclType(ClassDecl), VBase.getType(),
4124           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4125           SourceRange(), DeclarationName(), nullptr);
4126     }
4127 
4128     MarkFunctionReferenced(Location, Dtor);
4129     DiagnoseUseOfDecl(Dtor, Location);
4130   }
4131 }
4132 
4133 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
4134   if (!CDtorDecl)
4135     return;
4136 
4137   if (CXXConstructorDecl *Constructor
4138       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
4139     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
4140     DiagnoseUninitializedFields(*this, Constructor);
4141   }
4142 }
4143 
4144 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4145                                   unsigned DiagID, AbstractDiagSelID SelID) {
4146   class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4147     unsigned DiagID;
4148     AbstractDiagSelID SelID;
4149 
4150   public:
4151     NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4152       : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
4153 
4154     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
4155       if (Suppressed) return;
4156       if (SelID == -1)
4157         S.Diag(Loc, DiagID) << T;
4158       else
4159         S.Diag(Loc, DiagID) << SelID << T;
4160     }
4161   } Diagnoser(DiagID, SelID);
4162 
4163   return RequireNonAbstractType(Loc, T, Diagnoser);
4164 }
4165 
4166 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4167                                   TypeDiagnoser &Diagnoser) {
4168   if (!getLangOpts().CPlusPlus)
4169     return false;
4170 
4171   if (const ArrayType *AT = Context.getAsArrayType(T))
4172     return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4173 
4174   if (const PointerType *PT = T->getAs<PointerType>()) {
4175     // Find the innermost pointer type.
4176     while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
4177       PT = T;
4178 
4179     if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
4180       return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4181   }
4182 
4183   const RecordType *RT = T->getAs<RecordType>();
4184   if (!RT)
4185     return false;
4186 
4187   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4188 
4189   // We can't answer whether something is abstract until it has a
4190   // definition.  If it's currently being defined, we'll walk back
4191   // over all the declarations when we have a full definition.
4192   const CXXRecordDecl *Def = RD->getDefinition();
4193   if (!Def || Def->isBeingDefined())
4194     return false;
4195 
4196   if (!RD->isAbstract())
4197     return false;
4198 
4199   Diagnoser.diagnose(*this, Loc, T);
4200   DiagnoseAbstractType(RD);
4201 
4202   return true;
4203 }
4204 
4205 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4206   // Check if we've already emitted the list of pure virtual functions
4207   // for this class.
4208   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
4209     return;
4210 
4211   // If the diagnostic is suppressed, don't emit the notes. We're only
4212   // going to emit them once, so try to attach them to a diagnostic we're
4213   // actually going to show.
4214   if (Diags.isLastDiagnosticIgnored())
4215     return;
4216 
4217   CXXFinalOverriderMap FinalOverriders;
4218   RD->getFinalOverriders(FinalOverriders);
4219 
4220   // Keep a set of seen pure methods so we won't diagnose the same method
4221   // more than once.
4222   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4223 
4224   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4225                                    MEnd = FinalOverriders.end();
4226        M != MEnd;
4227        ++M) {
4228     for (OverridingMethods::iterator SO = M->second.begin(),
4229                                   SOEnd = M->second.end();
4230          SO != SOEnd; ++SO) {
4231       // C++ [class.abstract]p4:
4232       //   A class is abstract if it contains or inherits at least one
4233       //   pure virtual function for which the final overrider is pure
4234       //   virtual.
4235 
4236       //
4237       if (SO->second.size() != 1)
4238         continue;
4239 
4240       if (!SO->second.front().Method->isPure())
4241         continue;
4242 
4243       if (!SeenPureMethods.insert(SO->second.front().Method))
4244         continue;
4245 
4246       Diag(SO->second.front().Method->getLocation(),
4247            diag::note_pure_virtual_function)
4248         << SO->second.front().Method->getDeclName() << RD->getDeclName();
4249     }
4250   }
4251 
4252   if (!PureVirtualClassDiagSet)
4253     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4254   PureVirtualClassDiagSet->insert(RD);
4255 }
4256 
4257 namespace {
4258 struct AbstractUsageInfo {
4259   Sema &S;
4260   CXXRecordDecl *Record;
4261   CanQualType AbstractType;
4262   bool Invalid;
4263 
4264   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4265     : S(S), Record(Record),
4266       AbstractType(S.Context.getCanonicalType(
4267                    S.Context.getTypeDeclType(Record))),
4268       Invalid(false) {}
4269 
4270   void DiagnoseAbstractType() {
4271     if (Invalid) return;
4272     S.DiagnoseAbstractType(Record);
4273     Invalid = true;
4274   }
4275 
4276   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4277 };
4278 
4279 struct CheckAbstractUsage {
4280   AbstractUsageInfo &Info;
4281   const NamedDecl *Ctx;
4282 
4283   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4284     : Info(Info), Ctx(Ctx) {}
4285 
4286   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4287     switch (TL.getTypeLocClass()) {
4288 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4289 #define TYPELOC(CLASS, PARENT) \
4290     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
4291 #include "clang/AST/TypeLocNodes.def"
4292     }
4293   }
4294 
4295   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4296     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
4297     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4298       if (!TL.getParam(I))
4299         continue;
4300 
4301       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
4302       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
4303     }
4304   }
4305 
4306   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4307     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4308   }
4309 
4310   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4311     // Visit the type parameters from a permissive context.
4312     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4313       TemplateArgumentLoc TAL = TL.getArgLoc(I);
4314       if (TAL.getArgument().getKind() == TemplateArgument::Type)
4315         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4316           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4317       // TODO: other template argument types?
4318     }
4319   }
4320 
4321   // Visit pointee types from a permissive context.
4322 #define CheckPolymorphic(Type) \
4323   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4324     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4325   }
4326   CheckPolymorphic(PointerTypeLoc)
4327   CheckPolymorphic(ReferenceTypeLoc)
4328   CheckPolymorphic(MemberPointerTypeLoc)
4329   CheckPolymorphic(BlockPointerTypeLoc)
4330   CheckPolymorphic(AtomicTypeLoc)
4331 
4332   /// Handle all the types we haven't given a more specific
4333   /// implementation for above.
4334   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4335     // Every other kind of type that we haven't called out already
4336     // that has an inner type is either (1) sugar or (2) contains that
4337     // inner type in some way as a subobject.
4338     if (TypeLoc Next = TL.getNextTypeLoc())
4339       return Visit(Next, Sel);
4340 
4341     // If there's no inner type and we're in a permissive context,
4342     // don't diagnose.
4343     if (Sel == Sema::AbstractNone) return;
4344 
4345     // Check whether the type matches the abstract type.
4346     QualType T = TL.getType();
4347     if (T->isArrayType()) {
4348       Sel = Sema::AbstractArrayType;
4349       T = Info.S.Context.getBaseElementType(T);
4350     }
4351     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4352     if (CT != Info.AbstractType) return;
4353 
4354     // It matched; do some magic.
4355     if (Sel == Sema::AbstractArrayType) {
4356       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4357         << T << TL.getSourceRange();
4358     } else {
4359       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4360         << Sel << T << TL.getSourceRange();
4361     }
4362     Info.DiagnoseAbstractType();
4363   }
4364 };
4365 
4366 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4367                                   Sema::AbstractDiagSelID Sel) {
4368   CheckAbstractUsage(*this, D).Visit(TL, Sel);
4369 }
4370 
4371 }
4372 
4373 /// Check for invalid uses of an abstract type in a method declaration.
4374 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4375                                     CXXMethodDecl *MD) {
4376   // No need to do the check on definitions, which require that
4377   // the return/param types be complete.
4378   if (MD->doesThisDeclarationHaveABody())
4379     return;
4380 
4381   // For safety's sake, just ignore it if we don't have type source
4382   // information.  This should never happen for non-implicit methods,
4383   // but...
4384   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4385     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4386 }
4387 
4388 /// Check for invalid uses of an abstract type within a class definition.
4389 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4390                                     CXXRecordDecl *RD) {
4391   for (auto *D : RD->decls()) {
4392     if (D->isImplicit()) continue;
4393 
4394     // Methods and method templates.
4395     if (isa<CXXMethodDecl>(D)) {
4396       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4397     } else if (isa<FunctionTemplateDecl>(D)) {
4398       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4399       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4400 
4401     // Fields and static variables.
4402     } else if (isa<FieldDecl>(D)) {
4403       FieldDecl *FD = cast<FieldDecl>(D);
4404       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4405         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4406     } else if (isa<VarDecl>(D)) {
4407       VarDecl *VD = cast<VarDecl>(D);
4408       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4409         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4410 
4411     // Nested classes and class templates.
4412     } else if (isa<CXXRecordDecl>(D)) {
4413       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4414     } else if (isa<ClassTemplateDecl>(D)) {
4415       CheckAbstractClassUsage(Info,
4416                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4417     }
4418   }
4419 }
4420 
4421 /// \brief Check class-level dllimport/dllexport attribute.
4422 static void checkDLLAttribute(Sema &S, CXXRecordDecl *Class) {
4423   Attr *ClassAttr = getDLLAttr(Class);
4424 
4425   // MSVC inherits DLL attributes to partial class template specializations.
4426   if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
4427     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
4428       if (Attr *TemplateAttr =
4429               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
4430         auto *A = cast<InheritableAttr>(TemplateAttr->clone(S.getASTContext()));
4431         A->setInherited(true);
4432         ClassAttr = A;
4433       }
4434     }
4435   }
4436 
4437   if (!ClassAttr)
4438     return;
4439 
4440   if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4441       !ClassAttr->isInherited()) {
4442     // Diagnose dll attributes on members of class with dll attribute.
4443     for (Decl *Member : Class->decls()) {
4444       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
4445         continue;
4446       InheritableAttr *MemberAttr = getDLLAttr(Member);
4447       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
4448         continue;
4449 
4450       S.Diag(MemberAttr->getLocation(),
4451              diag::err_attribute_dll_member_of_dll_class)
4452           << MemberAttr << ClassAttr;
4453       S.Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
4454       Member->setInvalidDecl();
4455     }
4456   }
4457 
4458   if (Class->getDescribedClassTemplate())
4459     // Don't inherit dll attribute until the template is instantiated.
4460     return;
4461 
4462   bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4463 
4464   // Force declaration of implicit members so they can inherit the attribute.
4465   S.ForceDeclarationOfImplicitMembers(Class);
4466 
4467   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4468   // seem to be true in practice?
4469 
4470   TemplateSpecializationKind TSK =
4471     Class->getTemplateSpecializationKind();
4472 
4473   for (Decl *Member : Class->decls()) {
4474     VarDecl *VD = dyn_cast<VarDecl>(Member);
4475     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4476 
4477     // Only methods and static fields inherit the attributes.
4478     if (!VD && !MD)
4479       continue;
4480 
4481     // Don't process deleted methods.
4482     if (MD && MD->isDeleted())
4483       continue;
4484 
4485     if (MD && MD->isMoveAssignmentOperator() && !ClassExported &&
4486         MD->isInlined()) {
4487       // Current MSVC versions don't export the move assignment operators, so
4488       // don't attempt to import them if we have a definition.
4489       continue;
4490     }
4491 
4492     if (!getDLLAttr(Member)) {
4493       auto *NewAttr =
4494           cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
4495       NewAttr->setInherited(true);
4496       Member->addAttr(NewAttr);
4497     }
4498 
4499     if (MD && ClassExported) {
4500       if (MD->isUserProvided()) {
4501         // Instantiate non-default methods..
4502 
4503         // .. except for certain kinds of template specializations.
4504         if (TSK == TSK_ExplicitInstantiationDeclaration)
4505           continue;
4506         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
4507           continue;
4508 
4509         S.MarkFunctionReferenced(Class->getLocation(), MD);
4510       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4511                  MD->isCopyAssignmentOperator() ||
4512                  MD->isMoveAssignmentOperator()) {
4513         // Instantiate non-trivial or explicitly defaulted methods, and the
4514         // copy assignment / move assignment operators.
4515         S.MarkFunctionReferenced(Class->getLocation(), MD);
4516         // Resolve its exception specification; CodeGen needs it.
4517         auto *FPT = MD->getType()->getAs<FunctionProtoType>();
4518         S.ResolveExceptionSpec(Class->getLocation(), FPT);
4519         S.ActOnFinishInlineMethodDef(MD);
4520       }
4521     }
4522   }
4523 }
4524 
4525 /// \brief Perform semantic checks on a class definition that has been
4526 /// completing, introducing implicitly-declared members, checking for
4527 /// abstract types, etc.
4528 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
4529   if (!Record)
4530     return;
4531 
4532   if (Record->isAbstract() && !Record->isInvalidDecl()) {
4533     AbstractUsageInfo Info(*this, Record);
4534     CheckAbstractClassUsage(Info, Record);
4535   }
4536 
4537   // If this is not an aggregate type and has no user-declared constructor,
4538   // complain about any non-static data members of reference or const scalar
4539   // type, since they will never get initializers.
4540   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
4541       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4542       !Record->isLambda()) {
4543     bool Complained = false;
4544     for (const auto *F : Record->fields()) {
4545       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
4546         continue;
4547 
4548       if (F->getType()->isReferenceType() ||
4549           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
4550         if (!Complained) {
4551           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4552             << Record->getTagKind() << Record;
4553           Complained = true;
4554         }
4555 
4556         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4557           << F->getType()->isReferenceType()
4558           << F->getDeclName();
4559       }
4560     }
4561   }
4562 
4563   if (Record->isDynamicClass() && !Record->isDependentType())
4564     DynamicClasses.push_back(Record);
4565 
4566   if (Record->getIdentifier()) {
4567     // C++ [class.mem]p13:
4568     //   If T is the name of a class, then each of the following shall have a
4569     //   name different from T:
4570     //     - every member of every anonymous union that is a member of class T.
4571     //
4572     // C++ [class.mem]p14:
4573     //   In addition, if class T has a user-declared constructor (12.1), every
4574     //   non-static data member of class T shall have a name different from T.
4575     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4576     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4577          ++I) {
4578       NamedDecl *D = *I;
4579       if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4580           isa<IndirectFieldDecl>(D)) {
4581         Diag(D->getLocation(), diag::err_member_name_of_class)
4582           << D->getDeclName();
4583         break;
4584       }
4585     }
4586   }
4587 
4588   // Warn if the class has virtual methods but non-virtual public destructor.
4589   if (Record->isPolymorphic() && !Record->isDependentType()) {
4590     CXXDestructorDecl *dtor = Record->getDestructor();
4591     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4592         !Record->hasAttr<FinalAttr>())
4593       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4594            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4595   }
4596 
4597   if (Record->isAbstract()) {
4598     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4599       Diag(Record->getLocation(), diag::warn_abstract_final_class)
4600         << FA->isSpelledAsSealed();
4601       DiagnoseAbstractType(Record);
4602     }
4603   }
4604 
4605   if (!Record->isDependentType()) {
4606     for (auto *M : Record->methods()) {
4607       // See if a method overloads virtual methods in a base
4608       // class without overriding any.
4609       if (!M->isStatic())
4610         DiagnoseHiddenVirtualMethods(M);
4611 
4612       // Check whether the explicitly-defaulted special members are valid.
4613       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4614         CheckExplicitlyDefaultedSpecialMember(M);
4615 
4616       // For an explicitly defaulted or deleted special member, we defer
4617       // determining triviality until the class is complete. That time is now!
4618       if (!M->isImplicit() && !M->isUserProvided()) {
4619         CXXSpecialMember CSM = getSpecialMember(M);
4620         if (CSM != CXXInvalid) {
4621           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
4622 
4623           // Inform the class that we've finished declaring this member.
4624           Record->finishedDefaultedOrDeletedMember(M);
4625         }
4626       }
4627     }
4628   }
4629 
4630   // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4631   // function that is not a constructor declares that member function to be
4632   // const. [...] The class of which that function is a member shall be
4633   // a literal type.
4634   //
4635   // If the class has virtual bases, any constexpr members will already have
4636   // been diagnosed by the checks performed on the member declaration, so
4637   // suppress this (less useful) diagnostic.
4638   //
4639   // We delay this until we know whether an explicitly-defaulted (or deleted)
4640   // destructor for the class is trivial.
4641   if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
4642       !Record->isLiteral() && !Record->getNumVBases()) {
4643     for (const auto *M : Record->methods()) {
4644       if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) {
4645         switch (Record->getTemplateSpecializationKind()) {
4646         case TSK_ImplicitInstantiation:
4647         case TSK_ExplicitInstantiationDeclaration:
4648         case TSK_ExplicitInstantiationDefinition:
4649           // If a template instantiates to a non-literal type, but its members
4650           // instantiate to constexpr functions, the template is technically
4651           // ill-formed, but we allow it for sanity.
4652           continue;
4653 
4654         case TSK_Undeclared:
4655         case TSK_ExplicitSpecialization:
4656           RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4657                              diag::err_constexpr_method_non_literal);
4658           break;
4659         }
4660 
4661         // Only produce one error per class.
4662         break;
4663       }
4664     }
4665   }
4666 
4667   // ms_struct is a request to use the same ABI rules as MSVC.  Check
4668   // whether this class uses any C++ features that are implemented
4669   // completely differently in MSVC, and if so, emit a diagnostic.
4670   // That diagnostic defaults to an error, but we allow projects to
4671   // map it down to a warning (or ignore it).  It's a fairly common
4672   // practice among users of the ms_struct pragma to mass-annotate
4673   // headers, sweeping up a bunch of types that the project doesn't
4674   // really rely on MSVC-compatible layout for.  We must therefore
4675   // support "ms_struct except for C++ stuff" as a secondary ABI.
4676   if (Record->isMsStruct(Context) &&
4677       (Record->isPolymorphic() || Record->getNumBases())) {
4678     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
4679   }
4680 
4681   // Declare inheriting constructors. We do this eagerly here because:
4682   // - The standard requires an eager diagnostic for conflicting inheriting
4683   //   constructors from different classes.
4684   // - The lazy declaration of the other implicit constructors is so as to not
4685   //   waste space and performance on classes that are not meant to be
4686   //   instantiated (e.g. meta-functions). This doesn't apply to classes that
4687   //   have inheriting constructors.
4688   DeclareInheritingConstructors(Record);
4689 
4690   checkDLLAttribute(*this, Record);
4691 }
4692 
4693 /// Look up the special member function that would be called by a special
4694 /// member function for a subobject of class type.
4695 ///
4696 /// \param Class The class type of the subobject.
4697 /// \param CSM The kind of special member function.
4698 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4699 /// \param ConstRHS True if this is a copy operation with a const object
4700 ///        on its RHS, that is, if the argument to the outer special member
4701 ///        function is 'const' and this is not a field marked 'mutable'.
4702 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
4703     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
4704     unsigned FieldQuals, bool ConstRHS) {
4705   unsigned LHSQuals = 0;
4706   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
4707     LHSQuals = FieldQuals;
4708 
4709   unsigned RHSQuals = FieldQuals;
4710   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4711     RHSQuals = 0;
4712   else if (ConstRHS)
4713     RHSQuals |= Qualifiers::Const;
4714 
4715   return S.LookupSpecialMember(Class, CSM,
4716                                RHSQuals & Qualifiers::Const,
4717                                RHSQuals & Qualifiers::Volatile,
4718                                false,
4719                                LHSQuals & Qualifiers::Const,
4720                                LHSQuals & Qualifiers::Volatile);
4721 }
4722 
4723 /// Is the special member function which would be selected to perform the
4724 /// specified operation on the specified class type a constexpr constructor?
4725 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4726                                      Sema::CXXSpecialMember CSM,
4727                                      unsigned Quals, bool ConstRHS) {
4728   Sema::SpecialMemberOverloadResult *SMOR =
4729       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
4730   if (!SMOR || !SMOR->getMethod())
4731     // A constructor we wouldn't select can't be "involved in initializing"
4732     // anything.
4733     return true;
4734   return SMOR->getMethod()->isConstexpr();
4735 }
4736 
4737 /// Determine whether the specified special member function would be constexpr
4738 /// if it were implicitly defined.
4739 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4740                                               Sema::CXXSpecialMember CSM,
4741                                               bool ConstArg) {
4742   if (!S.getLangOpts().CPlusPlus11)
4743     return false;
4744 
4745   // C++11 [dcl.constexpr]p4:
4746   // In the definition of a constexpr constructor [...]
4747   bool Ctor = true;
4748   switch (CSM) {
4749   case Sema::CXXDefaultConstructor:
4750     // Since default constructor lookup is essentially trivial (and cannot
4751     // involve, for instance, template instantiation), we compute whether a
4752     // defaulted default constructor is constexpr directly within CXXRecordDecl.
4753     //
4754     // This is important for performance; we need to know whether the default
4755     // constructor is constexpr to determine whether the type is a literal type.
4756     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4757 
4758   case Sema::CXXCopyConstructor:
4759   case Sema::CXXMoveConstructor:
4760     // For copy or move constructors, we need to perform overload resolution.
4761     break;
4762 
4763   case Sema::CXXCopyAssignment:
4764   case Sema::CXXMoveAssignment:
4765     if (!S.getLangOpts().CPlusPlus14)
4766       return false;
4767     // In C++1y, we need to perform overload resolution.
4768     Ctor = false;
4769     break;
4770 
4771   case Sema::CXXDestructor:
4772   case Sema::CXXInvalid:
4773     return false;
4774   }
4775 
4776   //   -- if the class is a non-empty union, or for each non-empty anonymous
4777   //      union member of a non-union class, exactly one non-static data member
4778   //      shall be initialized; [DR1359]
4779   //
4780   // If we squint, this is guaranteed, since exactly one non-static data member
4781   // will be initialized (if the constructor isn't deleted), we just don't know
4782   // which one.
4783   if (Ctor && ClassDecl->isUnion())
4784     return true;
4785 
4786   //   -- the class shall not have any virtual base classes;
4787   if (Ctor && ClassDecl->getNumVBases())
4788     return false;
4789 
4790   // C++1y [class.copy]p26:
4791   //   -- [the class] is a literal type, and
4792   if (!Ctor && !ClassDecl->isLiteral())
4793     return false;
4794 
4795   //   -- every constructor involved in initializing [...] base class
4796   //      sub-objects shall be a constexpr constructor;
4797   //   -- the assignment operator selected to copy/move each direct base
4798   //      class is a constexpr function, and
4799   for (const auto &B : ClassDecl->bases()) {
4800     const RecordType *BaseType = B.getType()->getAs<RecordType>();
4801     if (!BaseType) continue;
4802 
4803     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4804     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
4805       return false;
4806   }
4807 
4808   //   -- every constructor involved in initializing non-static data members
4809   //      [...] shall be a constexpr constructor;
4810   //   -- every non-static data member and base class sub-object shall be
4811   //      initialized
4812   //   -- for each non-static data member of X that is of class type (or array
4813   //      thereof), the assignment operator selected to copy/move that member is
4814   //      a constexpr function
4815   for (const auto *F : ClassDecl->fields()) {
4816     if (F->isInvalidDecl())
4817       continue;
4818     QualType BaseType = S.Context.getBaseElementType(F->getType());
4819     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
4820       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4821       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
4822                                     BaseType.getCVRQualifiers(),
4823                                     ConstArg && !F->isMutable()))
4824         return false;
4825     }
4826   }
4827 
4828   // All OK, it's constexpr!
4829   return true;
4830 }
4831 
4832 static Sema::ImplicitExceptionSpecification
4833 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4834   switch (S.getSpecialMember(MD)) {
4835   case Sema::CXXDefaultConstructor:
4836     return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4837   case Sema::CXXCopyConstructor:
4838     return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4839   case Sema::CXXCopyAssignment:
4840     return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4841   case Sema::CXXMoveConstructor:
4842     return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4843   case Sema::CXXMoveAssignment:
4844     return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4845   case Sema::CXXDestructor:
4846     return S.ComputeDefaultedDtorExceptionSpec(MD);
4847   case Sema::CXXInvalid:
4848     break;
4849   }
4850   assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4851          "only special members have implicit exception specs");
4852   return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
4853 }
4854 
4855 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4856                                                             CXXMethodDecl *MD) {
4857   FunctionProtoType::ExtProtoInfo EPI;
4858 
4859   // Build an exception specification pointing back at this member.
4860   EPI.ExceptionSpec.Type = EST_Unevaluated;
4861   EPI.ExceptionSpec.SourceDecl = MD;
4862 
4863   // Set the calling convention to the default for C++ instance methods.
4864   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4865       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4866                                             /*IsCXXMethod=*/true));
4867   return EPI;
4868 }
4869 
4870 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4871   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4872   if (FPT->getExceptionSpecType() != EST_Unevaluated)
4873     return;
4874 
4875   // Evaluate the exception specification.
4876   auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
4877 
4878   // Update the type of the special member to use it.
4879   UpdateExceptionSpec(MD, ESI);
4880 
4881   // A user-provided destructor can be defined outside the class. When that
4882   // happens, be sure to update the exception specification on both
4883   // declarations.
4884   const FunctionProtoType *CanonicalFPT =
4885     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4886   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4887     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
4888 }
4889 
4890 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4891   CXXRecordDecl *RD = MD->getParent();
4892   CXXSpecialMember CSM = getSpecialMember(MD);
4893 
4894   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4895          "not an explicitly-defaulted special member");
4896 
4897   // Whether this was the first-declared instance of the constructor.
4898   // This affects whether we implicitly add an exception spec and constexpr.
4899   bool First = MD == MD->getCanonicalDecl();
4900 
4901   bool HadError = false;
4902 
4903   // C++11 [dcl.fct.def.default]p1:
4904   //   A function that is explicitly defaulted shall
4905   //     -- be a special member function (checked elsewhere),
4906   //     -- have the same type (except for ref-qualifiers, and except that a
4907   //        copy operation can take a non-const reference) as an implicit
4908   //        declaration, and
4909   //     -- not have default arguments.
4910   unsigned ExpectedParams = 1;
4911   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4912     ExpectedParams = 0;
4913   if (MD->getNumParams() != ExpectedParams) {
4914     // This also checks for default arguments: a copy or move constructor with a
4915     // default argument is classified as a default constructor, and assignment
4916     // operations and destructors can't have default arguments.
4917     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4918       << CSM << MD->getSourceRange();
4919     HadError = true;
4920   } else if (MD->isVariadic()) {
4921     Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4922       << CSM << MD->getSourceRange();
4923     HadError = true;
4924   }
4925 
4926   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
4927 
4928   bool CanHaveConstParam = false;
4929   if (CSM == CXXCopyConstructor)
4930     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
4931   else if (CSM == CXXCopyAssignment)
4932     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
4933 
4934   QualType ReturnType = Context.VoidTy;
4935   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4936     // Check for return type matching.
4937     ReturnType = Type->getReturnType();
4938     QualType ExpectedReturnType =
4939         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4940     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4941       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4942         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4943       HadError = true;
4944     }
4945 
4946     // A defaulted special member cannot have cv-qualifiers.
4947     if (Type->getTypeQuals()) {
4948       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4949         << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
4950       HadError = true;
4951     }
4952   }
4953 
4954   // Check for parameter type matching.
4955   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
4956   bool HasConstParam = false;
4957   if (ExpectedParams && ArgType->isReferenceType()) {
4958     // Argument must be reference to possibly-const T.
4959     QualType ReferentType = ArgType->getPointeeType();
4960     HasConstParam = ReferentType.isConstQualified();
4961 
4962     if (ReferentType.isVolatileQualified()) {
4963       Diag(MD->getLocation(),
4964            diag::err_defaulted_special_member_volatile_param) << CSM;
4965       HadError = true;
4966     }
4967 
4968     if (HasConstParam && !CanHaveConstParam) {
4969       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4970         Diag(MD->getLocation(),
4971              diag::err_defaulted_special_member_copy_const_param)
4972           << (CSM == CXXCopyAssignment);
4973         // FIXME: Explain why this special member can't be const.
4974       } else {
4975         Diag(MD->getLocation(),
4976              diag::err_defaulted_special_member_move_const_param)
4977           << (CSM == CXXMoveAssignment);
4978       }
4979       HadError = true;
4980     }
4981   } else if (ExpectedParams) {
4982     // A copy assignment operator can take its argument by value, but a
4983     // defaulted one cannot.
4984     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
4985     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
4986     HadError = true;
4987   }
4988 
4989   // C++11 [dcl.fct.def.default]p2:
4990   //   An explicitly-defaulted function may be declared constexpr only if it
4991   //   would have been implicitly declared as constexpr,
4992   // Do not apply this rule to members of class templates, since core issue 1358
4993   // makes such functions always instantiate to constexpr functions. For
4994   // functions which cannot be constexpr (for non-constructors in C++11 and for
4995   // destructors in C++1y), this is checked elsewhere.
4996   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4997                                                      HasConstParam);
4998   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
4999                                  : isa<CXXConstructorDecl>(MD)) &&
5000       MD->isConstexpr() && !Constexpr &&
5001       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
5002     Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
5003     // FIXME: Explain why the special member can't be constexpr.
5004     HadError = true;
5005   }
5006 
5007   //   and may have an explicit exception-specification only if it is compatible
5008   //   with the exception-specification on the implicit declaration.
5009   if (Type->hasExceptionSpec()) {
5010     // Delay the check if this is the first declaration of the special member,
5011     // since we may not have parsed some necessary in-class initializers yet.
5012     if (First) {
5013       // If the exception specification needs to be instantiated, do so now,
5014       // before we clobber it with an EST_Unevaluated specification below.
5015       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
5016         InstantiateExceptionSpec(MD->getLocStart(), MD);
5017         Type = MD->getType()->getAs<FunctionProtoType>();
5018       }
5019       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
5020     } else
5021       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
5022   }
5023 
5024   //   If a function is explicitly defaulted on its first declaration,
5025   if (First) {
5026     //  -- it is implicitly considered to be constexpr if the implicit
5027     //     definition would be,
5028     MD->setConstexpr(Constexpr);
5029 
5030     //  -- it is implicitly considered to have the same exception-specification
5031     //     as if it had been implicitly declared,
5032     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
5033     EPI.ExceptionSpec.Type = EST_Unevaluated;
5034     EPI.ExceptionSpec.SourceDecl = MD;
5035     MD->setType(Context.getFunctionType(ReturnType,
5036                                         ArrayRef<QualType>(&ArgType,
5037                                                            ExpectedParams),
5038                                         EPI));
5039   }
5040 
5041   if (ShouldDeleteSpecialMember(MD, CSM)) {
5042     if (First) {
5043       SetDeclDeleted(MD, MD->getLocation());
5044     } else {
5045       // C++11 [dcl.fct.def.default]p4:
5046       //   [For a] user-provided explicitly-defaulted function [...] if such a
5047       //   function is implicitly defined as deleted, the program is ill-formed.
5048       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
5049       ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
5050       HadError = true;
5051     }
5052   }
5053 
5054   if (HadError)
5055     MD->setInvalidDecl();
5056 }
5057 
5058 /// Check whether the exception specification provided for an
5059 /// explicitly-defaulted special member matches the exception specification
5060 /// that would have been generated for an implicit special member, per
5061 /// C++11 [dcl.fct.def.default]p2.
5062 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
5063     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
5064   // Compute the implicit exception specification.
5065   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5066                                                        /*IsCXXMethod=*/true);
5067   FunctionProtoType::ExtProtoInfo EPI(CC);
5068   EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
5069                           .getExceptionSpec();
5070   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
5071     Context.getFunctionType(Context.VoidTy, None, EPI));
5072 
5073   // Ensure that it matches.
5074   CheckEquivalentExceptionSpec(
5075     PDiag(diag::err_incorrect_defaulted_exception_spec)
5076       << getSpecialMember(MD), PDiag(),
5077     ImplicitType, SourceLocation(),
5078     SpecifiedType, MD->getLocation());
5079 }
5080 
5081 void Sema::CheckDelayedMemberExceptionSpecs() {
5082   SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
5083               2> Checks;
5084   SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
5085 
5086   std::swap(Checks, DelayedDestructorExceptionSpecChecks);
5087   std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
5088 
5089   // Perform any deferred checking of exception specifications for virtual
5090   // destructors.
5091   for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
5092     const CXXDestructorDecl *Dtor = Checks[i].first;
5093     assert(!Dtor->getParent()->isDependentType() &&
5094            "Should not ever add destructors of templates into the list.");
5095     CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
5096   }
5097 
5098   // Check that any explicitly-defaulted methods have exception specifications
5099   // compatible with their implicit exception specifications.
5100   for (unsigned I = 0, N = Specs.size(); I != N; ++I)
5101     CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
5102                                                 Specs[I].second);
5103 }
5104 
5105 namespace {
5106 struct SpecialMemberDeletionInfo {
5107   Sema &S;
5108   CXXMethodDecl *MD;
5109   Sema::CXXSpecialMember CSM;
5110   bool Diagnose;
5111 
5112   // Properties of the special member, computed for convenience.
5113   bool IsConstructor, IsAssignment, IsMove, ConstArg;
5114   SourceLocation Loc;
5115 
5116   bool AllFieldsAreConst;
5117 
5118   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
5119                             Sema::CXXSpecialMember CSM, bool Diagnose)
5120     : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
5121       IsConstructor(false), IsAssignment(false), IsMove(false),
5122       ConstArg(false), Loc(MD->getLocation()),
5123       AllFieldsAreConst(true) {
5124     switch (CSM) {
5125       case Sema::CXXDefaultConstructor:
5126       case Sema::CXXCopyConstructor:
5127         IsConstructor = true;
5128         break;
5129       case Sema::CXXMoveConstructor:
5130         IsConstructor = true;
5131         IsMove = true;
5132         break;
5133       case Sema::CXXCopyAssignment:
5134         IsAssignment = true;
5135         break;
5136       case Sema::CXXMoveAssignment:
5137         IsAssignment = true;
5138         IsMove = true;
5139         break;
5140       case Sema::CXXDestructor:
5141         break;
5142       case Sema::CXXInvalid:
5143         llvm_unreachable("invalid special member kind");
5144     }
5145 
5146     if (MD->getNumParams()) {
5147       if (const ReferenceType *RT =
5148               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5149         ConstArg = RT->getPointeeType().isConstQualified();
5150     }
5151   }
5152 
5153   bool inUnion() const { return MD->getParent()->isUnion(); }
5154 
5155   /// Look up the corresponding special member in the given class.
5156   Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
5157                                               unsigned Quals, bool IsMutable) {
5158     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5159                                        ConstArg && !IsMutable);
5160   }
5161 
5162   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
5163 
5164   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
5165   bool shouldDeleteForField(FieldDecl *FD);
5166   bool shouldDeleteForAllConstMembers();
5167 
5168   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5169                                      unsigned Quals);
5170   bool shouldDeleteForSubobjectCall(Subobject Subobj,
5171                                     Sema::SpecialMemberOverloadResult *SMOR,
5172                                     bool IsDtorCallInCtor);
5173 
5174   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
5175 };
5176 }
5177 
5178 /// Is the given special member inaccessible when used on the given
5179 /// sub-object.
5180 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5181                                              CXXMethodDecl *target) {
5182   /// If we're operating on a base class, the object type is the
5183   /// type of this special member.
5184   QualType objectTy;
5185   AccessSpecifier access = target->getAccess();
5186   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5187     objectTy = S.Context.getTypeDeclType(MD->getParent());
5188     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5189 
5190   // If we're operating on a field, the object type is the type of the field.
5191   } else {
5192     objectTy = S.Context.getTypeDeclType(target->getParent());
5193   }
5194 
5195   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5196 }
5197 
5198 /// Check whether we should delete a special member due to the implicit
5199 /// definition containing a call to a special member of a subobject.
5200 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5201     Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5202     bool IsDtorCallInCtor) {
5203   CXXMethodDecl *Decl = SMOR->getMethod();
5204   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5205 
5206   int DiagKind = -1;
5207 
5208   if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5209     DiagKind = !Decl ? 0 : 1;
5210   else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5211     DiagKind = 2;
5212   else if (!isAccessible(Subobj, Decl))
5213     DiagKind = 3;
5214   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5215            !Decl->isTrivial()) {
5216     // A member of a union must have a trivial corresponding special member.
5217     // As a weird special case, a destructor call from a union's constructor
5218     // must be accessible and non-deleted, but need not be trivial. Such a
5219     // destructor is never actually called, but is semantically checked as
5220     // if it were.
5221     DiagKind = 4;
5222   }
5223 
5224   if (DiagKind == -1)
5225     return false;
5226 
5227   if (Diagnose) {
5228     if (Field) {
5229       S.Diag(Field->getLocation(),
5230              diag::note_deleted_special_member_class_subobject)
5231         << CSM << MD->getParent() << /*IsField*/true
5232         << Field << DiagKind << IsDtorCallInCtor;
5233     } else {
5234       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5235       S.Diag(Base->getLocStart(),
5236              diag::note_deleted_special_member_class_subobject)
5237         << CSM << MD->getParent() << /*IsField*/false
5238         << Base->getType() << DiagKind << IsDtorCallInCtor;
5239     }
5240 
5241     if (DiagKind == 1)
5242       S.NoteDeletedFunction(Decl);
5243     // FIXME: Explain inaccessibility if DiagKind == 3.
5244   }
5245 
5246   return true;
5247 }
5248 
5249 /// Check whether we should delete a special member function due to having a
5250 /// direct or virtual base class or non-static data member of class type M.
5251 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
5252     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
5253   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5254   bool IsMutable = Field && Field->isMutable();
5255 
5256   // C++11 [class.ctor]p5:
5257   // -- any direct or virtual base class, or non-static data member with no
5258   //    brace-or-equal-initializer, has class type M (or array thereof) and
5259   //    either M has no default constructor or overload resolution as applied
5260   //    to M's default constructor results in an ambiguity or in a function
5261   //    that is deleted or inaccessible
5262   // C++11 [class.copy]p11, C++11 [class.copy]p23:
5263   // -- a direct or virtual base class B that cannot be copied/moved because
5264   //    overload resolution, as applied to B's corresponding special member,
5265   //    results in an ambiguity or a function that is deleted or inaccessible
5266   //    from the defaulted special member
5267   // C++11 [class.dtor]p5:
5268   // -- any direct or virtual base class [...] has a type with a destructor
5269   //    that is deleted or inaccessible
5270   if (!(CSM == Sema::CXXDefaultConstructor &&
5271         Field && Field->hasInClassInitializer()) &&
5272       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5273                                    false))
5274     return true;
5275 
5276   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5277   // -- any direct or virtual base class or non-static data member has a
5278   //    type with a destructor that is deleted or inaccessible
5279   if (IsConstructor) {
5280     Sema::SpecialMemberOverloadResult *SMOR =
5281         S.LookupSpecialMember(Class, Sema::CXXDestructor,
5282                               false, false, false, false, false);
5283     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5284       return true;
5285   }
5286 
5287   return false;
5288 }
5289 
5290 /// Check whether we should delete a special member function due to the class
5291 /// having a particular direct or virtual base class.
5292 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
5293   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
5294   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
5295 }
5296 
5297 /// Check whether we should delete a special member function due to the class
5298 /// having a particular non-static data member.
5299 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5300   QualType FieldType = S.Context.getBaseElementType(FD->getType());
5301   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5302 
5303   if (CSM == Sema::CXXDefaultConstructor) {
5304     // For a default constructor, all references must be initialized in-class
5305     // and, if a union, it must have a non-const member.
5306     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5307       if (Diagnose)
5308         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5309           << MD->getParent() << FD << FieldType << /*Reference*/0;
5310       return true;
5311     }
5312     // C++11 [class.ctor]p5: any non-variant non-static data member of
5313     // const-qualified type (or array thereof) with no
5314     // brace-or-equal-initializer does not have a user-provided default
5315     // constructor.
5316     if (!inUnion() && FieldType.isConstQualified() &&
5317         !FD->hasInClassInitializer() &&
5318         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5319       if (Diagnose)
5320         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5321           << MD->getParent() << FD << FD->getType() << /*Const*/1;
5322       return true;
5323     }
5324 
5325     if (inUnion() && !FieldType.isConstQualified())
5326       AllFieldsAreConst = false;
5327   } else if (CSM == Sema::CXXCopyConstructor) {
5328     // For a copy constructor, data members must not be of rvalue reference
5329     // type.
5330     if (FieldType->isRValueReferenceType()) {
5331       if (Diagnose)
5332         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5333           << MD->getParent() << FD << FieldType;
5334       return true;
5335     }
5336   } else if (IsAssignment) {
5337     // For an assignment operator, data members must not be of reference type.
5338     if (FieldType->isReferenceType()) {
5339       if (Diagnose)
5340         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5341           << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
5342       return true;
5343     }
5344     if (!FieldRecord && FieldType.isConstQualified()) {
5345       // C++11 [class.copy]p23:
5346       // -- a non-static data member of const non-class type (or array thereof)
5347       if (Diagnose)
5348         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5349           << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
5350       return true;
5351     }
5352   }
5353 
5354   if (FieldRecord) {
5355     // Some additional restrictions exist on the variant members.
5356     if (!inUnion() && FieldRecord->isUnion() &&
5357         FieldRecord->isAnonymousStructOrUnion()) {
5358       bool AllVariantFieldsAreConst = true;
5359 
5360       // FIXME: Handle anonymous unions declared within anonymous unions.
5361       for (auto *UI : FieldRecord->fields()) {
5362         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
5363 
5364         if (!UnionFieldType.isConstQualified())
5365           AllVariantFieldsAreConst = false;
5366 
5367         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5368         if (UnionFieldRecord &&
5369             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
5370                                           UnionFieldType.getCVRQualifiers()))
5371           return true;
5372       }
5373 
5374       // At least one member in each anonymous union must be non-const
5375       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
5376           !FieldRecord->field_empty()) {
5377         if (Diagnose)
5378           S.Diag(FieldRecord->getLocation(),
5379                  diag::note_deleted_default_ctor_all_const)
5380             << MD->getParent() << /*anonymous union*/1;
5381         return true;
5382       }
5383 
5384       // Don't check the implicit member of the anonymous union type.
5385       // This is technically non-conformant, but sanity demands it.
5386       return false;
5387     }
5388 
5389     if (shouldDeleteForClassSubobject(FieldRecord, FD,
5390                                       FieldType.getCVRQualifiers()))
5391       return true;
5392   }
5393 
5394   return false;
5395 }
5396 
5397 /// C++11 [class.ctor] p5:
5398 ///   A defaulted default constructor for a class X is defined as deleted if
5399 /// X is a union and all of its variant members are of const-qualified type.
5400 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
5401   // This is a silly definition, because it gives an empty union a deleted
5402   // default constructor. Don't do that.
5403   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5404       !MD->getParent()->field_empty()) {
5405     if (Diagnose)
5406       S.Diag(MD->getParent()->getLocation(),
5407              diag::note_deleted_default_ctor_all_const)
5408         << MD->getParent() << /*not anonymous union*/0;
5409     return true;
5410   }
5411   return false;
5412 }
5413 
5414 /// Determine whether a defaulted special member function should be defined as
5415 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5416 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
5417 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5418                                      bool Diagnose) {
5419   if (MD->isInvalidDecl())
5420     return false;
5421   CXXRecordDecl *RD = MD->getParent();
5422   assert(!RD->isDependentType() && "do deletion after instantiation");
5423   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
5424     return false;
5425 
5426   // C++11 [expr.lambda.prim]p19:
5427   //   The closure type associated with a lambda-expression has a
5428   //   deleted (8.4.3) default constructor and a deleted copy
5429   //   assignment operator.
5430   if (RD->isLambda() &&
5431       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5432     if (Diagnose)
5433       Diag(RD->getLocation(), diag::note_lambda_decl);
5434     return true;
5435   }
5436 
5437   // For an anonymous struct or union, the copy and assignment special members
5438   // will never be used, so skip the check. For an anonymous union declared at
5439   // namespace scope, the constructor and destructor are used.
5440   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5441       RD->isAnonymousStructOrUnion())
5442     return false;
5443 
5444   // C++11 [class.copy]p7, p18:
5445   //   If the class definition declares a move constructor or move assignment
5446   //   operator, an implicitly declared copy constructor or copy assignment
5447   //   operator is defined as deleted.
5448   if (MD->isImplicit() &&
5449       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5450     CXXMethodDecl *UserDeclaredMove = nullptr;
5451 
5452     // In Microsoft mode, a user-declared move only causes the deletion of the
5453     // corresponding copy operation, not both copy operations.
5454     if (RD->hasUserDeclaredMoveConstructor() &&
5455         (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
5456       if (!Diagnose) return true;
5457 
5458       // Find any user-declared move constructor.
5459       for (auto *I : RD->ctors()) {
5460         if (I->isMoveConstructor()) {
5461           UserDeclaredMove = I;
5462           break;
5463         }
5464       }
5465       assert(UserDeclaredMove);
5466     } else if (RD->hasUserDeclaredMoveAssignment() &&
5467                (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
5468       if (!Diagnose) return true;
5469 
5470       // Find any user-declared move assignment operator.
5471       for (auto *I : RD->methods()) {
5472         if (I->isMoveAssignmentOperator()) {
5473           UserDeclaredMove = I;
5474           break;
5475         }
5476       }
5477       assert(UserDeclaredMove);
5478     }
5479 
5480     if (UserDeclaredMove) {
5481       Diag(UserDeclaredMove->getLocation(),
5482            diag::note_deleted_copy_user_declared_move)
5483         << (CSM == CXXCopyAssignment) << RD
5484         << UserDeclaredMove->isMoveAssignmentOperator();
5485       return true;
5486     }
5487   }
5488 
5489   // Do access control from the special member function
5490   ContextRAII MethodContext(*this, MD);
5491 
5492   // C++11 [class.dtor]p5:
5493   // -- for a virtual destructor, lookup of the non-array deallocation function
5494   //    results in an ambiguity or in a function that is deleted or inaccessible
5495   if (CSM == CXXDestructor && MD->isVirtual()) {
5496     FunctionDecl *OperatorDelete = nullptr;
5497     DeclarationName Name =
5498       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5499     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
5500                                  OperatorDelete, false)) {
5501       if (Diagnose)
5502         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
5503       return true;
5504     }
5505   }
5506 
5507   SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
5508 
5509   for (auto &BI : RD->bases())
5510     if (!BI.isVirtual() &&
5511         SMI.shouldDeleteForBase(&BI))
5512       return true;
5513 
5514   // Per DR1611, do not consider virtual bases of constructors of abstract
5515   // classes, since we are not going to construct them.
5516   if (!RD->isAbstract() || !SMI.IsConstructor) {
5517     for (auto &BI : RD->vbases())
5518       if (SMI.shouldDeleteForBase(&BI))
5519         return true;
5520   }
5521 
5522   for (auto *FI : RD->fields())
5523     if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
5524         SMI.shouldDeleteForField(FI))
5525       return true;
5526 
5527   if (SMI.shouldDeleteForAllConstMembers())
5528     return true;
5529 
5530   return false;
5531 }
5532 
5533 /// Perform lookup for a special member of the specified kind, and determine
5534 /// whether it is trivial. If the triviality can be determined without the
5535 /// lookup, skip it. This is intended for use when determining whether a
5536 /// special member of a containing object is trivial, and thus does not ever
5537 /// perform overload resolution for default constructors.
5538 ///
5539 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5540 /// member that was most likely to be intended to be trivial, if any.
5541 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5542                                      Sema::CXXSpecialMember CSM, unsigned Quals,
5543                                      bool ConstRHS, CXXMethodDecl **Selected) {
5544   if (Selected)
5545     *Selected = nullptr;
5546 
5547   switch (CSM) {
5548   case Sema::CXXInvalid:
5549     llvm_unreachable("not a special member");
5550 
5551   case Sema::CXXDefaultConstructor:
5552     // C++11 [class.ctor]p5:
5553     //   A default constructor is trivial if:
5554     //    - all the [direct subobjects] have trivial default constructors
5555     //
5556     // Note, no overload resolution is performed in this case.
5557     if (RD->hasTrivialDefaultConstructor())
5558       return true;
5559 
5560     if (Selected) {
5561       // If there's a default constructor which could have been trivial, dig it
5562       // out. Otherwise, if there's any user-provided default constructor, point
5563       // to that as an example of why there's not a trivial one.
5564       CXXConstructorDecl *DefCtor = nullptr;
5565       if (RD->needsImplicitDefaultConstructor())
5566         S.DeclareImplicitDefaultConstructor(RD);
5567       for (auto *CI : RD->ctors()) {
5568         if (!CI->isDefaultConstructor())
5569           continue;
5570         DefCtor = CI;
5571         if (!DefCtor->isUserProvided())
5572           break;
5573       }
5574 
5575       *Selected = DefCtor;
5576     }
5577 
5578     return false;
5579 
5580   case Sema::CXXDestructor:
5581     // C++11 [class.dtor]p5:
5582     //   A destructor is trivial if:
5583     //    - all the direct [subobjects] have trivial destructors
5584     if (RD->hasTrivialDestructor())
5585       return true;
5586 
5587     if (Selected) {
5588       if (RD->needsImplicitDestructor())
5589         S.DeclareImplicitDestructor(RD);
5590       *Selected = RD->getDestructor();
5591     }
5592 
5593     return false;
5594 
5595   case Sema::CXXCopyConstructor:
5596     // C++11 [class.copy]p12:
5597     //   A copy constructor is trivial if:
5598     //    - the constructor selected to copy each direct [subobject] is trivial
5599     if (RD->hasTrivialCopyConstructor()) {
5600       if (Quals == Qualifiers::Const)
5601         // We must either select the trivial copy constructor or reach an
5602         // ambiguity; no need to actually perform overload resolution.
5603         return true;
5604     } else if (!Selected) {
5605       return false;
5606     }
5607     // In C++98, we are not supposed to perform overload resolution here, but we
5608     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5609     // cases like B as having a non-trivial copy constructor:
5610     //   struct A { template<typename T> A(T&); };
5611     //   struct B { mutable A a; };
5612     goto NeedOverloadResolution;
5613 
5614   case Sema::CXXCopyAssignment:
5615     // C++11 [class.copy]p25:
5616     //   A copy assignment operator is trivial if:
5617     //    - the assignment operator selected to copy each direct [subobject] is
5618     //      trivial
5619     if (RD->hasTrivialCopyAssignment()) {
5620       if (Quals == Qualifiers::Const)
5621         return true;
5622     } else if (!Selected) {
5623       return false;
5624     }
5625     // In C++98, we are not supposed to perform overload resolution here, but we
5626     // treat that as a language defect.
5627     goto NeedOverloadResolution;
5628 
5629   case Sema::CXXMoveConstructor:
5630   case Sema::CXXMoveAssignment:
5631   NeedOverloadResolution:
5632     Sema::SpecialMemberOverloadResult *SMOR =
5633         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
5634 
5635     // The standard doesn't describe how to behave if the lookup is ambiguous.
5636     // We treat it as not making the member non-trivial, just like the standard
5637     // mandates for the default constructor. This should rarely matter, because
5638     // the member will also be deleted.
5639     if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5640       return true;
5641 
5642     if (!SMOR->getMethod()) {
5643       assert(SMOR->getKind() ==
5644              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5645       return false;
5646     }
5647 
5648     // We deliberately don't check if we found a deleted special member. We're
5649     // not supposed to!
5650     if (Selected)
5651       *Selected = SMOR->getMethod();
5652     return SMOR->getMethod()->isTrivial();
5653   }
5654 
5655   llvm_unreachable("unknown special method kind");
5656 }
5657 
5658 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
5659   for (auto *CI : RD->ctors())
5660     if (!CI->isImplicit())
5661       return CI;
5662 
5663   // Look for constructor templates.
5664   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5665   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5666     if (CXXConstructorDecl *CD =
5667           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5668       return CD;
5669   }
5670 
5671   return nullptr;
5672 }
5673 
5674 /// The kind of subobject we are checking for triviality. The values of this
5675 /// enumeration are used in diagnostics.
5676 enum TrivialSubobjectKind {
5677   /// The subobject is a base class.
5678   TSK_BaseClass,
5679   /// The subobject is a non-static data member.
5680   TSK_Field,
5681   /// The object is actually the complete object.
5682   TSK_CompleteObject
5683 };
5684 
5685 /// Check whether the special member selected for a given type would be trivial.
5686 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5687                                       QualType SubType, bool ConstRHS,
5688                                       Sema::CXXSpecialMember CSM,
5689                                       TrivialSubobjectKind Kind,
5690                                       bool Diagnose) {
5691   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5692   if (!SubRD)
5693     return true;
5694 
5695   CXXMethodDecl *Selected;
5696   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5697                                ConstRHS, Diagnose ? &Selected : nullptr))
5698     return true;
5699 
5700   if (Diagnose) {
5701     if (ConstRHS)
5702       SubType.addConst();
5703 
5704     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5705       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5706         << Kind << SubType.getUnqualifiedType();
5707       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5708         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5709     } else if (!Selected)
5710       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5711         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5712     else if (Selected->isUserProvided()) {
5713       if (Kind == TSK_CompleteObject)
5714         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5715           << Kind << SubType.getUnqualifiedType() << CSM;
5716       else {
5717         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5718           << Kind << SubType.getUnqualifiedType() << CSM;
5719         S.Diag(Selected->getLocation(), diag::note_declared_at);
5720       }
5721     } else {
5722       if (Kind != TSK_CompleteObject)
5723         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5724           << Kind << SubType.getUnqualifiedType() << CSM;
5725 
5726       // Explain why the defaulted or deleted special member isn't trivial.
5727       S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5728     }
5729   }
5730 
5731   return false;
5732 }
5733 
5734 /// Check whether the members of a class type allow a special member to be
5735 /// trivial.
5736 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5737                                      Sema::CXXSpecialMember CSM,
5738                                      bool ConstArg, bool Diagnose) {
5739   for (const auto *FI : RD->fields()) {
5740     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5741       continue;
5742 
5743     QualType FieldType = S.Context.getBaseElementType(FI->getType());
5744 
5745     // Pretend anonymous struct or union members are members of this class.
5746     if (FI->isAnonymousStructOrUnion()) {
5747       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5748                                     CSM, ConstArg, Diagnose))
5749         return false;
5750       continue;
5751     }
5752 
5753     // C++11 [class.ctor]p5:
5754     //   A default constructor is trivial if [...]
5755     //    -- no non-static data member of its class has a
5756     //       brace-or-equal-initializer
5757     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5758       if (Diagnose)
5759         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
5760       return false;
5761     }
5762 
5763     // Objective C ARC 4.3.5:
5764     //   [...] nontrivally ownership-qualified types are [...] not trivially
5765     //   default constructible, copy constructible, move constructible, copy
5766     //   assignable, move assignable, or destructible [...]
5767     if (S.getLangOpts().ObjCAutoRefCount &&
5768         FieldType.hasNonTrivialObjCLifetime()) {
5769       if (Diagnose)
5770         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5771           << RD << FieldType.getObjCLifetime();
5772       return false;
5773     }
5774 
5775     bool ConstRHS = ConstArg && !FI->isMutable();
5776     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
5777                                    CSM, TSK_Field, Diagnose))
5778       return false;
5779   }
5780 
5781   return true;
5782 }
5783 
5784 /// Diagnose why the specified class does not have a trivial special member of
5785 /// the given kind.
5786 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5787   QualType Ty = Context.getRecordType(RD);
5788 
5789   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
5790   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
5791                             TSK_CompleteObject, /*Diagnose*/true);
5792 }
5793 
5794 /// Determine whether a defaulted or deleted special member function is trivial,
5795 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5796 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5797 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5798                                   bool Diagnose) {
5799   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5800 
5801   CXXRecordDecl *RD = MD->getParent();
5802 
5803   bool ConstArg = false;
5804 
5805   // C++11 [class.copy]p12, p25: [DR1593]
5806   //   A [special member] is trivial if [...] its parameter-type-list is
5807   //   equivalent to the parameter-type-list of an implicit declaration [...]
5808   switch (CSM) {
5809   case CXXDefaultConstructor:
5810   case CXXDestructor:
5811     // Trivial default constructors and destructors cannot have parameters.
5812     break;
5813 
5814   case CXXCopyConstructor:
5815   case CXXCopyAssignment: {
5816     // Trivial copy operations always have const, non-volatile parameter types.
5817     ConstArg = true;
5818     const ParmVarDecl *Param0 = MD->getParamDecl(0);
5819     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5820     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5821       if (Diagnose)
5822         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5823           << Param0->getSourceRange() << Param0->getType()
5824           << Context.getLValueReferenceType(
5825                Context.getRecordType(RD).withConst());
5826       return false;
5827     }
5828     break;
5829   }
5830 
5831   case CXXMoveConstructor:
5832   case CXXMoveAssignment: {
5833     // Trivial move operations always have non-cv-qualified parameters.
5834     const ParmVarDecl *Param0 = MD->getParamDecl(0);
5835     const RValueReferenceType *RT =
5836       Param0->getType()->getAs<RValueReferenceType>();
5837     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5838       if (Diagnose)
5839         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5840           << Param0->getSourceRange() << Param0->getType()
5841           << Context.getRValueReferenceType(Context.getRecordType(RD));
5842       return false;
5843     }
5844     break;
5845   }
5846 
5847   case CXXInvalid:
5848     llvm_unreachable("not a special member");
5849   }
5850 
5851   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5852     if (Diagnose)
5853       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5854            diag::note_nontrivial_default_arg)
5855         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5856     return false;
5857   }
5858   if (MD->isVariadic()) {
5859     if (Diagnose)
5860       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5861     return false;
5862   }
5863 
5864   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5865   //   A copy/move [constructor or assignment operator] is trivial if
5866   //    -- the [member] selected to copy/move each direct base class subobject
5867   //       is trivial
5868   //
5869   // C++11 [class.copy]p12, C++11 [class.copy]p25:
5870   //   A [default constructor or destructor] is trivial if
5871   //    -- all the direct base classes have trivial [default constructors or
5872   //       destructors]
5873   for (const auto &BI : RD->bases())
5874     if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
5875                                    ConstArg, CSM, TSK_BaseClass, Diagnose))
5876       return false;
5877 
5878   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5879   //   A copy/move [constructor or assignment operator] for a class X is
5880   //   trivial if
5881   //    -- for each non-static data member of X that is of class type (or array
5882   //       thereof), the constructor selected to copy/move that member is
5883   //       trivial
5884   //
5885   // C++11 [class.copy]p12, C++11 [class.copy]p25:
5886   //   A [default constructor or destructor] is trivial if
5887   //    -- for all of the non-static data members of its class that are of class
5888   //       type (or array thereof), each such class has a trivial [default
5889   //       constructor or destructor]
5890   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5891     return false;
5892 
5893   // C++11 [class.dtor]p5:
5894   //   A destructor is trivial if [...]
5895   //    -- the destructor is not virtual
5896   if (CSM == CXXDestructor && MD->isVirtual()) {
5897     if (Diagnose)
5898       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5899     return false;
5900   }
5901 
5902   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5903   //   A [special member] for class X is trivial if [...]
5904   //    -- class X has no virtual functions and no virtual base classes
5905   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5906     if (!Diagnose)
5907       return false;
5908 
5909     if (RD->getNumVBases()) {
5910       // Check for virtual bases. We already know that the corresponding
5911       // member in all bases is trivial, so vbases must all be direct.
5912       CXXBaseSpecifier &BS = *RD->vbases_begin();
5913       assert(BS.isVirtual());
5914       Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5915       return false;
5916     }
5917 
5918     // Must have a virtual method.
5919     for (const auto *MI : RD->methods()) {
5920       if (MI->isVirtual()) {
5921         SourceLocation MLoc = MI->getLocStart();
5922         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5923         return false;
5924       }
5925     }
5926 
5927     llvm_unreachable("dynamic class with no vbases and no virtual functions");
5928   }
5929 
5930   // Looks like it's trivial!
5931   return true;
5932 }
5933 
5934 /// \brief Data used with FindHiddenVirtualMethod
5935 namespace {
5936   struct FindHiddenVirtualMethodData {
5937     Sema *S;
5938     CXXMethodDecl *Method;
5939     llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
5940     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5941   };
5942 }
5943 
5944 /// \brief Check whether any most overriden method from MD in Methods
5945 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5946                   const llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
5947   if (MD->size_overridden_methods() == 0)
5948     return Methods.count(MD->getCanonicalDecl());
5949   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5950                                       E = MD->end_overridden_methods();
5951        I != E; ++I)
5952     if (CheckMostOverridenMethods(*I, Methods))
5953       return true;
5954   return false;
5955 }
5956 
5957 /// \brief Member lookup function that determines whether a given C++
5958 /// method overloads virtual methods in a base class without overriding any,
5959 /// to be used with CXXRecordDecl::lookupInBases().
5960 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5961                                     CXXBasePath &Path,
5962                                     void *UserData) {
5963   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5964 
5965   FindHiddenVirtualMethodData &Data
5966     = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5967 
5968   DeclarationName Name = Data.Method->getDeclName();
5969   assert(Name.getNameKind() == DeclarationName::Identifier);
5970 
5971   bool foundSameNameMethod = false;
5972   SmallVector<CXXMethodDecl *, 8> overloadedMethods;
5973   for (Path.Decls = BaseRecord->lookup(Name);
5974        !Path.Decls.empty();
5975        Path.Decls = Path.Decls.slice(1)) {
5976     NamedDecl *D = Path.Decls.front();
5977     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5978       MD = MD->getCanonicalDecl();
5979       foundSameNameMethod = true;
5980       // Interested only in hidden virtual methods.
5981       if (!MD->isVirtual())
5982         continue;
5983       // If the method we are checking overrides a method from its base
5984       // don't warn about the other overloaded methods. Clang deviates from GCC
5985       // by only diagnosing overloads of inherited virtual functions that do not
5986       // override any other virtual functions in the base. GCC's
5987       // -Woverloaded-virtual diagnoses any derived function hiding a virtual
5988       // function from a base class. These cases may be better served by a
5989       // warning (not specific to virtual functions) on call sites when the call
5990       // would select a different function from the base class, were it visible.
5991       // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
5992       if (!Data.S->IsOverload(Data.Method, MD, false))
5993         return true;
5994       // Collect the overload only if its hidden.
5995       if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
5996         overloadedMethods.push_back(MD);
5997     }
5998   }
5999 
6000   if (foundSameNameMethod)
6001     Data.OverloadedMethods.append(overloadedMethods.begin(),
6002                                    overloadedMethods.end());
6003   return foundSameNameMethod;
6004 }
6005 
6006 /// \brief Add the most overriden methods from MD to Methods
6007 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
6008                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
6009   if (MD->size_overridden_methods() == 0)
6010     Methods.insert(MD->getCanonicalDecl());
6011   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6012                                       E = MD->end_overridden_methods();
6013        I != E; ++I)
6014     AddMostOverridenMethods(*I, Methods);
6015 }
6016 
6017 /// \brief Check if a method overloads virtual methods in a base class without
6018 /// overriding any.
6019 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
6020                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6021   if (!MD->getDeclName().isIdentifier())
6022     return;
6023 
6024   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
6025                      /*bool RecordPaths=*/false,
6026                      /*bool DetectVirtual=*/false);
6027   FindHiddenVirtualMethodData Data;
6028   Data.Method = MD;
6029   Data.S = this;
6030 
6031   // Keep the base methods that were overriden or introduced in the subclass
6032   // by 'using' in a set. A base method not in this set is hidden.
6033   CXXRecordDecl *DC = MD->getParent();
6034   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
6035   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
6036     NamedDecl *ND = *I;
6037     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
6038       ND = shad->getTargetDecl();
6039     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6040       AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
6041   }
6042 
6043   if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
6044     OverloadedMethods = Data.OverloadedMethods;
6045 }
6046 
6047 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6048                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6049   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
6050     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
6051     PartialDiagnostic PD = PDiag(
6052          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
6053     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
6054     Diag(overloadedMD->getLocation(), PD);
6055   }
6056 }
6057 
6058 /// \brief Diagnose methods which overload virtual methods in a base class
6059 /// without overriding any.
6060 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
6061   if (MD->isInvalidDecl())
6062     return;
6063 
6064   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
6065     return;
6066 
6067   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6068   FindHiddenVirtualMethods(MD, OverloadedMethods);
6069   if (!OverloadedMethods.empty()) {
6070     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
6071       << MD << (OverloadedMethods.size() > 1);
6072 
6073     NoteHiddenVirtualMethods(MD, OverloadedMethods);
6074   }
6075 }
6076 
6077 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
6078                                              Decl *TagDecl,
6079                                              SourceLocation LBrac,
6080                                              SourceLocation RBrac,
6081                                              AttributeList *AttrList) {
6082   if (!TagDecl)
6083     return;
6084 
6085   AdjustDeclIfTemplate(TagDecl);
6086 
6087   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6088     if (l->getKind() != AttributeList::AT_Visibility)
6089       continue;
6090     l->setInvalid();
6091     Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
6092       l->getName();
6093   }
6094 
6095   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
6096               // strict aliasing violation!
6097               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
6098               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
6099 
6100   CheckCompletedCXXClass(
6101                         dyn_cast_or_null<CXXRecordDecl>(TagDecl));
6102 }
6103 
6104 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6105 /// special functions, such as the default constructor, copy
6106 /// constructor, or destructor, to the given C++ class (C++
6107 /// [special]p1).  This routine can only be executed just before the
6108 /// definition of the class is complete.
6109 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
6110   if (!ClassDecl->hasUserDeclaredConstructor())
6111     ++ASTContext::NumImplicitDefaultConstructors;
6112 
6113   if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
6114     ++ASTContext::NumImplicitCopyConstructors;
6115 
6116     // If the properties or semantics of the copy constructor couldn't be
6117     // determined while the class was being declared, force a declaration
6118     // of it now.
6119     if (ClassDecl->needsOverloadResolutionForCopyConstructor())
6120       DeclareImplicitCopyConstructor(ClassDecl);
6121   }
6122 
6123   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
6124     ++ASTContext::NumImplicitMoveConstructors;
6125 
6126     if (ClassDecl->needsOverloadResolutionForMoveConstructor())
6127       DeclareImplicitMoveConstructor(ClassDecl);
6128   }
6129 
6130   if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6131     ++ASTContext::NumImplicitCopyAssignmentOperators;
6132 
6133     // If we have a dynamic class, then the copy assignment operator may be
6134     // virtual, so we have to declare it immediately. This ensures that, e.g.,
6135     // it shows up in the right place in the vtable and that we diagnose
6136     // problems with the implicit exception specification.
6137     if (ClassDecl->isDynamicClass() ||
6138         ClassDecl->needsOverloadResolutionForCopyAssignment())
6139       DeclareImplicitCopyAssignment(ClassDecl);
6140   }
6141 
6142   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
6143     ++ASTContext::NumImplicitMoveAssignmentOperators;
6144 
6145     // Likewise for the move assignment operator.
6146     if (ClassDecl->isDynamicClass() ||
6147         ClassDecl->needsOverloadResolutionForMoveAssignment())
6148       DeclareImplicitMoveAssignment(ClassDecl);
6149   }
6150 
6151   if (!ClassDecl->hasUserDeclaredDestructor()) {
6152     ++ASTContext::NumImplicitDestructors;
6153 
6154     // If we have a dynamic class, then the destructor may be virtual, so we
6155     // have to declare the destructor immediately. This ensures that, e.g., it
6156     // shows up in the right place in the vtable and that we diagnose problems
6157     // with the implicit exception specification.
6158     if (ClassDecl->isDynamicClass() ||
6159         ClassDecl->needsOverloadResolutionForDestructor())
6160       DeclareImplicitDestructor(ClassDecl);
6161   }
6162 }
6163 
6164 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
6165   if (!D)
6166     return 0;
6167 
6168   // The order of template parameters is not important here. All names
6169   // get added to the same scope.
6170   SmallVector<TemplateParameterList *, 4> ParameterLists;
6171 
6172   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6173     D = TD->getTemplatedDecl();
6174 
6175   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6176     ParameterLists.push_back(PSD->getTemplateParameters());
6177 
6178   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6179     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6180       ParameterLists.push_back(DD->getTemplateParameterList(i));
6181 
6182     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6183       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6184         ParameterLists.push_back(FTD->getTemplateParameters());
6185     }
6186   }
6187 
6188   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6189     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6190       ParameterLists.push_back(TD->getTemplateParameterList(i));
6191 
6192     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6193       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6194         ParameterLists.push_back(CTD->getTemplateParameters());
6195     }
6196   }
6197 
6198   unsigned Count = 0;
6199   for (TemplateParameterList *Params : ParameterLists) {
6200     if (Params->size() > 0)
6201       // Ignore explicit specializations; they don't contribute to the template
6202       // depth.
6203       ++Count;
6204     for (NamedDecl *Param : *Params) {
6205       if (Param->getDeclName()) {
6206         S->AddDecl(Param);
6207         IdResolver.AddDecl(Param);
6208       }
6209     }
6210   }
6211 
6212   return Count;
6213 }
6214 
6215 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6216   if (!RecordD) return;
6217   AdjustDeclIfTemplate(RecordD);
6218   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
6219   PushDeclContext(S, Record);
6220 }
6221 
6222 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6223   if (!RecordD) return;
6224   PopDeclContext();
6225 }
6226 
6227 /// This is used to implement the constant expression evaluation part of the
6228 /// attribute enable_if extension. There is nothing in standard C++ which would
6229 /// require reentering parameters.
6230 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6231   if (!Param)
6232     return;
6233 
6234   S->AddDecl(Param);
6235   if (Param->getDeclName())
6236     IdResolver.AddDecl(Param);
6237 }
6238 
6239 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
6240 /// parsing a top-level (non-nested) C++ class, and we are now
6241 /// parsing those parts of the given Method declaration that could
6242 /// not be parsed earlier (C++ [class.mem]p2), such as default
6243 /// arguments. This action should enter the scope of the given
6244 /// Method declaration as if we had just parsed the qualified method
6245 /// name. However, it should not bring the parameters into scope;
6246 /// that will be performed by ActOnDelayedCXXMethodParameter.
6247 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6248 }
6249 
6250 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
6251 /// C++ method declaration. We're (re-)introducing the given
6252 /// function parameter into scope for use in parsing later parts of
6253 /// the method declaration. For example, we could see an
6254 /// ActOnParamDefaultArgument event for this parameter.
6255 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
6256   if (!ParamD)
6257     return;
6258 
6259   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
6260 
6261   // If this parameter has an unparsed default argument, clear it out
6262   // to make way for the parsed default argument.
6263   if (Param->hasUnparsedDefaultArg())
6264     Param->setDefaultArg(nullptr);
6265 
6266   S->AddDecl(Param);
6267   if (Param->getDeclName())
6268     IdResolver.AddDecl(Param);
6269 }
6270 
6271 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6272 /// processing the delayed method declaration for Method. The method
6273 /// declaration is now considered finished. There may be a separate
6274 /// ActOnStartOfFunctionDef action later (not necessarily
6275 /// immediately!) for this method, if it was also defined inside the
6276 /// class body.
6277 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6278   if (!MethodD)
6279     return;
6280 
6281   AdjustDeclIfTemplate(MethodD);
6282 
6283   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
6284 
6285   // Now that we have our default arguments, check the constructor
6286   // again. It could produce additional diagnostics or affect whether
6287   // the class has implicitly-declared destructors, among other
6288   // things.
6289   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6290     CheckConstructor(Constructor);
6291 
6292   // Check the default arguments, which we may have added.
6293   if (!Method->isInvalidDecl())
6294     CheckCXXDefaultArguments(Method);
6295 }
6296 
6297 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
6298 /// the well-formedness of the constructor declarator @p D with type @p
6299 /// R. If there are any errors in the declarator, this routine will
6300 /// emit diagnostics and set the invalid bit to true.  In any case, the type
6301 /// will be updated to reflect a well-formed type for the constructor and
6302 /// returned.
6303 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
6304                                           StorageClass &SC) {
6305   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6306 
6307   // C++ [class.ctor]p3:
6308   //   A constructor shall not be virtual (10.3) or static (9.4). A
6309   //   constructor can be invoked for a const, volatile or const
6310   //   volatile object. A constructor shall not be declared const,
6311   //   volatile, or const volatile (9.3.2).
6312   if (isVirtual) {
6313     if (!D.isInvalidType())
6314       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6315         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6316         << SourceRange(D.getIdentifierLoc());
6317     D.setInvalidType();
6318   }
6319   if (SC == SC_Static) {
6320     if (!D.isInvalidType())
6321       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6322         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6323         << SourceRange(D.getIdentifierLoc());
6324     D.setInvalidType();
6325     SC = SC_None;
6326   }
6327 
6328   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6329     diagnoseIgnoredQualifiers(
6330         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
6331         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
6332         D.getDeclSpec().getRestrictSpecLoc(),
6333         D.getDeclSpec().getAtomicSpecLoc());
6334     D.setInvalidType();
6335   }
6336 
6337   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6338   if (FTI.TypeQuals != 0) {
6339     if (FTI.TypeQuals & Qualifiers::Const)
6340       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6341         << "const" << SourceRange(D.getIdentifierLoc());
6342     if (FTI.TypeQuals & Qualifiers::Volatile)
6343       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6344         << "volatile" << SourceRange(D.getIdentifierLoc());
6345     if (FTI.TypeQuals & Qualifiers::Restrict)
6346       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6347         << "restrict" << SourceRange(D.getIdentifierLoc());
6348     D.setInvalidType();
6349   }
6350 
6351   // C++0x [class.ctor]p4:
6352   //   A constructor shall not be declared with a ref-qualifier.
6353   if (FTI.hasRefQualifier()) {
6354     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6355       << FTI.RefQualifierIsLValueRef
6356       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6357     D.setInvalidType();
6358   }
6359 
6360   // Rebuild the function type "R" without any type qualifiers (in
6361   // case any of the errors above fired) and with "void" as the
6362   // return type, since constructors don't have return types.
6363   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6364   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
6365     return R;
6366 
6367   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6368   EPI.TypeQuals = 0;
6369   EPI.RefQualifier = RQ_None;
6370 
6371   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
6372 }
6373 
6374 /// CheckConstructor - Checks a fully-formed constructor for
6375 /// well-formedness, issuing any diagnostics required. Returns true if
6376 /// the constructor declarator is invalid.
6377 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
6378   CXXRecordDecl *ClassDecl
6379     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6380   if (!ClassDecl)
6381     return Constructor->setInvalidDecl();
6382 
6383   // C++ [class.copy]p3:
6384   //   A declaration of a constructor for a class X is ill-formed if
6385   //   its first parameter is of type (optionally cv-qualified) X and
6386   //   either there are no other parameters or else all other
6387   //   parameters have default arguments.
6388   if (!Constructor->isInvalidDecl() &&
6389       ((Constructor->getNumParams() == 1) ||
6390        (Constructor->getNumParams() > 1 &&
6391         Constructor->getParamDecl(1)->hasDefaultArg())) &&
6392       Constructor->getTemplateSpecializationKind()
6393                                               != TSK_ImplicitInstantiation) {
6394     QualType ParamType = Constructor->getParamDecl(0)->getType();
6395     QualType ClassTy = Context.getTagDeclType(ClassDecl);
6396     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
6397       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
6398       const char *ConstRef
6399         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6400                                                         : " const &";
6401       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
6402         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
6403 
6404       // FIXME: Rather that making the constructor invalid, we should endeavor
6405       // to fix the type.
6406       Constructor->setInvalidDecl();
6407     }
6408   }
6409 }
6410 
6411 /// CheckDestructor - Checks a fully-formed destructor definition for
6412 /// well-formedness, issuing any diagnostics required.  Returns true
6413 /// on error.
6414 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
6415   CXXRecordDecl *RD = Destructor->getParent();
6416 
6417   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
6418     SourceLocation Loc;
6419 
6420     if (!Destructor->isImplicit())
6421       Loc = Destructor->getLocation();
6422     else
6423       Loc = RD->getLocation();
6424 
6425     // If we have a virtual destructor, look up the deallocation function
6426     FunctionDecl *OperatorDelete = nullptr;
6427     DeclarationName Name =
6428     Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6429     if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
6430       return true;
6431     // If there's no class-specific operator delete, look up the global
6432     // non-array delete.
6433     if (!OperatorDelete)
6434       OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
6435 
6436     MarkFunctionReferenced(Loc, OperatorDelete);
6437 
6438     Destructor->setOperatorDelete(OperatorDelete);
6439   }
6440 
6441   return false;
6442 }
6443 
6444 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6445 /// the well-formednes of the destructor declarator @p D with type @p
6446 /// R. If there are any errors in the declarator, this routine will
6447 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
6448 /// will be updated to reflect a well-formed type for the destructor and
6449 /// returned.
6450 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
6451                                          StorageClass& SC) {
6452   // C++ [class.dtor]p1:
6453   //   [...] A typedef-name that names a class is a class-name
6454   //   (7.1.3); however, a typedef-name that names a class shall not
6455   //   be used as the identifier in the declarator for a destructor
6456   //   declaration.
6457   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
6458   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
6459     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6460       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
6461   else if (const TemplateSpecializationType *TST =
6462              DeclaratorType->getAs<TemplateSpecializationType>())
6463     if (TST->isTypeAlias())
6464       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6465         << DeclaratorType << 1;
6466 
6467   // C++ [class.dtor]p2:
6468   //   A destructor is used to destroy objects of its class type. A
6469   //   destructor takes no parameters, and no return type can be
6470   //   specified for it (not even void). The address of a destructor
6471   //   shall not be taken. A destructor shall not be static. A
6472   //   destructor can be invoked for a const, volatile or const
6473   //   volatile object. A destructor shall not be declared const,
6474   //   volatile or const volatile (9.3.2).
6475   if (SC == SC_Static) {
6476     if (!D.isInvalidType())
6477       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6478         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6479         << SourceRange(D.getIdentifierLoc())
6480         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6481 
6482     SC = SC_None;
6483   }
6484   if (!D.isInvalidType()) {
6485     // Destructors don't have return types, but the parser will
6486     // happily parse something like:
6487     //
6488     //   class X {
6489     //     float ~X();
6490     //   };
6491     //
6492     // The return type will be eliminated later.
6493     if (D.getDeclSpec().hasTypeSpecifier())
6494       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6495         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6496         << SourceRange(D.getIdentifierLoc());
6497     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6498       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
6499                                 SourceLocation(),
6500                                 D.getDeclSpec().getConstSpecLoc(),
6501                                 D.getDeclSpec().getVolatileSpecLoc(),
6502                                 D.getDeclSpec().getRestrictSpecLoc(),
6503                                 D.getDeclSpec().getAtomicSpecLoc());
6504       D.setInvalidType();
6505     }
6506   }
6507 
6508   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6509   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
6510     if (FTI.TypeQuals & Qualifiers::Const)
6511       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6512         << "const" << SourceRange(D.getIdentifierLoc());
6513     if (FTI.TypeQuals & Qualifiers::Volatile)
6514       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6515         << "volatile" << SourceRange(D.getIdentifierLoc());
6516     if (FTI.TypeQuals & Qualifiers::Restrict)
6517       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6518         << "restrict" << SourceRange(D.getIdentifierLoc());
6519     D.setInvalidType();
6520   }
6521 
6522   // C++0x [class.dtor]p2:
6523   //   A destructor shall not be declared with a ref-qualifier.
6524   if (FTI.hasRefQualifier()) {
6525     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6526       << FTI.RefQualifierIsLValueRef
6527       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6528     D.setInvalidType();
6529   }
6530 
6531   // Make sure we don't have any parameters.
6532   if (FTIHasNonVoidParameters(FTI)) {
6533     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6534 
6535     // Delete the parameters.
6536     FTI.freeParams();
6537     D.setInvalidType();
6538   }
6539 
6540   // Make sure the destructor isn't variadic.
6541   if (FTI.isVariadic) {
6542     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
6543     D.setInvalidType();
6544   }
6545 
6546   // Rebuild the function type "R" without any type qualifiers or
6547   // parameters (in case any of the errors above fired) and with
6548   // "void" as the return type, since destructors don't have return
6549   // types.
6550   if (!D.isInvalidType())
6551     return R;
6552 
6553   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6554   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6555   EPI.Variadic = false;
6556   EPI.TypeQuals = 0;
6557   EPI.RefQualifier = RQ_None;
6558   return Context.getFunctionType(Context.VoidTy, None, EPI);
6559 }
6560 
6561 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6562 /// well-formednes of the conversion function declarator @p D with
6563 /// type @p R. If there are any errors in the declarator, this routine
6564 /// will emit diagnostics and return true. Otherwise, it will return
6565 /// false. Either way, the type @p R will be updated to reflect a
6566 /// well-formed type for the conversion operator.
6567 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
6568                                      StorageClass& SC) {
6569   // C++ [class.conv.fct]p1:
6570   //   Neither parameter types nor return type can be specified. The
6571   //   type of a conversion function (8.3.5) is "function taking no
6572   //   parameter returning conversion-type-id."
6573   if (SC == SC_Static) {
6574     if (!D.isInvalidType())
6575       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
6576         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6577         << D.getName().getSourceRange();
6578     D.setInvalidType();
6579     SC = SC_None;
6580   }
6581 
6582   QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6583 
6584   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
6585     // Conversion functions don't have return types, but the parser will
6586     // happily parse something like:
6587     //
6588     //   class X {
6589     //     float operator bool();
6590     //   };
6591     //
6592     // The return type will be changed later anyway.
6593     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6594       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6595       << SourceRange(D.getIdentifierLoc());
6596     D.setInvalidType();
6597   }
6598 
6599   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6600 
6601   // Make sure we don't have any parameters.
6602   if (Proto->getNumParams() > 0) {
6603     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6604 
6605     // Delete the parameters.
6606     D.getFunctionTypeInfo().freeParams();
6607     D.setInvalidType();
6608   } else if (Proto->isVariadic()) {
6609     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
6610     D.setInvalidType();
6611   }
6612 
6613   // Diagnose "&operator bool()" and other such nonsense.  This
6614   // is actually a gcc extension which we don't support.
6615   if (Proto->getReturnType() != ConvType) {
6616     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6617         << Proto->getReturnType();
6618     D.setInvalidType();
6619     ConvType = Proto->getReturnType();
6620   }
6621 
6622   // C++ [class.conv.fct]p4:
6623   //   The conversion-type-id shall not represent a function type nor
6624   //   an array type.
6625   if (ConvType->isArrayType()) {
6626     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6627     ConvType = Context.getPointerType(ConvType);
6628     D.setInvalidType();
6629   } else if (ConvType->isFunctionType()) {
6630     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6631     ConvType = Context.getPointerType(ConvType);
6632     D.setInvalidType();
6633   }
6634 
6635   // Rebuild the function type "R" without any parameters (in case any
6636   // of the errors above fired) and with the conversion type as the
6637   // return type.
6638   if (D.isInvalidType())
6639     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
6640 
6641   // C++0x explicit conversion operators.
6642   if (D.getDeclSpec().isExplicitSpecified())
6643     Diag(D.getDeclSpec().getExplicitSpecLoc(),
6644          getLangOpts().CPlusPlus11 ?
6645            diag::warn_cxx98_compat_explicit_conversion_functions :
6646            diag::ext_explicit_conversion_functions)
6647       << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
6648 }
6649 
6650 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6651 /// the declaration of the given C++ conversion function. This routine
6652 /// is responsible for recording the conversion function in the C++
6653 /// class, if possible.
6654 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
6655   assert(Conversion && "Expected to receive a conversion function declaration");
6656 
6657   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
6658 
6659   // Make sure we aren't redeclaring the conversion function.
6660   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
6661 
6662   // C++ [class.conv.fct]p1:
6663   //   [...] A conversion function is never used to convert a
6664   //   (possibly cv-qualified) object to the (possibly cv-qualified)
6665   //   same object type (or a reference to it), to a (possibly
6666   //   cv-qualified) base class of that type (or a reference to it),
6667   //   or to (possibly cv-qualified) void.
6668   // FIXME: Suppress this warning if the conversion function ends up being a
6669   // virtual function that overrides a virtual function in a base class.
6670   QualType ClassType
6671     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6672   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
6673     ConvType = ConvTypeRef->getPointeeType();
6674   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6675       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
6676     /* Suppress diagnostics for instantiations. */;
6677   else if (ConvType->isRecordType()) {
6678     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6679     if (ConvType == ClassType)
6680       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
6681         << ClassType;
6682     else if (IsDerivedFrom(ClassType, ConvType))
6683       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
6684         <<  ClassType << ConvType;
6685   } else if (ConvType->isVoidType()) {
6686     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
6687       << ClassType << ConvType;
6688   }
6689 
6690   if (FunctionTemplateDecl *ConversionTemplate
6691                                 = Conversion->getDescribedFunctionTemplate())
6692     return ConversionTemplate;
6693 
6694   return Conversion;
6695 }
6696 
6697 //===----------------------------------------------------------------------===//
6698 // Namespace Handling
6699 //===----------------------------------------------------------------------===//
6700 
6701 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6702 /// reopened.
6703 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6704                                             SourceLocation Loc,
6705                                             IdentifierInfo *II, bool *IsInline,
6706                                             NamespaceDecl *PrevNS) {
6707   assert(*IsInline != PrevNS->isInline());
6708 
6709   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6710   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6711   // inline namespaces, with the intention of bringing names into namespace std.
6712   //
6713   // We support this just well enough to get that case working; this is not
6714   // sufficient to support reopening namespaces as inline in general.
6715   if (*IsInline && II && II->getName().startswith("__atomic") &&
6716       S.getSourceManager().isInSystemHeader(Loc)) {
6717     // Mark all prior declarations of the namespace as inline.
6718     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6719          NS = NS->getPreviousDecl())
6720       NS->setInline(*IsInline);
6721     // Patch up the lookup table for the containing namespace. This isn't really
6722     // correct, but it's good enough for this particular case.
6723     for (auto *I : PrevNS->decls())
6724       if (auto *ND = dyn_cast<NamedDecl>(I))
6725         PrevNS->getParent()->makeDeclVisibleInContext(ND);
6726     return;
6727   }
6728 
6729   if (PrevNS->isInline())
6730     // The user probably just forgot the 'inline', so suggest that it
6731     // be added back.
6732     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6733       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6734   else
6735     S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
6736 
6737   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6738   *IsInline = PrevNS->isInline();
6739 }
6740 
6741 /// ActOnStartNamespaceDef - This is called at the start of a namespace
6742 /// definition.
6743 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
6744                                    SourceLocation InlineLoc,
6745                                    SourceLocation NamespaceLoc,
6746                                    SourceLocation IdentLoc,
6747                                    IdentifierInfo *II,
6748                                    SourceLocation LBrace,
6749                                    AttributeList *AttrList) {
6750   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6751   // For anonymous namespace, take the location of the left brace.
6752   SourceLocation Loc = II ? IdentLoc : LBrace;
6753   bool IsInline = InlineLoc.isValid();
6754   bool IsInvalid = false;
6755   bool IsStd = false;
6756   bool AddToKnown = false;
6757   Scope *DeclRegionScope = NamespcScope->getParent();
6758 
6759   NamespaceDecl *PrevNS = nullptr;
6760   if (II) {
6761     // C++ [namespace.def]p2:
6762     //   The identifier in an original-namespace-definition shall not
6763     //   have been previously defined in the declarative region in
6764     //   which the original-namespace-definition appears. The
6765     //   identifier in an original-namespace-definition is the name of
6766     //   the namespace. Subsequently in that declarative region, it is
6767     //   treated as an original-namespace-name.
6768     //
6769     // Since namespace names are unique in their scope, and we don't
6770     // look through using directives, just look for any ordinary names.
6771 
6772     const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
6773     Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6774     Decl::IDNS_Namespace;
6775     NamedDecl *PrevDecl = nullptr;
6776     DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6777     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6778          ++I) {
6779       if ((*I)->getIdentifierNamespace() & IDNS) {
6780         PrevDecl = *I;
6781         break;
6782       }
6783     }
6784 
6785     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6786 
6787     if (PrevNS) {
6788       // This is an extended namespace definition.
6789       if (IsInline != PrevNS->isInline())
6790         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6791                                         &IsInline, PrevNS);
6792     } else if (PrevDecl) {
6793       // This is an invalid name redefinition.
6794       Diag(Loc, diag::err_redefinition_different_kind)
6795         << II;
6796       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6797       IsInvalid = true;
6798       // Continue on to push Namespc as current DeclContext and return it.
6799     } else if (II->isStr("std") &&
6800                CurContext->getRedeclContext()->isTranslationUnit()) {
6801       // This is the first "real" definition of the namespace "std", so update
6802       // our cache of the "std" namespace to point at this definition.
6803       PrevNS = getStdNamespace();
6804       IsStd = true;
6805       AddToKnown = !IsInline;
6806     } else {
6807       // We've seen this namespace for the first time.
6808       AddToKnown = !IsInline;
6809     }
6810   } else {
6811     // Anonymous namespaces.
6812 
6813     // Determine whether the parent already has an anonymous namespace.
6814     DeclContext *Parent = CurContext->getRedeclContext();
6815     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6816       PrevNS = TU->getAnonymousNamespace();
6817     } else {
6818       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
6819       PrevNS = ND->getAnonymousNamespace();
6820     }
6821 
6822     if (PrevNS && IsInline != PrevNS->isInline())
6823       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6824                                       &IsInline, PrevNS);
6825   }
6826 
6827   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6828                                                  StartLoc, Loc, II, PrevNS);
6829   if (IsInvalid)
6830     Namespc->setInvalidDecl();
6831 
6832   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
6833 
6834   // FIXME: Should we be merging attributes?
6835   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
6836     PushNamespaceVisibilityAttr(Attr, Loc);
6837 
6838   if (IsStd)
6839     StdNamespace = Namespc;
6840   if (AddToKnown)
6841     KnownNamespaces[Namespc] = false;
6842 
6843   if (II) {
6844     PushOnScopeChains(Namespc, DeclRegionScope);
6845   } else {
6846     // Link the anonymous namespace into its parent.
6847     DeclContext *Parent = CurContext->getRedeclContext();
6848     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6849       TU->setAnonymousNamespace(Namespc);
6850     } else {
6851       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
6852     }
6853 
6854     CurContext->addDecl(Namespc);
6855 
6856     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
6857     //   behaves as if it were replaced by
6858     //     namespace unique { /* empty body */ }
6859     //     using namespace unique;
6860     //     namespace unique { namespace-body }
6861     //   where all occurrences of 'unique' in a translation unit are
6862     //   replaced by the same identifier and this identifier differs
6863     //   from all other identifiers in the entire program.
6864 
6865     // We just create the namespace with an empty name and then add an
6866     // implicit using declaration, just like the standard suggests.
6867     //
6868     // CodeGen enforces the "universally unique" aspect by giving all
6869     // declarations semantically contained within an anonymous
6870     // namespace internal linkage.
6871 
6872     if (!PrevNS) {
6873       UsingDirectiveDecl* UD
6874         = UsingDirectiveDecl::Create(Context, Parent,
6875                                      /* 'using' */ LBrace,
6876                                      /* 'namespace' */ SourceLocation(),
6877                                      /* qualifier */ NestedNameSpecifierLoc(),
6878                                      /* identifier */ SourceLocation(),
6879                                      Namespc,
6880                                      /* Ancestor */ Parent);
6881       UD->setImplicit();
6882       Parent->addDecl(UD);
6883     }
6884   }
6885 
6886   ActOnDocumentableDecl(Namespc);
6887 
6888   // Although we could have an invalid decl (i.e. the namespace name is a
6889   // redefinition), push it as current DeclContext and try to continue parsing.
6890   // FIXME: We should be able to push Namespc here, so that the each DeclContext
6891   // for the namespace has the declarations that showed up in that particular
6892   // namespace definition.
6893   PushDeclContext(NamespcScope, Namespc);
6894   return Namespc;
6895 }
6896 
6897 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6898 /// is a namespace alias, returns the namespace it points to.
6899 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6900   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6901     return AD->getNamespace();
6902   return dyn_cast_or_null<NamespaceDecl>(D);
6903 }
6904 
6905 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
6906 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
6907 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
6908   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6909   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
6910   Namespc->setRBraceLoc(RBrace);
6911   PopDeclContext();
6912   if (Namespc->hasAttr<VisibilityAttr>())
6913     PopPragmaVisibility(true, RBrace);
6914 }
6915 
6916 CXXRecordDecl *Sema::getStdBadAlloc() const {
6917   return cast_or_null<CXXRecordDecl>(
6918                                   StdBadAlloc.get(Context.getExternalSource()));
6919 }
6920 
6921 NamespaceDecl *Sema::getStdNamespace() const {
6922   return cast_or_null<NamespaceDecl>(
6923                                  StdNamespace.get(Context.getExternalSource()));
6924 }
6925 
6926 /// \brief Retrieve the special "std" namespace, which may require us to
6927 /// implicitly define the namespace.
6928 NamespaceDecl *Sema::getOrCreateStdNamespace() {
6929   if (!StdNamespace) {
6930     // The "std" namespace has not yet been defined, so build one implicitly.
6931     StdNamespace = NamespaceDecl::Create(Context,
6932                                          Context.getTranslationUnitDecl(),
6933                                          /*Inline=*/false,
6934                                          SourceLocation(), SourceLocation(),
6935                                          &PP.getIdentifierTable().get("std"),
6936                                          /*PrevDecl=*/nullptr);
6937     getStdNamespace()->setImplicit(true);
6938   }
6939 
6940   return getStdNamespace();
6941 }
6942 
6943 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
6944   assert(getLangOpts().CPlusPlus &&
6945          "Looking for std::initializer_list outside of C++.");
6946 
6947   // We're looking for implicit instantiations of
6948   // template <typename E> class std::initializer_list.
6949 
6950   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6951     return false;
6952 
6953   ClassTemplateDecl *Template = nullptr;
6954   const TemplateArgument *Arguments = nullptr;
6955 
6956   if (const RecordType *RT = Ty->getAs<RecordType>()) {
6957 
6958     ClassTemplateSpecializationDecl *Specialization =
6959         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6960     if (!Specialization)
6961       return false;
6962 
6963     Template = Specialization->getSpecializedTemplate();
6964     Arguments = Specialization->getTemplateArgs().data();
6965   } else if (const TemplateSpecializationType *TST =
6966                  Ty->getAs<TemplateSpecializationType>()) {
6967     Template = dyn_cast_or_null<ClassTemplateDecl>(
6968         TST->getTemplateName().getAsTemplateDecl());
6969     Arguments = TST->getArgs();
6970   }
6971   if (!Template)
6972     return false;
6973 
6974   if (!StdInitializerList) {
6975     // Haven't recognized std::initializer_list yet, maybe this is it.
6976     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6977     if (TemplateClass->getIdentifier() !=
6978             &PP.getIdentifierTable().get("initializer_list") ||
6979         !getStdNamespace()->InEnclosingNamespaceSetOf(
6980             TemplateClass->getDeclContext()))
6981       return false;
6982     // This is a template called std::initializer_list, but is it the right
6983     // template?
6984     TemplateParameterList *Params = Template->getTemplateParameters();
6985     if (Params->getMinRequiredArguments() != 1)
6986       return false;
6987     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6988       return false;
6989 
6990     // It's the right template.
6991     StdInitializerList = Template;
6992   }
6993 
6994   if (Template != StdInitializerList)
6995     return false;
6996 
6997   // This is an instance of std::initializer_list. Find the argument type.
6998   if (Element)
6999     *Element = Arguments[0].getAsType();
7000   return true;
7001 }
7002 
7003 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
7004   NamespaceDecl *Std = S.getStdNamespace();
7005   if (!Std) {
7006     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
7007     return nullptr;
7008   }
7009 
7010   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
7011                       Loc, Sema::LookupOrdinaryName);
7012   if (!S.LookupQualifiedName(Result, Std)) {
7013     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
7014     return nullptr;
7015   }
7016   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
7017   if (!Template) {
7018     Result.suppressDiagnostics();
7019     // We found something weird. Complain about the first thing we found.
7020     NamedDecl *Found = *Result.begin();
7021     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
7022     return nullptr;
7023   }
7024 
7025   // We found some template called std::initializer_list. Now verify that it's
7026   // correct.
7027   TemplateParameterList *Params = Template->getTemplateParameters();
7028   if (Params->getMinRequiredArguments() != 1 ||
7029       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
7030     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
7031     return nullptr;
7032   }
7033 
7034   return Template;
7035 }
7036 
7037 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
7038   if (!StdInitializerList) {
7039     StdInitializerList = LookupStdInitializerList(*this, Loc);
7040     if (!StdInitializerList)
7041       return QualType();
7042   }
7043 
7044   TemplateArgumentListInfo Args(Loc, Loc);
7045   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
7046                                        Context.getTrivialTypeSourceInfo(Element,
7047                                                                         Loc)));
7048   return Context.getCanonicalType(
7049       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
7050 }
7051 
7052 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
7053   // C++ [dcl.init.list]p2:
7054   //   A constructor is an initializer-list constructor if its first parameter
7055   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
7056   //   std::initializer_list<E> for some type E, and either there are no other
7057   //   parameters or else all other parameters have default arguments.
7058   if (Ctor->getNumParams() < 1 ||
7059       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
7060     return false;
7061 
7062   QualType ArgType = Ctor->getParamDecl(0)->getType();
7063   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
7064     ArgType = RT->getPointeeType().getUnqualifiedType();
7065 
7066   return isStdInitializerList(ArgType, nullptr);
7067 }
7068 
7069 /// \brief Determine whether a using statement is in a context where it will be
7070 /// apply in all contexts.
7071 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
7072   switch (CurContext->getDeclKind()) {
7073     case Decl::TranslationUnit:
7074       return true;
7075     case Decl::LinkageSpec:
7076       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
7077     default:
7078       return false;
7079   }
7080 }
7081 
7082 namespace {
7083 
7084 // Callback to only accept typo corrections that are namespaces.
7085 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
7086 public:
7087   bool ValidateCandidate(const TypoCorrection &candidate) override {
7088     if (NamedDecl *ND = candidate.getCorrectionDecl())
7089       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
7090     return false;
7091   }
7092 };
7093 
7094 }
7095 
7096 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
7097                                        CXXScopeSpec &SS,
7098                                        SourceLocation IdentLoc,
7099                                        IdentifierInfo *Ident) {
7100   NamespaceValidatorCCC Validator;
7101   R.clear();
7102   if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
7103                                                R.getLookupKind(), Sc, &SS,
7104                                                Validator,
7105                                                Sema::CTK_ErrorRecovery)) {
7106     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
7107       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
7108       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
7109                               Ident->getName().equals(CorrectedStr);
7110       S.diagnoseTypo(Corrected,
7111                      S.PDiag(diag::err_using_directive_member_suggest)
7112                        << Ident << DC << DroppedSpecifier << SS.getRange(),
7113                      S.PDiag(diag::note_namespace_defined_here));
7114     } else {
7115       S.diagnoseTypo(Corrected,
7116                      S.PDiag(diag::err_using_directive_suggest) << Ident,
7117                      S.PDiag(diag::note_namespace_defined_here));
7118     }
7119     R.addDecl(Corrected.getCorrectionDecl());
7120     return true;
7121   }
7122   return false;
7123 }
7124 
7125 Decl *Sema::ActOnUsingDirective(Scope *S,
7126                                           SourceLocation UsingLoc,
7127                                           SourceLocation NamespcLoc,
7128                                           CXXScopeSpec &SS,
7129                                           SourceLocation IdentLoc,
7130                                           IdentifierInfo *NamespcName,
7131                                           AttributeList *AttrList) {
7132   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7133   assert(NamespcName && "Invalid NamespcName.");
7134   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
7135 
7136   // This can only happen along a recovery path.
7137   while (S->getFlags() & Scope::TemplateParamScope)
7138     S = S->getParent();
7139   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7140 
7141   UsingDirectiveDecl *UDir = nullptr;
7142   NestedNameSpecifier *Qualifier = nullptr;
7143   if (SS.isSet())
7144     Qualifier = SS.getScopeRep();
7145 
7146   // Lookup namespace name.
7147   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7148   LookupParsedName(R, S, &SS);
7149   if (R.isAmbiguous())
7150     return nullptr;
7151 
7152   if (R.empty()) {
7153     R.clear();
7154     // Allow "using namespace std;" or "using namespace ::std;" even if
7155     // "std" hasn't been defined yet, for GCC compatibility.
7156     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7157         NamespcName->isStr("std")) {
7158       Diag(IdentLoc, diag::ext_using_undefined_std);
7159       R.addDecl(getOrCreateStdNamespace());
7160       R.resolveKind();
7161     }
7162     // Otherwise, attempt typo correction.
7163     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
7164   }
7165 
7166   if (!R.empty()) {
7167     NamedDecl *Named = R.getFoundDecl();
7168     assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
7169         && "expected namespace decl");
7170     // C++ [namespace.udir]p1:
7171     //   A using-directive specifies that the names in the nominated
7172     //   namespace can be used in the scope in which the
7173     //   using-directive appears after the using-directive. During
7174     //   unqualified name lookup (3.4.1), the names appear as if they
7175     //   were declared in the nearest enclosing namespace which
7176     //   contains both the using-directive and the nominated
7177     //   namespace. [Note: in this context, "contains" means "contains
7178     //   directly or indirectly". ]
7179 
7180     // Find enclosing context containing both using-directive and
7181     // nominated namespace.
7182     NamespaceDecl *NS = getNamespaceDecl(Named);
7183     DeclContext *CommonAncestor = cast<DeclContext>(NS);
7184     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7185       CommonAncestor = CommonAncestor->getParent();
7186 
7187     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
7188                                       SS.getWithLocInContext(Context),
7189                                       IdentLoc, Named, CommonAncestor);
7190 
7191     if (IsUsingDirectiveInToplevelContext(CurContext) &&
7192         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
7193       Diag(IdentLoc, diag::warn_using_directive_in_header);
7194     }
7195 
7196     PushUsingDirective(S, UDir);
7197   } else {
7198     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
7199   }
7200 
7201   if (UDir)
7202     ProcessDeclAttributeList(S, UDir, AttrList);
7203 
7204   return UDir;
7205 }
7206 
7207 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
7208   // If the scope has an associated entity and the using directive is at
7209   // namespace or translation unit scope, add the UsingDirectiveDecl into
7210   // its lookup structure so qualified name lookup can find it.
7211   DeclContext *Ctx = S->getEntity();
7212   if (Ctx && !Ctx->isFunctionOrMethod())
7213     Ctx->addDecl(UDir);
7214   else
7215     // Otherwise, it is at block scope. The using-directives will affect lookup
7216     // only to the end of the scope.
7217     S->PushUsingDirective(UDir);
7218 }
7219 
7220 
7221 Decl *Sema::ActOnUsingDeclaration(Scope *S,
7222                                   AccessSpecifier AS,
7223                                   bool HasUsingKeyword,
7224                                   SourceLocation UsingLoc,
7225                                   CXXScopeSpec &SS,
7226                                   UnqualifiedId &Name,
7227                                   AttributeList *AttrList,
7228                                   bool HasTypenameKeyword,
7229                                   SourceLocation TypenameLoc) {
7230   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7231 
7232   switch (Name.getKind()) {
7233   case UnqualifiedId::IK_ImplicitSelfParam:
7234   case UnqualifiedId::IK_Identifier:
7235   case UnqualifiedId::IK_OperatorFunctionId:
7236   case UnqualifiedId::IK_LiteralOperatorId:
7237   case UnqualifiedId::IK_ConversionFunctionId:
7238     break;
7239 
7240   case UnqualifiedId::IK_ConstructorName:
7241   case UnqualifiedId::IK_ConstructorTemplateId:
7242     // C++11 inheriting constructors.
7243     Diag(Name.getLocStart(),
7244          getLangOpts().CPlusPlus11 ?
7245            diag::warn_cxx98_compat_using_decl_constructor :
7246            diag::err_using_decl_constructor)
7247       << SS.getRange();
7248 
7249     if (getLangOpts().CPlusPlus11) break;
7250 
7251     return nullptr;
7252 
7253   case UnqualifiedId::IK_DestructorName:
7254     Diag(Name.getLocStart(), diag::err_using_decl_destructor)
7255       << SS.getRange();
7256     return nullptr;
7257 
7258   case UnqualifiedId::IK_TemplateId:
7259     Diag(Name.getLocStart(), diag::err_using_decl_template_id)
7260       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
7261     return nullptr;
7262   }
7263 
7264   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7265   DeclarationName TargetName = TargetNameInfo.getName();
7266   if (!TargetName)
7267     return nullptr;
7268 
7269   // Warn about access declarations.
7270   if (!HasUsingKeyword) {
7271     Diag(Name.getLocStart(),
7272          getLangOpts().CPlusPlus11 ? diag::err_access_decl
7273                                    : diag::warn_access_decl_deprecated)
7274       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
7275   }
7276 
7277   if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7278       DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7279     return nullptr;
7280 
7281   NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
7282                                         TargetNameInfo, AttrList,
7283                                         /* IsInstantiation */ false,
7284                                         HasTypenameKeyword, TypenameLoc);
7285   if (UD)
7286     PushOnScopeChains(UD, S, /*AddToContext*/ false);
7287 
7288   return UD;
7289 }
7290 
7291 /// \brief Determine whether a using declaration considers the given
7292 /// declarations as "equivalent", e.g., if they are redeclarations of
7293 /// the same entity or are both typedefs of the same type.
7294 static bool
7295 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7296   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
7297     return true;
7298 
7299   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
7300     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
7301       return Context.hasSameType(TD1->getUnderlyingType(),
7302                                  TD2->getUnderlyingType());
7303 
7304   return false;
7305 }
7306 
7307 
7308 /// Determines whether to create a using shadow decl for a particular
7309 /// decl, given the set of decls existing prior to this using lookup.
7310 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
7311                                 const LookupResult &Previous,
7312                                 UsingShadowDecl *&PrevShadow) {
7313   // Diagnose finding a decl which is not from a base class of the
7314   // current class.  We do this now because there are cases where this
7315   // function will silently decide not to build a shadow decl, which
7316   // will pre-empt further diagnostics.
7317   //
7318   // We don't need to do this in C++0x because we do the check once on
7319   // the qualifier.
7320   //
7321   // FIXME: diagnose the following if we care enough:
7322   //   struct A { int foo; };
7323   //   struct B : A { using A::foo; };
7324   //   template <class T> struct C : A {};
7325   //   template <class T> struct D : C<T> { using B::foo; } // <---
7326   // This is invalid (during instantiation) in C++03 because B::foo
7327   // resolves to the using decl in B, which is not a base class of D<T>.
7328   // We can't diagnose it immediately because C<T> is an unknown
7329   // specialization.  The UsingShadowDecl in D<T> then points directly
7330   // to A::foo, which will look well-formed when we instantiate.
7331   // The right solution is to not collapse the shadow-decl chain.
7332   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
7333     DeclContext *OrigDC = Orig->getDeclContext();
7334 
7335     // Handle enums and anonymous structs.
7336     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7337     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7338     while (OrigRec->isAnonymousStructOrUnion())
7339       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7340 
7341     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7342       if (OrigDC == CurContext) {
7343         Diag(Using->getLocation(),
7344              diag::err_using_decl_nested_name_specifier_is_current_class)
7345           << Using->getQualifierLoc().getSourceRange();
7346         Diag(Orig->getLocation(), diag::note_using_decl_target);
7347         return true;
7348       }
7349 
7350       Diag(Using->getQualifierLoc().getBeginLoc(),
7351            diag::err_using_decl_nested_name_specifier_is_not_base_class)
7352         << Using->getQualifier()
7353         << cast<CXXRecordDecl>(CurContext)
7354         << Using->getQualifierLoc().getSourceRange();
7355       Diag(Orig->getLocation(), diag::note_using_decl_target);
7356       return true;
7357     }
7358   }
7359 
7360   if (Previous.empty()) return false;
7361 
7362   NamedDecl *Target = Orig;
7363   if (isa<UsingShadowDecl>(Target))
7364     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7365 
7366   // If the target happens to be one of the previous declarations, we
7367   // don't have a conflict.
7368   //
7369   // FIXME: but we might be increasing its access, in which case we
7370   // should redeclare it.
7371   NamedDecl *NonTag = nullptr, *Tag = nullptr;
7372   bool FoundEquivalentDecl = false;
7373   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7374          I != E; ++I) {
7375     NamedDecl *D = (*I)->getUnderlyingDecl();
7376     if (IsEquivalentForUsingDecl(Context, D, Target)) {
7377       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7378         PrevShadow = Shadow;
7379       FoundEquivalentDecl = true;
7380     }
7381 
7382     (isa<TagDecl>(D) ? Tag : NonTag) = D;
7383   }
7384 
7385   if (FoundEquivalentDecl)
7386     return false;
7387 
7388   if (FunctionDecl *FD = Target->getAsFunction()) {
7389     NamedDecl *OldDecl = nullptr;
7390     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7391                           /*IsForUsingDecl*/ true)) {
7392     case Ovl_Overload:
7393       return false;
7394 
7395     case Ovl_NonFunction:
7396       Diag(Using->getLocation(), diag::err_using_decl_conflict);
7397       break;
7398 
7399     // We found a decl with the exact signature.
7400     case Ovl_Match:
7401       // If we're in a record, we want to hide the target, so we
7402       // return true (without a diagnostic) to tell the caller not to
7403       // build a shadow decl.
7404       if (CurContext->isRecord())
7405         return true;
7406 
7407       // If we're not in a record, this is an error.
7408       Diag(Using->getLocation(), diag::err_using_decl_conflict);
7409       break;
7410     }
7411 
7412     Diag(Target->getLocation(), diag::note_using_decl_target);
7413     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7414     return true;
7415   }
7416 
7417   // Target is not a function.
7418 
7419   if (isa<TagDecl>(Target)) {
7420     // No conflict between a tag and a non-tag.
7421     if (!Tag) return false;
7422 
7423     Diag(Using->getLocation(), diag::err_using_decl_conflict);
7424     Diag(Target->getLocation(), diag::note_using_decl_target);
7425     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7426     return true;
7427   }
7428 
7429   // No conflict between a tag and a non-tag.
7430   if (!NonTag) return false;
7431 
7432   Diag(Using->getLocation(), diag::err_using_decl_conflict);
7433   Diag(Target->getLocation(), diag::note_using_decl_target);
7434   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7435   return true;
7436 }
7437 
7438 /// Builds a shadow declaration corresponding to a 'using' declaration.
7439 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
7440                                             UsingDecl *UD,
7441                                             NamedDecl *Orig,
7442                                             UsingShadowDecl *PrevDecl) {
7443 
7444   // If we resolved to another shadow declaration, just coalesce them.
7445   NamedDecl *Target = Orig;
7446   if (isa<UsingShadowDecl>(Target)) {
7447     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7448     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
7449   }
7450 
7451   UsingShadowDecl *Shadow
7452     = UsingShadowDecl::Create(Context, CurContext,
7453                               UD->getLocation(), UD, Target);
7454   UD->addShadowDecl(Shadow);
7455 
7456   Shadow->setAccess(UD->getAccess());
7457   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7458     Shadow->setInvalidDecl();
7459 
7460   Shadow->setPreviousDecl(PrevDecl);
7461 
7462   if (S)
7463     PushOnScopeChains(Shadow, S);
7464   else
7465     CurContext->addDecl(Shadow);
7466 
7467 
7468   return Shadow;
7469 }
7470 
7471 /// Hides a using shadow declaration.  This is required by the current
7472 /// using-decl implementation when a resolvable using declaration in a
7473 /// class is followed by a declaration which would hide or override
7474 /// one or more of the using decl's targets; for example:
7475 ///
7476 ///   struct Base { void foo(int); };
7477 ///   struct Derived : Base {
7478 ///     using Base::foo;
7479 ///     void foo(int);
7480 ///   };
7481 ///
7482 /// The governing language is C++03 [namespace.udecl]p12:
7483 ///
7484 ///   When a using-declaration brings names from a base class into a
7485 ///   derived class scope, member functions in the derived class
7486 ///   override and/or hide member functions with the same name and
7487 ///   parameter types in a base class (rather than conflicting).
7488 ///
7489 /// There are two ways to implement this:
7490 ///   (1) optimistically create shadow decls when they're not hidden
7491 ///       by existing declarations, or
7492 ///   (2) don't create any shadow decls (or at least don't make them
7493 ///       visible) until we've fully parsed/instantiated the class.
7494 /// The problem with (1) is that we might have to retroactively remove
7495 /// a shadow decl, which requires several O(n) operations because the
7496 /// decl structures are (very reasonably) not designed for removal.
7497 /// (2) avoids this but is very fiddly and phase-dependent.
7498 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
7499   if (Shadow->getDeclName().getNameKind() ==
7500         DeclarationName::CXXConversionFunctionName)
7501     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7502 
7503   // Remove it from the DeclContext...
7504   Shadow->getDeclContext()->removeDecl(Shadow);
7505 
7506   // ...and the scope, if applicable...
7507   if (S) {
7508     S->RemoveDecl(Shadow);
7509     IdResolver.RemoveDecl(Shadow);
7510   }
7511 
7512   // ...and the using decl.
7513   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7514 
7515   // TODO: complain somehow if Shadow was used.  It shouldn't
7516   // be possible for this to happen, because...?
7517 }
7518 
7519 /// Find the base specifier for a base class with the given type.
7520 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7521                                                 QualType DesiredBase,
7522                                                 bool &AnyDependentBases) {
7523   // Check whether the named type is a direct base class.
7524   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7525   for (auto &Base : Derived->bases()) {
7526     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7527     if (CanonicalDesiredBase == BaseType)
7528       return &Base;
7529     if (BaseType->isDependentType())
7530       AnyDependentBases = true;
7531   }
7532   return nullptr;
7533 }
7534 
7535 namespace {
7536 class UsingValidatorCCC : public CorrectionCandidateCallback {
7537 public:
7538   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
7539                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
7540       : HasTypenameKeyword(HasTypenameKeyword),
7541         IsInstantiation(IsInstantiation), OldNNS(NNS),
7542         RequireMemberOf(RequireMemberOf) {}
7543 
7544   bool ValidateCandidate(const TypoCorrection &Candidate) override {
7545     NamedDecl *ND = Candidate.getCorrectionDecl();
7546 
7547     // Keywords are not valid here.
7548     if (!ND || isa<NamespaceDecl>(ND))
7549       return false;
7550 
7551     // Completely unqualified names are invalid for a 'using' declaration.
7552     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7553       return false;
7554 
7555     if (RequireMemberOf) {
7556       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
7557       if (FoundRecord && FoundRecord->isInjectedClassName()) {
7558         // No-one ever wants a using-declaration to name an injected-class-name
7559         // of a base class, unless they're declaring an inheriting constructor.
7560         ASTContext &Ctx = ND->getASTContext();
7561         if (!Ctx.getLangOpts().CPlusPlus11)
7562           return false;
7563         QualType FoundType = Ctx.getRecordType(FoundRecord);
7564 
7565         // Check that the injected-class-name is named as a member of its own
7566         // type; we don't want to suggest 'using Derived::Base;', since that
7567         // means something else.
7568         NestedNameSpecifier *Specifier =
7569             Candidate.WillReplaceSpecifier()
7570                 ? Candidate.getCorrectionSpecifier()
7571                 : OldNNS;
7572         if (!Specifier->getAsType() ||
7573             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
7574           return false;
7575 
7576         // Check that this inheriting constructor declaration actually names a
7577         // direct base class of the current class.
7578         bool AnyDependentBases = false;
7579         if (!findDirectBaseWithType(RequireMemberOf,
7580                                     Ctx.getRecordType(FoundRecord),
7581                                     AnyDependentBases) &&
7582             !AnyDependentBases)
7583           return false;
7584       } else {
7585         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
7586         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
7587           return false;
7588 
7589         // FIXME: Check that the base class member is accessible?
7590       }
7591     }
7592 
7593     if (isa<TypeDecl>(ND))
7594       return HasTypenameKeyword || !IsInstantiation;
7595 
7596     return !HasTypenameKeyword;
7597   }
7598 
7599 private:
7600   bool HasTypenameKeyword;
7601   bool IsInstantiation;
7602   NestedNameSpecifier *OldNNS;
7603   CXXRecordDecl *RequireMemberOf;
7604 };
7605 } // end anonymous namespace
7606 
7607 /// Builds a using declaration.
7608 ///
7609 /// \param IsInstantiation - Whether this call arises from an
7610 ///   instantiation of an unresolved using declaration.  We treat
7611 ///   the lookup differently for these declarations.
7612 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7613                                        SourceLocation UsingLoc,
7614                                        CXXScopeSpec &SS,
7615                                        DeclarationNameInfo NameInfo,
7616                                        AttributeList *AttrList,
7617                                        bool IsInstantiation,
7618                                        bool HasTypenameKeyword,
7619                                        SourceLocation TypenameLoc) {
7620   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7621   SourceLocation IdentLoc = NameInfo.getLoc();
7622   assert(IdentLoc.isValid() && "Invalid TargetName location.");
7623 
7624   // FIXME: We ignore attributes for now.
7625 
7626   if (SS.isEmpty()) {
7627     Diag(IdentLoc, diag::err_using_requires_qualname);
7628     return nullptr;
7629   }
7630 
7631   // Do the redeclaration lookup in the current scope.
7632   LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
7633                         ForRedeclaration);
7634   Previous.setHideTags(false);
7635   if (S) {
7636     LookupName(Previous, S);
7637 
7638     // It is really dumb that we have to do this.
7639     LookupResult::Filter F = Previous.makeFilter();
7640     while (F.hasNext()) {
7641       NamedDecl *D = F.next();
7642       if (!isDeclInScope(D, CurContext, S))
7643         F.erase();
7644       // If we found a local extern declaration that's not ordinarily visible,
7645       // and this declaration is being added to a non-block scope, ignore it.
7646       // We're only checking for scope conflicts here, not also for violations
7647       // of the linkage rules.
7648       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
7649                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
7650         F.erase();
7651     }
7652     F.done();
7653   } else {
7654     assert(IsInstantiation && "no scope in non-instantiation");
7655     assert(CurContext->isRecord() && "scope not record in instantiation");
7656     LookupQualifiedName(Previous, CurContext);
7657   }
7658 
7659   // Check for invalid redeclarations.
7660   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7661                                   SS, IdentLoc, Previous))
7662     return nullptr;
7663 
7664   // Check for bad qualifiers.
7665   if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
7666     return nullptr;
7667 
7668   DeclContext *LookupContext = computeDeclContext(SS);
7669   NamedDecl *D;
7670   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
7671   if (!LookupContext) {
7672     if (HasTypenameKeyword) {
7673       // FIXME: not all declaration name kinds are legal here
7674       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7675                                               UsingLoc, TypenameLoc,
7676                                               QualifierLoc,
7677                                               IdentLoc, NameInfo.getName());
7678     } else {
7679       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7680                                            QualifierLoc, NameInfo);
7681     }
7682     D->setAccess(AS);
7683     CurContext->addDecl(D);
7684     return D;
7685   }
7686 
7687   auto Build = [&](bool Invalid) {
7688     UsingDecl *UD =
7689         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
7690                           HasTypenameKeyword);
7691     UD->setAccess(AS);
7692     CurContext->addDecl(UD);
7693     UD->setInvalidDecl(Invalid);
7694     return UD;
7695   };
7696   auto BuildInvalid = [&]{ return Build(true); };
7697   auto BuildValid = [&]{ return Build(false); };
7698 
7699   if (RequireCompleteDeclContext(SS, LookupContext))
7700     return BuildInvalid();
7701 
7702   // The normal rules do not apply to inheriting constructor declarations.
7703   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
7704     UsingDecl *UD = BuildValid();
7705     CheckInheritingConstructorUsingDecl(UD);
7706     return UD;
7707   }
7708 
7709   // Otherwise, look up the target name.
7710 
7711   LookupResult R(*this, NameInfo, LookupOrdinaryName);
7712 
7713   // Unlike most lookups, we don't always want to hide tag
7714   // declarations: tag names are visible through the using declaration
7715   // even if hidden by ordinary names, *except* in a dependent context
7716   // where it's important for the sanity of two-phase lookup.
7717   if (!IsInstantiation)
7718     R.setHideTags(false);
7719 
7720   // For the purposes of this lookup, we have a base object type
7721   // equal to that of the current context.
7722   if (CurContext->isRecord()) {
7723     R.setBaseObjectType(
7724                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7725   }
7726 
7727   LookupQualifiedName(R, LookupContext);
7728 
7729   // Try to correct typos if possible.
7730   if (R.empty()) {
7731     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
7732                           dyn_cast<CXXRecordDecl>(CurContext));
7733     if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
7734                                                R.getLookupKind(), S, &SS, CCC,
7735                                                CTK_ErrorRecovery)){
7736       // We reject any correction for which ND would be NULL.
7737       NamedDecl *ND = Corrected.getCorrectionDecl();
7738 
7739       // We reject candidates where DroppedSpecifier == true, hence the
7740       // literal '0' below.
7741       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7742                                 << NameInfo.getName() << LookupContext << 0
7743                                 << SS.getRange());
7744 
7745       // If we corrected to an inheriting constructor, handle it as one.
7746       auto *RD = dyn_cast<CXXRecordDecl>(ND);
7747       if (RD && RD->isInjectedClassName()) {
7748         // Fix up the information we'll use to build the using declaration.
7749         if (Corrected.WillReplaceSpecifier()) {
7750           NestedNameSpecifierLocBuilder Builder;
7751           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
7752                               QualifierLoc.getSourceRange());
7753           QualifierLoc = Builder.getWithLocInContext(Context);
7754         }
7755 
7756         NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
7757             Context.getCanonicalType(Context.getRecordType(RD))));
7758         NameInfo.setNamedTypeInfo(nullptr);
7759 
7760         // Build it and process it as an inheriting constructor.
7761         UsingDecl *UD = BuildValid();
7762         CheckInheritingConstructorUsingDecl(UD);
7763         return UD;
7764       }
7765 
7766       // FIXME: Pick up all the declarations if we found an overloaded function.
7767       R.setLookupName(Corrected.getCorrection());
7768       R.addDecl(ND);
7769     } else {
7770       Diag(IdentLoc, diag::err_no_member)
7771         << NameInfo.getName() << LookupContext << SS.getRange();
7772       return BuildInvalid();
7773     }
7774   }
7775 
7776   if (R.isAmbiguous())
7777     return BuildInvalid();
7778 
7779   if (HasTypenameKeyword) {
7780     // If we asked for a typename and got a non-type decl, error out.
7781     if (!R.getAsSingle<TypeDecl>()) {
7782       Diag(IdentLoc, diag::err_using_typename_non_type);
7783       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7784         Diag((*I)->getUnderlyingDecl()->getLocation(),
7785              diag::note_using_decl_target);
7786       return BuildInvalid();
7787     }
7788   } else {
7789     // If we asked for a non-typename and we got a type, error out,
7790     // but only if this is an instantiation of an unresolved using
7791     // decl.  Otherwise just silently find the type name.
7792     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
7793       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7794       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
7795       return BuildInvalid();
7796     }
7797   }
7798 
7799   // C++0x N2914 [namespace.udecl]p6:
7800   // A using-declaration shall not name a namespace.
7801   if (R.getAsSingle<NamespaceDecl>()) {
7802     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7803       << SS.getRange();
7804     return BuildInvalid();
7805   }
7806 
7807   UsingDecl *UD = BuildValid();
7808   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7809     UsingShadowDecl *PrevDecl = nullptr;
7810     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
7811       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
7812   }
7813 
7814   return UD;
7815 }
7816 
7817 /// Additional checks for a using declaration referring to a constructor name.
7818 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
7819   assert(!UD->hasTypename() && "expecting a constructor name");
7820 
7821   const Type *SourceType = UD->getQualifier()->getAsType();
7822   assert(SourceType &&
7823          "Using decl naming constructor doesn't have type in scope spec.");
7824   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7825 
7826   // Check whether the named type is a direct base class.
7827   bool AnyDependentBases = false;
7828   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
7829                                       AnyDependentBases);
7830   if (!Base && !AnyDependentBases) {
7831     Diag(UD->getUsingLoc(),
7832          diag::err_using_decl_constructor_not_in_direct_base)
7833       << UD->getNameInfo().getSourceRange()
7834       << QualType(SourceType, 0) << TargetClass;
7835     UD->setInvalidDecl();
7836     return true;
7837   }
7838 
7839   if (Base)
7840     Base->setInheritConstructors();
7841 
7842   return false;
7843 }
7844 
7845 /// Checks that the given using declaration is not an invalid
7846 /// redeclaration.  Note that this is checking only for the using decl
7847 /// itself, not for any ill-formedness among the UsingShadowDecls.
7848 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7849                                        bool HasTypenameKeyword,
7850                                        const CXXScopeSpec &SS,
7851                                        SourceLocation NameLoc,
7852                                        const LookupResult &Prev) {
7853   // C++03 [namespace.udecl]p8:
7854   // C++0x [namespace.udecl]p10:
7855   //   A using-declaration is a declaration and can therefore be used
7856   //   repeatedly where (and only where) multiple declarations are
7857   //   allowed.
7858   //
7859   // That's in non-member contexts.
7860   if (!CurContext->getRedeclContext()->isRecord())
7861     return false;
7862 
7863   NestedNameSpecifier *Qual = SS.getScopeRep();
7864 
7865   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7866     NamedDecl *D = *I;
7867 
7868     bool DTypename;
7869     NestedNameSpecifier *DQual;
7870     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7871       DTypename = UD->hasTypename();
7872       DQual = UD->getQualifier();
7873     } else if (UnresolvedUsingValueDecl *UD
7874                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7875       DTypename = false;
7876       DQual = UD->getQualifier();
7877     } else if (UnresolvedUsingTypenameDecl *UD
7878                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7879       DTypename = true;
7880       DQual = UD->getQualifier();
7881     } else continue;
7882 
7883     // using decls differ if one says 'typename' and the other doesn't.
7884     // FIXME: non-dependent using decls?
7885     if (HasTypenameKeyword != DTypename) continue;
7886 
7887     // using decls differ if they name different scopes (but note that
7888     // template instantiation can cause this check to trigger when it
7889     // didn't before instantiation).
7890     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7891         Context.getCanonicalNestedNameSpecifier(DQual))
7892       continue;
7893 
7894     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
7895     Diag(D->getLocation(), diag::note_using_decl) << 1;
7896     return true;
7897   }
7898 
7899   return false;
7900 }
7901 
7902 
7903 /// Checks that the given nested-name qualifier used in a using decl
7904 /// in the current context is appropriately related to the current
7905 /// scope.  If an error is found, diagnoses it and returns true.
7906 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7907                                    const CXXScopeSpec &SS,
7908                                    const DeclarationNameInfo &NameInfo,
7909                                    SourceLocation NameLoc) {
7910   DeclContext *NamedContext = computeDeclContext(SS);
7911 
7912   if (!CurContext->isRecord()) {
7913     // C++03 [namespace.udecl]p3:
7914     // C++0x [namespace.udecl]p8:
7915     //   A using-declaration for a class member shall be a member-declaration.
7916 
7917     // If we weren't able to compute a valid scope, it must be a
7918     // dependent class scope.
7919     if (!NamedContext || NamedContext->isRecord()) {
7920       auto *RD = dyn_cast<CXXRecordDecl>(NamedContext);
7921       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
7922         RD = nullptr;
7923 
7924       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7925         << SS.getRange();
7926 
7927       // If we have a complete, non-dependent source type, try to suggest a
7928       // way to get the same effect.
7929       if (!RD)
7930         return true;
7931 
7932       // Find what this using-declaration was referring to.
7933       LookupResult R(*this, NameInfo, LookupOrdinaryName);
7934       R.setHideTags(false);
7935       R.suppressDiagnostics();
7936       LookupQualifiedName(R, RD);
7937 
7938       if (R.getAsSingle<TypeDecl>()) {
7939         if (getLangOpts().CPlusPlus11) {
7940           // Convert 'using X::Y;' to 'using Y = X::Y;'.
7941           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
7942             << 0 // alias declaration
7943             << FixItHint::CreateInsertion(SS.getBeginLoc(),
7944                                           NameInfo.getName().getAsString() +
7945                                               " = ");
7946         } else {
7947           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
7948           SourceLocation InsertLoc =
7949               PP.getLocForEndOfToken(NameInfo.getLocEnd());
7950           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
7951             << 1 // typedef declaration
7952             << FixItHint::CreateReplacement(UsingLoc, "typedef")
7953             << FixItHint::CreateInsertion(
7954                    InsertLoc, " " + NameInfo.getName().getAsString());
7955         }
7956       } else if (R.getAsSingle<VarDecl>()) {
7957         // Don't provide a fixit outside C++11 mode; we don't want to suggest
7958         // repeating the type of the static data member here.
7959         FixItHint FixIt;
7960         if (getLangOpts().CPlusPlus11) {
7961           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
7962           FixIt = FixItHint::CreateReplacement(
7963               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
7964         }
7965 
7966         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
7967           << 2 // reference declaration
7968           << FixIt;
7969       }
7970       return true;
7971     }
7972 
7973     // Otherwise, everything is known to be fine.
7974     return false;
7975   }
7976 
7977   // The current scope is a record.
7978 
7979   // If the named context is dependent, we can't decide much.
7980   if (!NamedContext) {
7981     // FIXME: in C++0x, we can diagnose if we can prove that the
7982     // nested-name-specifier does not refer to a base class, which is
7983     // still possible in some cases.
7984 
7985     // Otherwise we have to conservatively report that things might be
7986     // okay.
7987     return false;
7988   }
7989 
7990   if (!NamedContext->isRecord()) {
7991     // Ideally this would point at the last name in the specifier,
7992     // but we don't have that level of source info.
7993     Diag(SS.getRange().getBegin(),
7994          diag::err_using_decl_nested_name_specifier_is_not_class)
7995       << SS.getScopeRep() << SS.getRange();
7996     return true;
7997   }
7998 
7999   if (!NamedContext->isDependentContext() &&
8000       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
8001     return true;
8002 
8003   if (getLangOpts().CPlusPlus11) {
8004     // C++0x [namespace.udecl]p3:
8005     //   In a using-declaration used as a member-declaration, the
8006     //   nested-name-specifier shall name a base class of the class
8007     //   being defined.
8008 
8009     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
8010                                  cast<CXXRecordDecl>(NamedContext))) {
8011       if (CurContext == NamedContext) {
8012         Diag(NameLoc,
8013              diag::err_using_decl_nested_name_specifier_is_current_class)
8014           << SS.getRange();
8015         return true;
8016       }
8017 
8018       Diag(SS.getRange().getBegin(),
8019            diag::err_using_decl_nested_name_specifier_is_not_base_class)
8020         << SS.getScopeRep()
8021         << cast<CXXRecordDecl>(CurContext)
8022         << SS.getRange();
8023       return true;
8024     }
8025 
8026     return false;
8027   }
8028 
8029   // C++03 [namespace.udecl]p4:
8030   //   A using-declaration used as a member-declaration shall refer
8031   //   to a member of a base class of the class being defined [etc.].
8032 
8033   // Salient point: SS doesn't have to name a base class as long as
8034   // lookup only finds members from base classes.  Therefore we can
8035   // diagnose here only if we can prove that that can't happen,
8036   // i.e. if the class hierarchies provably don't intersect.
8037 
8038   // TODO: it would be nice if "definitely valid" results were cached
8039   // in the UsingDecl and UsingShadowDecl so that these checks didn't
8040   // need to be repeated.
8041 
8042   struct UserData {
8043     llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
8044 
8045     static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
8046       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8047       Data->Bases.insert(Base);
8048       return true;
8049     }
8050 
8051     bool hasDependentBases(const CXXRecordDecl *Class) {
8052       return !Class->forallBases(collect, this);
8053     }
8054 
8055     /// Returns true if the base is dependent or is one of the
8056     /// accumulated base classes.
8057     static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
8058       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8059       return !Data->Bases.count(Base);
8060     }
8061 
8062     bool mightShareBases(const CXXRecordDecl *Class) {
8063       return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
8064     }
8065   };
8066 
8067   UserData Data;
8068 
8069   // Returns false if we find a dependent base.
8070   if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
8071     return false;
8072 
8073   // Returns false if the class has a dependent base or if it or one
8074   // of its bases is present in the base set of the current context.
8075   if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
8076     return false;
8077 
8078   Diag(SS.getRange().getBegin(),
8079        diag::err_using_decl_nested_name_specifier_is_not_base_class)
8080     << SS.getScopeRep()
8081     << cast<CXXRecordDecl>(CurContext)
8082     << SS.getRange();
8083 
8084   return true;
8085 }
8086 
8087 Decl *Sema::ActOnAliasDeclaration(Scope *S,
8088                                   AccessSpecifier AS,
8089                                   MultiTemplateParamsArg TemplateParamLists,
8090                                   SourceLocation UsingLoc,
8091                                   UnqualifiedId &Name,
8092                                   AttributeList *AttrList,
8093                                   TypeResult Type) {
8094   // Skip up to the relevant declaration scope.
8095   while (S->getFlags() & Scope::TemplateParamScope)
8096     S = S->getParent();
8097   assert((S->getFlags() & Scope::DeclScope) &&
8098          "got alias-declaration outside of declaration scope");
8099 
8100   if (Type.isInvalid())
8101     return nullptr;
8102 
8103   bool Invalid = false;
8104   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
8105   TypeSourceInfo *TInfo = nullptr;
8106   GetTypeFromParser(Type.get(), &TInfo);
8107 
8108   if (DiagnoseClassNameShadow(CurContext, NameInfo))
8109     return nullptr;
8110 
8111   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
8112                                       UPPC_DeclarationType)) {
8113     Invalid = true;
8114     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8115                                              TInfo->getTypeLoc().getBeginLoc());
8116   }
8117 
8118   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
8119   LookupName(Previous, S);
8120 
8121   // Warn about shadowing the name of a template parameter.
8122   if (Previous.isSingleResult() &&
8123       Previous.getFoundDecl()->isTemplateParameter()) {
8124     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
8125     Previous.clear();
8126   }
8127 
8128   assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8129          "name in alias declaration must be an identifier");
8130   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
8131                                                Name.StartLocation,
8132                                                Name.Identifier, TInfo);
8133 
8134   NewTD->setAccess(AS);
8135 
8136   if (Invalid)
8137     NewTD->setInvalidDecl();
8138 
8139   ProcessDeclAttributeList(S, NewTD, AttrList);
8140 
8141   CheckTypedefForVariablyModifiedType(S, NewTD);
8142   Invalid |= NewTD->isInvalidDecl();
8143 
8144   bool Redeclaration = false;
8145 
8146   NamedDecl *NewND;
8147   if (TemplateParamLists.size()) {
8148     TypeAliasTemplateDecl *OldDecl = nullptr;
8149     TemplateParameterList *OldTemplateParams = nullptr;
8150 
8151     if (TemplateParamLists.size() != 1) {
8152       Diag(UsingLoc, diag::err_alias_template_extra_headers)
8153         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8154          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
8155     }
8156     TemplateParameterList *TemplateParams = TemplateParamLists[0];
8157 
8158     // Only consider previous declarations in the same scope.
8159     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8160                          /*ExplicitInstantiationOrSpecialization*/false);
8161     if (!Previous.empty()) {
8162       Redeclaration = true;
8163 
8164       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8165       if (!OldDecl && !Invalid) {
8166         Diag(UsingLoc, diag::err_redefinition_different_kind)
8167           << Name.Identifier;
8168 
8169         NamedDecl *OldD = Previous.getRepresentativeDecl();
8170         if (OldD->getLocation().isValid())
8171           Diag(OldD->getLocation(), diag::note_previous_definition);
8172 
8173         Invalid = true;
8174       }
8175 
8176       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8177         if (TemplateParameterListsAreEqual(TemplateParams,
8178                                            OldDecl->getTemplateParameters(),
8179                                            /*Complain=*/true,
8180                                            TPL_TemplateMatch))
8181           OldTemplateParams = OldDecl->getTemplateParameters();
8182         else
8183           Invalid = true;
8184 
8185         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8186         if (!Invalid &&
8187             !Context.hasSameType(OldTD->getUnderlyingType(),
8188                                  NewTD->getUnderlyingType())) {
8189           // FIXME: The C++0x standard does not clearly say this is ill-formed,
8190           // but we can't reasonably accept it.
8191           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8192             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8193           if (OldTD->getLocation().isValid())
8194             Diag(OldTD->getLocation(), diag::note_previous_definition);
8195           Invalid = true;
8196         }
8197       }
8198     }
8199 
8200     // Merge any previous default template arguments into our parameters,
8201     // and check the parameter list.
8202     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8203                                    TPC_TypeAliasTemplate))
8204       return nullptr;
8205 
8206     TypeAliasTemplateDecl *NewDecl =
8207       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8208                                     Name.Identifier, TemplateParams,
8209                                     NewTD);
8210 
8211     NewDecl->setAccess(AS);
8212 
8213     if (Invalid)
8214       NewDecl->setInvalidDecl();
8215     else if (OldDecl)
8216       NewDecl->setPreviousDecl(OldDecl);
8217 
8218     NewND = NewDecl;
8219   } else {
8220     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8221     NewND = NewTD;
8222   }
8223 
8224   if (!Redeclaration)
8225     PushOnScopeChains(NewND, S);
8226 
8227   ActOnDocumentableDecl(NewND);
8228   return NewND;
8229 }
8230 
8231 Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
8232                                              SourceLocation NamespaceLoc,
8233                                              SourceLocation AliasLoc,
8234                                              IdentifierInfo *Alias,
8235                                              CXXScopeSpec &SS,
8236                                              SourceLocation IdentLoc,
8237                                              IdentifierInfo *Ident) {
8238 
8239   // Lookup the namespace name.
8240   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8241   LookupParsedName(R, S, &SS);
8242 
8243   // Check if we have a previous declaration with the same name.
8244   NamedDecl *PrevDecl
8245     = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
8246                        ForRedeclaration);
8247   if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
8248     PrevDecl = nullptr;
8249 
8250   if (PrevDecl) {
8251     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
8252       // We already have an alias with the same name that points to the same
8253       // namespace, so don't create a new one.
8254       // FIXME: At some point, we'll want to create the (redundant)
8255       // declaration to maintain better source information.
8256       if (!R.isAmbiguous() && !R.empty() &&
8257           AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
8258         return nullptr;
8259     }
8260 
8261     unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
8262       diag::err_redefinition_different_kind;
8263     Diag(AliasLoc, DiagID) << Alias;
8264     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8265     return nullptr;
8266   }
8267 
8268   if (R.isAmbiguous())
8269     return nullptr;
8270 
8271   if (R.empty()) {
8272     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
8273       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
8274       return nullptr;
8275     }
8276   }
8277 
8278   NamespaceAliasDecl *AliasDecl =
8279     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
8280                                Alias, SS.getWithLocInContext(Context),
8281                                IdentLoc, R.getFoundDecl());
8282 
8283   PushOnScopeChains(AliasDecl, S);
8284   return AliasDecl;
8285 }
8286 
8287 Sema::ImplicitExceptionSpecification
8288 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8289                                                CXXMethodDecl *MD) {
8290   CXXRecordDecl *ClassDecl = MD->getParent();
8291 
8292   // C++ [except.spec]p14:
8293   //   An implicitly declared special member function (Clause 12) shall have an
8294   //   exception-specification. [...]
8295   ImplicitExceptionSpecification ExceptSpec(*this);
8296   if (ClassDecl->isInvalidDecl())
8297     return ExceptSpec;
8298 
8299   // Direct base-class constructors.
8300   for (const auto &B : ClassDecl->bases()) {
8301     if (B.isVirtual()) // Handled below.
8302       continue;
8303 
8304     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8305       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8306       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8307       // If this is a deleted function, add it anyway. This might be conformant
8308       // with the standard. This might not. I'm not sure. It might not matter.
8309       if (Constructor)
8310         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8311     }
8312   }
8313 
8314   // Virtual base-class constructors.
8315   for (const auto &B : ClassDecl->vbases()) {
8316     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8317       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8318       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8319       // If this is a deleted function, add it anyway. This might be conformant
8320       // with the standard. This might not. I'm not sure. It might not matter.
8321       if (Constructor)
8322         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8323     }
8324   }
8325 
8326   // Field constructors.
8327   for (const auto *F : ClassDecl->fields()) {
8328     if (F->hasInClassInitializer()) {
8329       if (Expr *E = F->getInClassInitializer())
8330         ExceptSpec.CalledExpr(E);
8331       else if (!F->isInvalidDecl())
8332         // DR1351:
8333         //   If the brace-or-equal-initializer of a non-static data member
8334         //   invokes a defaulted default constructor of its class or of an
8335         //   enclosing class in a potentially evaluated subexpression, the
8336         //   program is ill-formed.
8337         //
8338         // This resolution is unworkable: the exception specification of the
8339         // default constructor can be needed in an unevaluated context, in
8340         // particular, in the operand of a noexcept-expression, and we can be
8341         // unable to compute an exception specification for an enclosed class.
8342         //
8343         // We do not allow an in-class initializer to require the evaluation
8344         // of the exception specification for any in-class initializer whose
8345         // definition is not lexically complete.
8346         Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
8347     } else if (const RecordType *RecordTy
8348               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8349       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8350       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8351       // If this is a deleted function, add it anyway. This might be conformant
8352       // with the standard. This might not. I'm not sure. It might not matter.
8353       // In particular, the problem is that this function never gets called. It
8354       // might just be ill-formed because this function attempts to refer to
8355       // a deleted function here.
8356       if (Constructor)
8357         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8358     }
8359   }
8360 
8361   return ExceptSpec;
8362 }
8363 
8364 Sema::ImplicitExceptionSpecification
8365 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8366   CXXRecordDecl *ClassDecl = CD->getParent();
8367 
8368   // C++ [except.spec]p14:
8369   //   An inheriting constructor [...] shall have an exception-specification. [...]
8370   ImplicitExceptionSpecification ExceptSpec(*this);
8371   if (ClassDecl->isInvalidDecl())
8372     return ExceptSpec;
8373 
8374   // Inherited constructor.
8375   const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8376   const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8377   // FIXME: Copying or moving the parameters could add extra exceptions to the
8378   // set, as could the default arguments for the inherited constructor. This
8379   // will be addressed when we implement the resolution of core issue 1351.
8380   ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8381 
8382   // Direct base-class constructors.
8383   for (const auto &B : ClassDecl->bases()) {
8384     if (B.isVirtual()) // Handled below.
8385       continue;
8386 
8387     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8388       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8389       if (BaseClassDecl == InheritedDecl)
8390         continue;
8391       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8392       if (Constructor)
8393         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8394     }
8395   }
8396 
8397   // Virtual base-class constructors.
8398   for (const auto &B : ClassDecl->vbases()) {
8399     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8400       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8401       if (BaseClassDecl == InheritedDecl)
8402         continue;
8403       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8404       if (Constructor)
8405         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8406     }
8407   }
8408 
8409   // Field constructors.
8410   for (const auto *F : ClassDecl->fields()) {
8411     if (F->hasInClassInitializer()) {
8412       if (Expr *E = F->getInClassInitializer())
8413         ExceptSpec.CalledExpr(E);
8414       else if (!F->isInvalidDecl())
8415         Diag(CD->getLocation(),
8416              diag::err_in_class_initializer_references_def_ctor) << CD;
8417     } else if (const RecordType *RecordTy
8418               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8419       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8420       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8421       if (Constructor)
8422         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8423     }
8424   }
8425 
8426   return ExceptSpec;
8427 }
8428 
8429 namespace {
8430 /// RAII object to register a special member as being currently declared.
8431 struct DeclaringSpecialMember {
8432   Sema &S;
8433   Sema::SpecialMemberDecl D;
8434   bool WasAlreadyBeingDeclared;
8435 
8436   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8437     : S(S), D(RD, CSM) {
8438     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8439     if (WasAlreadyBeingDeclared)
8440       // This almost never happens, but if it does, ensure that our cache
8441       // doesn't contain a stale result.
8442       S.SpecialMemberCache.clear();
8443 
8444     // FIXME: Register a note to be produced if we encounter an error while
8445     // declaring the special member.
8446   }
8447   ~DeclaringSpecialMember() {
8448     if (!WasAlreadyBeingDeclared)
8449       S.SpecialMembersBeingDeclared.erase(D);
8450   }
8451 
8452   /// \brief Are we already trying to declare this special member?
8453   bool isAlreadyBeingDeclared() const {
8454     return WasAlreadyBeingDeclared;
8455   }
8456 };
8457 }
8458 
8459 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8460                                                      CXXRecordDecl *ClassDecl) {
8461   // C++ [class.ctor]p5:
8462   //   A default constructor for a class X is a constructor of class X
8463   //   that can be called without an argument. If there is no
8464   //   user-declared constructor for class X, a default constructor is
8465   //   implicitly declared. An implicitly-declared default constructor
8466   //   is an inline public member of its class.
8467   assert(ClassDecl->needsImplicitDefaultConstructor() &&
8468          "Should not build implicit default constructor!");
8469 
8470   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8471   if (DSM.isAlreadyBeingDeclared())
8472     return nullptr;
8473 
8474   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8475                                                      CXXDefaultConstructor,
8476                                                      false);
8477 
8478   // Create the actual constructor declaration.
8479   CanQualType ClassType
8480     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8481   SourceLocation ClassLoc = ClassDecl->getLocation();
8482   DeclarationName Name
8483     = Context.DeclarationNames.getCXXConstructorName(ClassType);
8484   DeclarationNameInfo NameInfo(Name, ClassLoc);
8485   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
8486       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8487       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8488       /*isImplicitlyDeclared=*/true, Constexpr);
8489   DefaultCon->setAccess(AS_public);
8490   DefaultCon->setDefaulted();
8491   DefaultCon->setImplicit();
8492 
8493   // Build an exception specification pointing back at this constructor.
8494   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
8495   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8496 
8497   // We don't need to use SpecialMemberIsTrivial here; triviality for default
8498   // constructors is easy to compute.
8499   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8500 
8501   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
8502     SetDeclDeleted(DefaultCon, ClassLoc);
8503 
8504   // Note that we have declared this constructor.
8505   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
8506 
8507   if (Scope *S = getScopeForContext(ClassDecl))
8508     PushOnScopeChains(DefaultCon, S, false);
8509   ClassDecl->addDecl(DefaultCon);
8510 
8511   return DefaultCon;
8512 }
8513 
8514 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8515                                             CXXConstructorDecl *Constructor) {
8516   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
8517           !Constructor->doesThisDeclarationHaveABody() &&
8518           !Constructor->isDeleted()) &&
8519     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
8520 
8521   CXXRecordDecl *ClassDecl = Constructor->getParent();
8522   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
8523 
8524   SynthesizedFunctionScope Scope(*this, Constructor);
8525   DiagnosticErrorTrap Trap(Diags);
8526   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8527       Trap.hasErrorOccurred()) {
8528     Diag(CurrentLocation, diag::note_member_synthesized_at)
8529       << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
8530     Constructor->setInvalidDecl();
8531     return;
8532   }
8533 
8534   SourceLocation Loc = Constructor->getLocEnd().isValid()
8535                            ? Constructor->getLocEnd()
8536                            : Constructor->getLocation();
8537   Constructor->setBody(new (Context) CompoundStmt(Loc));
8538 
8539   Constructor->markUsed(Context);
8540   MarkVTableUsed(CurrentLocation, ClassDecl);
8541 
8542   if (ASTMutationListener *L = getASTMutationListener()) {
8543     L->CompletedImplicitDefinition(Constructor);
8544   }
8545 
8546   DiagnoseUninitializedFields(*this, Constructor);
8547 }
8548 
8549 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
8550   // Perform any delayed checks on exception specifications.
8551   CheckDelayedMemberExceptionSpecs();
8552 }
8553 
8554 namespace {
8555 /// Information on inheriting constructors to declare.
8556 class InheritingConstructorInfo {
8557 public:
8558   InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8559       : SemaRef(SemaRef), Derived(Derived) {
8560     // Mark the constructors that we already have in the derived class.
8561     //
8562     // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8563     //   unless there is a user-declared constructor with the same signature in
8564     //   the class where the using-declaration appears.
8565     visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8566   }
8567 
8568   void inheritAll(CXXRecordDecl *RD) {
8569     visitAll(RD, &InheritingConstructorInfo::inherit);
8570   }
8571 
8572 private:
8573   /// Information about an inheriting constructor.
8574   struct InheritingConstructor {
8575     InheritingConstructor()
8576       : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
8577 
8578     /// If \c true, a constructor with this signature is already declared
8579     /// in the derived class.
8580     bool DeclaredInDerived;
8581 
8582     /// The constructor which is inherited.
8583     const CXXConstructorDecl *BaseCtor;
8584 
8585     /// The derived constructor we declared.
8586     CXXConstructorDecl *DerivedCtor;
8587   };
8588 
8589   /// Inheriting constructors with a given canonical type. There can be at
8590   /// most one such non-template constructor, and any number of templated
8591   /// constructors.
8592   struct InheritingConstructorsForType {
8593     InheritingConstructor NonTemplate;
8594     SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8595         Templates;
8596 
8597     InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8598       if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8599         TemplateParameterList *ParamList = FTD->getTemplateParameters();
8600         for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8601           if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8602                                                false, S.TPL_TemplateMatch))
8603             return Templates[I].second;
8604         Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8605         return Templates.back().second;
8606       }
8607 
8608       return NonTemplate;
8609     }
8610   };
8611 
8612   /// Get or create the inheriting constructor record for a constructor.
8613   InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8614                                   QualType CtorType) {
8615     return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8616         .getEntry(SemaRef, Ctor);
8617   }
8618 
8619   typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8620 
8621   /// Process all constructors for a class.
8622   void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
8623     for (const auto *Ctor : RD->ctors())
8624       (this->*Callback)(Ctor);
8625     for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8626              I(RD->decls_begin()), E(RD->decls_end());
8627          I != E; ++I) {
8628       const FunctionDecl *FD = (*I)->getTemplatedDecl();
8629       if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8630         (this->*Callback)(CD);
8631     }
8632   }
8633 
8634   /// Note that a constructor (or constructor template) was declared in Derived.
8635   void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8636     getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8637   }
8638 
8639   /// Inherit a single constructor.
8640   void inherit(const CXXConstructorDecl *Ctor) {
8641     const FunctionProtoType *CtorType =
8642         Ctor->getType()->castAs<FunctionProtoType>();
8643     ArrayRef<QualType> ArgTypes(CtorType->getParamTypes());
8644     FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8645 
8646     SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8647 
8648     // Core issue (no number yet): the ellipsis is always discarded.
8649     if (EPI.Variadic) {
8650       SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8651       SemaRef.Diag(Ctor->getLocation(),
8652                    diag::note_using_decl_constructor_ellipsis);
8653       EPI.Variadic = false;
8654     }
8655 
8656     // Declare a constructor for each number of parameters.
8657     //
8658     // C++11 [class.inhctor]p1:
8659     //   The candidate set of inherited constructors from the class X named in
8660     //   the using-declaration consists of [... modulo defects ...] for each
8661     //   constructor or constructor template of X, the set of constructors or
8662     //   constructor templates that results from omitting any ellipsis parameter
8663     //   specification and successively omitting parameters with a default
8664     //   argument from the end of the parameter-type-list
8665     unsigned MinParams = minParamsToInherit(Ctor);
8666     unsigned Params = Ctor->getNumParams();
8667     if (Params >= MinParams) {
8668       do
8669         declareCtor(UsingLoc, Ctor,
8670                     SemaRef.Context.getFunctionType(
8671                         Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
8672       while (Params > MinParams &&
8673              Ctor->getParamDecl(--Params)->hasDefaultArg());
8674     }
8675   }
8676 
8677   /// Find the using-declaration which specified that we should inherit the
8678   /// constructors of \p Base.
8679   SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8680     // No fancy lookup required; just look for the base constructor name
8681     // directly within the derived class.
8682     ASTContext &Context = SemaRef.Context;
8683     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8684         Context.getCanonicalType(Context.getRecordType(Base)));
8685     DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8686     return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8687   }
8688 
8689   unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8690     // C++11 [class.inhctor]p3:
8691     //   [F]or each constructor template in the candidate set of inherited
8692     //   constructors, a constructor template is implicitly declared
8693     if (Ctor->getDescribedFunctionTemplate())
8694       return 0;
8695 
8696     //   For each non-template constructor in the candidate set of inherited
8697     //   constructors other than a constructor having no parameters or a
8698     //   copy/move constructor having a single parameter, a constructor is
8699     //   implicitly declared [...]
8700     if (Ctor->getNumParams() == 0)
8701       return 1;
8702     if (Ctor->isCopyOrMoveConstructor())
8703       return 2;
8704 
8705     // Per discussion on core reflector, never inherit a constructor which
8706     // would become a default, copy, or move constructor of Derived either.
8707     const ParmVarDecl *PD = Ctor->getParamDecl(0);
8708     const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8709     return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8710   }
8711 
8712   /// Declare a single inheriting constructor, inheriting the specified
8713   /// constructor, with the given type.
8714   void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8715                    QualType DerivedType) {
8716     InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8717 
8718     // C++11 [class.inhctor]p3:
8719     //   ... a constructor is implicitly declared with the same constructor
8720     //   characteristics unless there is a user-declared constructor with
8721     //   the same signature in the class where the using-declaration appears
8722     if (Entry.DeclaredInDerived)
8723       return;
8724 
8725     // C++11 [class.inhctor]p7:
8726     //   If two using-declarations declare inheriting constructors with the
8727     //   same signature, the program is ill-formed
8728     if (Entry.DerivedCtor) {
8729       if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8730         // Only diagnose this once per constructor.
8731         if (Entry.DerivedCtor->isInvalidDecl())
8732           return;
8733         Entry.DerivedCtor->setInvalidDecl();
8734 
8735         SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8736         SemaRef.Diag(BaseCtor->getLocation(),
8737                      diag::note_using_decl_constructor_conflict_current_ctor);
8738         SemaRef.Diag(Entry.BaseCtor->getLocation(),
8739                      diag::note_using_decl_constructor_conflict_previous_ctor);
8740         SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8741                      diag::note_using_decl_constructor_conflict_previous_using);
8742       } else {
8743         // Core issue (no number): if the same inheriting constructor is
8744         // produced by multiple base class constructors from the same base
8745         // class, the inheriting constructor is defined as deleted.
8746         SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8747       }
8748 
8749       return;
8750     }
8751 
8752     ASTContext &Context = SemaRef.Context;
8753     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8754         Context.getCanonicalType(Context.getRecordType(Derived)));
8755     DeclarationNameInfo NameInfo(Name, UsingLoc);
8756 
8757     TemplateParameterList *TemplateParams = nullptr;
8758     if (const FunctionTemplateDecl *FTD =
8759             BaseCtor->getDescribedFunctionTemplate()) {
8760       TemplateParams = FTD->getTemplateParameters();
8761       // We're reusing template parameters from a different DeclContext. This
8762       // is questionable at best, but works out because the template depth in
8763       // both places is guaranteed to be 0.
8764       // FIXME: Rebuild the template parameters in the new context, and
8765       // transform the function type to refer to them.
8766     }
8767 
8768     // Build type source info pointing at the using-declaration. This is
8769     // required by template instantiation.
8770     TypeSourceInfo *TInfo =
8771         Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8772     FunctionProtoTypeLoc ProtoLoc =
8773         TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8774 
8775     CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8776         Context, Derived, UsingLoc, NameInfo, DerivedType,
8777         TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8778         /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8779 
8780     // Build an unevaluated exception specification for this constructor.
8781     const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8782     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8783     EPI.ExceptionSpec.Type = EST_Unevaluated;
8784     EPI.ExceptionSpec.SourceDecl = DerivedCtor;
8785     DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
8786                                                  FPT->getParamTypes(), EPI));
8787 
8788     // Build the parameter declarations.
8789     SmallVector<ParmVarDecl *, 16> ParamDecls;
8790     for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
8791       TypeSourceInfo *TInfo =
8792           Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
8793       ParmVarDecl *PD = ParmVarDecl::Create(
8794           Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
8795           FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
8796       PD->setScopeInfo(0, I);
8797       PD->setImplicit();
8798       ParamDecls.push_back(PD);
8799       ProtoLoc.setParam(I, PD);
8800     }
8801 
8802     // Set up the new constructor.
8803     DerivedCtor->setAccess(BaseCtor->getAccess());
8804     DerivedCtor->setParams(ParamDecls);
8805     DerivedCtor->setInheritedConstructor(BaseCtor);
8806     if (BaseCtor->isDeleted())
8807       SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8808 
8809     // If this is a constructor template, build the template declaration.
8810     if (TemplateParams) {
8811       FunctionTemplateDecl *DerivedTemplate =
8812           FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8813                                        TemplateParams, DerivedCtor);
8814       DerivedTemplate->setAccess(BaseCtor->getAccess());
8815       DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8816       Derived->addDecl(DerivedTemplate);
8817     } else {
8818       Derived->addDecl(DerivedCtor);
8819     }
8820 
8821     Entry.BaseCtor = BaseCtor;
8822     Entry.DerivedCtor = DerivedCtor;
8823   }
8824 
8825   Sema &SemaRef;
8826   CXXRecordDecl *Derived;
8827   typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8828   MapType Map;
8829 };
8830 }
8831 
8832 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8833   // Defer declaring the inheriting constructors until the class is
8834   // instantiated.
8835   if (ClassDecl->isDependentContext())
8836     return;
8837 
8838   // Find base classes from which we might inherit constructors.
8839   SmallVector<CXXRecordDecl*, 4> InheritedBases;
8840   for (const auto &BaseIt : ClassDecl->bases())
8841     if (BaseIt.getInheritConstructors())
8842       InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
8843 
8844   // Go no further if we're not inheriting any constructors.
8845   if (InheritedBases.empty())
8846     return;
8847 
8848   // Declare the inherited constructors.
8849   InheritingConstructorInfo ICI(*this, ClassDecl);
8850   for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8851     ICI.inheritAll(InheritedBases[I]);
8852 }
8853 
8854 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8855                                        CXXConstructorDecl *Constructor) {
8856   CXXRecordDecl *ClassDecl = Constructor->getParent();
8857   assert(Constructor->getInheritedConstructor() &&
8858          !Constructor->doesThisDeclarationHaveABody() &&
8859          !Constructor->isDeleted());
8860 
8861   SynthesizedFunctionScope Scope(*this, Constructor);
8862   DiagnosticErrorTrap Trap(Diags);
8863   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8864       Trap.hasErrorOccurred()) {
8865     Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8866       << Context.getTagDeclType(ClassDecl);
8867     Constructor->setInvalidDecl();
8868     return;
8869   }
8870 
8871   SourceLocation Loc = Constructor->getLocation();
8872   Constructor->setBody(new (Context) CompoundStmt(Loc));
8873 
8874   Constructor->markUsed(Context);
8875   MarkVTableUsed(CurrentLocation, ClassDecl);
8876 
8877   if (ASTMutationListener *L = getASTMutationListener()) {
8878     L->CompletedImplicitDefinition(Constructor);
8879   }
8880 }
8881 
8882 
8883 Sema::ImplicitExceptionSpecification
8884 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8885   CXXRecordDecl *ClassDecl = MD->getParent();
8886 
8887   // C++ [except.spec]p14:
8888   //   An implicitly declared special member function (Clause 12) shall have
8889   //   an exception-specification.
8890   ImplicitExceptionSpecification ExceptSpec(*this);
8891   if (ClassDecl->isInvalidDecl())
8892     return ExceptSpec;
8893 
8894   // Direct base-class destructors.
8895   for (const auto &B : ClassDecl->bases()) {
8896     if (B.isVirtual()) // Handled below.
8897       continue;
8898 
8899     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8900       ExceptSpec.CalledDecl(B.getLocStart(),
8901                    LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
8902   }
8903 
8904   // Virtual base-class destructors.
8905   for (const auto &B : ClassDecl->vbases()) {
8906     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8907       ExceptSpec.CalledDecl(B.getLocStart(),
8908                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
8909   }
8910 
8911   // Field destructors.
8912   for (const auto *F : ClassDecl->fields()) {
8913     if (const RecordType *RecordTy
8914         = Context.getBaseElementType(F->getType())->getAs<RecordType>())
8915       ExceptSpec.CalledDecl(F->getLocation(),
8916                   LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
8917   }
8918 
8919   return ExceptSpec;
8920 }
8921 
8922 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8923   // C++ [class.dtor]p2:
8924   //   If a class has no user-declared destructor, a destructor is
8925   //   declared implicitly. An implicitly-declared destructor is an
8926   //   inline public member of its class.
8927   assert(ClassDecl->needsImplicitDestructor());
8928 
8929   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8930   if (DSM.isAlreadyBeingDeclared())
8931     return nullptr;
8932 
8933   // Create the actual destructor declaration.
8934   CanQualType ClassType
8935     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8936   SourceLocation ClassLoc = ClassDecl->getLocation();
8937   DeclarationName Name
8938     = Context.DeclarationNames.getCXXDestructorName(ClassType);
8939   DeclarationNameInfo NameInfo(Name, ClassLoc);
8940   CXXDestructorDecl *Destructor
8941       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8942                                   QualType(), nullptr, /*isInline=*/true,
8943                                   /*isImplicitlyDeclared=*/true);
8944   Destructor->setAccess(AS_public);
8945   Destructor->setDefaulted();
8946   Destructor->setImplicit();
8947 
8948   // Build an exception specification pointing back at this destructor.
8949   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
8950   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8951 
8952   AddOverriddenMethods(ClassDecl, Destructor);
8953 
8954   // We don't need to use SpecialMemberIsTrivial here; triviality for
8955   // destructors is easy to compute.
8956   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8957 
8958   if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
8959     SetDeclDeleted(Destructor, ClassLoc);
8960 
8961   // Note that we have declared this destructor.
8962   ++ASTContext::NumImplicitDestructorsDeclared;
8963 
8964   // Introduce this destructor into its scope.
8965   if (Scope *S = getScopeForContext(ClassDecl))
8966     PushOnScopeChains(Destructor, S, false);
8967   ClassDecl->addDecl(Destructor);
8968 
8969   return Destructor;
8970 }
8971 
8972 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
8973                                     CXXDestructorDecl *Destructor) {
8974   assert((Destructor->isDefaulted() &&
8975           !Destructor->doesThisDeclarationHaveABody() &&
8976           !Destructor->isDeleted()) &&
8977          "DefineImplicitDestructor - call it for implicit default dtor");
8978   CXXRecordDecl *ClassDecl = Destructor->getParent();
8979   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
8980 
8981   if (Destructor->isInvalidDecl())
8982     return;
8983 
8984   SynthesizedFunctionScope Scope(*this, Destructor);
8985 
8986   DiagnosticErrorTrap Trap(Diags);
8987   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8988                                          Destructor->getParent());
8989 
8990   if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
8991     Diag(CurrentLocation, diag::note_member_synthesized_at)
8992       << CXXDestructor << Context.getTagDeclType(ClassDecl);
8993 
8994     Destructor->setInvalidDecl();
8995     return;
8996   }
8997 
8998   SourceLocation Loc = Destructor->getLocEnd().isValid()
8999                            ? Destructor->getLocEnd()
9000                            : Destructor->getLocation();
9001   Destructor->setBody(new (Context) CompoundStmt(Loc));
9002   Destructor->markUsed(Context);
9003   MarkVTableUsed(CurrentLocation, ClassDecl);
9004 
9005   if (ASTMutationListener *L = getASTMutationListener()) {
9006     L->CompletedImplicitDefinition(Destructor);
9007   }
9008 }
9009 
9010 /// \brief Perform any semantic analysis which needs to be delayed until all
9011 /// pending class member declarations have been parsed.
9012 void Sema::ActOnFinishCXXMemberDecls() {
9013   // If the context is an invalid C++ class, just suppress these checks.
9014   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
9015     if (Record->isInvalidDecl()) {
9016       DelayedDefaultedMemberExceptionSpecs.clear();
9017       DelayedDestructorExceptionSpecChecks.clear();
9018       return;
9019     }
9020   }
9021 }
9022 
9023 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
9024                                          CXXDestructorDecl *Destructor) {
9025   assert(getLangOpts().CPlusPlus11 &&
9026          "adjusting dtor exception specs was introduced in c++11");
9027 
9028   // C++11 [class.dtor]p3:
9029   //   A declaration of a destructor that does not have an exception-
9030   //   specification is implicitly considered to have the same exception-
9031   //   specification as an implicit declaration.
9032   const FunctionProtoType *DtorType = Destructor->getType()->
9033                                         getAs<FunctionProtoType>();
9034   if (DtorType->hasExceptionSpec())
9035     return;
9036 
9037   // Replace the destructor's type, building off the existing one. Fortunately,
9038   // the only thing of interest in the destructor type is its extended info.
9039   // The return and arguments are fixed.
9040   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
9041   EPI.ExceptionSpec.Type = EST_Unevaluated;
9042   EPI.ExceptionSpec.SourceDecl = Destructor;
9043   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9044 
9045   // FIXME: If the destructor has a body that could throw, and the newly created
9046   // spec doesn't allow exceptions, we should emit a warning, because this
9047   // change in behavior can break conforming C++03 programs at runtime.
9048   // However, we don't have a body or an exception specification yet, so it
9049   // needs to be done somewhere else.
9050 }
9051 
9052 namespace {
9053 /// \brief An abstract base class for all helper classes used in building the
9054 //  copy/move operators. These classes serve as factory functions and help us
9055 //  avoid using the same Expr* in the AST twice.
9056 class ExprBuilder {
9057   ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
9058   ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
9059 
9060 protected:
9061   static Expr *assertNotNull(Expr *E) {
9062     assert(E && "Expression construction must not fail.");
9063     return E;
9064   }
9065 
9066 public:
9067   ExprBuilder() {}
9068   virtual ~ExprBuilder() {}
9069 
9070   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
9071 };
9072 
9073 class RefBuilder: public ExprBuilder {
9074   VarDecl *Var;
9075   QualType VarType;
9076 
9077 public:
9078   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9079     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
9080   }
9081 
9082   RefBuilder(VarDecl *Var, QualType VarType)
9083       : Var(Var), VarType(VarType) {}
9084 };
9085 
9086 class ThisBuilder: public ExprBuilder {
9087 public:
9088   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9089     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
9090   }
9091 };
9092 
9093 class CastBuilder: public ExprBuilder {
9094   const ExprBuilder &Builder;
9095   QualType Type;
9096   ExprValueKind Kind;
9097   const CXXCastPath &Path;
9098 
9099 public:
9100   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9101     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
9102                                              CK_UncheckedDerivedToBase, Kind,
9103                                              &Path).get());
9104   }
9105 
9106   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
9107               const CXXCastPath &Path)
9108       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
9109 };
9110 
9111 class DerefBuilder: public ExprBuilder {
9112   const ExprBuilder &Builder;
9113 
9114 public:
9115   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9116     return assertNotNull(
9117         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
9118   }
9119 
9120   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9121 };
9122 
9123 class MemberBuilder: public ExprBuilder {
9124   const ExprBuilder &Builder;
9125   QualType Type;
9126   CXXScopeSpec SS;
9127   bool IsArrow;
9128   LookupResult &MemberLookup;
9129 
9130 public:
9131   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9132     return assertNotNull(S.BuildMemberReferenceExpr(
9133         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
9134         nullptr, MemberLookup, nullptr).get());
9135   }
9136 
9137   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9138                 LookupResult &MemberLookup)
9139       : Builder(Builder), Type(Type), IsArrow(IsArrow),
9140         MemberLookup(MemberLookup) {}
9141 };
9142 
9143 class MoveCastBuilder: public ExprBuilder {
9144   const ExprBuilder &Builder;
9145 
9146 public:
9147   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9148     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9149   }
9150 
9151   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9152 };
9153 
9154 class LvalueConvBuilder: public ExprBuilder {
9155   const ExprBuilder &Builder;
9156 
9157 public:
9158   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9159     return assertNotNull(
9160         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
9161   }
9162 
9163   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9164 };
9165 
9166 class SubscriptBuilder: public ExprBuilder {
9167   const ExprBuilder &Base;
9168   const ExprBuilder &Index;
9169 
9170 public:
9171   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9172     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
9173         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
9174   }
9175 
9176   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9177       : Base(Base), Index(Index) {}
9178 };
9179 
9180 } // end anonymous namespace
9181 
9182 /// When generating a defaulted copy or move assignment operator, if a field
9183 /// should be copied with __builtin_memcpy rather than via explicit assignments,
9184 /// do so. This optimization only applies for arrays of scalars, and for arrays
9185 /// of class type where the selected copy/move-assignment operator is trivial.
9186 static StmtResult
9187 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
9188                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
9189   // Compute the size of the memory buffer to be copied.
9190   QualType SizeType = S.Context.getSizeType();
9191   llvm::APInt Size(S.Context.getTypeSize(SizeType),
9192                    S.Context.getTypeSizeInChars(T).getQuantity());
9193 
9194   // Take the address of the field references for "from" and "to". We
9195   // directly construct UnaryOperators here because semantic analysis
9196   // does not permit us to take the address of an xvalue.
9197   Expr *From = FromB.build(S, Loc);
9198   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9199                          S.Context.getPointerType(From->getType()),
9200                          VK_RValue, OK_Ordinary, Loc);
9201   Expr *To = ToB.build(S, Loc);
9202   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9203                        S.Context.getPointerType(To->getType()),
9204                        VK_RValue, OK_Ordinary, Loc);
9205 
9206   const Type *E = T->getBaseElementTypeUnsafe();
9207   bool NeedsCollectableMemCpy =
9208     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9209 
9210   // Create a reference to the __builtin_objc_memmove_collectable function
9211   StringRef MemCpyName = NeedsCollectableMemCpy ?
9212     "__builtin_objc_memmove_collectable" :
9213     "__builtin_memcpy";
9214   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9215                  Sema::LookupOrdinaryName);
9216   S.LookupName(R, S.TUScope, true);
9217 
9218   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9219   if (!MemCpy)
9220     // Something went horribly wrong earlier, and we will have complained
9221     // about it.
9222     return StmtError();
9223 
9224   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
9225                                             VK_RValue, Loc, nullptr);
9226   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9227 
9228   Expr *CallArgs[] = {
9229     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9230   };
9231   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
9232                                     Loc, CallArgs, Loc);
9233 
9234   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
9235   return Call.getAs<Stmt>();
9236 }
9237 
9238 /// \brief Builds a statement that copies/moves the given entity from \p From to
9239 /// \c To.
9240 ///
9241 /// This routine is used to copy/move the members of a class with an
9242 /// implicitly-declared copy/move assignment operator. When the entities being
9243 /// copied are arrays, this routine builds for loops to copy them.
9244 ///
9245 /// \param S The Sema object used for type-checking.
9246 ///
9247 /// \param Loc The location where the implicit copy/move is being generated.
9248 ///
9249 /// \param T The type of the expressions being copied/moved. Both expressions
9250 /// must have this type.
9251 ///
9252 /// \param To The expression we are copying/moving to.
9253 ///
9254 /// \param From The expression we are copying/moving from.
9255 ///
9256 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
9257 /// Otherwise, it's a non-static member subobject.
9258 ///
9259 /// \param Copying Whether we're copying or moving.
9260 ///
9261 /// \param Depth Internal parameter recording the depth of the recursion.
9262 ///
9263 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9264 /// if a memcpy should be used instead.
9265 static StmtResult
9266 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
9267                                  const ExprBuilder &To, const ExprBuilder &From,
9268                                  bool CopyingBaseSubobject, bool Copying,
9269                                  unsigned Depth = 0) {
9270   // C++11 [class.copy]p28:
9271   //   Each subobject is assigned in the manner appropriate to its type:
9272   //
9273   //     - if the subobject is of class type, as if by a call to operator= with
9274   //       the subobject as the object expression and the corresponding
9275   //       subobject of x as a single function argument (as if by explicit
9276   //       qualification; that is, ignoring any possible virtual overriding
9277   //       functions in more derived classes);
9278   //
9279   // C++03 [class.copy]p13:
9280   //     - if the subobject is of class type, the copy assignment operator for
9281   //       the class is used (as if by explicit qualification; that is,
9282   //       ignoring any possible virtual overriding functions in more derived
9283   //       classes);
9284   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9285     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9286 
9287     // Look for operator=.
9288     DeclarationName Name
9289       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9290     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9291     S.LookupQualifiedName(OpLookup, ClassDecl, false);
9292 
9293     // Prior to C++11, filter out any result that isn't a copy/move-assignment
9294     // operator.
9295     if (!S.getLangOpts().CPlusPlus11) {
9296       LookupResult::Filter F = OpLookup.makeFilter();
9297       while (F.hasNext()) {
9298         NamedDecl *D = F.next();
9299         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9300           if (Method->isCopyAssignmentOperator() ||
9301               (!Copying && Method->isMoveAssignmentOperator()))
9302             continue;
9303 
9304         F.erase();
9305       }
9306       F.done();
9307     }
9308 
9309     // Suppress the protected check (C++ [class.protected]) for each of the
9310     // assignment operators we found. This strange dance is required when
9311     // we're assigning via a base classes's copy-assignment operator. To
9312     // ensure that we're getting the right base class subobject (without
9313     // ambiguities), we need to cast "this" to that subobject type; to
9314     // ensure that we don't go through the virtual call mechanism, we need
9315     // to qualify the operator= name with the base class (see below). However,
9316     // this means that if the base class has a protected copy assignment
9317     // operator, the protected member access check will fail. So, we
9318     // rewrite "protected" access to "public" access in this case, since we
9319     // know by construction that we're calling from a derived class.
9320     if (CopyingBaseSubobject) {
9321       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9322            L != LEnd; ++L) {
9323         if (L.getAccess() == AS_protected)
9324           L.setAccess(AS_public);
9325       }
9326     }
9327 
9328     // Create the nested-name-specifier that will be used to qualify the
9329     // reference to operator=; this is required to suppress the virtual
9330     // call mechanism.
9331     CXXScopeSpec SS;
9332     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
9333     SS.MakeTrivial(S.Context,
9334                    NestedNameSpecifier::Create(S.Context, nullptr, false,
9335                                                CanonicalT),
9336                    Loc);
9337 
9338     // Create the reference to operator=.
9339     ExprResult OpEqualRef
9340       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9341                                    SS, /*TemplateKWLoc=*/SourceLocation(),
9342                                    /*FirstQualifierInScope=*/nullptr,
9343                                    OpLookup,
9344                                    /*TemplateArgs=*/nullptr,
9345                                    /*SuppressQualifierCheck=*/true);
9346     if (OpEqualRef.isInvalid())
9347       return StmtError();
9348 
9349     // Build the call to the assignment operator.
9350 
9351     Expr *FromInst = From.build(S, Loc);
9352     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
9353                                                   OpEqualRef.getAs<Expr>(),
9354                                                   Loc, FromInst, Loc);
9355     if (Call.isInvalid())
9356       return StmtError();
9357 
9358     // If we built a call to a trivial 'operator=' while copying an array,
9359     // bail out. We'll replace the whole shebang with a memcpy.
9360     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9361     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9362       return StmtResult((Stmt*)nullptr);
9363 
9364     // Convert to an expression-statement, and clean up any produced
9365     // temporaries.
9366     return S.ActOnExprStmt(Call);
9367   }
9368 
9369   //     - if the subobject is of scalar type, the built-in assignment
9370   //       operator is used.
9371   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
9372   if (!ArrayTy) {
9373     ExprResult Assignment = S.CreateBuiltinBinOp(
9374         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
9375     if (Assignment.isInvalid())
9376       return StmtError();
9377     return S.ActOnExprStmt(Assignment);
9378   }
9379 
9380   //     - if the subobject is an array, each element is assigned, in the
9381   //       manner appropriate to the element type;
9382 
9383   // Construct a loop over the array bounds, e.g.,
9384   //
9385   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9386   //
9387   // that will copy each of the array elements.
9388   QualType SizeType = S.Context.getSizeType();
9389 
9390   // Create the iteration variable.
9391   IdentifierInfo *IterationVarName = nullptr;
9392   {
9393     SmallString<8> Str;
9394     llvm::raw_svector_ostream OS(Str);
9395     OS << "__i" << Depth;
9396     IterationVarName = &S.Context.Idents.get(OS.str());
9397   }
9398   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
9399                                           IterationVarName, SizeType,
9400                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
9401                                           SC_None);
9402 
9403   // Initialize the iteration variable to zero.
9404   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
9405   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
9406 
9407   // Creates a reference to the iteration variable.
9408   RefBuilder IterationVarRef(IterationVar, SizeType);
9409   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
9410 
9411   // Create the DeclStmt that holds the iteration variable.
9412   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
9413 
9414   // Subscript the "from" and "to" expressions with the iteration variable.
9415   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9416   MoveCastBuilder FromIndexMove(FromIndexCopy);
9417   const ExprBuilder *FromIndex;
9418   if (Copying)
9419     FromIndex = &FromIndexCopy;
9420   else
9421     FromIndex = &FromIndexMove;
9422 
9423   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
9424 
9425   // Build the copy/move for an individual element of the array.
9426   StmtResult Copy =
9427     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
9428                                      ToIndex, *FromIndex, CopyingBaseSubobject,
9429                                      Copying, Depth + 1);
9430   // Bail out if copying fails or if we determined that we should use memcpy.
9431   if (Copy.isInvalid() || !Copy.get())
9432     return Copy;
9433 
9434   // Create the comparison against the array bound.
9435   llvm::APInt Upper
9436     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9437   Expr *Comparison
9438     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
9439                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9440                                      BO_NE, S.Context.BoolTy,
9441                                      VK_RValue, OK_Ordinary, Loc, false);
9442 
9443   // Create the pre-increment of the iteration variable.
9444   Expr *Increment
9445     = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9446                                     SizeType, VK_LValue, OK_Ordinary, Loc);
9447 
9448   // Construct the loop that copies all elements of this array.
9449   return S.ActOnForStmt(Loc, Loc, InitStmt,
9450                         S.MakeFullExpr(Comparison),
9451                         nullptr, S.MakeFullDiscardedValueExpr(Increment),
9452                         Loc, Copy.get());
9453 }
9454 
9455 static StmtResult
9456 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
9457                       const ExprBuilder &To, const ExprBuilder &From,
9458                       bool CopyingBaseSubobject, bool Copying) {
9459   // Maybe we should use a memcpy?
9460   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9461       T.isTriviallyCopyableType(S.Context))
9462     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9463 
9464   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9465                                                      CopyingBaseSubobject,
9466                                                      Copying, 0));
9467 
9468   // If we ended up picking a trivial assignment operator for an array of a
9469   // non-trivially-copyable class type, just emit a memcpy.
9470   if (!Result.isInvalid() && !Result.get())
9471     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9472 
9473   return Result;
9474 }
9475 
9476 Sema::ImplicitExceptionSpecification
9477 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9478   CXXRecordDecl *ClassDecl = MD->getParent();
9479 
9480   ImplicitExceptionSpecification ExceptSpec(*this);
9481   if (ClassDecl->isInvalidDecl())
9482     return ExceptSpec;
9483 
9484   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9485   assert(T->getNumParams() == 1 && "not a copy assignment op");
9486   unsigned ArgQuals =
9487       T->getParamType(0).getNonReferenceType().getCVRQualifiers();
9488 
9489   // C++ [except.spec]p14:
9490   //   An implicitly declared special member function (Clause 12) shall have an
9491   //   exception-specification. [...]
9492 
9493   // It is unspecified whether or not an implicit copy assignment operator
9494   // attempts to deduplicate calls to assignment operators of virtual bases are
9495   // made. As such, this exception specification is effectively unspecified.
9496   // Based on a similar decision made for constness in C++0x, we're erring on
9497   // the side of assuming such calls to be made regardless of whether they
9498   // actually happen.
9499   for (const auto &Base : ClassDecl->bases()) {
9500     if (Base.isVirtual())
9501       continue;
9502 
9503     CXXRecordDecl *BaseClassDecl
9504       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9505     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9506                                                             ArgQuals, false, 0))
9507       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
9508   }
9509 
9510   for (const auto &Base : ClassDecl->vbases()) {
9511     CXXRecordDecl *BaseClassDecl
9512       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9513     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9514                                                             ArgQuals, false, 0))
9515       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
9516   }
9517 
9518   for (const auto *Field : ClassDecl->fields()) {
9519     QualType FieldType = Context.getBaseElementType(Field->getType());
9520     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9521       if (CXXMethodDecl *CopyAssign =
9522           LookupCopyingAssignment(FieldClassDecl,
9523                                   ArgQuals | FieldType.getCVRQualifiers(),
9524                                   false, 0))
9525         ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
9526     }
9527   }
9528 
9529   return ExceptSpec;
9530 }
9531 
9532 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9533   // Note: The following rules are largely analoguous to the copy
9534   // constructor rules. Note that virtual bases are not taken into account
9535   // for determining the argument type of the operator. Note also that
9536   // operators taking an object instead of a reference are allowed.
9537   assert(ClassDecl->needsImplicitCopyAssignment());
9538 
9539   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9540   if (DSM.isAlreadyBeingDeclared())
9541     return nullptr;
9542 
9543   QualType ArgType = Context.getTypeDeclType(ClassDecl);
9544   QualType RetType = Context.getLValueReferenceType(ArgType);
9545   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9546   if (Const)
9547     ArgType = ArgType.withConst();
9548   ArgType = Context.getLValueReferenceType(ArgType);
9549 
9550   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9551                                                      CXXCopyAssignment,
9552                                                      Const);
9553 
9554   //   An implicitly-declared copy assignment operator is an inline public
9555   //   member of its class.
9556   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9557   SourceLocation ClassLoc = ClassDecl->getLocation();
9558   DeclarationNameInfo NameInfo(Name, ClassLoc);
9559   CXXMethodDecl *CopyAssignment =
9560       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9561                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
9562                             /*isInline=*/true, Constexpr, SourceLocation());
9563   CopyAssignment->setAccess(AS_public);
9564   CopyAssignment->setDefaulted();
9565   CopyAssignment->setImplicit();
9566 
9567   // Build an exception specification pointing back at this member.
9568   FunctionProtoType::ExtProtoInfo EPI =
9569       getImplicitMethodEPI(*this, CopyAssignment);
9570   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
9571 
9572   // Add the parameter to the operator.
9573   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
9574                                                ClassLoc, ClassLoc,
9575                                                /*Id=*/nullptr, ArgType,
9576                                                /*TInfo=*/nullptr, SC_None,
9577                                                nullptr);
9578   CopyAssignment->setParams(FromParam);
9579 
9580   AddOverriddenMethods(ClassDecl, CopyAssignment);
9581 
9582   CopyAssignment->setTrivial(
9583     ClassDecl->needsOverloadResolutionForCopyAssignment()
9584       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9585       : ClassDecl->hasTrivialCopyAssignment());
9586 
9587   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
9588     SetDeclDeleted(CopyAssignment, ClassLoc);
9589 
9590   // Note that we have added this copy-assignment operator.
9591   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9592 
9593   if (Scope *S = getScopeForContext(ClassDecl))
9594     PushOnScopeChains(CopyAssignment, S, false);
9595   ClassDecl->addDecl(CopyAssignment);
9596 
9597   return CopyAssignment;
9598 }
9599 
9600 /// Diagnose an implicit copy operation for a class which is odr-used, but
9601 /// which is deprecated because the class has a user-declared copy constructor,
9602 /// copy assignment operator, or destructor.
9603 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9604                                             SourceLocation UseLoc) {
9605   assert(CopyOp->isImplicit());
9606 
9607   CXXRecordDecl *RD = CopyOp->getParent();
9608   CXXMethodDecl *UserDeclaredOperation = nullptr;
9609 
9610   // In Microsoft mode, assignment operations don't affect constructors and
9611   // vice versa.
9612   if (RD->hasUserDeclaredDestructor()) {
9613     UserDeclaredOperation = RD->getDestructor();
9614   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9615              RD->hasUserDeclaredCopyConstructor() &&
9616              !S.getLangOpts().MSVCCompat) {
9617     // Find any user-declared copy constructor.
9618     for (auto *I : RD->ctors()) {
9619       if (I->isCopyConstructor()) {
9620         UserDeclaredOperation = I;
9621         break;
9622       }
9623     }
9624     assert(UserDeclaredOperation);
9625   } else if (isa<CXXConstructorDecl>(CopyOp) &&
9626              RD->hasUserDeclaredCopyAssignment() &&
9627              !S.getLangOpts().MSVCCompat) {
9628     // Find any user-declared move assignment operator.
9629     for (auto *I : RD->methods()) {
9630       if (I->isCopyAssignmentOperator()) {
9631         UserDeclaredOperation = I;
9632         break;
9633       }
9634     }
9635     assert(UserDeclaredOperation);
9636   }
9637 
9638   if (UserDeclaredOperation) {
9639     S.Diag(UserDeclaredOperation->getLocation(),
9640          diag::warn_deprecated_copy_operation)
9641       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9642       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9643     S.Diag(UseLoc, diag::note_member_synthesized_at)
9644       << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9645                                           : Sema::CXXCopyAssignment)
9646       << RD;
9647   }
9648 }
9649 
9650 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9651                                         CXXMethodDecl *CopyAssignOperator) {
9652   assert((CopyAssignOperator->isDefaulted() &&
9653           CopyAssignOperator->isOverloadedOperator() &&
9654           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
9655           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9656           !CopyAssignOperator->isDeleted()) &&
9657          "DefineImplicitCopyAssignment called for wrong function");
9658 
9659   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9660 
9661   if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9662     CopyAssignOperator->setInvalidDecl();
9663     return;
9664   }
9665 
9666   // C++11 [class.copy]p18:
9667   //   The [definition of an implicitly declared copy assignment operator] is
9668   //   deprecated if the class has a user-declared copy constructor or a
9669   //   user-declared destructor.
9670   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9671     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9672 
9673   CopyAssignOperator->markUsed(Context);
9674 
9675   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
9676   DiagnosticErrorTrap Trap(Diags);
9677 
9678   // C++0x [class.copy]p30:
9679   //   The implicitly-defined or explicitly-defaulted copy assignment operator
9680   //   for a non-union class X performs memberwise copy assignment of its
9681   //   subobjects. The direct base classes of X are assigned first, in the
9682   //   order of their declaration in the base-specifier-list, and then the
9683   //   immediate non-static data members of X are assigned, in the order in
9684   //   which they were declared in the class definition.
9685 
9686   // The statements that form the synthesized function body.
9687   SmallVector<Stmt*, 8> Statements;
9688 
9689   // The parameter for the "other" object, which we are copying from.
9690   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9691   Qualifiers OtherQuals = Other->getType().getQualifiers();
9692   QualType OtherRefType = Other->getType();
9693   if (const LValueReferenceType *OtherRef
9694                                 = OtherRefType->getAs<LValueReferenceType>()) {
9695     OtherRefType = OtherRef->getPointeeType();
9696     OtherQuals = OtherRefType.getQualifiers();
9697   }
9698 
9699   // Our location for everything implicitly-generated.
9700   SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
9701                            ? CopyAssignOperator->getLocEnd()
9702                            : CopyAssignOperator->getLocation();
9703 
9704   // Builds a DeclRefExpr for the "other" object.
9705   RefBuilder OtherRef(Other, OtherRefType);
9706 
9707   // Builds the "this" pointer.
9708   ThisBuilder This;
9709 
9710   // Assign base classes.
9711   bool Invalid = false;
9712   for (auto &Base : ClassDecl->bases()) {
9713     // Form the assignment:
9714     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
9715     QualType BaseType = Base.getType().getUnqualifiedType();
9716     if (!BaseType->isRecordType()) {
9717       Invalid = true;
9718       continue;
9719     }
9720 
9721     CXXCastPath BasePath;
9722     BasePath.push_back(&Base);
9723 
9724     // Construct the "from" expression, which is an implicit cast to the
9725     // appropriately-qualified base type.
9726     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9727                      VK_LValue, BasePath);
9728 
9729     // Dereference "this".
9730     DerefBuilder DerefThis(This);
9731     CastBuilder To(DerefThis,
9732                    Context.getCVRQualifiedType(
9733                        BaseType, CopyAssignOperator->getTypeQualifiers()),
9734                    VK_LValue, BasePath);
9735 
9736     // Build the copy.
9737     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
9738                                             To, From,
9739                                             /*CopyingBaseSubobject=*/true,
9740                                             /*Copying=*/true);
9741     if (Copy.isInvalid()) {
9742       Diag(CurrentLocation, diag::note_member_synthesized_at)
9743         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9744       CopyAssignOperator->setInvalidDecl();
9745       return;
9746     }
9747 
9748     // Success! Record the copy.
9749     Statements.push_back(Copy.getAs<Expr>());
9750   }
9751 
9752   // Assign non-static members.
9753   for (auto *Field : ClassDecl->fields()) {
9754     if (Field->isUnnamedBitfield())
9755       continue;
9756 
9757     if (Field->isInvalidDecl()) {
9758       Invalid = true;
9759       continue;
9760     }
9761 
9762     // Check for members of reference type; we can't copy those.
9763     if (Field->getType()->isReferenceType()) {
9764       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9765         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9766       Diag(Field->getLocation(), diag::note_declared_at);
9767       Diag(CurrentLocation, diag::note_member_synthesized_at)
9768         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9769       Invalid = true;
9770       continue;
9771     }
9772 
9773     // Check for members of const-qualified, non-class type.
9774     QualType BaseType = Context.getBaseElementType(Field->getType());
9775     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9776       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9777         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9778       Diag(Field->getLocation(), diag::note_declared_at);
9779       Diag(CurrentLocation, diag::note_member_synthesized_at)
9780         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9781       Invalid = true;
9782       continue;
9783     }
9784 
9785     // Suppress assigning zero-width bitfields.
9786     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9787       continue;
9788 
9789     QualType FieldType = Field->getType().getNonReferenceType();
9790     if (FieldType->isIncompleteArrayType()) {
9791       assert(ClassDecl->hasFlexibleArrayMember() &&
9792              "Incomplete array type is not valid");
9793       continue;
9794     }
9795 
9796     // Build references to the field in the object we're copying from and to.
9797     CXXScopeSpec SS; // Intentionally empty
9798     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9799                               LookupMemberName);
9800     MemberLookup.addDecl(Field);
9801     MemberLookup.resolveKind();
9802 
9803     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9804 
9805     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
9806 
9807     // Build the copy of this field.
9808     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
9809                                             To, From,
9810                                             /*CopyingBaseSubobject=*/false,
9811                                             /*Copying=*/true);
9812     if (Copy.isInvalid()) {
9813       Diag(CurrentLocation, diag::note_member_synthesized_at)
9814         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9815       CopyAssignOperator->setInvalidDecl();
9816       return;
9817     }
9818 
9819     // Success! Record the copy.
9820     Statements.push_back(Copy.getAs<Stmt>());
9821   }
9822 
9823   if (!Invalid) {
9824     // Add a "return *this;"
9825     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
9826 
9827     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
9828     if (Return.isInvalid())
9829       Invalid = true;
9830     else {
9831       Statements.push_back(Return.getAs<Stmt>());
9832 
9833       if (Trap.hasErrorOccurred()) {
9834         Diag(CurrentLocation, diag::note_member_synthesized_at)
9835           << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9836         Invalid = true;
9837       }
9838     }
9839   }
9840 
9841   if (Invalid) {
9842     CopyAssignOperator->setInvalidDecl();
9843     return;
9844   }
9845 
9846   StmtResult Body;
9847   {
9848     CompoundScopeRAII CompoundScope(*this);
9849     Body = ActOnCompoundStmt(Loc, Loc, Statements,
9850                              /*isStmtExpr=*/false);
9851     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9852   }
9853   CopyAssignOperator->setBody(Body.getAs<Stmt>());
9854 
9855   if (ASTMutationListener *L = getASTMutationListener()) {
9856     L->CompletedImplicitDefinition(CopyAssignOperator);
9857   }
9858 }
9859 
9860 Sema::ImplicitExceptionSpecification
9861 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9862   CXXRecordDecl *ClassDecl = MD->getParent();
9863 
9864   ImplicitExceptionSpecification ExceptSpec(*this);
9865   if (ClassDecl->isInvalidDecl())
9866     return ExceptSpec;
9867 
9868   // C++0x [except.spec]p14:
9869   //   An implicitly declared special member function (Clause 12) shall have an
9870   //   exception-specification. [...]
9871 
9872   // It is unspecified whether or not an implicit move assignment operator
9873   // attempts to deduplicate calls to assignment operators of virtual bases are
9874   // made. As such, this exception specification is effectively unspecified.
9875   // Based on a similar decision made for constness in C++0x, we're erring on
9876   // the side of assuming such calls to be made regardless of whether they
9877   // actually happen.
9878   // Note that a move constructor is not implicitly declared when there are
9879   // virtual bases, but it can still be user-declared and explicitly defaulted.
9880   for (const auto &Base : ClassDecl->bases()) {
9881     if (Base.isVirtual())
9882       continue;
9883 
9884     CXXRecordDecl *BaseClassDecl
9885       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9886     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
9887                                                            0, false, 0))
9888       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
9889   }
9890 
9891   for (const auto &Base : ClassDecl->vbases()) {
9892     CXXRecordDecl *BaseClassDecl
9893       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9894     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
9895                                                            0, false, 0))
9896       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
9897   }
9898 
9899   for (const auto *Field : ClassDecl->fields()) {
9900     QualType FieldType = Context.getBaseElementType(Field->getType());
9901     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9902       if (CXXMethodDecl *MoveAssign =
9903               LookupMovingAssignment(FieldClassDecl,
9904                                      FieldType.getCVRQualifiers(),
9905                                      false, 0))
9906         ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
9907     }
9908   }
9909 
9910   return ExceptSpec;
9911 }
9912 
9913 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
9914   assert(ClassDecl->needsImplicitMoveAssignment());
9915 
9916   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9917   if (DSM.isAlreadyBeingDeclared())
9918     return nullptr;
9919 
9920   // Note: The following rules are largely analoguous to the move
9921   // constructor rules.
9922 
9923   QualType ArgType = Context.getTypeDeclType(ClassDecl);
9924   QualType RetType = Context.getLValueReferenceType(ArgType);
9925   ArgType = Context.getRValueReferenceType(ArgType);
9926 
9927   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9928                                                      CXXMoveAssignment,
9929                                                      false);
9930 
9931   //   An implicitly-declared move assignment operator is an inline public
9932   //   member of its class.
9933   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9934   SourceLocation ClassLoc = ClassDecl->getLocation();
9935   DeclarationNameInfo NameInfo(Name, ClassLoc);
9936   CXXMethodDecl *MoveAssignment =
9937       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9938                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
9939                             /*isInline=*/true, Constexpr, SourceLocation());
9940   MoveAssignment->setAccess(AS_public);
9941   MoveAssignment->setDefaulted();
9942   MoveAssignment->setImplicit();
9943 
9944   // Build an exception specification pointing back at this member.
9945   FunctionProtoType::ExtProtoInfo EPI =
9946       getImplicitMethodEPI(*this, MoveAssignment);
9947   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
9948 
9949   // Add the parameter to the operator.
9950   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9951                                                ClassLoc, ClassLoc,
9952                                                /*Id=*/nullptr, ArgType,
9953                                                /*TInfo=*/nullptr, SC_None,
9954                                                nullptr);
9955   MoveAssignment->setParams(FromParam);
9956 
9957   AddOverriddenMethods(ClassDecl, MoveAssignment);
9958 
9959   MoveAssignment->setTrivial(
9960     ClassDecl->needsOverloadResolutionForMoveAssignment()
9961       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9962       : ClassDecl->hasTrivialMoveAssignment());
9963 
9964   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
9965     ClassDecl->setImplicitMoveAssignmentIsDeleted();
9966     SetDeclDeleted(MoveAssignment, ClassLoc);
9967   }
9968 
9969   // Note that we have added this copy-assignment operator.
9970   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9971 
9972   if (Scope *S = getScopeForContext(ClassDecl))
9973     PushOnScopeChains(MoveAssignment, S, false);
9974   ClassDecl->addDecl(MoveAssignment);
9975 
9976   return MoveAssignment;
9977 }
9978 
9979 /// Check if we're implicitly defining a move assignment operator for a class
9980 /// with virtual bases. Such a move assignment might move-assign the virtual
9981 /// base multiple times.
9982 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
9983                                                SourceLocation CurrentLocation) {
9984   assert(!Class->isDependentContext() && "should not define dependent move");
9985 
9986   // Only a virtual base could get implicitly move-assigned multiple times.
9987   // Only a non-trivial move assignment can observe this. We only want to
9988   // diagnose if we implicitly define an assignment operator that assigns
9989   // two base classes, both of which move-assign the same virtual base.
9990   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
9991       Class->getNumBases() < 2)
9992     return;
9993 
9994   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
9995   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
9996   VBaseMap VBases;
9997 
9998   for (auto &BI : Class->bases()) {
9999     Worklist.push_back(&BI);
10000     while (!Worklist.empty()) {
10001       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
10002       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
10003 
10004       // If the base has no non-trivial move assignment operators,
10005       // we don't care about moves from it.
10006       if (!Base->hasNonTrivialMoveAssignment())
10007         continue;
10008 
10009       // If there's nothing virtual here, skip it.
10010       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
10011         continue;
10012 
10013       // If we're not actually going to call a move assignment for this base,
10014       // or the selected move assignment is trivial, skip it.
10015       Sema::SpecialMemberOverloadResult *SMOR =
10016         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
10017                               /*ConstArg*/false, /*VolatileArg*/false,
10018                               /*RValueThis*/true, /*ConstThis*/false,
10019                               /*VolatileThis*/false);
10020       if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
10021           !SMOR->getMethod()->isMoveAssignmentOperator())
10022         continue;
10023 
10024       if (BaseSpec->isVirtual()) {
10025         // We're going to move-assign this virtual base, and its move
10026         // assignment operator is not trivial. If this can happen for
10027         // multiple distinct direct bases of Class, diagnose it. (If it
10028         // only happens in one base, we'll diagnose it when synthesizing
10029         // that base class's move assignment operator.)
10030         CXXBaseSpecifier *&Existing =
10031             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
10032                 .first->second;
10033         if (Existing && Existing != &BI) {
10034           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
10035             << Class << Base;
10036           S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
10037             << (Base->getCanonicalDecl() ==
10038                 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10039             << Base << Existing->getType() << Existing->getSourceRange();
10040           S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
10041             << (Base->getCanonicalDecl() ==
10042                 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10043             << Base << BI.getType() << BaseSpec->getSourceRange();
10044 
10045           // Only diagnose each vbase once.
10046           Existing = nullptr;
10047         }
10048       } else {
10049         // Only walk over bases that have defaulted move assignment operators.
10050         // We assume that any user-provided move assignment operator handles
10051         // the multiple-moves-of-vbase case itself somehow.
10052         if (!SMOR->getMethod()->isDefaulted())
10053           continue;
10054 
10055         // We're going to move the base classes of Base. Add them to the list.
10056         for (auto &BI : Base->bases())
10057           Worklist.push_back(&BI);
10058       }
10059     }
10060   }
10061 }
10062 
10063 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
10064                                         CXXMethodDecl *MoveAssignOperator) {
10065   assert((MoveAssignOperator->isDefaulted() &&
10066           MoveAssignOperator->isOverloadedOperator() &&
10067           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
10068           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
10069           !MoveAssignOperator->isDeleted()) &&
10070          "DefineImplicitMoveAssignment called for wrong function");
10071 
10072   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
10073 
10074   if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
10075     MoveAssignOperator->setInvalidDecl();
10076     return;
10077   }
10078 
10079   MoveAssignOperator->markUsed(Context);
10080 
10081   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
10082   DiagnosticErrorTrap Trap(Diags);
10083 
10084   // C++0x [class.copy]p28:
10085   //   The implicitly-defined or move assignment operator for a non-union class
10086   //   X performs memberwise move assignment of its subobjects. The direct base
10087   //   classes of X are assigned first, in the order of their declaration in the
10088   //   base-specifier-list, and then the immediate non-static data members of X
10089   //   are assigned, in the order in which they were declared in the class
10090   //   definition.
10091 
10092   // Issue a warning if our implicit move assignment operator will move
10093   // from a virtual base more than once.
10094   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
10095 
10096   // The statements that form the synthesized function body.
10097   SmallVector<Stmt*, 8> Statements;
10098 
10099   // The parameter for the "other" object, which we are move from.
10100   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
10101   QualType OtherRefType = Other->getType()->
10102       getAs<RValueReferenceType>()->getPointeeType();
10103   assert(!OtherRefType.getQualifiers() &&
10104          "Bad argument type of defaulted move assignment");
10105 
10106   // Our location for everything implicitly-generated.
10107   SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
10108                            ? MoveAssignOperator->getLocEnd()
10109                            : MoveAssignOperator->getLocation();
10110 
10111   // Builds a reference to the "other" object.
10112   RefBuilder OtherRef(Other, OtherRefType);
10113   // Cast to rvalue.
10114   MoveCastBuilder MoveOther(OtherRef);
10115 
10116   // Builds the "this" pointer.
10117   ThisBuilder This;
10118 
10119   // Assign base classes.
10120   bool Invalid = false;
10121   for (auto &Base : ClassDecl->bases()) {
10122     // C++11 [class.copy]p28:
10123     //   It is unspecified whether subobjects representing virtual base classes
10124     //   are assigned more than once by the implicitly-defined copy assignment
10125     //   operator.
10126     // FIXME: Do not assign to a vbase that will be assigned by some other base
10127     // class. For a move-assignment, this can result in the vbase being moved
10128     // multiple times.
10129 
10130     // Form the assignment:
10131     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
10132     QualType BaseType = Base.getType().getUnqualifiedType();
10133     if (!BaseType->isRecordType()) {
10134       Invalid = true;
10135       continue;
10136     }
10137 
10138     CXXCastPath BasePath;
10139     BasePath.push_back(&Base);
10140 
10141     // Construct the "from" expression, which is an implicit cast to the
10142     // appropriately-qualified base type.
10143     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
10144 
10145     // Dereference "this".
10146     DerefBuilder DerefThis(This);
10147 
10148     // Implicitly cast "this" to the appropriately-qualified base type.
10149     CastBuilder To(DerefThis,
10150                    Context.getCVRQualifiedType(
10151                        BaseType, MoveAssignOperator->getTypeQualifiers()),
10152                    VK_LValue, BasePath);
10153 
10154     // Build the move.
10155     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
10156                                             To, From,
10157                                             /*CopyingBaseSubobject=*/true,
10158                                             /*Copying=*/false);
10159     if (Move.isInvalid()) {
10160       Diag(CurrentLocation, diag::note_member_synthesized_at)
10161         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10162       MoveAssignOperator->setInvalidDecl();
10163       return;
10164     }
10165 
10166     // Success! Record the move.
10167     Statements.push_back(Move.getAs<Expr>());
10168   }
10169 
10170   // Assign non-static members.
10171   for (auto *Field : ClassDecl->fields()) {
10172     if (Field->isUnnamedBitfield())
10173       continue;
10174 
10175     if (Field->isInvalidDecl()) {
10176       Invalid = true;
10177       continue;
10178     }
10179 
10180     // Check for members of reference type; we can't move those.
10181     if (Field->getType()->isReferenceType()) {
10182       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10183         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10184       Diag(Field->getLocation(), diag::note_declared_at);
10185       Diag(CurrentLocation, diag::note_member_synthesized_at)
10186         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10187       Invalid = true;
10188       continue;
10189     }
10190 
10191     // Check for members of const-qualified, non-class type.
10192     QualType BaseType = Context.getBaseElementType(Field->getType());
10193     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10194       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10195         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10196       Diag(Field->getLocation(), diag::note_declared_at);
10197       Diag(CurrentLocation, diag::note_member_synthesized_at)
10198         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10199       Invalid = true;
10200       continue;
10201     }
10202 
10203     // Suppress assigning zero-width bitfields.
10204     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10205       continue;
10206 
10207     QualType FieldType = Field->getType().getNonReferenceType();
10208     if (FieldType->isIncompleteArrayType()) {
10209       assert(ClassDecl->hasFlexibleArrayMember() &&
10210              "Incomplete array type is not valid");
10211       continue;
10212     }
10213 
10214     // Build references to the field in the object we're copying from and to.
10215     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10216                               LookupMemberName);
10217     MemberLookup.addDecl(Field);
10218     MemberLookup.resolveKind();
10219     MemberBuilder From(MoveOther, OtherRefType,
10220                        /*IsArrow=*/false, MemberLookup);
10221     MemberBuilder To(This, getCurrentThisType(),
10222                      /*IsArrow=*/true, MemberLookup);
10223 
10224     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
10225         "Member reference with rvalue base must be rvalue except for reference "
10226         "members, which aren't allowed for move assignment.");
10227 
10228     // Build the move of this field.
10229     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
10230                                             To, From,
10231                                             /*CopyingBaseSubobject=*/false,
10232                                             /*Copying=*/false);
10233     if (Move.isInvalid()) {
10234       Diag(CurrentLocation, diag::note_member_synthesized_at)
10235         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10236       MoveAssignOperator->setInvalidDecl();
10237       return;
10238     }
10239 
10240     // Success! Record the copy.
10241     Statements.push_back(Move.getAs<Stmt>());
10242   }
10243 
10244   if (!Invalid) {
10245     // Add a "return *this;"
10246     ExprResult ThisObj =
10247         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10248 
10249     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
10250     if (Return.isInvalid())
10251       Invalid = true;
10252     else {
10253       Statements.push_back(Return.getAs<Stmt>());
10254 
10255       if (Trap.hasErrorOccurred()) {
10256         Diag(CurrentLocation, diag::note_member_synthesized_at)
10257           << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10258         Invalid = true;
10259       }
10260     }
10261   }
10262 
10263   if (Invalid) {
10264     MoveAssignOperator->setInvalidDecl();
10265     return;
10266   }
10267 
10268   StmtResult Body;
10269   {
10270     CompoundScopeRAII CompoundScope(*this);
10271     Body = ActOnCompoundStmt(Loc, Loc, Statements,
10272                              /*isStmtExpr=*/false);
10273     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10274   }
10275   MoveAssignOperator->setBody(Body.getAs<Stmt>());
10276 
10277   if (ASTMutationListener *L = getASTMutationListener()) {
10278     L->CompletedImplicitDefinition(MoveAssignOperator);
10279   }
10280 }
10281 
10282 Sema::ImplicitExceptionSpecification
10283 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10284   CXXRecordDecl *ClassDecl = MD->getParent();
10285 
10286   ImplicitExceptionSpecification ExceptSpec(*this);
10287   if (ClassDecl->isInvalidDecl())
10288     return ExceptSpec;
10289 
10290   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
10291   assert(T->getNumParams() >= 1 && "not a copy ctor");
10292   unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
10293 
10294   // C++ [except.spec]p14:
10295   //   An implicitly declared special member function (Clause 12) shall have an
10296   //   exception-specification. [...]
10297   for (const auto &Base : ClassDecl->bases()) {
10298     // Virtual bases are handled below.
10299     if (Base.isVirtual())
10300       continue;
10301 
10302     CXXRecordDecl *BaseClassDecl
10303       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10304     if (CXXConstructorDecl *CopyConstructor =
10305           LookupCopyingConstructor(BaseClassDecl, Quals))
10306       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10307   }
10308   for (const auto &Base : ClassDecl->vbases()) {
10309     CXXRecordDecl *BaseClassDecl
10310       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10311     if (CXXConstructorDecl *CopyConstructor =
10312           LookupCopyingConstructor(BaseClassDecl, Quals))
10313       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10314   }
10315   for (const auto *Field : ClassDecl->fields()) {
10316     QualType FieldType = Context.getBaseElementType(Field->getType());
10317     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10318       if (CXXConstructorDecl *CopyConstructor =
10319               LookupCopyingConstructor(FieldClassDecl,
10320                                        Quals | FieldType.getCVRQualifiers()))
10321       ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
10322     }
10323   }
10324 
10325   return ExceptSpec;
10326 }
10327 
10328 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10329                                                     CXXRecordDecl *ClassDecl) {
10330   // C++ [class.copy]p4:
10331   //   If the class definition does not explicitly declare a copy
10332   //   constructor, one is declared implicitly.
10333   assert(ClassDecl->needsImplicitCopyConstructor());
10334 
10335   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10336   if (DSM.isAlreadyBeingDeclared())
10337     return nullptr;
10338 
10339   QualType ClassType = Context.getTypeDeclType(ClassDecl);
10340   QualType ArgType = ClassType;
10341   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
10342   if (Const)
10343     ArgType = ArgType.withConst();
10344   ArgType = Context.getLValueReferenceType(ArgType);
10345 
10346   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10347                                                      CXXCopyConstructor,
10348                                                      Const);
10349 
10350   DeclarationName Name
10351     = Context.DeclarationNames.getCXXConstructorName(
10352                                            Context.getCanonicalType(ClassType));
10353   SourceLocation ClassLoc = ClassDecl->getLocation();
10354   DeclarationNameInfo NameInfo(Name, ClassLoc);
10355 
10356   //   An implicitly-declared copy constructor is an inline public
10357   //   member of its class.
10358   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
10359       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
10360       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10361       Constexpr);
10362   CopyConstructor->setAccess(AS_public);
10363   CopyConstructor->setDefaulted();
10364 
10365   // Build an exception specification pointing back at this member.
10366   FunctionProtoType::ExtProtoInfo EPI =
10367       getImplicitMethodEPI(*this, CopyConstructor);
10368   CopyConstructor->setType(
10369       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10370 
10371   // Add the parameter to the constructor.
10372   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
10373                                                ClassLoc, ClassLoc,
10374                                                /*IdentifierInfo=*/nullptr,
10375                                                ArgType, /*TInfo=*/nullptr,
10376                                                SC_None, nullptr);
10377   CopyConstructor->setParams(FromParam);
10378 
10379   CopyConstructor->setTrivial(
10380     ClassDecl->needsOverloadResolutionForCopyConstructor()
10381       ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10382       : ClassDecl->hasTrivialCopyConstructor());
10383 
10384   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
10385     SetDeclDeleted(CopyConstructor, ClassLoc);
10386 
10387   // Note that we have declared this constructor.
10388   ++ASTContext::NumImplicitCopyConstructorsDeclared;
10389 
10390   if (Scope *S = getScopeForContext(ClassDecl))
10391     PushOnScopeChains(CopyConstructor, S, false);
10392   ClassDecl->addDecl(CopyConstructor);
10393 
10394   return CopyConstructor;
10395 }
10396 
10397 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
10398                                    CXXConstructorDecl *CopyConstructor) {
10399   assert((CopyConstructor->isDefaulted() &&
10400           CopyConstructor->isCopyConstructor() &&
10401           !CopyConstructor->doesThisDeclarationHaveABody() &&
10402           !CopyConstructor->isDeleted()) &&
10403          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
10404 
10405   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
10406   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
10407 
10408   // C++11 [class.copy]p7:
10409   //   The [definition of an implicitly declared copy constructor] is
10410   //   deprecated if the class has a user-declared copy assignment operator
10411   //   or a user-declared destructor.
10412   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10413     diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10414 
10415   SynthesizedFunctionScope Scope(*this, CopyConstructor);
10416   DiagnosticErrorTrap Trap(Diags);
10417 
10418   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
10419       Trap.hasErrorOccurred()) {
10420     Diag(CurrentLocation, diag::note_member_synthesized_at)
10421       << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
10422     CopyConstructor->setInvalidDecl();
10423   }  else {
10424     SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
10425                              ? CopyConstructor->getLocEnd()
10426                              : CopyConstructor->getLocation();
10427     Sema::CompoundScopeRAII CompoundScope(*this);
10428     CopyConstructor->setBody(
10429         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
10430   }
10431 
10432   CopyConstructor->markUsed(Context);
10433   MarkVTableUsed(CurrentLocation, ClassDecl);
10434 
10435   if (ASTMutationListener *L = getASTMutationListener()) {
10436     L->CompletedImplicitDefinition(CopyConstructor);
10437   }
10438 }
10439 
10440 Sema::ImplicitExceptionSpecification
10441 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10442   CXXRecordDecl *ClassDecl = MD->getParent();
10443 
10444   // C++ [except.spec]p14:
10445   //   An implicitly declared special member function (Clause 12) shall have an
10446   //   exception-specification. [...]
10447   ImplicitExceptionSpecification ExceptSpec(*this);
10448   if (ClassDecl->isInvalidDecl())
10449     return ExceptSpec;
10450 
10451   // Direct base-class constructors.
10452   for (const auto &B : ClassDecl->bases()) {
10453     if (B.isVirtual()) // Handled below.
10454       continue;
10455 
10456     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
10457       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10458       CXXConstructorDecl *Constructor =
10459           LookupMovingConstructor(BaseClassDecl, 0);
10460       // If this is a deleted function, add it anyway. This might be conformant
10461       // with the standard. This might not. I'm not sure. It might not matter.
10462       if (Constructor)
10463         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
10464     }
10465   }
10466 
10467   // Virtual base-class constructors.
10468   for (const auto &B : ClassDecl->vbases()) {
10469     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
10470       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10471       CXXConstructorDecl *Constructor =
10472           LookupMovingConstructor(BaseClassDecl, 0);
10473       // If this is a deleted function, add it anyway. This might be conformant
10474       // with the standard. This might not. I'm not sure. It might not matter.
10475       if (Constructor)
10476         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
10477     }
10478   }
10479 
10480   // Field constructors.
10481   for (const auto *F : ClassDecl->fields()) {
10482     QualType FieldType = Context.getBaseElementType(F->getType());
10483     if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10484       CXXConstructorDecl *Constructor =
10485           LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
10486       // If this is a deleted function, add it anyway. This might be conformant
10487       // with the standard. This might not. I'm not sure. It might not matter.
10488       // In particular, the problem is that this function never gets called. It
10489       // might just be ill-formed because this function attempts to refer to
10490       // a deleted function here.
10491       if (Constructor)
10492         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
10493     }
10494   }
10495 
10496   return ExceptSpec;
10497 }
10498 
10499 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10500                                                     CXXRecordDecl *ClassDecl) {
10501   assert(ClassDecl->needsImplicitMoveConstructor());
10502 
10503   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10504   if (DSM.isAlreadyBeingDeclared())
10505     return nullptr;
10506 
10507   QualType ClassType = Context.getTypeDeclType(ClassDecl);
10508   QualType ArgType = Context.getRValueReferenceType(ClassType);
10509 
10510   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10511                                                      CXXMoveConstructor,
10512                                                      false);
10513 
10514   DeclarationName Name
10515     = Context.DeclarationNames.getCXXConstructorName(
10516                                            Context.getCanonicalType(ClassType));
10517   SourceLocation ClassLoc = ClassDecl->getLocation();
10518   DeclarationNameInfo NameInfo(Name, ClassLoc);
10519 
10520   // C++11 [class.copy]p11:
10521   //   An implicitly-declared copy/move constructor is an inline public
10522   //   member of its class.
10523   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
10524       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
10525       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10526       Constexpr);
10527   MoveConstructor->setAccess(AS_public);
10528   MoveConstructor->setDefaulted();
10529 
10530   // Build an exception specification pointing back at this member.
10531   FunctionProtoType::ExtProtoInfo EPI =
10532       getImplicitMethodEPI(*this, MoveConstructor);
10533   MoveConstructor->setType(
10534       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10535 
10536   // Add the parameter to the constructor.
10537   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10538                                                ClassLoc, ClassLoc,
10539                                                /*IdentifierInfo=*/nullptr,
10540                                                ArgType, /*TInfo=*/nullptr,
10541                                                SC_None, nullptr);
10542   MoveConstructor->setParams(FromParam);
10543 
10544   MoveConstructor->setTrivial(
10545     ClassDecl->needsOverloadResolutionForMoveConstructor()
10546       ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10547       : ClassDecl->hasTrivialMoveConstructor());
10548 
10549   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
10550     ClassDecl->setImplicitMoveConstructorIsDeleted();
10551     SetDeclDeleted(MoveConstructor, ClassLoc);
10552   }
10553 
10554   // Note that we have declared this constructor.
10555   ++ASTContext::NumImplicitMoveConstructorsDeclared;
10556 
10557   if (Scope *S = getScopeForContext(ClassDecl))
10558     PushOnScopeChains(MoveConstructor, S, false);
10559   ClassDecl->addDecl(MoveConstructor);
10560 
10561   return MoveConstructor;
10562 }
10563 
10564 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10565                                    CXXConstructorDecl *MoveConstructor) {
10566   assert((MoveConstructor->isDefaulted() &&
10567           MoveConstructor->isMoveConstructor() &&
10568           !MoveConstructor->doesThisDeclarationHaveABody() &&
10569           !MoveConstructor->isDeleted()) &&
10570          "DefineImplicitMoveConstructor - call it for implicit move ctor");
10571 
10572   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10573   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10574 
10575   SynthesizedFunctionScope Scope(*this, MoveConstructor);
10576   DiagnosticErrorTrap Trap(Diags);
10577 
10578   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
10579       Trap.hasErrorOccurred()) {
10580     Diag(CurrentLocation, diag::note_member_synthesized_at)
10581       << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10582     MoveConstructor->setInvalidDecl();
10583   }  else {
10584     SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
10585                              ? MoveConstructor->getLocEnd()
10586                              : MoveConstructor->getLocation();
10587     Sema::CompoundScopeRAII CompoundScope(*this);
10588     MoveConstructor->setBody(ActOnCompoundStmt(
10589         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
10590   }
10591 
10592   MoveConstructor->markUsed(Context);
10593   MarkVTableUsed(CurrentLocation, ClassDecl);
10594 
10595   if (ASTMutationListener *L = getASTMutationListener()) {
10596     L->CompletedImplicitDefinition(MoveConstructor);
10597   }
10598 }
10599 
10600 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
10601   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
10602 }
10603 
10604 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
10605                             SourceLocation CurrentLocation,
10606                             CXXConversionDecl *Conv) {
10607   CXXRecordDecl *Lambda = Conv->getParent();
10608   CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10609   // If we are defining a specialization of a conversion to function-ptr
10610   // cache the deduced template arguments for this specialization
10611   // so that we can use them to retrieve the corresponding call-operator
10612   // and static-invoker.
10613   const TemplateArgumentList *DeducedTemplateArgs = nullptr;
10614 
10615   // Retrieve the corresponding call-operator specialization.
10616   if (Lambda->isGenericLambda()) {
10617     assert(Conv->isFunctionTemplateSpecialization());
10618     FunctionTemplateDecl *CallOpTemplate =
10619         CallOp->getDescribedFunctionTemplate();
10620     DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
10621     void *InsertPos = nullptr;
10622     FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
10623                                                 DeducedTemplateArgs->asArray(),
10624                                                 InsertPos);
10625     assert(CallOpSpec &&
10626           "Conversion operator must have a corresponding call operator");
10627     CallOp = cast<CXXMethodDecl>(CallOpSpec);
10628   }
10629   // Mark the call operator referenced (and add to pending instantiations
10630   // if necessary).
10631   // For both the conversion and static-invoker template specializations
10632   // we construct their body's in this function, so no need to add them
10633   // to the PendingInstantiations.
10634   MarkFunctionReferenced(CurrentLocation, CallOp);
10635 
10636   SynthesizedFunctionScope Scope(*this, Conv);
10637   DiagnosticErrorTrap Trap(Diags);
10638 
10639   // Retrieve the static invoker...
10640   CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10641   // ... and get the corresponding specialization for a generic lambda.
10642   if (Lambda->isGenericLambda()) {
10643     assert(DeducedTemplateArgs &&
10644       "Must have deduced template arguments from Conversion Operator");
10645     FunctionTemplateDecl *InvokeTemplate =
10646                           Invoker->getDescribedFunctionTemplate();
10647     void *InsertPos = nullptr;
10648     FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
10649                                                 DeducedTemplateArgs->asArray(),
10650                                                 InsertPos);
10651     assert(InvokeSpec &&
10652       "Must have a corresponding static invoker specialization");
10653     Invoker = cast<CXXMethodDecl>(InvokeSpec);
10654   }
10655   // Construct the body of the conversion function { return __invoke; }.
10656   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
10657                                         VK_LValue, Conv->getLocation()).get();
10658    assert(FunctionRef && "Can't refer to __invoke function?");
10659    Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
10660    Conv->setBody(new (Context) CompoundStmt(Context, Return,
10661                                             Conv->getLocation(),
10662                                             Conv->getLocation()));
10663 
10664   Conv->markUsed(Context);
10665   Conv->setReferenced();
10666 
10667   // Fill in the __invoke function with a dummy implementation. IR generation
10668   // will fill in the actual details.
10669   Invoker->markUsed(Context);
10670   Invoker->setReferenced();
10671   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10672 
10673   if (ASTMutationListener *L = getASTMutationListener()) {
10674     L->CompletedImplicitDefinition(Conv);
10675     L->CompletedImplicitDefinition(Invoker);
10676    }
10677 }
10678 
10679 
10680 
10681 void Sema::DefineImplicitLambdaToBlockPointerConversion(
10682        SourceLocation CurrentLocation,
10683        CXXConversionDecl *Conv)
10684 {
10685   assert(!Conv->getParent()->isGenericLambda());
10686 
10687   Conv->markUsed(Context);
10688 
10689   SynthesizedFunctionScope Scope(*this, Conv);
10690   DiagnosticErrorTrap Trap(Diags);
10691 
10692   // Copy-initialize the lambda object as needed to capture it.
10693   Expr *This = ActOnCXXThis(CurrentLocation).get();
10694   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
10695 
10696   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10697                                                         Conv->getLocation(),
10698                                                         Conv, DerefThis);
10699 
10700   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10701   // behavior.  Note that only the general conversion function does this
10702   // (since it's unusable otherwise); in the case where we inline the
10703   // block literal, it has block literal lifetime semantics.
10704   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
10705     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10706                                           CK_CopyAndAutoreleaseBlockObject,
10707                                           BuildBlock.get(), nullptr, VK_RValue);
10708 
10709   if (BuildBlock.isInvalid()) {
10710     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10711     Conv->setInvalidDecl();
10712     return;
10713   }
10714 
10715   // Create the return statement that returns the block from the conversion
10716   // function.
10717   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
10718   if (Return.isInvalid()) {
10719     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10720     Conv->setInvalidDecl();
10721     return;
10722   }
10723 
10724   // Set the body of the conversion function.
10725   Stmt *ReturnS = Return.get();
10726   Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
10727                                            Conv->getLocation(),
10728                                            Conv->getLocation()));
10729 
10730   // We're done; notify the mutation listener, if any.
10731   if (ASTMutationListener *L = getASTMutationListener()) {
10732     L->CompletedImplicitDefinition(Conv);
10733   }
10734 }
10735 
10736 /// \brief Determine whether the given list arguments contains exactly one
10737 /// "real" (non-default) argument.
10738 static bool hasOneRealArgument(MultiExprArg Args) {
10739   switch (Args.size()) {
10740   case 0:
10741     return false;
10742 
10743   default:
10744     if (!Args[1]->isDefaultArgument())
10745       return false;
10746 
10747     // fall through
10748   case 1:
10749     return !Args[0]->isDefaultArgument();
10750   }
10751 
10752   return false;
10753 }
10754 
10755 ExprResult
10756 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10757                             CXXConstructorDecl *Constructor,
10758                             MultiExprArg ExprArgs,
10759                             bool HadMultipleCandidates,
10760                             bool IsListInitialization,
10761                             bool IsStdInitListInitialization,
10762                             bool RequiresZeroInit,
10763                             unsigned ConstructKind,
10764                             SourceRange ParenRange) {
10765   bool Elidable = false;
10766 
10767   // C++0x [class.copy]p34:
10768   //   When certain criteria are met, an implementation is allowed to
10769   //   omit the copy/move construction of a class object, even if the
10770   //   copy/move constructor and/or destructor for the object have
10771   //   side effects. [...]
10772   //     - when a temporary class object that has not been bound to a
10773   //       reference (12.2) would be copied/moved to a class object
10774   //       with the same cv-unqualified type, the copy/move operation
10775   //       can be omitted by constructing the temporary object
10776   //       directly into the target of the omitted copy/move
10777   if (ConstructKind == CXXConstructExpr::CK_Complete &&
10778       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
10779     Expr *SubExpr = ExprArgs[0];
10780     Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
10781   }
10782 
10783   return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
10784                                Elidable, ExprArgs, HadMultipleCandidates,
10785                                IsListInitialization,
10786                                IsStdInitListInitialization, RequiresZeroInit,
10787                                ConstructKind, ParenRange);
10788 }
10789 
10790 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
10791 /// including handling of its default argument expressions.
10792 ExprResult
10793 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10794                             CXXConstructorDecl *Constructor, bool Elidable,
10795                             MultiExprArg ExprArgs,
10796                             bool HadMultipleCandidates,
10797                             bool IsListInitialization,
10798                             bool IsStdInitListInitialization,
10799                             bool RequiresZeroInit,
10800                             unsigned ConstructKind,
10801                             SourceRange ParenRange) {
10802   MarkFunctionReferenced(ConstructLoc, Constructor);
10803   return CXXConstructExpr::Create(
10804       Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
10805       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
10806       RequiresZeroInit,
10807       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10808       ParenRange);
10809 }
10810 
10811 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
10812   if (VD->isInvalidDecl()) return;
10813 
10814   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
10815   if (ClassDecl->isInvalidDecl()) return;
10816   if (ClassDecl->hasIrrelevantDestructor()) return;
10817   if (ClassDecl->isDependentContext()) return;
10818 
10819   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10820   MarkFunctionReferenced(VD->getLocation(), Destructor);
10821   CheckDestructorAccess(VD->getLocation(), Destructor,
10822                         PDiag(diag::err_access_dtor_var)
10823                         << VD->getDeclName()
10824                         << VD->getType());
10825   DiagnoseUseOfDecl(Destructor, VD->getLocation());
10826 
10827   if (Destructor->isTrivial()) return;
10828   if (!VD->hasGlobalStorage()) return;
10829 
10830   // Emit warning for non-trivial dtor in global scope (a real global,
10831   // class-static, function-static).
10832   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10833 
10834   // TODO: this should be re-enabled for static locals by !CXAAtExit
10835   if (!VD->isStaticLocal())
10836     Diag(VD->getLocation(), diag::warn_global_destructor);
10837 }
10838 
10839 /// \brief Given a constructor and the set of arguments provided for the
10840 /// constructor, convert the arguments and add any required default arguments
10841 /// to form a proper call to this constructor.
10842 ///
10843 /// \returns true if an error occurred, false otherwise.
10844 bool
10845 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10846                               MultiExprArg ArgsPtr,
10847                               SourceLocation Loc,
10848                               SmallVectorImpl<Expr*> &ConvertedArgs,
10849                               bool AllowExplicit,
10850                               bool IsListInitialization) {
10851   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10852   unsigned NumArgs = ArgsPtr.size();
10853   Expr **Args = ArgsPtr.data();
10854 
10855   const FunctionProtoType *Proto
10856     = Constructor->getType()->getAs<FunctionProtoType>();
10857   assert(Proto && "Constructor without a prototype?");
10858   unsigned NumParams = Proto->getNumParams();
10859 
10860   // If too few arguments are available, we'll fill in the rest with defaults.
10861   if (NumArgs < NumParams)
10862     ConvertedArgs.reserve(NumParams);
10863   else
10864     ConvertedArgs.reserve(NumArgs);
10865 
10866   VariadicCallType CallType =
10867     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
10868   SmallVector<Expr *, 8> AllArgs;
10869   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
10870                                         Proto, 0,
10871                                         llvm::makeArrayRef(Args, NumArgs),
10872                                         AllArgs,
10873                                         CallType, AllowExplicit,
10874                                         IsListInitialization);
10875   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
10876 
10877   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
10878 
10879   CheckConstructorCall(Constructor,
10880                        llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10881                                                         AllArgs.size()),
10882                        Proto, Loc);
10883 
10884   return Invalid;
10885 }
10886 
10887 static inline bool
10888 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10889                                        const FunctionDecl *FnDecl) {
10890   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
10891   if (isa<NamespaceDecl>(DC)) {
10892     return SemaRef.Diag(FnDecl->getLocation(),
10893                         diag::err_operator_new_delete_declared_in_namespace)
10894       << FnDecl->getDeclName();
10895   }
10896 
10897   if (isa<TranslationUnitDecl>(DC) &&
10898       FnDecl->getStorageClass() == SC_Static) {
10899     return SemaRef.Diag(FnDecl->getLocation(),
10900                         diag::err_operator_new_delete_declared_static)
10901       << FnDecl->getDeclName();
10902   }
10903 
10904   return false;
10905 }
10906 
10907 static inline bool
10908 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10909                             CanQualType ExpectedResultType,
10910                             CanQualType ExpectedFirstParamType,
10911                             unsigned DependentParamTypeDiag,
10912                             unsigned InvalidParamTypeDiag) {
10913   QualType ResultType =
10914       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
10915 
10916   // Check that the result type is not dependent.
10917   if (ResultType->isDependentType())
10918     return SemaRef.Diag(FnDecl->getLocation(),
10919                         diag::err_operator_new_delete_dependent_result_type)
10920     << FnDecl->getDeclName() << ExpectedResultType;
10921 
10922   // Check that the result type is what we expect.
10923   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10924     return SemaRef.Diag(FnDecl->getLocation(),
10925                         diag::err_operator_new_delete_invalid_result_type)
10926     << FnDecl->getDeclName() << ExpectedResultType;
10927 
10928   // A function template must have at least 2 parameters.
10929   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10930     return SemaRef.Diag(FnDecl->getLocation(),
10931                       diag::err_operator_new_delete_template_too_few_parameters)
10932         << FnDecl->getDeclName();
10933 
10934   // The function decl must have at least 1 parameter.
10935   if (FnDecl->getNumParams() == 0)
10936     return SemaRef.Diag(FnDecl->getLocation(),
10937                         diag::err_operator_new_delete_too_few_parameters)
10938       << FnDecl->getDeclName();
10939 
10940   // Check the first parameter type is not dependent.
10941   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10942   if (FirstParamType->isDependentType())
10943     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10944       << FnDecl->getDeclName() << ExpectedFirstParamType;
10945 
10946   // Check that the first parameter type is what we expect.
10947   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
10948       ExpectedFirstParamType)
10949     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10950     << FnDecl->getDeclName() << ExpectedFirstParamType;
10951 
10952   return false;
10953 }
10954 
10955 static bool
10956 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
10957   // C++ [basic.stc.dynamic.allocation]p1:
10958   //   A program is ill-formed if an allocation function is declared in a
10959   //   namespace scope other than global scope or declared static in global
10960   //   scope.
10961   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10962     return true;
10963 
10964   CanQualType SizeTy =
10965     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10966 
10967   // C++ [basic.stc.dynamic.allocation]p1:
10968   //  The return type shall be void*. The first parameter shall have type
10969   //  std::size_t.
10970   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10971                                   SizeTy,
10972                                   diag::err_operator_new_dependent_param_type,
10973                                   diag::err_operator_new_param_type))
10974     return true;
10975 
10976   // C++ [basic.stc.dynamic.allocation]p1:
10977   //  The first parameter shall not have an associated default argument.
10978   if (FnDecl->getParamDecl(0)->hasDefaultArg())
10979     return SemaRef.Diag(FnDecl->getLocation(),
10980                         diag::err_operator_new_default_arg)
10981       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10982 
10983   return false;
10984 }
10985 
10986 static bool
10987 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
10988   // C++ [basic.stc.dynamic.deallocation]p1:
10989   //   A program is ill-formed if deallocation functions are declared in a
10990   //   namespace scope other than global scope or declared static in global
10991   //   scope.
10992   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10993     return true;
10994 
10995   // C++ [basic.stc.dynamic.deallocation]p2:
10996   //   Each deallocation function shall return void and its first parameter
10997   //   shall be void*.
10998   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10999                                   SemaRef.Context.VoidPtrTy,
11000                                  diag::err_operator_delete_dependent_param_type,
11001                                  diag::err_operator_delete_param_type))
11002     return true;
11003 
11004   return false;
11005 }
11006 
11007 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
11008 /// of this overloaded operator is well-formed. If so, returns false;
11009 /// otherwise, emits appropriate diagnostics and returns true.
11010 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
11011   assert(FnDecl && FnDecl->isOverloadedOperator() &&
11012          "Expected an overloaded operator declaration");
11013 
11014   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
11015 
11016   // C++ [over.oper]p5:
11017   //   The allocation and deallocation functions, operator new,
11018   //   operator new[], operator delete and operator delete[], are
11019   //   described completely in 3.7.3. The attributes and restrictions
11020   //   found in the rest of this subclause do not apply to them unless
11021   //   explicitly stated in 3.7.3.
11022   if (Op == OO_Delete || Op == OO_Array_Delete)
11023     return CheckOperatorDeleteDeclaration(*this, FnDecl);
11024 
11025   if (Op == OO_New || Op == OO_Array_New)
11026     return CheckOperatorNewDeclaration(*this, FnDecl);
11027 
11028   // C++ [over.oper]p6:
11029   //   An operator function shall either be a non-static member
11030   //   function or be a non-member function and have at least one
11031   //   parameter whose type is a class, a reference to a class, an
11032   //   enumeration, or a reference to an enumeration.
11033   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
11034     if (MethodDecl->isStatic())
11035       return Diag(FnDecl->getLocation(),
11036                   diag::err_operator_overload_static) << FnDecl->getDeclName();
11037   } else {
11038     bool ClassOrEnumParam = false;
11039     for (auto Param : FnDecl->params()) {
11040       QualType ParamType = Param->getType().getNonReferenceType();
11041       if (ParamType->isDependentType() || ParamType->isRecordType() ||
11042           ParamType->isEnumeralType()) {
11043         ClassOrEnumParam = true;
11044         break;
11045       }
11046     }
11047 
11048     if (!ClassOrEnumParam)
11049       return Diag(FnDecl->getLocation(),
11050                   diag::err_operator_overload_needs_class_or_enum)
11051         << FnDecl->getDeclName();
11052   }
11053 
11054   // C++ [over.oper]p8:
11055   //   An operator function cannot have default arguments (8.3.6),
11056   //   except where explicitly stated below.
11057   //
11058   // Only the function-call operator allows default arguments
11059   // (C++ [over.call]p1).
11060   if (Op != OO_Call) {
11061     for (auto Param : FnDecl->params()) {
11062       if (Param->hasDefaultArg())
11063         return Diag(Param->getLocation(),
11064                     diag::err_operator_overload_default_arg)
11065           << FnDecl->getDeclName() << Param->getDefaultArgRange();
11066     }
11067   }
11068 
11069   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
11070     { false, false, false }
11071 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11072     , { Unary, Binary, MemberOnly }
11073 #include "clang/Basic/OperatorKinds.def"
11074   };
11075 
11076   bool CanBeUnaryOperator = OperatorUses[Op][0];
11077   bool CanBeBinaryOperator = OperatorUses[Op][1];
11078   bool MustBeMemberOperator = OperatorUses[Op][2];
11079 
11080   // C++ [over.oper]p8:
11081   //   [...] Operator functions cannot have more or fewer parameters
11082   //   than the number required for the corresponding operator, as
11083   //   described in the rest of this subclause.
11084   unsigned NumParams = FnDecl->getNumParams()
11085                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
11086   if (Op != OO_Call &&
11087       ((NumParams == 1 && !CanBeUnaryOperator) ||
11088        (NumParams == 2 && !CanBeBinaryOperator) ||
11089        (NumParams < 1) || (NumParams > 2))) {
11090     // We have the wrong number of parameters.
11091     unsigned ErrorKind;
11092     if (CanBeUnaryOperator && CanBeBinaryOperator) {
11093       ErrorKind = 2;  // 2 -> unary or binary.
11094     } else if (CanBeUnaryOperator) {
11095       ErrorKind = 0;  // 0 -> unary
11096     } else {
11097       assert(CanBeBinaryOperator &&
11098              "All non-call overloaded operators are unary or binary!");
11099       ErrorKind = 1;  // 1 -> binary
11100     }
11101 
11102     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
11103       << FnDecl->getDeclName() << NumParams << ErrorKind;
11104   }
11105 
11106   // Overloaded operators other than operator() cannot be variadic.
11107   if (Op != OO_Call &&
11108       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
11109     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
11110       << FnDecl->getDeclName();
11111   }
11112 
11113   // Some operators must be non-static member functions.
11114   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
11115     return Diag(FnDecl->getLocation(),
11116                 diag::err_operator_overload_must_be_member)
11117       << FnDecl->getDeclName();
11118   }
11119 
11120   // C++ [over.inc]p1:
11121   //   The user-defined function called operator++ implements the
11122   //   prefix and postfix ++ operator. If this function is a member
11123   //   function with no parameters, or a non-member function with one
11124   //   parameter of class or enumeration type, it defines the prefix
11125   //   increment operator ++ for objects of that type. If the function
11126   //   is a member function with one parameter (which shall be of type
11127   //   int) or a non-member function with two parameters (the second
11128   //   of which shall be of type int), it defines the postfix
11129   //   increment operator ++ for objects of that type.
11130   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11131     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
11132     QualType ParamType = LastParam->getType();
11133 
11134     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11135         !ParamType->isDependentType())
11136       return Diag(LastParam->getLocation(),
11137                   diag::err_operator_overload_post_incdec_must_be_int)
11138         << LastParam->getType() << (Op == OO_MinusMinus);
11139   }
11140 
11141   return false;
11142 }
11143 
11144 /// CheckLiteralOperatorDeclaration - Check whether the declaration
11145 /// of this literal operator function is well-formed. If so, returns
11146 /// false; otherwise, emits appropriate diagnostics and returns true.
11147 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
11148   if (isa<CXXMethodDecl>(FnDecl)) {
11149     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11150       << FnDecl->getDeclName();
11151     return true;
11152   }
11153 
11154   if (FnDecl->isExternC()) {
11155     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11156     return true;
11157   }
11158 
11159   bool Valid = false;
11160 
11161   // This might be the definition of a literal operator template.
11162   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11163   // This might be a specialization of a literal operator template.
11164   if (!TpDecl)
11165     TpDecl = FnDecl->getPrimaryTemplate();
11166 
11167   // template <char...> type operator "" name() and
11168   // template <class T, T...> type operator "" name() are the only valid
11169   // template signatures, and the only valid signatures with no parameters.
11170   if (TpDecl) {
11171     if (FnDecl->param_size() == 0) {
11172       // Must have one or two template parameters
11173       TemplateParameterList *Params = TpDecl->getTemplateParameters();
11174       if (Params->size() == 1) {
11175         NonTypeTemplateParmDecl *PmDecl =
11176           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
11177 
11178         // The template parameter must be a char parameter pack.
11179         if (PmDecl && PmDecl->isTemplateParameterPack() &&
11180             Context.hasSameType(PmDecl->getType(), Context.CharTy))
11181           Valid = true;
11182       } else if (Params->size() == 2) {
11183         TemplateTypeParmDecl *PmType =
11184           dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
11185         NonTypeTemplateParmDecl *PmArgs =
11186           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
11187 
11188         // The second template parameter must be a parameter pack with the
11189         // first template parameter as its type.
11190         if (PmType && PmArgs &&
11191             !PmType->isTemplateParameterPack() &&
11192             PmArgs->isTemplateParameterPack()) {
11193           const TemplateTypeParmType *TArgs =
11194             PmArgs->getType()->getAs<TemplateTypeParmType>();
11195           if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11196               TArgs->getIndex() == PmType->getIndex()) {
11197             Valid = true;
11198             if (ActiveTemplateInstantiations.empty())
11199               Diag(FnDecl->getLocation(),
11200                    diag::ext_string_literal_operator_template);
11201           }
11202         }
11203       }
11204     }
11205   } else if (FnDecl->param_size()) {
11206     // Check the first parameter
11207     FunctionDecl::param_iterator Param = FnDecl->param_begin();
11208 
11209     QualType T = (*Param)->getType().getUnqualifiedType();
11210 
11211     // unsigned long long int, long double, and any character type are allowed
11212     // as the only parameters.
11213     if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
11214         Context.hasSameType(T, Context.LongDoubleTy) ||
11215         Context.hasSameType(T, Context.CharTy) ||
11216         Context.hasSameType(T, Context.WideCharTy) ||
11217         Context.hasSameType(T, Context.Char16Ty) ||
11218         Context.hasSameType(T, Context.Char32Ty)) {
11219       if (++Param == FnDecl->param_end())
11220         Valid = true;
11221       goto FinishedParams;
11222     }
11223 
11224     // Otherwise it must be a pointer to const; let's strip those qualifiers.
11225     const PointerType *PT = T->getAs<PointerType>();
11226     if (!PT)
11227       goto FinishedParams;
11228     T = PT->getPointeeType();
11229     if (!T.isConstQualified() || T.isVolatileQualified())
11230       goto FinishedParams;
11231     T = T.getUnqualifiedType();
11232 
11233     // Move on to the second parameter;
11234     ++Param;
11235 
11236     // If there is no second parameter, the first must be a const char *
11237     if (Param == FnDecl->param_end()) {
11238       if (Context.hasSameType(T, Context.CharTy))
11239         Valid = true;
11240       goto FinishedParams;
11241     }
11242 
11243     // const char *, const wchar_t*, const char16_t*, and const char32_t*
11244     // are allowed as the first parameter to a two-parameter function
11245     if (!(Context.hasSameType(T, Context.CharTy) ||
11246           Context.hasSameType(T, Context.WideCharTy) ||
11247           Context.hasSameType(T, Context.Char16Ty) ||
11248           Context.hasSameType(T, Context.Char32Ty)))
11249       goto FinishedParams;
11250 
11251     // The second and final parameter must be an std::size_t
11252     T = (*Param)->getType().getUnqualifiedType();
11253     if (Context.hasSameType(T, Context.getSizeType()) &&
11254         ++Param == FnDecl->param_end())
11255       Valid = true;
11256   }
11257 
11258   // FIXME: This diagnostic is absolutely terrible.
11259 FinishedParams:
11260   if (!Valid) {
11261     Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11262       << FnDecl->getDeclName();
11263     return true;
11264   }
11265 
11266   // A parameter-declaration-clause containing a default argument is not
11267   // equivalent to any of the permitted forms.
11268   for (auto Param : FnDecl->params()) {
11269     if (Param->hasDefaultArg()) {
11270       Diag(Param->getDefaultArgRange().getBegin(),
11271            diag::err_literal_operator_default_argument)
11272         << Param->getDefaultArgRange();
11273       break;
11274     }
11275   }
11276 
11277   StringRef LiteralName
11278     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11279   if (LiteralName[0] != '_') {
11280     // C++11 [usrlit.suffix]p1:
11281     //   Literal suffix identifiers that do not start with an underscore
11282     //   are reserved for future standardization.
11283     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11284       << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
11285   }
11286 
11287   return false;
11288 }
11289 
11290 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11291 /// linkage specification, including the language and (if present)
11292 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
11293 /// language string literal. LBraceLoc, if valid, provides the location of
11294 /// the '{' brace. Otherwise, this linkage specification does not
11295 /// have any braces.
11296 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
11297                                            Expr *LangStr,
11298                                            SourceLocation LBraceLoc) {
11299   StringLiteral *Lit = cast<StringLiteral>(LangStr);
11300   if (!Lit->isAscii()) {
11301     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11302       << LangStr->getSourceRange();
11303     return nullptr;
11304   }
11305 
11306   StringRef Lang = Lit->getString();
11307   LinkageSpecDecl::LanguageIDs Language;
11308   if (Lang == "C")
11309     Language = LinkageSpecDecl::lang_c;
11310   else if (Lang == "C++")
11311     Language = LinkageSpecDecl::lang_cxx;
11312   else {
11313     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11314       << LangStr->getSourceRange();
11315     return nullptr;
11316   }
11317 
11318   // FIXME: Add all the various semantics of linkage specifications
11319 
11320   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11321                                                LangStr->getExprLoc(), Language,
11322                                                LBraceLoc.isValid());
11323   CurContext->addDecl(D);
11324   PushDeclContext(S, D);
11325   return D;
11326 }
11327 
11328 /// ActOnFinishLinkageSpecification - Complete the definition of
11329 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
11330 /// valid, it's the position of the closing '}' brace in a linkage
11331 /// specification that uses braces.
11332 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
11333                                             Decl *LinkageSpec,
11334                                             SourceLocation RBraceLoc) {
11335   if (RBraceLoc.isValid()) {
11336     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11337     LSDecl->setRBraceLoc(RBraceLoc);
11338   }
11339   PopDeclContext();
11340   return LinkageSpec;
11341 }
11342 
11343 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11344                                   AttributeList *AttrList,
11345                                   SourceLocation SemiLoc) {
11346   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11347   // Attribute declarations appertain to empty declaration so we handle
11348   // them here.
11349   if (AttrList)
11350     ProcessDeclAttributeList(S, ED, AttrList);
11351 
11352   CurContext->addDecl(ED);
11353   return ED;
11354 }
11355 
11356 /// \brief Perform semantic analysis for the variable declaration that
11357 /// occurs within a C++ catch clause, returning the newly-created
11358 /// variable.
11359 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
11360                                          TypeSourceInfo *TInfo,
11361                                          SourceLocation StartLoc,
11362                                          SourceLocation Loc,
11363                                          IdentifierInfo *Name) {
11364   bool Invalid = false;
11365   QualType ExDeclType = TInfo->getType();
11366 
11367   // Arrays and functions decay.
11368   if (ExDeclType->isArrayType())
11369     ExDeclType = Context.getArrayDecayedType(ExDeclType);
11370   else if (ExDeclType->isFunctionType())
11371     ExDeclType = Context.getPointerType(ExDeclType);
11372 
11373   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11374   // The exception-declaration shall not denote a pointer or reference to an
11375   // incomplete type, other than [cv] void*.
11376   // N2844 forbids rvalue references.
11377   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
11378     Diag(Loc, diag::err_catch_rvalue_ref);
11379     Invalid = true;
11380   }
11381 
11382   QualType BaseType = ExDeclType;
11383   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
11384   unsigned DK = diag::err_catch_incomplete;
11385   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
11386     BaseType = Ptr->getPointeeType();
11387     Mode = 1;
11388     DK = diag::err_catch_incomplete_ptr;
11389   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
11390     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
11391     BaseType = Ref->getPointeeType();
11392     Mode = 2;
11393     DK = diag::err_catch_incomplete_ref;
11394   }
11395   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
11396       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
11397     Invalid = true;
11398 
11399   if (!Invalid && !ExDeclType->isDependentType() &&
11400       RequireNonAbstractType(Loc, ExDeclType,
11401                              diag::err_abstract_type_in_decl,
11402                              AbstractVariableType))
11403     Invalid = true;
11404 
11405   // Only the non-fragile NeXT runtime currently supports C++ catches
11406   // of ObjC types, and no runtime supports catching ObjC types by value.
11407   if (!Invalid && getLangOpts().ObjC1) {
11408     QualType T = ExDeclType;
11409     if (const ReferenceType *RT = T->getAs<ReferenceType>())
11410       T = RT->getPointeeType();
11411 
11412     if (T->isObjCObjectType()) {
11413       Diag(Loc, diag::err_objc_object_catch);
11414       Invalid = true;
11415     } else if (T->isObjCObjectPointerType()) {
11416       // FIXME: should this be a test for macosx-fragile specifically?
11417       if (getLangOpts().ObjCRuntime.isFragile())
11418         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
11419     }
11420   }
11421 
11422   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
11423                                     ExDeclType, TInfo, SC_None);
11424   ExDecl->setExceptionVariable(true);
11425 
11426   // In ARC, infer 'retaining' for variables of retainable type.
11427   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
11428     Invalid = true;
11429 
11430   if (!Invalid && !ExDeclType->isDependentType()) {
11431     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
11432       // Insulate this from anything else we might currently be parsing.
11433       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11434 
11435       // C++ [except.handle]p16:
11436       //   The object declared in an exception-declaration or, if the
11437       //   exception-declaration does not specify a name, a temporary (12.2) is
11438       //   copy-initialized (8.5) from the exception object. [...]
11439       //   The object is destroyed when the handler exits, after the destruction
11440       //   of any automatic objects initialized within the handler.
11441       //
11442       // We just pretend to initialize the object with itself, then make sure
11443       // it can be destroyed later.
11444       QualType initType = ExDeclType;
11445 
11446       InitializedEntity entity =
11447         InitializedEntity::InitializeVariable(ExDecl);
11448       InitializationKind initKind =
11449         InitializationKind::CreateCopy(Loc, SourceLocation());
11450 
11451       Expr *opaqueValue =
11452         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
11453       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11454       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
11455       if (result.isInvalid())
11456         Invalid = true;
11457       else {
11458         // If the constructor used was non-trivial, set this as the
11459         // "initializer".
11460         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
11461         if (!construct->getConstructor()->isTrivial()) {
11462           Expr *init = MaybeCreateExprWithCleanups(construct);
11463           ExDecl->setInit(init);
11464         }
11465 
11466         // And make sure it's destructable.
11467         FinalizeVarWithDestructor(ExDecl, recordType);
11468       }
11469     }
11470   }
11471 
11472   if (Invalid)
11473     ExDecl->setInvalidDecl();
11474 
11475   return ExDecl;
11476 }
11477 
11478 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11479 /// handler.
11480 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
11481   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11482   bool Invalid = D.isInvalidType();
11483 
11484   // Check for unexpanded parameter packs.
11485   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11486                                       UPPC_ExceptionType)) {
11487     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11488                                              D.getIdentifierLoc());
11489     Invalid = true;
11490   }
11491 
11492   IdentifierInfo *II = D.getIdentifier();
11493   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
11494                                              LookupOrdinaryName,
11495                                              ForRedeclaration)) {
11496     // The scope should be freshly made just for us. There is just no way
11497     // it contains any previous declaration, except for function parameters in
11498     // a function-try-block's catch statement.
11499     assert(!S->isDeclScope(PrevDecl));
11500     if (isDeclInScope(PrevDecl, CurContext, S)) {
11501       Diag(D.getIdentifierLoc(), diag::err_redefinition)
11502         << D.getIdentifier();
11503       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11504       Invalid = true;
11505     } else if (PrevDecl->isTemplateParameter())
11506       // Maybe we will complain about the shadowed template parameter.
11507       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11508   }
11509 
11510   if (D.getCXXScopeSpec().isSet() && !Invalid) {
11511     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11512       << D.getCXXScopeSpec().getRange();
11513     Invalid = true;
11514   }
11515 
11516   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
11517                                               D.getLocStart(),
11518                                               D.getIdentifierLoc(),
11519                                               D.getIdentifier());
11520   if (Invalid)
11521     ExDecl->setInvalidDecl();
11522 
11523   // Add the exception declaration into this scope.
11524   if (II)
11525     PushOnScopeChains(ExDecl, S);
11526   else
11527     CurContext->addDecl(ExDecl);
11528 
11529   ProcessDeclAttributes(S, ExDecl, D);
11530   return ExDecl;
11531 }
11532 
11533 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11534                                          Expr *AssertExpr,
11535                                          Expr *AssertMessageExpr,
11536                                          SourceLocation RParenLoc) {
11537   StringLiteral *AssertMessage =
11538       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
11539 
11540   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
11541     return nullptr;
11542 
11543   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11544                                       AssertMessage, RParenLoc, false);
11545 }
11546 
11547 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11548                                          Expr *AssertExpr,
11549                                          StringLiteral *AssertMessage,
11550                                          SourceLocation RParenLoc,
11551                                          bool Failed) {
11552   assert(AssertExpr != nullptr && "Expected non-null condition");
11553   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11554       !Failed) {
11555     // In a static_assert-declaration, the constant-expression shall be a
11556     // constant expression that can be contextually converted to bool.
11557     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11558     if (Converted.isInvalid())
11559       Failed = true;
11560 
11561     llvm::APSInt Cond;
11562     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
11563           diag::err_static_assert_expression_is_not_constant,
11564           /*AllowFold=*/false).isInvalid())
11565       Failed = true;
11566 
11567     if (!Failed && !Cond) {
11568       SmallString<256> MsgBuffer;
11569       llvm::raw_svector_ostream Msg(MsgBuffer);
11570       if (AssertMessage)
11571         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
11572       Diag(StaticAssertLoc, diag::err_static_assert_failed)
11573         << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
11574       Failed = true;
11575     }
11576   }
11577 
11578   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
11579                                         AssertExpr, AssertMessage, RParenLoc,
11580                                         Failed);
11581 
11582   CurContext->addDecl(Decl);
11583   return Decl;
11584 }
11585 
11586 /// \brief Perform semantic analysis of the given friend type declaration.
11587 ///
11588 /// \returns A friend declaration that.
11589 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
11590                                       SourceLocation FriendLoc,
11591                                       TypeSourceInfo *TSInfo) {
11592   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11593 
11594   QualType T = TSInfo->getType();
11595   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
11596 
11597   // C++03 [class.friend]p2:
11598   //   An elaborated-type-specifier shall be used in a friend declaration
11599   //   for a class.*
11600   //
11601   //   * The class-key of the elaborated-type-specifier is required.
11602   if (!ActiveTemplateInstantiations.empty()) {
11603     // Do not complain about the form of friend template types during
11604     // template instantiation; we will already have complained when the
11605     // template was declared.
11606   } else {
11607     if (!T->isElaboratedTypeSpecifier()) {
11608       // If we evaluated the type to a record type, suggest putting
11609       // a tag in front.
11610       if (const RecordType *RT = T->getAs<RecordType>()) {
11611         RecordDecl *RD = RT->getDecl();
11612 
11613         SmallString<16> InsertionText(" ");
11614         InsertionText += RD->getKindName();
11615 
11616         Diag(TypeRange.getBegin(),
11617              getLangOpts().CPlusPlus11 ?
11618                diag::warn_cxx98_compat_unelaborated_friend_type :
11619                diag::ext_unelaborated_friend_type)
11620           << (unsigned) RD->getTagKind()
11621           << T
11622           << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11623                                         InsertionText);
11624       } else {
11625         Diag(FriendLoc,
11626              getLangOpts().CPlusPlus11 ?
11627                diag::warn_cxx98_compat_nonclass_type_friend :
11628                diag::ext_nonclass_type_friend)
11629           << T
11630           << TypeRange;
11631       }
11632     } else if (T->getAs<EnumType>()) {
11633       Diag(FriendLoc,
11634            getLangOpts().CPlusPlus11 ?
11635              diag::warn_cxx98_compat_enum_friend :
11636              diag::ext_enum_friend)
11637         << T
11638         << TypeRange;
11639     }
11640 
11641     // C++11 [class.friend]p3:
11642     //   A friend declaration that does not declare a function shall have one
11643     //   of the following forms:
11644     //     friend elaborated-type-specifier ;
11645     //     friend simple-type-specifier ;
11646     //     friend typename-specifier ;
11647     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11648       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11649   }
11650 
11651   //   If the type specifier in a friend declaration designates a (possibly
11652   //   cv-qualified) class type, that class is declared as a friend; otherwise,
11653   //   the friend declaration is ignored.
11654   return FriendDecl::Create(Context, CurContext,
11655                             TSInfo->getTypeLoc().getLocStart(), TSInfo,
11656                             FriendLoc);
11657 }
11658 
11659 /// Handle a friend tag declaration where the scope specifier was
11660 /// templated.
11661 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11662                                     unsigned TagSpec, SourceLocation TagLoc,
11663                                     CXXScopeSpec &SS,
11664                                     IdentifierInfo *Name,
11665                                     SourceLocation NameLoc,
11666                                     AttributeList *Attr,
11667                                     MultiTemplateParamsArg TempParamLists) {
11668   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11669 
11670   bool isExplicitSpecialization = false;
11671   bool Invalid = false;
11672 
11673   if (TemplateParameterList *TemplateParams =
11674           MatchTemplateParametersToScopeSpecifier(
11675               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
11676               isExplicitSpecialization, Invalid)) {
11677     if (TemplateParams->size() > 0) {
11678       // This is a declaration of a class template.
11679       if (Invalid)
11680         return nullptr;
11681 
11682       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
11683                                 NameLoc, Attr, TemplateParams, AS_public,
11684                                 /*ModulePrivateLoc=*/SourceLocation(),
11685                                 FriendLoc, TempParamLists.size() - 1,
11686                                 TempParamLists.data()).get();
11687     } else {
11688       // The "template<>" header is extraneous.
11689       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11690         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11691       isExplicitSpecialization = true;
11692     }
11693   }
11694 
11695   if (Invalid) return nullptr;
11696 
11697   bool isAllExplicitSpecializations = true;
11698   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
11699     if (TempParamLists[I]->size()) {
11700       isAllExplicitSpecializations = false;
11701       break;
11702     }
11703   }
11704 
11705   // FIXME: don't ignore attributes.
11706 
11707   // If it's explicit specializations all the way down, just forget
11708   // about the template header and build an appropriate non-templated
11709   // friend.  TODO: for source fidelity, remember the headers.
11710   if (isAllExplicitSpecializations) {
11711     if (SS.isEmpty()) {
11712       bool Owned = false;
11713       bool IsDependent = false;
11714       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
11715                       Attr, AS_public,
11716                       /*ModulePrivateLoc=*/SourceLocation(),
11717                       MultiTemplateParamsArg(), Owned, IsDependent,
11718                       /*ScopedEnumKWLoc=*/SourceLocation(),
11719                       /*ScopedEnumUsesClassTag=*/false,
11720                       /*UnderlyingType=*/TypeResult(),
11721                       /*IsTypeSpecifier=*/false);
11722     }
11723 
11724     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11725     ElaboratedTypeKeyword Keyword
11726       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11727     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
11728                                    *Name, NameLoc);
11729     if (T.isNull())
11730       return nullptr;
11731 
11732     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11733     if (isa<DependentNameType>(T)) {
11734       DependentNameTypeLoc TL =
11735           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
11736       TL.setElaboratedKeywordLoc(TagLoc);
11737       TL.setQualifierLoc(QualifierLoc);
11738       TL.setNameLoc(NameLoc);
11739     } else {
11740       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
11741       TL.setElaboratedKeywordLoc(TagLoc);
11742       TL.setQualifierLoc(QualifierLoc);
11743       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
11744     }
11745 
11746     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
11747                                             TSI, FriendLoc, TempParamLists);
11748     Friend->setAccess(AS_public);
11749     CurContext->addDecl(Friend);
11750     return Friend;
11751   }
11752 
11753   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11754 
11755 
11756 
11757   // Handle the case of a templated-scope friend class.  e.g.
11758   //   template <class T> class A<T>::B;
11759   // FIXME: we don't support these right now.
11760   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
11761     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
11762   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11763   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11764   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11765   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
11766   TL.setElaboratedKeywordLoc(TagLoc);
11767   TL.setQualifierLoc(SS.getWithLocInContext(Context));
11768   TL.setNameLoc(NameLoc);
11769 
11770   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
11771                                           TSI, FriendLoc, TempParamLists);
11772   Friend->setAccess(AS_public);
11773   Friend->setUnsupportedFriend(true);
11774   CurContext->addDecl(Friend);
11775   return Friend;
11776 }
11777 
11778 
11779 /// Handle a friend type declaration.  This works in tandem with
11780 /// ActOnTag.
11781 ///
11782 /// Notes on friend class templates:
11783 ///
11784 /// We generally treat friend class declarations as if they were
11785 /// declaring a class.  So, for example, the elaborated type specifier
11786 /// in a friend declaration is required to obey the restrictions of a
11787 /// class-head (i.e. no typedefs in the scope chain), template
11788 /// parameters are required to match up with simple template-ids, &c.
11789 /// However, unlike when declaring a template specialization, it's
11790 /// okay to refer to a template specialization without an empty
11791 /// template parameter declaration, e.g.
11792 ///   friend class A<T>::B<unsigned>;
11793 /// We permit this as a special case; if there are any template
11794 /// parameters present at all, require proper matching, i.e.
11795 ///   template <> template \<class T> friend class A<int>::B;
11796 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
11797                                 MultiTemplateParamsArg TempParams) {
11798   SourceLocation Loc = DS.getLocStart();
11799 
11800   assert(DS.isFriendSpecified());
11801   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11802 
11803   // Try to convert the decl specifier to a type.  This works for
11804   // friend templates because ActOnTag never produces a ClassTemplateDecl
11805   // for a TUK_Friend.
11806   Declarator TheDeclarator(DS, Declarator::MemberContext);
11807   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11808   QualType T = TSI->getType();
11809   if (TheDeclarator.isInvalidType())
11810     return nullptr;
11811 
11812   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11813     return nullptr;
11814 
11815   // This is definitely an error in C++98.  It's probably meant to
11816   // be forbidden in C++0x, too, but the specification is just
11817   // poorly written.
11818   //
11819   // The problem is with declarations like the following:
11820   //   template <T> friend A<T>::foo;
11821   // where deciding whether a class C is a friend or not now hinges
11822   // on whether there exists an instantiation of A that causes
11823   // 'foo' to equal C.  There are restrictions on class-heads
11824   // (which we declare (by fiat) elaborated friend declarations to
11825   // be) that makes this tractable.
11826   //
11827   // FIXME: handle "template <> friend class A<T>;", which
11828   // is possibly well-formed?  Who even knows?
11829   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
11830     Diag(Loc, diag::err_tagless_friend_type_template)
11831       << DS.getSourceRange();
11832     return nullptr;
11833   }
11834 
11835   // C++98 [class.friend]p1: A friend of a class is a function
11836   //   or class that is not a member of the class . . .
11837   // This is fixed in DR77, which just barely didn't make the C++03
11838   // deadline.  It's also a very silly restriction that seriously
11839   // affects inner classes and which nobody else seems to implement;
11840   // thus we never diagnose it, not even in -pedantic.
11841   //
11842   // But note that we could warn about it: it's always useless to
11843   // friend one of your own members (it's not, however, worthless to
11844   // friend a member of an arbitrary specialization of your template).
11845 
11846   Decl *D;
11847   if (unsigned NumTempParamLists = TempParams.size())
11848     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
11849                                    NumTempParamLists,
11850                                    TempParams.data(),
11851                                    TSI,
11852                                    DS.getFriendSpecLoc());
11853   else
11854     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
11855 
11856   if (!D)
11857     return nullptr;
11858 
11859   D->setAccess(AS_public);
11860   CurContext->addDecl(D);
11861 
11862   return D;
11863 }
11864 
11865 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11866                                         MultiTemplateParamsArg TemplateParams) {
11867   const DeclSpec &DS = D.getDeclSpec();
11868 
11869   assert(DS.isFriendSpecified());
11870   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11871 
11872   SourceLocation Loc = D.getIdentifierLoc();
11873   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11874 
11875   // C++ [class.friend]p1
11876   //   A friend of a class is a function or class....
11877   // Note that this sees through typedefs, which is intended.
11878   // It *doesn't* see through dependent types, which is correct
11879   // according to [temp.arg.type]p3:
11880   //   If a declaration acquires a function type through a
11881   //   type dependent on a template-parameter and this causes
11882   //   a declaration that does not use the syntactic form of a
11883   //   function declarator to have a function type, the program
11884   //   is ill-formed.
11885   if (!TInfo->getType()->isFunctionType()) {
11886     Diag(Loc, diag::err_unexpected_friend);
11887 
11888     // It might be worthwhile to try to recover by creating an
11889     // appropriate declaration.
11890     return nullptr;
11891   }
11892 
11893   // C++ [namespace.memdef]p3
11894   //  - If a friend declaration in a non-local class first declares a
11895   //    class or function, the friend class or function is a member
11896   //    of the innermost enclosing namespace.
11897   //  - The name of the friend is not found by simple name lookup
11898   //    until a matching declaration is provided in that namespace
11899   //    scope (either before or after the class declaration granting
11900   //    friendship).
11901   //  - If a friend function is called, its name may be found by the
11902   //    name lookup that considers functions from namespaces and
11903   //    classes associated with the types of the function arguments.
11904   //  - When looking for a prior declaration of a class or a function
11905   //    declared as a friend, scopes outside the innermost enclosing
11906   //    namespace scope are not considered.
11907 
11908   CXXScopeSpec &SS = D.getCXXScopeSpec();
11909   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11910   DeclarationName Name = NameInfo.getName();
11911   assert(Name);
11912 
11913   // Check for unexpanded parameter packs.
11914   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11915       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11916       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11917     return nullptr;
11918 
11919   // The context we found the declaration in, or in which we should
11920   // create the declaration.
11921   DeclContext *DC;
11922   Scope *DCScope = S;
11923   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
11924                         ForRedeclaration);
11925 
11926   // There are five cases here.
11927   //   - There's no scope specifier and we're in a local class. Only look
11928   //     for functions declared in the immediately-enclosing block scope.
11929   // We recover from invalid scope qualifiers as if they just weren't there.
11930   FunctionDecl *FunctionContainingLocalClass = nullptr;
11931   if ((SS.isInvalid() || !SS.isSet()) &&
11932       (FunctionContainingLocalClass =
11933            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11934     // C++11 [class.friend]p11:
11935     //   If a friend declaration appears in a local class and the name
11936     //   specified is an unqualified name, a prior declaration is
11937     //   looked up without considering scopes that are outside the
11938     //   innermost enclosing non-class scope. For a friend function
11939     //   declaration, if there is no prior declaration, the program is
11940     //   ill-formed.
11941 
11942     // Find the innermost enclosing non-class scope. This is the block
11943     // scope containing the local class definition (or for a nested class,
11944     // the outer local class).
11945     DCScope = S->getFnParent();
11946 
11947     // Look up the function name in the scope.
11948     Previous.clear(LookupLocalFriendName);
11949     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11950 
11951     if (!Previous.empty()) {
11952       // All possible previous declarations must have the same context:
11953       // either they were declared at block scope or they are members of
11954       // one of the enclosing local classes.
11955       DC = Previous.getRepresentativeDecl()->getDeclContext();
11956     } else {
11957       // This is ill-formed, but provide the context that we would have
11958       // declared the function in, if we were permitted to, for error recovery.
11959       DC = FunctionContainingLocalClass;
11960     }
11961     adjustContextForLocalExternDecl(DC);
11962 
11963     // C++ [class.friend]p6:
11964     //   A function can be defined in a friend declaration of a class if and
11965     //   only if the class is a non-local class (9.8), the function name is
11966     //   unqualified, and the function has namespace scope.
11967     if (D.isFunctionDefinition()) {
11968       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11969     }
11970 
11971   //   - There's no scope specifier, in which case we just go to the
11972   //     appropriate scope and look for a function or function template
11973   //     there as appropriate.
11974   } else if (SS.isInvalid() || !SS.isSet()) {
11975     // C++11 [namespace.memdef]p3:
11976     //   If the name in a friend declaration is neither qualified nor
11977     //   a template-id and the declaration is a function or an
11978     //   elaborated-type-specifier, the lookup to determine whether
11979     //   the entity has been previously declared shall not consider
11980     //   any scopes outside the innermost enclosing namespace.
11981     bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
11982 
11983     // Find the appropriate context according to the above.
11984     DC = CurContext;
11985 
11986     // Skip class contexts.  If someone can cite chapter and verse
11987     // for this behavior, that would be nice --- it's what GCC and
11988     // EDG do, and it seems like a reasonable intent, but the spec
11989     // really only says that checks for unqualified existing
11990     // declarations should stop at the nearest enclosing namespace,
11991     // not that they should only consider the nearest enclosing
11992     // namespace.
11993     while (DC->isRecord())
11994       DC = DC->getParent();
11995 
11996     DeclContext *LookupDC = DC;
11997     while (LookupDC->isTransparentContext())
11998       LookupDC = LookupDC->getParent();
11999 
12000     while (true) {
12001       LookupQualifiedName(Previous, LookupDC);
12002 
12003       if (!Previous.empty()) {
12004         DC = LookupDC;
12005         break;
12006       }
12007 
12008       if (isTemplateId) {
12009         if (isa<TranslationUnitDecl>(LookupDC)) break;
12010       } else {
12011         if (LookupDC->isFileContext()) break;
12012       }
12013       LookupDC = LookupDC->getParent();
12014     }
12015 
12016     DCScope = getScopeForDeclContext(S, DC);
12017 
12018   //   - There's a non-dependent scope specifier, in which case we
12019   //     compute it and do a previous lookup there for a function
12020   //     or function template.
12021   } else if (!SS.getScopeRep()->isDependent()) {
12022     DC = computeDeclContext(SS);
12023     if (!DC) return nullptr;
12024 
12025     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
12026 
12027     LookupQualifiedName(Previous, DC);
12028 
12029     // Ignore things found implicitly in the wrong scope.
12030     // TODO: better diagnostics for this case.  Suggesting the right
12031     // qualified scope would be nice...
12032     LookupResult::Filter F = Previous.makeFilter();
12033     while (F.hasNext()) {
12034       NamedDecl *D = F.next();
12035       if (!DC->InEnclosingNamespaceSetOf(
12036               D->getDeclContext()->getRedeclContext()))
12037         F.erase();
12038     }
12039     F.done();
12040 
12041     if (Previous.empty()) {
12042       D.setInvalidType();
12043       Diag(Loc, diag::err_qualified_friend_not_found)
12044           << Name << TInfo->getType();
12045       return nullptr;
12046     }
12047 
12048     // C++ [class.friend]p1: A friend of a class is a function or
12049     //   class that is not a member of the class . . .
12050     if (DC->Equals(CurContext))
12051       Diag(DS.getFriendSpecLoc(),
12052            getLangOpts().CPlusPlus11 ?
12053              diag::warn_cxx98_compat_friend_is_member :
12054              diag::err_friend_is_member);
12055 
12056     if (D.isFunctionDefinition()) {
12057       // C++ [class.friend]p6:
12058       //   A function can be defined in a friend declaration of a class if and
12059       //   only if the class is a non-local class (9.8), the function name is
12060       //   unqualified, and the function has namespace scope.
12061       SemaDiagnosticBuilder DB
12062         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
12063 
12064       DB << SS.getScopeRep();
12065       if (DC->isFileContext())
12066         DB << FixItHint::CreateRemoval(SS.getRange());
12067       SS.clear();
12068     }
12069 
12070   //   - There's a scope specifier that does not match any template
12071   //     parameter lists, in which case we use some arbitrary context,
12072   //     create a method or method template, and wait for instantiation.
12073   //   - There's a scope specifier that does match some template
12074   //     parameter lists, which we don't handle right now.
12075   } else {
12076     if (D.isFunctionDefinition()) {
12077       // C++ [class.friend]p6:
12078       //   A function can be defined in a friend declaration of a class if and
12079       //   only if the class is a non-local class (9.8), the function name is
12080       //   unqualified, and the function has namespace scope.
12081       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
12082         << SS.getScopeRep();
12083     }
12084 
12085     DC = CurContext;
12086     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
12087   }
12088 
12089   if (!DC->isRecord()) {
12090     // This implies that it has to be an operator or function.
12091     if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
12092         D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
12093         D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
12094       Diag(Loc, diag::err_introducing_special_friend) <<
12095         (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
12096          D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
12097       return nullptr;
12098     }
12099   }
12100 
12101   // FIXME: This is an egregious hack to cope with cases where the scope stack
12102   // does not contain the declaration context, i.e., in an out-of-line
12103   // definition of a class.
12104   Scope FakeDCScope(S, Scope::DeclScope, Diags);
12105   if (!DCScope) {
12106     FakeDCScope.setEntity(DC);
12107     DCScope = &FakeDCScope;
12108   }
12109 
12110   bool AddToScope = true;
12111   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
12112                                           TemplateParams, AddToScope);
12113   if (!ND) return nullptr;
12114 
12115   assert(ND->getLexicalDeclContext() == CurContext);
12116 
12117   // If we performed typo correction, we might have added a scope specifier
12118   // and changed the decl context.
12119   DC = ND->getDeclContext();
12120 
12121   // Add the function declaration to the appropriate lookup tables,
12122   // adjusting the redeclarations list as necessary.  We don't
12123   // want to do this yet if the friending class is dependent.
12124   //
12125   // Also update the scope-based lookup if the target context's
12126   // lookup context is in lexical scope.
12127   if (!CurContext->isDependentContext()) {
12128     DC = DC->getRedeclContext();
12129     DC->makeDeclVisibleInContext(ND);
12130     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
12131       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
12132   }
12133 
12134   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
12135                                        D.getIdentifierLoc(), ND,
12136                                        DS.getFriendSpecLoc());
12137   FrD->setAccess(AS_public);
12138   CurContext->addDecl(FrD);
12139 
12140   if (ND->isInvalidDecl()) {
12141     FrD->setInvalidDecl();
12142   } else {
12143     if (DC->isRecord()) CheckFriendAccess(ND);
12144 
12145     FunctionDecl *FD;
12146     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12147       FD = FTD->getTemplatedDecl();
12148     else
12149       FD = cast<FunctionDecl>(ND);
12150 
12151     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12152     // default argument expression, that declaration shall be a definition
12153     // and shall be the only declaration of the function or function
12154     // template in the translation unit.
12155     if (functionDeclHasDefaultArgument(FD)) {
12156       if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12157         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12158         Diag(OldFD->getLocation(), diag::note_previous_declaration);
12159       } else if (!D.isFunctionDefinition())
12160         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12161     }
12162 
12163     // Mark templated-scope function declarations as unsupported.
12164     if (FD->getNumTemplateParameterLists())
12165       FrD->setUnsupportedFriend(true);
12166   }
12167 
12168   return ND;
12169 }
12170 
12171 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12172   AdjustDeclIfTemplate(Dcl);
12173 
12174   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
12175   if (!Fn) {
12176     Diag(DelLoc, diag::err_deleted_non_function);
12177     return;
12178   }
12179 
12180   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
12181     // Don't consider the implicit declaration we generate for explicit
12182     // specializations. FIXME: Do not generate these implicit declarations.
12183     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12184          Prev->getPreviousDecl()) &&
12185         !Prev->isDefined()) {
12186       Diag(DelLoc, diag::err_deleted_decl_not_first);
12187       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12188            Prev->isImplicit() ? diag::note_previous_implicit_declaration
12189                               : diag::note_previous_declaration);
12190     }
12191     // If the declaration wasn't the first, we delete the function anyway for
12192     // recovery.
12193     Fn = Fn->getCanonicalDecl();
12194   }
12195 
12196   // dllimport/dllexport cannot be deleted.
12197   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12198     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12199     Fn->setInvalidDecl();
12200   }
12201 
12202   if (Fn->isDeleted())
12203     return;
12204 
12205   // See if we're deleting a function which is already known to override a
12206   // non-deleted virtual function.
12207   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
12208     bool IssuedDiagnostic = false;
12209     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
12210                                         E = MD->end_overridden_methods();
12211          I != E; ++I) {
12212       if (!(*MD->begin_overridden_methods())->isDeleted()) {
12213         if (!IssuedDiagnostic) {
12214           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
12215           IssuedDiagnostic = true;
12216         }
12217         Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
12218       }
12219     }
12220   }
12221 
12222   // C++11 [basic.start.main]p3:
12223   //   A program that defines main as deleted [...] is ill-formed.
12224   if (Fn->isMain())
12225     Diag(DelLoc, diag::err_deleted_main);
12226 
12227   Fn->setDeletedAsWritten();
12228 }
12229 
12230 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
12231   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
12232 
12233   if (MD) {
12234     if (MD->getParent()->isDependentType()) {
12235       MD->setDefaulted();
12236       MD->setExplicitlyDefaulted();
12237       return;
12238     }
12239 
12240     CXXSpecialMember Member = getSpecialMember(MD);
12241     if (Member == CXXInvalid) {
12242       if (!MD->isInvalidDecl())
12243         Diag(DefaultLoc, diag::err_default_special_members);
12244       return;
12245     }
12246 
12247     MD->setDefaulted();
12248     MD->setExplicitlyDefaulted();
12249 
12250     // If this definition appears within the record, do the checking when
12251     // the record is complete.
12252     const FunctionDecl *Primary = MD;
12253     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
12254       // Find the uninstantiated declaration that actually had the '= default'
12255       // on it.
12256       Pattern->isDefined(Primary);
12257 
12258     // If the method was defaulted on its first declaration, we will have
12259     // already performed the checking in CheckCompletedCXXClass. Such a
12260     // declaration doesn't trigger an implicit definition.
12261     if (Primary == Primary->getCanonicalDecl())
12262       return;
12263 
12264     CheckExplicitlyDefaultedSpecialMember(MD);
12265 
12266     // The exception specification is needed because we are defining the
12267     // function.
12268     ResolveExceptionSpec(DefaultLoc,
12269                          MD->getType()->castAs<FunctionProtoType>());
12270 
12271     if (MD->isInvalidDecl())
12272       return;
12273 
12274     switch (Member) {
12275     case CXXDefaultConstructor:
12276       DefineImplicitDefaultConstructor(DefaultLoc,
12277                                        cast<CXXConstructorDecl>(MD));
12278       break;
12279     case CXXCopyConstructor:
12280       DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
12281       break;
12282     case CXXCopyAssignment:
12283       DefineImplicitCopyAssignment(DefaultLoc, MD);
12284       break;
12285     case CXXDestructor:
12286       DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
12287       break;
12288     case CXXMoveConstructor:
12289       DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
12290       break;
12291     case CXXMoveAssignment:
12292       DefineImplicitMoveAssignment(DefaultLoc, MD);
12293       break;
12294     case CXXInvalid:
12295       llvm_unreachable("Invalid special member.");
12296     }
12297   } else {
12298     Diag(DefaultLoc, diag::err_default_special_members);
12299   }
12300 }
12301 
12302 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
12303   for (Stmt::child_range CI = S->children(); CI; ++CI) {
12304     Stmt *SubStmt = *CI;
12305     if (!SubStmt)
12306       continue;
12307     if (isa<ReturnStmt>(SubStmt))
12308       Self.Diag(SubStmt->getLocStart(),
12309            diag::err_return_in_constructor_handler);
12310     if (!isa<Expr>(SubStmt))
12311       SearchForReturnInStmt(Self, SubStmt);
12312   }
12313 }
12314 
12315 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12316   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12317     CXXCatchStmt *Handler = TryBlock->getHandler(I);
12318     SearchForReturnInStmt(*this, Handler);
12319   }
12320 }
12321 
12322 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
12323                                              const CXXMethodDecl *Old) {
12324   const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12325   const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12326 
12327   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12328 
12329   // If the calling conventions match, everything is fine
12330   if (NewCC == OldCC)
12331     return false;
12332 
12333   // If the calling conventions mismatch because the new function is static,
12334   // suppress the calling convention mismatch error; the error about static
12335   // function override (err_static_overrides_virtual from
12336   // Sema::CheckFunctionDeclaration) is more clear.
12337   if (New->getStorageClass() == SC_Static)
12338     return false;
12339 
12340   Diag(New->getLocation(),
12341        diag::err_conflicting_overriding_cc_attributes)
12342     << New->getDeclName() << New->getType() << Old->getType();
12343   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12344   return true;
12345 }
12346 
12347 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
12348                                              const CXXMethodDecl *Old) {
12349   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12350   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
12351 
12352   if (Context.hasSameType(NewTy, OldTy) ||
12353       NewTy->isDependentType() || OldTy->isDependentType())
12354     return false;
12355 
12356   // Check if the return types are covariant
12357   QualType NewClassTy, OldClassTy;
12358 
12359   /// Both types must be pointers or references to classes.
12360   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12361     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
12362       NewClassTy = NewPT->getPointeeType();
12363       OldClassTy = OldPT->getPointeeType();
12364     }
12365   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12366     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12367       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12368         NewClassTy = NewRT->getPointeeType();
12369         OldClassTy = OldRT->getPointeeType();
12370       }
12371     }
12372   }
12373 
12374   // The return types aren't either both pointers or references to a class type.
12375   if (NewClassTy.isNull()) {
12376     Diag(New->getLocation(),
12377          diag::err_different_return_type_for_overriding_virtual_function)
12378         << New->getDeclName() << NewTy << OldTy
12379         << New->getReturnTypeSourceRange();
12380     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12381         << Old->getReturnTypeSourceRange();
12382 
12383     return true;
12384   }
12385 
12386   // C++ [class.virtual]p6:
12387   //   If the return type of D::f differs from the return type of B::f, the
12388   //   class type in the return type of D::f shall be complete at the point of
12389   //   declaration of D::f or shall be the class type D.
12390   if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12391     if (!RT->isBeingDefined() &&
12392         RequireCompleteType(New->getLocation(), NewClassTy,
12393                             diag::err_covariant_return_incomplete,
12394                             New->getDeclName()))
12395     return true;
12396   }
12397 
12398   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
12399     // Check if the new class derives from the old class.
12400     if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12401       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
12402           << New->getDeclName() << NewTy << OldTy
12403           << New->getReturnTypeSourceRange();
12404       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12405           << Old->getReturnTypeSourceRange();
12406       return true;
12407     }
12408 
12409     // Check if we the conversion from derived to base is valid.
12410     if (CheckDerivedToBaseConversion(
12411             NewClassTy, OldClassTy,
12412             diag::err_covariant_return_inaccessible_base,
12413             diag::err_covariant_return_ambiguous_derived_to_base_conv,
12414             New->getLocation(), New->getReturnTypeSourceRange(),
12415             New->getDeclName(), nullptr)) {
12416       // FIXME: this note won't trigger for delayed access control
12417       // diagnostics, and it's impossible to get an undelayed error
12418       // here from access control during the original parse because
12419       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
12420       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12421           << Old->getReturnTypeSourceRange();
12422       return true;
12423     }
12424   }
12425 
12426   // The qualifiers of the return types must be the same.
12427   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
12428     Diag(New->getLocation(),
12429          diag::err_covariant_return_type_different_qualifications)
12430         << New->getDeclName() << NewTy << OldTy
12431         << New->getReturnTypeSourceRange();
12432     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12433         << Old->getReturnTypeSourceRange();
12434     return true;
12435   };
12436 
12437 
12438   // The new class type must have the same or less qualifiers as the old type.
12439   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12440     Diag(New->getLocation(),
12441          diag::err_covariant_return_type_class_type_more_qualified)
12442         << New->getDeclName() << NewTy << OldTy
12443         << New->getReturnTypeSourceRange();
12444     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12445         << Old->getReturnTypeSourceRange();
12446     return true;
12447   };
12448 
12449   return false;
12450 }
12451 
12452 /// \brief Mark the given method pure.
12453 ///
12454 /// \param Method the method to be marked pure.
12455 ///
12456 /// \param InitRange the source range that covers the "0" initializer.
12457 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
12458   SourceLocation EndLoc = InitRange.getEnd();
12459   if (EndLoc.isValid())
12460     Method->setRangeEnd(EndLoc);
12461 
12462   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12463     Method->setPure();
12464     return false;
12465   }
12466 
12467   if (!Method->isInvalidDecl())
12468     Diag(Method->getLocation(), diag::err_non_virtual_pure)
12469       << Method->getDeclName() << InitRange;
12470   return true;
12471 }
12472 
12473 /// \brief Determine whether the given declaration is a static data member.
12474 static bool isStaticDataMember(const Decl *D) {
12475   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12476     return Var->isStaticDataMember();
12477 
12478   return false;
12479 }
12480 
12481 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12482 /// an initializer for the out-of-line declaration 'Dcl'.  The scope
12483 /// is a fresh scope pushed for just this purpose.
12484 ///
12485 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12486 /// static data member of class X, names should be looked up in the scope of
12487 /// class X.
12488 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
12489   // If there is no declaration, there was an error parsing it.
12490   if (!D || D->isInvalidDecl())
12491     return;
12492 
12493   // We will always have a nested name specifier here, but this declaration
12494   // might not be out of line if the specifier names the current namespace:
12495   //   extern int n;
12496   //   int ::n = 0;
12497   if (D->isOutOfLine())
12498     EnterDeclaratorContext(S, D->getDeclContext());
12499 
12500   // If we are parsing the initializer for a static data member, push a
12501   // new expression evaluation context that is associated with this static
12502   // data member.
12503   if (isStaticDataMember(D))
12504     PushExpressionEvaluationContext(PotentiallyEvaluated, D);
12505 }
12506 
12507 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
12508 /// initializer for the out-of-line declaration 'D'.
12509 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
12510   // If there is no declaration, there was an error parsing it.
12511   if (!D || D->isInvalidDecl())
12512     return;
12513 
12514   if (isStaticDataMember(D))
12515     PopExpressionEvaluationContext();
12516 
12517   if (D->isOutOfLine())
12518     ExitDeclaratorContext(S);
12519 }
12520 
12521 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12522 /// C++ if/switch/while/for statement.
12523 /// e.g: "if (int x = f()) {...}"
12524 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
12525   // C++ 6.4p2:
12526   // The declarator shall not specify a function or an array.
12527   // The type-specifier-seq shall not contain typedef and shall not declare a
12528   // new class or enumeration.
12529   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12530          "Parser allowed 'typedef' as storage class of condition decl.");
12531 
12532   Decl *Dcl = ActOnDeclarator(S, D);
12533   if (!Dcl)
12534     return true;
12535 
12536   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12537     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
12538       << D.getSourceRange();
12539     return true;
12540   }
12541 
12542   return Dcl;
12543 }
12544 
12545 void Sema::LoadExternalVTableUses() {
12546   if (!ExternalSource)
12547     return;
12548 
12549   SmallVector<ExternalVTableUse, 4> VTables;
12550   ExternalSource->ReadUsedVTables(VTables);
12551   SmallVector<VTableUse, 4> NewUses;
12552   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12553     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12554       = VTablesUsed.find(VTables[I].Record);
12555     // Even if a definition wasn't required before, it may be required now.
12556     if (Pos != VTablesUsed.end()) {
12557       if (!Pos->second && VTables[I].DefinitionRequired)
12558         Pos->second = true;
12559       continue;
12560     }
12561 
12562     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12563     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12564   }
12565 
12566   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12567 }
12568 
12569 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12570                           bool DefinitionRequired) {
12571   // Ignore any vtable uses in unevaluated operands or for classes that do
12572   // not have a vtable.
12573   if (!Class->isDynamicClass() || Class->isDependentContext() ||
12574       CurContext->isDependentContext() || isUnevaluatedContext())
12575     return;
12576 
12577   // Try to insert this class into the map.
12578   LoadExternalVTableUses();
12579   Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12580   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12581     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12582   if (!Pos.second) {
12583     // If we already had an entry, check to see if we are promoting this vtable
12584     // to required a definition. If so, we need to reappend to the VTableUses
12585     // list, since we may have already processed the first entry.
12586     if (DefinitionRequired && !Pos.first->second) {
12587       Pos.first->second = true;
12588     } else {
12589       // Otherwise, we can early exit.
12590       return;
12591     }
12592   } else {
12593     // The Microsoft ABI requires that we perform the destructor body
12594     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
12595     // the deleting destructor is emitted with the vtable, not with the
12596     // destructor definition as in the Itanium ABI.
12597     // If it has a definition, we do the check at that point instead.
12598     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12599         Class->hasUserDeclaredDestructor() &&
12600         !Class->getDestructor()->isDefined() &&
12601         !Class->getDestructor()->isDeleted()) {
12602       CXXDestructorDecl *DD = Class->getDestructor();
12603       ContextRAII SavedContext(*this, DD);
12604       CheckDestructor(DD);
12605     }
12606   }
12607 
12608   // Local classes need to have their virtual members marked
12609   // immediately. For all other classes, we mark their virtual members
12610   // at the end of the translation unit.
12611   if (Class->isLocalClass())
12612     MarkVirtualMembersReferenced(Loc, Class);
12613   else
12614     VTableUses.push_back(std::make_pair(Class, Loc));
12615 }
12616 
12617 bool Sema::DefineUsedVTables() {
12618   LoadExternalVTableUses();
12619   if (VTableUses.empty())
12620     return false;
12621 
12622   // Note: The VTableUses vector could grow as a result of marking
12623   // the members of a class as "used", so we check the size each
12624   // time through the loop and prefer indices (which are stable) to
12625   // iterators (which are not).
12626   bool DefinedAnything = false;
12627   for (unsigned I = 0; I != VTableUses.size(); ++I) {
12628     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
12629     if (!Class)
12630       continue;
12631 
12632     SourceLocation Loc = VTableUses[I].second;
12633 
12634     bool DefineVTable = true;
12635 
12636     // If this class has a key function, but that key function is
12637     // defined in another translation unit, we don't need to emit the
12638     // vtable even though we're using it.
12639     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
12640     if (KeyFunction && !KeyFunction->hasBody()) {
12641       // The key function is in another translation unit.
12642       DefineVTable = false;
12643       TemplateSpecializationKind TSK =
12644           KeyFunction->getTemplateSpecializationKind();
12645       assert(TSK != TSK_ExplicitInstantiationDefinition &&
12646              TSK != TSK_ImplicitInstantiation &&
12647              "Instantiations don't have key functions");
12648       (void)TSK;
12649     } else if (!KeyFunction) {
12650       // If we have a class with no key function that is the subject
12651       // of an explicit instantiation declaration, suppress the
12652       // vtable; it will live with the explicit instantiation
12653       // definition.
12654       bool IsExplicitInstantiationDeclaration
12655         = Class->getTemplateSpecializationKind()
12656                                       == TSK_ExplicitInstantiationDeclaration;
12657       for (auto R : Class->redecls()) {
12658         TemplateSpecializationKind TSK
12659           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
12660         if (TSK == TSK_ExplicitInstantiationDeclaration)
12661           IsExplicitInstantiationDeclaration = true;
12662         else if (TSK == TSK_ExplicitInstantiationDefinition) {
12663           IsExplicitInstantiationDeclaration = false;
12664           break;
12665         }
12666       }
12667 
12668       if (IsExplicitInstantiationDeclaration)
12669         DefineVTable = false;
12670     }
12671 
12672     // The exception specifications for all virtual members may be needed even
12673     // if we are not providing an authoritative form of the vtable in this TU.
12674     // We may choose to emit it available_externally anyway.
12675     if (!DefineVTable) {
12676       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12677       continue;
12678     }
12679 
12680     // Mark all of the virtual members of this class as referenced, so
12681     // that we can build a vtable. Then, tell the AST consumer that a
12682     // vtable for this class is required.
12683     DefinedAnything = true;
12684     MarkVirtualMembersReferenced(Loc, Class);
12685     CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12686     Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12687 
12688     // Optionally warn if we're emitting a weak vtable.
12689     if (Class->isExternallyVisible() &&
12690         Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
12691       const FunctionDecl *KeyFunctionDef = nullptr;
12692       if (!KeyFunction ||
12693           (KeyFunction->hasBody(KeyFunctionDef) &&
12694            KeyFunctionDef->isInlined()))
12695         Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12696              TSK_ExplicitInstantiationDefinition
12697              ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12698           << Class;
12699     }
12700   }
12701   VTableUses.clear();
12702 
12703   return DefinedAnything;
12704 }
12705 
12706 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12707                                                  const CXXRecordDecl *RD) {
12708   for (const auto *I : RD->methods())
12709     if (I->isVirtual() && !I->isPure())
12710       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
12711 }
12712 
12713 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12714                                         const CXXRecordDecl *RD) {
12715   // Mark all functions which will appear in RD's vtable as used.
12716   CXXFinalOverriderMap FinalOverriders;
12717   RD->getFinalOverriders(FinalOverriders);
12718   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12719                                             E = FinalOverriders.end();
12720        I != E; ++I) {
12721     for (OverridingMethods::const_iterator OI = I->second.begin(),
12722                                            OE = I->second.end();
12723          OI != OE; ++OI) {
12724       assert(OI->second.size() > 0 && "no final overrider");
12725       CXXMethodDecl *Overrider = OI->second.front().Method;
12726 
12727       // C++ [basic.def.odr]p2:
12728       //   [...] A virtual member function is used if it is not pure. [...]
12729       if (!Overrider->isPure())
12730         MarkFunctionReferenced(Loc, Overrider);
12731     }
12732   }
12733 
12734   // Only classes that have virtual bases need a VTT.
12735   if (RD->getNumVBases() == 0)
12736     return;
12737 
12738   for (const auto &I : RD->bases()) {
12739     const CXXRecordDecl *Base =
12740         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
12741     if (Base->getNumVBases() == 0)
12742       continue;
12743     MarkVirtualMembersReferenced(Loc, Base);
12744   }
12745 }
12746 
12747 /// SetIvarInitializers - This routine builds initialization ASTs for the
12748 /// Objective-C implementation whose ivars need be initialized.
12749 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
12750   if (!getLangOpts().CPlusPlus)
12751     return;
12752   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
12753     SmallVector<ObjCIvarDecl*, 8> ivars;
12754     CollectIvarsToConstructOrDestruct(OID, ivars);
12755     if (ivars.empty())
12756       return;
12757     SmallVector<CXXCtorInitializer*, 32> AllToInit;
12758     for (unsigned i = 0; i < ivars.size(); i++) {
12759       FieldDecl *Field = ivars[i];
12760       if (Field->isInvalidDecl())
12761         continue;
12762 
12763       CXXCtorInitializer *Member;
12764       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12765       InitializationKind InitKind =
12766         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
12767 
12768       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12769       ExprResult MemberInit =
12770         InitSeq.Perform(*this, InitEntity, InitKind, None);
12771       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
12772       // Note, MemberInit could actually come back empty if no initialization
12773       // is required (e.g., because it would call a trivial default constructor)
12774       if (!MemberInit.get() || MemberInit.isInvalid())
12775         continue;
12776 
12777       Member =
12778         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12779                                          SourceLocation(),
12780                                          MemberInit.getAs<Expr>(),
12781                                          SourceLocation());
12782       AllToInit.push_back(Member);
12783 
12784       // Be sure that the destructor is accessible and is marked as referenced.
12785       if (const RecordType *RecordTy
12786                   = Context.getBaseElementType(Field->getType())
12787                                                         ->getAs<RecordType>()) {
12788                     CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
12789         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
12790           MarkFunctionReferenced(Field->getLocation(), Destructor);
12791           CheckDestructorAccess(Field->getLocation(), Destructor,
12792                             PDiag(diag::err_access_dtor_ivar)
12793                               << Context.getBaseElementType(Field->getType()));
12794         }
12795       }
12796     }
12797     ObjCImplementation->setIvarInitializers(Context,
12798                                             AllToInit.data(), AllToInit.size());
12799   }
12800 }
12801 
12802 static
12803 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12804                            llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12805                            llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12806                            llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12807                            Sema &S) {
12808   if (Ctor->isInvalidDecl())
12809     return;
12810 
12811   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12812 
12813   // Target may not be determinable yet, for instance if this is a dependent
12814   // call in an uninstantiated template.
12815   if (Target) {
12816     const FunctionDecl *FNTarget = nullptr;
12817     (void)Target->hasBody(FNTarget);
12818     Target = const_cast<CXXConstructorDecl*>(
12819       cast_or_null<CXXConstructorDecl>(FNTarget));
12820   }
12821 
12822   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12823                      // Avoid dereferencing a null pointer here.
12824                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
12825 
12826   if (!Current.insert(Canonical))
12827     return;
12828 
12829   // We know that beyond here, we aren't chaining into a cycle.
12830   if (!Target || !Target->isDelegatingConstructor() ||
12831       Target->isInvalidDecl() || Valid.count(TCanonical)) {
12832     Valid.insert(Current.begin(), Current.end());
12833     Current.clear();
12834   // We've hit a cycle.
12835   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12836              Current.count(TCanonical)) {
12837     // If we haven't diagnosed this cycle yet, do so now.
12838     if (!Invalid.count(TCanonical)) {
12839       S.Diag((*Ctor->init_begin())->getSourceLocation(),
12840              diag::warn_delegating_ctor_cycle)
12841         << Ctor;
12842 
12843       // Don't add a note for a function delegating directly to itself.
12844       if (TCanonical != Canonical)
12845         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12846 
12847       CXXConstructorDecl *C = Target;
12848       while (C->getCanonicalDecl() != Canonical) {
12849         const FunctionDecl *FNTarget = nullptr;
12850         (void)C->getTargetConstructor()->hasBody(FNTarget);
12851         assert(FNTarget && "Ctor cycle through bodiless function");
12852 
12853         C = const_cast<CXXConstructorDecl*>(
12854           cast<CXXConstructorDecl>(FNTarget));
12855         S.Diag(C->getLocation(), diag::note_which_delegates_to);
12856       }
12857     }
12858 
12859     Invalid.insert(Current.begin(), Current.end());
12860     Current.clear();
12861   } else {
12862     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12863   }
12864 }
12865 
12866 
12867 void Sema::CheckDelegatingCtorCycles() {
12868   llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12869 
12870   for (DelegatingCtorDeclsType::iterator
12871          I = DelegatingCtorDecls.begin(ExternalSource),
12872          E = DelegatingCtorDecls.end();
12873        I != E; ++I)
12874     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
12875 
12876   for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12877                                                          CE = Invalid.end();
12878        CI != CE; ++CI)
12879     (*CI)->setInvalidDecl();
12880 }
12881 
12882 namespace {
12883   /// \brief AST visitor that finds references to the 'this' expression.
12884   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12885     Sema &S;
12886 
12887   public:
12888     explicit FindCXXThisExpr(Sema &S) : S(S) { }
12889 
12890     bool VisitCXXThisExpr(CXXThisExpr *E) {
12891       S.Diag(E->getLocation(), diag::err_this_static_member_func)
12892         << E->isImplicit();
12893       return false;
12894     }
12895   };
12896 }
12897 
12898 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12899   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12900   if (!TSInfo)
12901     return false;
12902 
12903   TypeLoc TL = TSInfo->getTypeLoc();
12904   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
12905   if (!ProtoTL)
12906     return false;
12907 
12908   // C++11 [expr.prim.general]p3:
12909   //   [The expression this] shall not appear before the optional
12910   //   cv-qualifier-seq and it shall not appear within the declaration of a
12911   //   static member function (although its type and value category are defined
12912   //   within a static member function as they are within a non-static member
12913   //   function). [ Note: this is because declaration matching does not occur
12914   //  until the complete declarator is known. - end note ]
12915   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
12916   FindCXXThisExpr Finder(*this);
12917 
12918   // If the return type came after the cv-qualifier-seq, check it now.
12919   if (Proto->hasTrailingReturn() &&
12920       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
12921     return true;
12922 
12923   // Check the exception specification.
12924   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12925     return true;
12926 
12927   return checkThisInStaticMemberFunctionAttributes(Method);
12928 }
12929 
12930 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12931   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12932   if (!TSInfo)
12933     return false;
12934 
12935   TypeLoc TL = TSInfo->getTypeLoc();
12936   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
12937   if (!ProtoTL)
12938     return false;
12939 
12940   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
12941   FindCXXThisExpr Finder(*this);
12942 
12943   switch (Proto->getExceptionSpecType()) {
12944   case EST_Uninstantiated:
12945   case EST_Unevaluated:
12946   case EST_BasicNoexcept:
12947   case EST_DynamicNone:
12948   case EST_MSAny:
12949   case EST_None:
12950     break;
12951 
12952   case EST_ComputedNoexcept:
12953     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12954       return true;
12955 
12956   case EST_Dynamic:
12957     for (const auto &E : Proto->exceptions()) {
12958       if (!Finder.TraverseType(E))
12959         return true;
12960     }
12961     break;
12962   }
12963 
12964   return false;
12965 }
12966 
12967 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12968   FindCXXThisExpr Finder(*this);
12969 
12970   // Check attributes.
12971   for (const auto *A : Method->attrs()) {
12972     // FIXME: This should be emitted by tblgen.
12973     Expr *Arg = nullptr;
12974     ArrayRef<Expr *> Args;
12975     if (const auto *G = dyn_cast<GuardedByAttr>(A))
12976       Arg = G->getArg();
12977     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
12978       Arg = G->getArg();
12979     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
12980       Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12981     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
12982       Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12983     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
12984       Arg = ETLF->getSuccessValue();
12985       Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12986     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
12987       Arg = STLF->getSuccessValue();
12988       Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12989     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
12990       Arg = LR->getArg();
12991     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
12992       Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12993     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
12994       Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
12995     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
12996       Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
12997     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
12998       Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
12999     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
13000       Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
13001 
13002     if (Arg && !Finder.TraverseStmt(Arg))
13003       return true;
13004 
13005     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
13006       if (!Finder.TraverseStmt(Args[I]))
13007         return true;
13008     }
13009   }
13010 
13011   return false;
13012 }
13013 
13014 void
13015 Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
13016                                   ArrayRef<ParsedType> DynamicExceptions,
13017                                   ArrayRef<SourceRange> DynamicExceptionRanges,
13018                                   Expr *NoexceptExpr,
13019                                   SmallVectorImpl<QualType> &Exceptions,
13020                                   FunctionProtoType::ExceptionSpecInfo &ESI) {
13021   Exceptions.clear();
13022   ESI.Type = EST;
13023   if (EST == EST_Dynamic) {
13024     Exceptions.reserve(DynamicExceptions.size());
13025     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
13026       // FIXME: Preserve type source info.
13027       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
13028 
13029       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13030       collectUnexpandedParameterPacks(ET, Unexpanded);
13031       if (!Unexpanded.empty()) {
13032         DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
13033                                          UPPC_ExceptionType,
13034                                          Unexpanded);
13035         continue;
13036       }
13037 
13038       // Check that the type is valid for an exception spec, and
13039       // drop it if not.
13040       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
13041         Exceptions.push_back(ET);
13042     }
13043     ESI.Exceptions = Exceptions;
13044     return;
13045   }
13046 
13047   if (EST == EST_ComputedNoexcept) {
13048     // If an error occurred, there's no expression here.
13049     if (NoexceptExpr) {
13050       assert((NoexceptExpr->isTypeDependent() ||
13051               NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
13052               Context.BoolTy) &&
13053              "Parser should have made sure that the expression is boolean");
13054       if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
13055         ESI.Type = EST_BasicNoexcept;
13056         return;
13057       }
13058 
13059       if (!NoexceptExpr->isValueDependent())
13060         NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
13061                          diag::err_noexcept_needs_constant_expression,
13062                          /*AllowFold*/ false).get();
13063       ESI.NoexceptExpr = NoexceptExpr;
13064     }
13065     return;
13066   }
13067 }
13068 
13069 /// IdentifyCUDATarget - Determine the CUDA compilation target for this function
13070 Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
13071   // Implicitly declared functions (e.g. copy constructors) are
13072   // __host__ __device__
13073   if (D->isImplicit())
13074     return CFT_HostDevice;
13075 
13076   if (D->hasAttr<CUDAGlobalAttr>())
13077     return CFT_Global;
13078 
13079   if (D->hasAttr<CUDADeviceAttr>()) {
13080     if (D->hasAttr<CUDAHostAttr>())
13081       return CFT_HostDevice;
13082     return CFT_Device;
13083   }
13084 
13085   return CFT_Host;
13086 }
13087 
13088 bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
13089                            CUDAFunctionTarget CalleeTarget) {
13090   // CUDA B.1.1 "The __device__ qualifier declares a function that is...
13091   // Callable from the device only."
13092   if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
13093     return true;
13094 
13095   // CUDA B.1.2 "The __global__ qualifier declares a function that is...
13096   // Callable from the host only."
13097   // CUDA B.1.3 "The __host__ qualifier declares a function that is...
13098   // Callable from the host only."
13099   if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
13100       (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
13101     return true;
13102 
13103   if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
13104     return true;
13105 
13106   return false;
13107 }
13108 
13109 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
13110 ///
13111 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
13112                                        SourceLocation DeclStart,
13113                                        Declarator &D, Expr *BitWidth,
13114                                        InClassInitStyle InitStyle,
13115                                        AccessSpecifier AS,
13116                                        AttributeList *MSPropertyAttr) {
13117   IdentifierInfo *II = D.getIdentifier();
13118   if (!II) {
13119     Diag(DeclStart, diag::err_anonymous_property);
13120     return nullptr;
13121   }
13122   SourceLocation Loc = D.getIdentifierLoc();
13123 
13124   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13125   QualType T = TInfo->getType();
13126   if (getLangOpts().CPlusPlus) {
13127     CheckExtraCXXDefaultArguments(D);
13128 
13129     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13130                                         UPPC_DataMemberType)) {
13131       D.setInvalidType();
13132       T = Context.IntTy;
13133       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13134     }
13135   }
13136 
13137   DiagnoseFunctionSpecifiers(D.getDeclSpec());
13138 
13139   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13140     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13141          diag::err_invalid_thread)
13142       << DeclSpec::getSpecifierName(TSCS);
13143 
13144   // Check to see if this name was declared as a member previously
13145   NamedDecl *PrevDecl = nullptr;
13146   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13147   LookupName(Previous, S);
13148   switch (Previous.getResultKind()) {
13149   case LookupResult::Found:
13150   case LookupResult::FoundUnresolvedValue:
13151     PrevDecl = Previous.getAsSingle<NamedDecl>();
13152     break;
13153 
13154   case LookupResult::FoundOverloaded:
13155     PrevDecl = Previous.getRepresentativeDecl();
13156     break;
13157 
13158   case LookupResult::NotFound:
13159   case LookupResult::NotFoundInCurrentInstantiation:
13160   case LookupResult::Ambiguous:
13161     break;
13162   }
13163 
13164   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13165     // Maybe we will complain about the shadowed template parameter.
13166     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13167     // Just pretend that we didn't see the previous declaration.
13168     PrevDecl = nullptr;
13169   }
13170 
13171   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13172     PrevDecl = nullptr;
13173 
13174   SourceLocation TSSL = D.getLocStart();
13175   const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
13176   MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13177       Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
13178   ProcessDeclAttributes(TUScope, NewPD, D);
13179   NewPD->setAccess(AS);
13180 
13181   if (NewPD->isInvalidDecl())
13182     Record->setInvalidDecl();
13183 
13184   if (D.getDeclSpec().isModulePrivateSpecified())
13185     NewPD->setModulePrivate();
13186 
13187   if (NewPD->isInvalidDecl() && PrevDecl) {
13188     // Don't introduce NewFD into scope; there's already something
13189     // with the same name in the same scope.
13190   } else if (II) {
13191     PushOnScopeChains(NewPD, S);
13192   } else
13193     Record->addDecl(NewPD);
13194 
13195   return NewPD;
13196 }
13197