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().CPlusPlus1y
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().CPlusPlus1y
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().CPlusPlus1y)
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().CPlusPlus1y
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().CPlusPlus1y &&
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().CPlusPlus1y
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::SmallPtrSet<ValueDecl*, 4> &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::SmallPtrSet<ValueDecl*, 4> &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         if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0)))
2319           if (ICE->getCastKind() == CK_NoOp)
2320             if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr()))
2321               HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
2322 
2323       Inherited::VisitCXXConstructExpr(E);
2324     }
2325 
2326     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2327       Expr *Callee = E->getCallee();
2328       if (isa<MemberExpr>(Callee))
2329         HandleValue(Callee);
2330 
2331       Inherited::VisitCXXMemberCallExpr(E);
2332     }
2333 
2334     void VisitBinaryOperator(BinaryOperator *E) {
2335       // If a field assignment is detected, remove the field from the
2336       // uninitiailized field set.
2337       if (E->getOpcode() == BO_Assign)
2338         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2339           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2340             if (!FD->getType()->isReferenceType())
2341               Decls.erase(FD);
2342 
2343       Inherited::VisitBinaryOperator(E);
2344     }
2345   };
2346   static void CheckInitExprContainsUninitializedFields(
2347       Sema &S, Expr *E, llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
2348       const CXXConstructorDecl *Constructor) {
2349     if (Decls.size() == 0)
2350       return;
2351 
2352     if (!E)
2353       return;
2354 
2355     if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(E)) {
2356       E = Default->getExpr();
2357       if (!E)
2358         return;
2359       // In class initializers will point to the constructor.
2360       UninitializedFieldVisitor(S, Decls, Constructor).Visit(E);
2361     } else {
2362       UninitializedFieldVisitor(S, Decls, nullptr).Visit(E);
2363     }
2364   }
2365 
2366   // Diagnose value-uses of fields to initialize themselves, e.g.
2367   //   foo(foo)
2368   // where foo is not also a parameter to the constructor.
2369   // Also diagnose across field uninitialized use such as
2370   //   x(y), y(x)
2371   // TODO: implement -Wuninitialized and fold this into that framework.
2372   static void DiagnoseUninitializedFields(
2373       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2374 
2375     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
2376                                            Constructor->getLocation())) {
2377       return;
2378     }
2379 
2380     if (Constructor->isInvalidDecl())
2381       return;
2382 
2383     const CXXRecordDecl *RD = Constructor->getParent();
2384 
2385     // Holds fields that are uninitialized.
2386     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2387 
2388     // At the beginning, all fields are uninitialized.
2389     for (auto *I : RD->decls()) {
2390       if (auto *FD = dyn_cast<FieldDecl>(I)) {
2391         UninitializedFields.insert(FD);
2392       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
2393         UninitializedFields.insert(IFD->getAnonField());
2394       }
2395     }
2396 
2397     for (const auto *FieldInit : Constructor->inits()) {
2398       Expr *InitExpr = FieldInit->getInit();
2399 
2400       CheckInitExprContainsUninitializedFields(
2401           SemaRef, InitExpr, UninitializedFields, Constructor);
2402 
2403       if (FieldDecl *Field = FieldInit->getAnyMember())
2404         UninitializedFields.erase(Field);
2405     }
2406   }
2407 } // namespace
2408 
2409 /// \brief Enter a new C++ default initializer scope. After calling this, the
2410 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2411 /// parsing or instantiating the initializer failed.
2412 void Sema::ActOnStartCXXInClassMemberInitializer() {
2413   // Create a synthetic function scope to represent the call to the constructor
2414   // that notionally surrounds a use of this initializer.
2415   PushFunctionScope();
2416 }
2417 
2418 /// \brief This is invoked after parsing an in-class initializer for a
2419 /// non-static C++ class member, and after instantiating an in-class initializer
2420 /// in a class template. Such actions are deferred until the class is complete.
2421 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2422                                                   SourceLocation InitLoc,
2423                                                   Expr *InitExpr) {
2424   // Pop the notional constructor scope we created earlier.
2425   PopFunctionScopeInfo(nullptr, D);
2426 
2427   FieldDecl *FD = cast<FieldDecl>(D);
2428   assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2429          "must set init style when field is created");
2430 
2431   if (!InitExpr) {
2432     FD->setInvalidDecl();
2433     FD->removeInClassInitializer();
2434     return;
2435   }
2436 
2437   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2438     FD->setInvalidDecl();
2439     FD->removeInClassInitializer();
2440     return;
2441   }
2442 
2443   ExprResult Init = InitExpr;
2444   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
2445     InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
2446     InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
2447         ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
2448         : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
2449     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2450     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
2451     if (Init.isInvalid()) {
2452       FD->setInvalidDecl();
2453       return;
2454     }
2455   }
2456 
2457   // C++11 [class.base.init]p7:
2458   //   The initialization of each base and member constitutes a
2459   //   full-expression.
2460   Init = ActOnFinishFullExpr(Init.get(), InitLoc);
2461   if (Init.isInvalid()) {
2462     FD->setInvalidDecl();
2463     return;
2464   }
2465 
2466   InitExpr = Init.get();
2467 
2468   FD->setInClassInitializer(InitExpr);
2469 }
2470 
2471 /// \brief Find the direct and/or virtual base specifiers that
2472 /// correspond to the given base type, for use in base initialization
2473 /// within a constructor.
2474 static bool FindBaseInitializer(Sema &SemaRef,
2475                                 CXXRecordDecl *ClassDecl,
2476                                 QualType BaseType,
2477                                 const CXXBaseSpecifier *&DirectBaseSpec,
2478                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
2479   // First, check for a direct base class.
2480   DirectBaseSpec = nullptr;
2481   for (const auto &Base : ClassDecl->bases()) {
2482     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
2483       // We found a direct base of this type. That's what we're
2484       // initializing.
2485       DirectBaseSpec = &Base;
2486       break;
2487     }
2488   }
2489 
2490   // Check for a virtual base class.
2491   // FIXME: We might be able to short-circuit this if we know in advance that
2492   // there are no virtual bases.
2493   VirtualBaseSpec = nullptr;
2494   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2495     // We haven't found a base yet; search the class hierarchy for a
2496     // virtual base class.
2497     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2498                        /*DetectVirtual=*/false);
2499     if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2500                               BaseType, Paths)) {
2501       for (CXXBasePaths::paths_iterator Path = Paths.begin();
2502            Path != Paths.end(); ++Path) {
2503         if (Path->back().Base->isVirtual()) {
2504           VirtualBaseSpec = Path->back().Base;
2505           break;
2506         }
2507       }
2508     }
2509   }
2510 
2511   return DirectBaseSpec || VirtualBaseSpec;
2512 }
2513 
2514 /// \brief Handle a C++ member initializer using braced-init-list syntax.
2515 MemInitResult
2516 Sema::ActOnMemInitializer(Decl *ConstructorD,
2517                           Scope *S,
2518                           CXXScopeSpec &SS,
2519                           IdentifierInfo *MemberOrBase,
2520                           ParsedType TemplateTypeTy,
2521                           const DeclSpec &DS,
2522                           SourceLocation IdLoc,
2523                           Expr *InitList,
2524                           SourceLocation EllipsisLoc) {
2525   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2526                              DS, IdLoc, InitList,
2527                              EllipsisLoc);
2528 }
2529 
2530 /// \brief Handle a C++ member initializer using parentheses syntax.
2531 MemInitResult
2532 Sema::ActOnMemInitializer(Decl *ConstructorD,
2533                           Scope *S,
2534                           CXXScopeSpec &SS,
2535                           IdentifierInfo *MemberOrBase,
2536                           ParsedType TemplateTypeTy,
2537                           const DeclSpec &DS,
2538                           SourceLocation IdLoc,
2539                           SourceLocation LParenLoc,
2540                           ArrayRef<Expr *> Args,
2541                           SourceLocation RParenLoc,
2542                           SourceLocation EllipsisLoc) {
2543   Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2544                                            Args, RParenLoc);
2545   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2546                              DS, IdLoc, List, EllipsisLoc);
2547 }
2548 
2549 namespace {
2550 
2551 // Callback to only accept typo corrections that can be a valid C++ member
2552 // intializer: either a non-static field member or a base class.
2553 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2554 public:
2555   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2556       : ClassDecl(ClassDecl) {}
2557 
2558   bool ValidateCandidate(const TypoCorrection &candidate) override {
2559     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2560       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2561         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2562       return isa<TypeDecl>(ND);
2563     }
2564     return false;
2565   }
2566 
2567 private:
2568   CXXRecordDecl *ClassDecl;
2569 };
2570 
2571 }
2572 
2573 /// \brief Handle a C++ member initializer.
2574 MemInitResult
2575 Sema::BuildMemInitializer(Decl *ConstructorD,
2576                           Scope *S,
2577                           CXXScopeSpec &SS,
2578                           IdentifierInfo *MemberOrBase,
2579                           ParsedType TemplateTypeTy,
2580                           const DeclSpec &DS,
2581                           SourceLocation IdLoc,
2582                           Expr *Init,
2583                           SourceLocation EllipsisLoc) {
2584   if (!ConstructorD)
2585     return true;
2586 
2587   AdjustDeclIfTemplate(ConstructorD);
2588 
2589   CXXConstructorDecl *Constructor
2590     = dyn_cast<CXXConstructorDecl>(ConstructorD);
2591   if (!Constructor) {
2592     // The user wrote a constructor initializer on a function that is
2593     // not a C++ constructor. Ignore the error for now, because we may
2594     // have more member initializers coming; we'll diagnose it just
2595     // once in ActOnMemInitializers.
2596     return true;
2597   }
2598 
2599   CXXRecordDecl *ClassDecl = Constructor->getParent();
2600 
2601   // C++ [class.base.init]p2:
2602   //   Names in a mem-initializer-id are looked up in the scope of the
2603   //   constructor's class and, if not found in that scope, are looked
2604   //   up in the scope containing the constructor's definition.
2605   //   [Note: if the constructor's class contains a member with the
2606   //   same name as a direct or virtual base class of the class, a
2607   //   mem-initializer-id naming the member or base class and composed
2608   //   of a single identifier refers to the class member. A
2609   //   mem-initializer-id for the hidden base class may be specified
2610   //   using a qualified name. ]
2611   if (!SS.getScopeRep() && !TemplateTypeTy) {
2612     // Look for a member, first.
2613     DeclContext::lookup_result Result
2614       = ClassDecl->lookup(MemberOrBase);
2615     if (!Result.empty()) {
2616       ValueDecl *Member;
2617       if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2618           (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
2619         if (EllipsisLoc.isValid())
2620           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
2621             << MemberOrBase
2622             << SourceRange(IdLoc, Init->getSourceRange().getEnd());
2623 
2624         return BuildMemberInitializer(Member, Init, IdLoc);
2625       }
2626     }
2627   }
2628   // It didn't name a member, so see if it names a class.
2629   QualType BaseType;
2630   TypeSourceInfo *TInfo = nullptr;
2631 
2632   if (TemplateTypeTy) {
2633     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
2634   } else if (DS.getTypeSpecType() == TST_decltype) {
2635     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
2636   } else {
2637     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2638     LookupParsedName(R, S, &SS);
2639 
2640     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2641     if (!TyD) {
2642       if (R.isAmbiguous()) return true;
2643 
2644       // We don't want access-control diagnostics here.
2645       R.suppressDiagnostics();
2646 
2647       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2648         bool NotUnknownSpecialization = false;
2649         DeclContext *DC = computeDeclContext(SS, false);
2650         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2651           NotUnknownSpecialization = !Record->hasAnyDependentBases();
2652 
2653         if (!NotUnknownSpecialization) {
2654           // When the scope specifier can refer to a member of an unknown
2655           // specialization, we take it as a type name.
2656           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2657                                        SS.getWithLocInContext(Context),
2658                                        *MemberOrBase, IdLoc);
2659           if (BaseType.isNull())
2660             return true;
2661 
2662           R.clear();
2663           R.setLookupName(MemberOrBase);
2664         }
2665       }
2666 
2667       // If no results were found, try to correct typos.
2668       TypoCorrection Corr;
2669       MemInitializerValidatorCCC Validator(ClassDecl);
2670       if (R.empty() && BaseType.isNull() &&
2671           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2672                               Validator, CTK_ErrorRecovery, ClassDecl))) {
2673         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
2674           // We have found a non-static data member with a similar
2675           // name to what was typed; complain and initialize that
2676           // member.
2677           diagnoseTypo(Corr,
2678                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
2679                          << MemberOrBase << true);
2680           return BuildMemberInitializer(Member, Init, IdLoc);
2681         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
2682           const CXXBaseSpecifier *DirectBaseSpec;
2683           const CXXBaseSpecifier *VirtualBaseSpec;
2684           if (FindBaseInitializer(*this, ClassDecl,
2685                                   Context.getTypeDeclType(Type),
2686                                   DirectBaseSpec, VirtualBaseSpec)) {
2687             // We have found a direct or virtual base class with a
2688             // similar name to what was typed; complain and initialize
2689             // that base class.
2690             diagnoseTypo(Corr,
2691                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
2692                            << MemberOrBase << false,
2693                          PDiag() /*Suppress note, we provide our own.*/);
2694 
2695             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2696                                                               : VirtualBaseSpec;
2697             Diag(BaseSpec->getLocStart(),
2698                  diag::note_base_class_specified_here)
2699               << BaseSpec->getType()
2700               << BaseSpec->getSourceRange();
2701 
2702             TyD = Type;
2703           }
2704         }
2705       }
2706 
2707       if (!TyD && BaseType.isNull()) {
2708         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
2709           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
2710         return true;
2711       }
2712     }
2713 
2714     if (BaseType.isNull()) {
2715       BaseType = Context.getTypeDeclType(TyD);
2716       if (SS.isSet())
2717         // FIXME: preserve source range information
2718         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2719                                              BaseType);
2720     }
2721   }
2722 
2723   if (!TInfo)
2724     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
2725 
2726   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
2727 }
2728 
2729 /// Checks a member initializer expression for cases where reference (or
2730 /// pointer) members are bound to by-value parameters (or their addresses).
2731 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2732                                                Expr *Init,
2733                                                SourceLocation IdLoc) {
2734   QualType MemberTy = Member->getType();
2735 
2736   // We only handle pointers and references currently.
2737   // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2738   if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2739     return;
2740 
2741   const bool IsPointer = MemberTy->isPointerType();
2742   if (IsPointer) {
2743     if (const UnaryOperator *Op
2744           = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2745       // The only case we're worried about with pointers requires taking the
2746       // address.
2747       if (Op->getOpcode() != UO_AddrOf)
2748         return;
2749 
2750       Init = Op->getSubExpr();
2751     } else {
2752       // We only handle address-of expression initializers for pointers.
2753       return;
2754     }
2755   }
2756 
2757   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2758     // We only warn when referring to a non-reference parameter declaration.
2759     const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2760     if (!Parameter || Parameter->getType()->isReferenceType())
2761       return;
2762 
2763     S.Diag(Init->getExprLoc(),
2764            IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2765                      : diag::warn_bind_ref_member_to_parameter)
2766       << Member << Parameter << Init->getSourceRange();
2767   } else {
2768     // Other initializers are fine.
2769     return;
2770   }
2771 
2772   S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2773     << (unsigned)IsPointer;
2774 }
2775 
2776 MemInitResult
2777 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
2778                              SourceLocation IdLoc) {
2779   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2780   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2781   assert((DirectMember || IndirectMember) &&
2782          "Member must be a FieldDecl or IndirectFieldDecl");
2783 
2784   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2785     return true;
2786 
2787   if (Member->isInvalidDecl())
2788     return true;
2789 
2790   MultiExprArg Args;
2791   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2792     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2793   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2794     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
2795   } else {
2796     // Template instantiation doesn't reconstruct ParenListExprs for us.
2797     Args = Init;
2798   }
2799 
2800   SourceRange InitRange = Init->getSourceRange();
2801 
2802   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
2803     // Can't check initialization for a member of dependent type or when
2804     // any of the arguments are type-dependent expressions.
2805     DiscardCleanupsInEvaluationContext();
2806   } else {
2807     bool InitList = false;
2808     if (isa<InitListExpr>(Init)) {
2809       InitList = true;
2810       Args = Init;
2811     }
2812 
2813     // Initialize the member.
2814     InitializedEntity MemberEntity =
2815       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
2816                    : InitializedEntity::InitializeMember(IndirectMember,
2817                                                          nullptr);
2818     InitializationKind Kind =
2819       InitList ? InitializationKind::CreateDirectList(IdLoc)
2820                : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2821                                                   InitRange.getEnd());
2822 
2823     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2824     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
2825                                             nullptr);
2826     if (MemberInit.isInvalid())
2827       return true;
2828 
2829     CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2830 
2831     // C++11 [class.base.init]p7:
2832     //   The initialization of each base and member constitutes a
2833     //   full-expression.
2834     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
2835     if (MemberInit.isInvalid())
2836       return true;
2837 
2838     Init = MemberInit.get();
2839   }
2840 
2841   if (DirectMember) {
2842     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2843                                             InitRange.getBegin(), Init,
2844                                             InitRange.getEnd());
2845   } else {
2846     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2847                                             InitRange.getBegin(), Init,
2848                                             InitRange.getEnd());
2849   }
2850 }
2851 
2852 MemInitResult
2853 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
2854                                  CXXRecordDecl *ClassDecl) {
2855   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
2856   if (!LangOpts.CPlusPlus11)
2857     return Diag(NameLoc, diag::err_delegating_ctor)
2858       << TInfo->getTypeLoc().getLocalSourceRange();
2859   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
2860 
2861   bool InitList = true;
2862   MultiExprArg Args = Init;
2863   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2864     InitList = false;
2865     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2866   }
2867 
2868   SourceRange InitRange = Init->getSourceRange();
2869   // Initialize the object.
2870   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2871                                      QualType(ClassDecl->getTypeForDecl(), 0));
2872   InitializationKind Kind =
2873     InitList ? InitializationKind::CreateDirectList(NameLoc)
2874              : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2875                                                 InitRange.getEnd());
2876   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
2877   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2878                                               Args, nullptr);
2879   if (DelegationInit.isInvalid())
2880     return true;
2881 
2882   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2883          "Delegating constructor with no target?");
2884 
2885   // C++11 [class.base.init]p7:
2886   //   The initialization of each base and member constitutes a
2887   //   full-expression.
2888   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2889                                        InitRange.getBegin());
2890   if (DelegationInit.isInvalid())
2891     return true;
2892 
2893   // If we are in a dependent context, template instantiation will
2894   // perform this type-checking again. Just save the arguments that we
2895   // received in a ParenListExpr.
2896   // FIXME: This isn't quite ideal, since our ASTs don't capture all
2897   // of the information that we have about the base
2898   // initializer. However, deconstructing the ASTs is a dicey process,
2899   // and this approach is far more likely to get the corner cases right.
2900   if (CurContext->isDependentContext())
2901     DelegationInit = Init;
2902 
2903   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
2904                                           DelegationInit.getAs<Expr>(),
2905                                           InitRange.getEnd());
2906 }
2907 
2908 MemInitResult
2909 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
2910                            Expr *Init, CXXRecordDecl *ClassDecl,
2911                            SourceLocation EllipsisLoc) {
2912   SourceLocation BaseLoc
2913     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
2914 
2915   if (!BaseType->isDependentType() && !BaseType->isRecordType())
2916     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2917              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2918 
2919   // C++ [class.base.init]p2:
2920   //   [...] Unless the mem-initializer-id names a nonstatic data
2921   //   member of the constructor's class or a direct or virtual base
2922   //   of that class, the mem-initializer is ill-formed. A
2923   //   mem-initializer-list can initialize a base class using any
2924   //   name that denotes that base class type.
2925   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
2926 
2927   SourceRange InitRange = Init->getSourceRange();
2928   if (EllipsisLoc.isValid()) {
2929     // This is a pack expansion.
2930     if (!BaseType->containsUnexpandedParameterPack())  {
2931       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2932         << SourceRange(BaseLoc, InitRange.getEnd());
2933 
2934       EllipsisLoc = SourceLocation();
2935     }
2936   } else {
2937     // Check for any unexpanded parameter packs.
2938     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2939       return true;
2940 
2941     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2942       return true;
2943   }
2944 
2945   // Check for direct and virtual base classes.
2946   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
2947   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
2948   if (!Dependent) {
2949     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2950                                        BaseType))
2951       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
2952 
2953     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2954                         VirtualBaseSpec);
2955 
2956     // C++ [base.class.init]p2:
2957     // Unless the mem-initializer-id names a nonstatic data member of the
2958     // constructor's class or a direct or virtual base of that class, the
2959     // mem-initializer is ill-formed.
2960     if (!DirectBaseSpec && !VirtualBaseSpec) {
2961       // If the class has any dependent bases, then it's possible that
2962       // one of those types will resolve to the same type as
2963       // BaseType. Therefore, just treat this as a dependent base
2964       // class initialization.  FIXME: Should we try to check the
2965       // initialization anyway? It seems odd.
2966       if (ClassDecl->hasAnyDependentBases())
2967         Dependent = true;
2968       else
2969         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2970           << BaseType << Context.getTypeDeclType(ClassDecl)
2971           << BaseTInfo->getTypeLoc().getLocalSourceRange();
2972     }
2973   }
2974 
2975   if (Dependent) {
2976     DiscardCleanupsInEvaluationContext();
2977 
2978     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2979                                             /*IsVirtual=*/false,
2980                                             InitRange.getBegin(), Init,
2981                                             InitRange.getEnd(), EllipsisLoc);
2982   }
2983 
2984   // C++ [base.class.init]p2:
2985   //   If a mem-initializer-id is ambiguous because it designates both
2986   //   a direct non-virtual base class and an inherited virtual base
2987   //   class, the mem-initializer is ill-formed.
2988   if (DirectBaseSpec && VirtualBaseSpec)
2989     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
2990       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2991 
2992   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
2993   if (!BaseSpec)
2994     BaseSpec = VirtualBaseSpec;
2995 
2996   // Initialize the base.
2997   bool InitList = true;
2998   MultiExprArg Args = Init;
2999   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3000     InitList = false;
3001     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3002   }
3003 
3004   InitializedEntity BaseEntity =
3005     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
3006   InitializationKind Kind =
3007     InitList ? InitializationKind::CreateDirectList(BaseLoc)
3008              : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
3009                                                 InitRange.getEnd());
3010   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
3011   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
3012   if (BaseInit.isInvalid())
3013     return true;
3014 
3015   // C++11 [class.base.init]p7:
3016   //   The initialization of each base and member constitutes a
3017   //   full-expression.
3018   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
3019   if (BaseInit.isInvalid())
3020     return true;
3021 
3022   // If we are in a dependent context, template instantiation will
3023   // perform this type-checking again. Just save the arguments that we
3024   // received in a ParenListExpr.
3025   // FIXME: This isn't quite ideal, since our ASTs don't capture all
3026   // of the information that we have about the base
3027   // initializer. However, deconstructing the ASTs is a dicey process,
3028   // and this approach is far more likely to get the corner cases right.
3029   if (CurContext->isDependentContext())
3030     BaseInit = Init;
3031 
3032   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3033                                           BaseSpec->isVirtual(),
3034                                           InitRange.getBegin(),
3035                                           BaseInit.getAs<Expr>(),
3036                                           InitRange.getEnd(), EllipsisLoc);
3037 }
3038 
3039 // Create a static_cast\<T&&>(expr).
3040 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
3041   if (T.isNull()) T = E->getType();
3042   QualType TargetType = SemaRef.BuildReferenceType(
3043       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
3044   SourceLocation ExprLoc = E->getLocStart();
3045   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
3046       TargetType, ExprLoc);
3047 
3048   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
3049                                    SourceRange(ExprLoc, ExprLoc),
3050                                    E->getSourceRange()).get();
3051 }
3052 
3053 /// ImplicitInitializerKind - How an implicit base or member initializer should
3054 /// initialize its base or member.
3055 enum ImplicitInitializerKind {
3056   IIK_Default,
3057   IIK_Copy,
3058   IIK_Move,
3059   IIK_Inherit
3060 };
3061 
3062 static bool
3063 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3064                              ImplicitInitializerKind ImplicitInitKind,
3065                              CXXBaseSpecifier *BaseSpec,
3066                              bool IsInheritedVirtualBase,
3067                              CXXCtorInitializer *&CXXBaseInit) {
3068   InitializedEntity InitEntity
3069     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3070                                         IsInheritedVirtualBase);
3071 
3072   ExprResult BaseInit;
3073 
3074   switch (ImplicitInitKind) {
3075   case IIK_Inherit: {
3076     const CXXRecordDecl *Inherited =
3077         Constructor->getInheritedConstructor()->getParent();
3078     const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3079     if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3080       // C++11 [class.inhctor]p8:
3081       //   Each expression in the expression-list is of the form
3082       //   static_cast<T&&>(p), where p is the name of the corresponding
3083       //   constructor parameter and T is the declared type of p.
3084       SmallVector<Expr*, 16> Args;
3085       for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3086         ParmVarDecl *PD = Constructor->getParamDecl(I);
3087         ExprResult ArgExpr =
3088             SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3089                                      VK_LValue, SourceLocation());
3090         if (ArgExpr.isInvalid())
3091           return true;
3092         Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
3093       }
3094 
3095       InitializationKind InitKind = InitializationKind::CreateDirect(
3096           Constructor->getLocation(), SourceLocation(), SourceLocation());
3097       InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
3098       BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3099       break;
3100     }
3101   }
3102   // Fall through.
3103   case IIK_Default: {
3104     InitializationKind InitKind
3105       = InitializationKind::CreateDefault(Constructor->getLocation());
3106     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3107     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3108     break;
3109   }
3110 
3111   case IIK_Move:
3112   case IIK_Copy: {
3113     bool Moving = ImplicitInitKind == IIK_Move;
3114     ParmVarDecl *Param = Constructor->getParamDecl(0);
3115     QualType ParamType = Param->getType().getNonReferenceType();
3116 
3117     Expr *CopyCtorArg =
3118       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3119                           SourceLocation(), Param, false,
3120                           Constructor->getLocation(), ParamType,
3121                           VK_LValue, nullptr);
3122 
3123     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3124 
3125     // Cast to the base class to avoid ambiguities.
3126     QualType ArgTy =
3127       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3128                                        ParamType.getQualifiers());
3129 
3130     if (Moving) {
3131       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3132     }
3133 
3134     CXXCastPath BasePath;
3135     BasePath.push_back(BaseSpec);
3136     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3137                                             CK_UncheckedDerivedToBase,
3138                                             Moving ? VK_XValue : VK_LValue,
3139                                             &BasePath).get();
3140 
3141     InitializationKind InitKind
3142       = InitializationKind::CreateDirect(Constructor->getLocation(),
3143                                          SourceLocation(), SourceLocation());
3144     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3145     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
3146     break;
3147   }
3148   }
3149 
3150   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
3151   if (BaseInit.isInvalid())
3152     return true;
3153 
3154   CXXBaseInit =
3155     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3156                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3157                                                         SourceLocation()),
3158                                              BaseSpec->isVirtual(),
3159                                              SourceLocation(),
3160                                              BaseInit.getAs<Expr>(),
3161                                              SourceLocation(),
3162                                              SourceLocation());
3163 
3164   return false;
3165 }
3166 
3167 static bool RefersToRValueRef(Expr *MemRef) {
3168   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3169   return Referenced->getType()->isRValueReferenceType();
3170 }
3171 
3172 static bool
3173 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3174                                ImplicitInitializerKind ImplicitInitKind,
3175                                FieldDecl *Field, IndirectFieldDecl *Indirect,
3176                                CXXCtorInitializer *&CXXMemberInit) {
3177   if (Field->isInvalidDecl())
3178     return true;
3179 
3180   SourceLocation Loc = Constructor->getLocation();
3181 
3182   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3183     bool Moving = ImplicitInitKind == IIK_Move;
3184     ParmVarDecl *Param = Constructor->getParamDecl(0);
3185     QualType ParamType = Param->getType().getNonReferenceType();
3186 
3187     // Suppress copying zero-width bitfields.
3188     if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3189       return false;
3190 
3191     Expr *MemberExprBase =
3192       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3193                           SourceLocation(), Param, false,
3194                           Loc, ParamType, VK_LValue, nullptr);
3195 
3196     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3197 
3198     if (Moving) {
3199       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3200     }
3201 
3202     // Build a reference to this field within the parameter.
3203     CXXScopeSpec SS;
3204     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3205                               Sema::LookupMemberName);
3206     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3207                                   : cast<ValueDecl>(Field), AS_public);
3208     MemberLookup.resolveKind();
3209     ExprResult CtorArg
3210       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
3211                                          ParamType, Loc,
3212                                          /*IsArrow=*/false,
3213                                          SS,
3214                                          /*TemplateKWLoc=*/SourceLocation(),
3215                                          /*FirstQualifierInScope=*/nullptr,
3216                                          MemberLookup,
3217                                          /*TemplateArgs=*/nullptr);
3218     if (CtorArg.isInvalid())
3219       return true;
3220 
3221     // C++11 [class.copy]p15:
3222     //   - if a member m has rvalue reference type T&&, it is direct-initialized
3223     //     with static_cast<T&&>(x.m);
3224     if (RefersToRValueRef(CtorArg.get())) {
3225       CtorArg = CastForMoving(SemaRef, CtorArg.get());
3226     }
3227 
3228     // When the field we are copying is an array, create index variables for
3229     // each dimension of the array. We use these index variables to subscript
3230     // the source array, and other clients (e.g., CodeGen) will perform the
3231     // necessary iteration with these index variables.
3232     SmallVector<VarDecl *, 4> IndexVariables;
3233     QualType BaseType = Field->getType();
3234     QualType SizeType = SemaRef.Context.getSizeType();
3235     bool InitializingArray = false;
3236     while (const ConstantArrayType *Array
3237                           = SemaRef.Context.getAsConstantArrayType(BaseType)) {
3238       InitializingArray = true;
3239       // Create the iteration variable for this array index.
3240       IdentifierInfo *IterationVarName = nullptr;
3241       {
3242         SmallString<8> Str;
3243         llvm::raw_svector_ostream OS(Str);
3244         OS << "__i" << IndexVariables.size();
3245         IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3246       }
3247       VarDecl *IterationVar
3248         = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
3249                           IterationVarName, SizeType,
3250                         SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
3251                           SC_None);
3252       IndexVariables.push_back(IterationVar);
3253 
3254       // Create a reference to the iteration variable.
3255       ExprResult IterationVarRef
3256         = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
3257       assert(!IterationVarRef.isInvalid() &&
3258              "Reference to invented variable cannot fail!");
3259       IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
3260       assert(!IterationVarRef.isInvalid() &&
3261              "Conversion of invented variable cannot fail!");
3262 
3263       // Subscript the array with this iteration variable.
3264       CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3265                                                         IterationVarRef.get(),
3266                                                         Loc);
3267       if (CtorArg.isInvalid())
3268         return true;
3269 
3270       BaseType = Array->getElementType();
3271     }
3272 
3273     // The array subscript expression is an lvalue, which is wrong for moving.
3274     if (Moving && InitializingArray)
3275       CtorArg = CastForMoving(SemaRef, CtorArg.get());
3276 
3277     // Construct the entity that we will be initializing. For an array, this
3278     // will be first element in the array, which may require several levels
3279     // of array-subscript entities.
3280     SmallVector<InitializedEntity, 4> Entities;
3281     Entities.reserve(1 + IndexVariables.size());
3282     if (Indirect)
3283       Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3284     else
3285       Entities.push_back(InitializedEntity::InitializeMember(Field));
3286     for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3287       Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3288                                                               0,
3289                                                               Entities.back()));
3290 
3291     // Direct-initialize to use the copy constructor.
3292     InitializationKind InitKind =
3293       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3294 
3295     Expr *CtorArgE = CtorArg.getAs<Expr>();
3296     InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
3297 
3298     ExprResult MemberInit
3299       = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
3300                         MultiExprArg(&CtorArgE, 1));
3301     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3302     if (MemberInit.isInvalid())
3303       return true;
3304 
3305     if (Indirect) {
3306       assert(IndexVariables.size() == 0 &&
3307              "Indirect field improperly initialized");
3308       CXXMemberInit
3309         = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3310                                                    Loc, Loc,
3311                                                    MemberInit.getAs<Expr>(),
3312                                                    Loc);
3313     } else
3314       CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3315                                                  Loc, MemberInit.getAs<Expr>(),
3316                                                  Loc,
3317                                                  IndexVariables.data(),
3318                                                  IndexVariables.size());
3319     return false;
3320   }
3321 
3322   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3323          "Unhandled implicit init kind!");
3324 
3325   QualType FieldBaseElementType =
3326     SemaRef.Context.getBaseElementType(Field->getType());
3327 
3328   if (FieldBaseElementType->isRecordType()) {
3329     InitializedEntity InitEntity
3330       = Indirect? InitializedEntity::InitializeMember(Indirect)
3331                 : InitializedEntity::InitializeMember(Field);
3332     InitializationKind InitKind =
3333       InitializationKind::CreateDefault(Loc);
3334 
3335     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3336     ExprResult MemberInit =
3337       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3338 
3339     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3340     if (MemberInit.isInvalid())
3341       return true;
3342 
3343     if (Indirect)
3344       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3345                                                                Indirect, Loc,
3346                                                                Loc,
3347                                                                MemberInit.get(),
3348                                                                Loc);
3349     else
3350       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3351                                                                Field, Loc, Loc,
3352                                                                MemberInit.get(),
3353                                                                Loc);
3354     return false;
3355   }
3356 
3357   if (!Field->getParent()->isUnion()) {
3358     if (FieldBaseElementType->isReferenceType()) {
3359       SemaRef.Diag(Constructor->getLocation(),
3360                    diag::err_uninitialized_member_in_ctor)
3361       << (int)Constructor->isImplicit()
3362       << SemaRef.Context.getTagDeclType(Constructor->getParent())
3363       << 0 << Field->getDeclName();
3364       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3365       return true;
3366     }
3367 
3368     if (FieldBaseElementType.isConstQualified()) {
3369       SemaRef.Diag(Constructor->getLocation(),
3370                    diag::err_uninitialized_member_in_ctor)
3371       << (int)Constructor->isImplicit()
3372       << SemaRef.Context.getTagDeclType(Constructor->getParent())
3373       << 1 << Field->getDeclName();
3374       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3375       return true;
3376     }
3377   }
3378 
3379   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
3380       FieldBaseElementType->isObjCRetainableType() &&
3381       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3382       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
3383     // ARC:
3384     //   Default-initialize Objective-C pointers to NULL.
3385     CXXMemberInit
3386       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3387                                                  Loc, Loc,
3388                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3389                                                  Loc);
3390     return false;
3391   }
3392 
3393   // Nothing to initialize.
3394   CXXMemberInit = nullptr;
3395   return false;
3396 }
3397 
3398 namespace {
3399 struct BaseAndFieldInfo {
3400   Sema &S;
3401   CXXConstructorDecl *Ctor;
3402   bool AnyErrorsInInits;
3403   ImplicitInitializerKind IIK;
3404   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
3405   SmallVector<CXXCtorInitializer*, 8> AllToInit;
3406   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
3407 
3408   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3409     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
3410     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3411     if (Generated && Ctor->isCopyConstructor())
3412       IIK = IIK_Copy;
3413     else if (Generated && Ctor->isMoveConstructor())
3414       IIK = IIK_Move;
3415     else if (Ctor->getInheritedConstructor())
3416       IIK = IIK_Inherit;
3417     else
3418       IIK = IIK_Default;
3419   }
3420 
3421   bool isImplicitCopyOrMove() const {
3422     switch (IIK) {
3423     case IIK_Copy:
3424     case IIK_Move:
3425       return true;
3426 
3427     case IIK_Default:
3428     case IIK_Inherit:
3429       return false;
3430     }
3431 
3432     llvm_unreachable("Invalid ImplicitInitializerKind!");
3433   }
3434 
3435   bool addFieldInitializer(CXXCtorInitializer *Init) {
3436     AllToInit.push_back(Init);
3437 
3438     // Check whether this initializer makes the field "used".
3439     if (Init->getInit()->HasSideEffects(S.Context))
3440       S.UnusedPrivateFields.remove(Init->getAnyMember());
3441 
3442     return false;
3443   }
3444 
3445   bool isInactiveUnionMember(FieldDecl *Field) {
3446     RecordDecl *Record = Field->getParent();
3447     if (!Record->isUnion())
3448       return false;
3449 
3450     if (FieldDecl *Active =
3451             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
3452       return Active != Field->getCanonicalDecl();
3453 
3454     // In an implicit copy or move constructor, ignore any in-class initializer.
3455     if (isImplicitCopyOrMove())
3456       return true;
3457 
3458     // If there's no explicit initialization, the field is active only if it
3459     // has an in-class initializer...
3460     if (Field->hasInClassInitializer())
3461       return false;
3462     // ... or it's an anonymous struct or union whose class has an in-class
3463     // initializer.
3464     if (!Field->isAnonymousStructOrUnion())
3465       return true;
3466     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3467     return !FieldRD->hasInClassInitializer();
3468   }
3469 
3470   /// \brief Determine whether the given field is, or is within, a union member
3471   /// that is inactive (because there was an initializer given for a different
3472   /// member of the union, or because the union was not initialized at all).
3473   bool isWithinInactiveUnionMember(FieldDecl *Field,
3474                                    IndirectFieldDecl *Indirect) {
3475     if (!Indirect)
3476       return isInactiveUnionMember(Field);
3477 
3478     for (auto *C : Indirect->chain()) {
3479       FieldDecl *Field = dyn_cast<FieldDecl>(C);
3480       if (Field && isInactiveUnionMember(Field))
3481         return true;
3482     }
3483     return false;
3484   }
3485 };
3486 }
3487 
3488 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
3489 /// array type.
3490 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3491   if (T->isIncompleteArrayType())
3492     return true;
3493 
3494   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3495     if (!ArrayT->getSize())
3496       return true;
3497 
3498     T = ArrayT->getElementType();
3499   }
3500 
3501   return false;
3502 }
3503 
3504 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
3505                                     FieldDecl *Field,
3506                                     IndirectFieldDecl *Indirect = nullptr) {
3507   if (Field->isInvalidDecl())
3508     return false;
3509 
3510   // Overwhelmingly common case: we have a direct initializer for this field.
3511   if (CXXCtorInitializer *Init =
3512           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
3513     return Info.addFieldInitializer(Init);
3514 
3515   // C++11 [class.base.init]p8:
3516   //   if the entity is a non-static data member that has a
3517   //   brace-or-equal-initializer and either
3518   //   -- the constructor's class is a union and no other variant member of that
3519   //      union is designated by a mem-initializer-id or
3520   //   -- the constructor's class is not a union, and, if the entity is a member
3521   //      of an anonymous union, no other member of that union is designated by
3522   //      a mem-initializer-id,
3523   //   the entity is initialized as specified in [dcl.init].
3524   //
3525   // We also apply the same rules to handle anonymous structs within anonymous
3526   // unions.
3527   if (Info.isWithinInactiveUnionMember(Field, Indirect))
3528     return false;
3529 
3530   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
3531     Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3532                                            Info.Ctor->getLocation(), Field);
3533     CXXCtorInitializer *Init;
3534     if (Indirect)
3535       Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3536                                                       SourceLocation(),
3537                                                       SourceLocation(), DIE,
3538                                                       SourceLocation());
3539     else
3540       Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3541                                                       SourceLocation(),
3542                                                       SourceLocation(), DIE,
3543                                                       SourceLocation());
3544     return Info.addFieldInitializer(Init);
3545   }
3546 
3547   // Don't initialize incomplete or zero-length arrays.
3548   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3549     return false;
3550 
3551   // Don't try to build an implicit initializer if there were semantic
3552   // errors in any of the initializers (and therefore we might be
3553   // missing some that the user actually wrote).
3554   if (Info.AnyErrorsInInits)
3555     return false;
3556 
3557   CXXCtorInitializer *Init = nullptr;
3558   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3559                                      Indirect, Init))
3560     return true;
3561 
3562   if (!Init)
3563     return false;
3564 
3565   return Info.addFieldInitializer(Init);
3566 }
3567 
3568 bool
3569 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3570                                CXXCtorInitializer *Initializer) {
3571   assert(Initializer->isDelegatingInitializer());
3572   Constructor->setNumCtorInitializers(1);
3573   CXXCtorInitializer **initializer =
3574     new (Context) CXXCtorInitializer*[1];
3575   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3576   Constructor->setCtorInitializers(initializer);
3577 
3578   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
3579     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
3580     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3581   }
3582 
3583   DelegatingCtorDecls.push_back(Constructor);
3584 
3585   return false;
3586 }
3587 
3588 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3589                                ArrayRef<CXXCtorInitializer *> Initializers) {
3590   if (Constructor->isDependentContext()) {
3591     // Just store the initializers as written, they will be checked during
3592     // instantiation.
3593     if (!Initializers.empty()) {
3594       Constructor->setNumCtorInitializers(Initializers.size());
3595       CXXCtorInitializer **baseOrMemberInitializers =
3596         new (Context) CXXCtorInitializer*[Initializers.size()];
3597       memcpy(baseOrMemberInitializers, Initializers.data(),
3598              Initializers.size() * sizeof(CXXCtorInitializer*));
3599       Constructor->setCtorInitializers(baseOrMemberInitializers);
3600     }
3601 
3602     // Let template instantiation know whether we had errors.
3603     if (AnyErrors)
3604       Constructor->setInvalidDecl();
3605 
3606     return false;
3607   }
3608 
3609   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
3610 
3611   // We need to build the initializer AST according to order of construction
3612   // and not what user specified in the Initializers list.
3613   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
3614   if (!ClassDecl)
3615     return true;
3616 
3617   bool HadError = false;
3618 
3619   for (unsigned i = 0; i < Initializers.size(); i++) {
3620     CXXCtorInitializer *Member = Initializers[i];
3621 
3622     if (Member->isBaseInitializer())
3623       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
3624     else {
3625       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
3626 
3627       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
3628         for (auto *C : F->chain()) {
3629           FieldDecl *FD = dyn_cast<FieldDecl>(C);
3630           if (FD && FD->getParent()->isUnion())
3631             Info.ActiveUnionMember.insert(std::make_pair(
3632                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3633         }
3634       } else if (FieldDecl *FD = Member->getMember()) {
3635         if (FD->getParent()->isUnion())
3636           Info.ActiveUnionMember.insert(std::make_pair(
3637               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3638       }
3639     }
3640   }
3641 
3642   // Keep track of the direct virtual bases.
3643   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3644   for (auto &I : ClassDecl->bases()) {
3645     if (I.isVirtual())
3646       DirectVBases.insert(&I);
3647   }
3648 
3649   // Push virtual bases before others.
3650   for (auto &VBase : ClassDecl->vbases()) {
3651     if (CXXCtorInitializer *Value
3652         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
3653       // [class.base.init]p7, per DR257:
3654       //   A mem-initializer where the mem-initializer-id names a virtual base
3655       //   class is ignored during execution of a constructor of any class that
3656       //   is not the most derived class.
3657       if (ClassDecl->isAbstract()) {
3658         // FIXME: Provide a fixit to remove the base specifier. This requires
3659         // tracking the location of the associated comma for a base specifier.
3660         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3661           << VBase.getType() << ClassDecl;
3662         DiagnoseAbstractType(ClassDecl);
3663       }
3664 
3665       Info.AllToInit.push_back(Value);
3666     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3667       // [class.base.init]p8, per DR257:
3668       //   If a given [...] base class is not named by a mem-initializer-id
3669       //   [...] and the entity is not a virtual base class of an abstract
3670       //   class, then [...] the entity is default-initialized.
3671       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
3672       CXXCtorInitializer *CXXBaseInit;
3673       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3674                                        &VBase, IsInheritedVirtualBase,
3675                                        CXXBaseInit)) {
3676         HadError = true;
3677         continue;
3678       }
3679 
3680       Info.AllToInit.push_back(CXXBaseInit);
3681     }
3682   }
3683 
3684   // Non-virtual bases.
3685   for (auto &Base : ClassDecl->bases()) {
3686     // Virtuals are in the virtual base list and already constructed.
3687     if (Base.isVirtual())
3688       continue;
3689 
3690     if (CXXCtorInitializer *Value
3691           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
3692       Info.AllToInit.push_back(Value);
3693     } else if (!AnyErrors) {
3694       CXXCtorInitializer *CXXBaseInit;
3695       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3696                                        &Base, /*IsInheritedVirtualBase=*/false,
3697                                        CXXBaseInit)) {
3698         HadError = true;
3699         continue;
3700       }
3701 
3702       Info.AllToInit.push_back(CXXBaseInit);
3703     }
3704   }
3705 
3706   // Fields.
3707   for (auto *Mem : ClassDecl->decls()) {
3708     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
3709       // C++ [class.bit]p2:
3710       //   A declaration for a bit-field that omits the identifier declares an
3711       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
3712       //   initialized.
3713       if (F->isUnnamedBitfield())
3714         continue;
3715 
3716       // If we're not generating the implicit copy/move constructor, then we'll
3717       // handle anonymous struct/union fields based on their individual
3718       // indirect fields.
3719       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
3720         continue;
3721 
3722       if (CollectFieldInitializer(*this, Info, F))
3723         HadError = true;
3724       continue;
3725     }
3726 
3727     // Beyond this point, we only consider default initialization.
3728     if (Info.isImplicitCopyOrMove())
3729       continue;
3730 
3731     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
3732       if (F->getType()->isIncompleteArrayType()) {
3733         assert(ClassDecl->hasFlexibleArrayMember() &&
3734                "Incomplete array type is not valid");
3735         continue;
3736       }
3737 
3738       // Initialize each field of an anonymous struct individually.
3739       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3740         HadError = true;
3741 
3742       continue;
3743     }
3744   }
3745 
3746   unsigned NumInitializers = Info.AllToInit.size();
3747   if (NumInitializers > 0) {
3748     Constructor->setNumCtorInitializers(NumInitializers);
3749     CXXCtorInitializer **baseOrMemberInitializers =
3750       new (Context) CXXCtorInitializer*[NumInitializers];
3751     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
3752            NumInitializers * sizeof(CXXCtorInitializer*));
3753     Constructor->setCtorInitializers(baseOrMemberInitializers);
3754 
3755     // Constructors implicitly reference the base and member
3756     // destructors.
3757     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3758                                            Constructor->getParent());
3759   }
3760 
3761   return HadError;
3762 }
3763 
3764 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
3765   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
3766     const RecordDecl *RD = RT->getDecl();
3767     if (RD->isAnonymousStructOrUnion()) {
3768       for (auto *Field : RD->fields())
3769         PopulateKeysForFields(Field, IdealInits);
3770       return;
3771     }
3772   }
3773   IdealInits.push_back(Field->getCanonicalDecl());
3774 }
3775 
3776 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3777   return Context.getCanonicalType(BaseType).getTypePtr();
3778 }
3779 
3780 static const void *GetKeyForMember(ASTContext &Context,
3781                                    CXXCtorInitializer *Member) {
3782   if (!Member->isAnyMemberInitializer())
3783     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
3784 
3785   return Member->getAnyMember()->getCanonicalDecl();
3786 }
3787 
3788 static void DiagnoseBaseOrMemInitializerOrder(
3789     Sema &SemaRef, const CXXConstructorDecl *Constructor,
3790     ArrayRef<CXXCtorInitializer *> Inits) {
3791   if (Constructor->getDeclContext()->isDependentContext())
3792     return;
3793 
3794   // Don't check initializers order unless the warning is enabled at the
3795   // location of at least one initializer.
3796   bool ShouldCheckOrder = false;
3797   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3798     CXXCtorInitializer *Init = Inits[InitIndex];
3799     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
3800                                  Init->getSourceLocation())) {
3801       ShouldCheckOrder = true;
3802       break;
3803     }
3804   }
3805   if (!ShouldCheckOrder)
3806     return;
3807 
3808   // Build the list of bases and members in the order that they'll
3809   // actually be initialized.  The explicit initializers should be in
3810   // this same order but may be missing things.
3811   SmallVector<const void*, 32> IdealInitKeys;
3812 
3813   const CXXRecordDecl *ClassDecl = Constructor->getParent();
3814 
3815   // 1. Virtual bases.
3816   for (const auto &VBase : ClassDecl->vbases())
3817     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
3818 
3819   // 2. Non-virtual bases.
3820   for (const auto &Base : ClassDecl->bases()) {
3821     if (Base.isVirtual())
3822       continue;
3823     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
3824   }
3825 
3826   // 3. Direct fields.
3827   for (auto *Field : ClassDecl->fields()) {
3828     if (Field->isUnnamedBitfield())
3829       continue;
3830 
3831     PopulateKeysForFields(Field, IdealInitKeys);
3832   }
3833 
3834   unsigned NumIdealInits = IdealInitKeys.size();
3835   unsigned IdealIndex = 0;
3836 
3837   CXXCtorInitializer *PrevInit = nullptr;
3838   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3839     CXXCtorInitializer *Init = Inits[InitIndex];
3840     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
3841 
3842     // Scan forward to try to find this initializer in the idealized
3843     // initializers list.
3844     for (; IdealIndex != NumIdealInits; ++IdealIndex)
3845       if (InitKey == IdealInitKeys[IdealIndex])
3846         break;
3847 
3848     // If we didn't find this initializer, it must be because we
3849     // scanned past it on a previous iteration.  That can only
3850     // happen if we're out of order;  emit a warning.
3851     if (IdealIndex == NumIdealInits && PrevInit) {
3852       Sema::SemaDiagnosticBuilder D =
3853         SemaRef.Diag(PrevInit->getSourceLocation(),
3854                      diag::warn_initializer_out_of_order);
3855 
3856       if (PrevInit->isAnyMemberInitializer())
3857         D << 0 << PrevInit->getAnyMember()->getDeclName();
3858       else
3859         D << 1 << PrevInit->getTypeSourceInfo()->getType();
3860 
3861       if (Init->isAnyMemberInitializer())
3862         D << 0 << Init->getAnyMember()->getDeclName();
3863       else
3864         D << 1 << Init->getTypeSourceInfo()->getType();
3865 
3866       // Move back to the initializer's location in the ideal list.
3867       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3868         if (InitKey == IdealInitKeys[IdealIndex])
3869           break;
3870 
3871       assert(IdealIndex != NumIdealInits &&
3872              "initializer not found in initializer list");
3873     }
3874 
3875     PrevInit = Init;
3876   }
3877 }
3878 
3879 namespace {
3880 bool CheckRedundantInit(Sema &S,
3881                         CXXCtorInitializer *Init,
3882                         CXXCtorInitializer *&PrevInit) {
3883   if (!PrevInit) {
3884     PrevInit = Init;
3885     return false;
3886   }
3887 
3888   if (FieldDecl *Field = Init->getAnyMember())
3889     S.Diag(Init->getSourceLocation(),
3890            diag::err_multiple_mem_initialization)
3891       << Field->getDeclName()
3892       << Init->getSourceRange();
3893   else {
3894     const Type *BaseClass = Init->getBaseClass();
3895     assert(BaseClass && "neither field nor base");
3896     S.Diag(Init->getSourceLocation(),
3897            diag::err_multiple_base_initialization)
3898       << QualType(BaseClass, 0)
3899       << Init->getSourceRange();
3900   }
3901   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3902     << 0 << PrevInit->getSourceRange();
3903 
3904   return true;
3905 }
3906 
3907 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
3908 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3909 
3910 bool CheckRedundantUnionInit(Sema &S,
3911                              CXXCtorInitializer *Init,
3912                              RedundantUnionMap &Unions) {
3913   FieldDecl *Field = Init->getAnyMember();
3914   RecordDecl *Parent = Field->getParent();
3915   NamedDecl *Child = Field;
3916 
3917   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
3918     if (Parent->isUnion()) {
3919       UnionEntry &En = Unions[Parent];
3920       if (En.first && En.first != Child) {
3921         S.Diag(Init->getSourceLocation(),
3922                diag::err_multiple_mem_union_initialization)
3923           << Field->getDeclName()
3924           << Init->getSourceRange();
3925         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3926           << 0 << En.second->getSourceRange();
3927         return true;
3928       }
3929       if (!En.first) {
3930         En.first = Child;
3931         En.second = Init;
3932       }
3933       if (!Parent->isAnonymousStructOrUnion())
3934         return false;
3935     }
3936 
3937     Child = Parent;
3938     Parent = cast<RecordDecl>(Parent->getDeclContext());
3939   }
3940 
3941   return false;
3942 }
3943 }
3944 
3945 /// ActOnMemInitializers - Handle the member initializers for a constructor.
3946 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
3947                                 SourceLocation ColonLoc,
3948                                 ArrayRef<CXXCtorInitializer*> MemInits,
3949                                 bool AnyErrors) {
3950   if (!ConstructorDecl)
3951     return;
3952 
3953   AdjustDeclIfTemplate(ConstructorDecl);
3954 
3955   CXXConstructorDecl *Constructor
3956     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
3957 
3958   if (!Constructor) {
3959     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3960     return;
3961   }
3962 
3963   // Mapping for the duplicate initializers check.
3964   // For member initializers, this is keyed with a FieldDecl*.
3965   // For base initializers, this is keyed with a Type*.
3966   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
3967 
3968   // Mapping for the inconsistent anonymous-union initializers check.
3969   RedundantUnionMap MemberUnions;
3970 
3971   bool HadError = false;
3972   for (unsigned i = 0; i < MemInits.size(); i++) {
3973     CXXCtorInitializer *Init = MemInits[i];
3974 
3975     // Set the source order index.
3976     Init->setSourceOrder(i);
3977 
3978     if (Init->isAnyMemberInitializer()) {
3979       const void *Key = GetKeyForMember(Context, Init);
3980       if (CheckRedundantInit(*this, Init, Members[Key]) ||
3981           CheckRedundantUnionInit(*this, Init, MemberUnions))
3982         HadError = true;
3983     } else if (Init->isBaseInitializer()) {
3984       const void *Key = GetKeyForMember(Context, Init);
3985       if (CheckRedundantInit(*this, Init, Members[Key]))
3986         HadError = true;
3987     } else {
3988       assert(Init->isDelegatingInitializer());
3989       // This must be the only initializer
3990       if (MemInits.size() != 1) {
3991         Diag(Init->getSourceLocation(),
3992              diag::err_delegating_initializer_alone)
3993           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
3994         // We will treat this as being the only initializer.
3995       }
3996       SetDelegatingInitializer(Constructor, MemInits[i]);
3997       // Return immediately as the initializer is set.
3998       return;
3999     }
4000   }
4001 
4002   if (HadError)
4003     return;
4004 
4005   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
4006 
4007   SetCtorInitializers(Constructor, AnyErrors, MemInits);
4008 
4009   DiagnoseUninitializedFields(*this, Constructor);
4010 }
4011 
4012 void
4013 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
4014                                              CXXRecordDecl *ClassDecl) {
4015   // Ignore dependent contexts. Also ignore unions, since their members never
4016   // have destructors implicitly called.
4017   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
4018     return;
4019 
4020   // FIXME: all the access-control diagnostics are positioned on the
4021   // field/base declaration.  That's probably good; that said, the
4022   // user might reasonably want to know why the destructor is being
4023   // emitted, and we currently don't say.
4024 
4025   // Non-static data members.
4026   for (auto *Field : ClassDecl->fields()) {
4027     if (Field->isInvalidDecl())
4028       continue;
4029 
4030     // Don't destroy incomplete or zero-length arrays.
4031     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
4032       continue;
4033 
4034     QualType FieldType = Context.getBaseElementType(Field->getType());
4035 
4036     const RecordType* RT = FieldType->getAs<RecordType>();
4037     if (!RT)
4038       continue;
4039 
4040     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4041     if (FieldClassDecl->isInvalidDecl())
4042       continue;
4043     if (FieldClassDecl->hasIrrelevantDestructor())
4044       continue;
4045     // The destructor for an implicit anonymous union member is never invoked.
4046     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4047       continue;
4048 
4049     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
4050     assert(Dtor && "No dtor found for FieldClassDecl!");
4051     CheckDestructorAccess(Field->getLocation(), Dtor,
4052                           PDiag(diag::err_access_dtor_field)
4053                             << Field->getDeclName()
4054                             << FieldType);
4055 
4056     MarkFunctionReferenced(Location, Dtor);
4057     DiagnoseUseOfDecl(Dtor, Location);
4058   }
4059 
4060   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4061 
4062   // Bases.
4063   for (const auto &Base : ClassDecl->bases()) {
4064     // Bases are always records in a well-formed non-dependent class.
4065     const RecordType *RT = Base.getType()->getAs<RecordType>();
4066 
4067     // Remember direct virtual bases.
4068     if (Base.isVirtual())
4069       DirectVirtualBases.insert(RT);
4070 
4071     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4072     // If our base class is invalid, we probably can't get its dtor anyway.
4073     if (BaseClassDecl->isInvalidDecl())
4074       continue;
4075     if (BaseClassDecl->hasIrrelevantDestructor())
4076       continue;
4077 
4078     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4079     assert(Dtor && "No dtor found for BaseClassDecl!");
4080 
4081     // FIXME: caret should be on the start of the class name
4082     CheckDestructorAccess(Base.getLocStart(), Dtor,
4083                           PDiag(diag::err_access_dtor_base)
4084                             << Base.getType()
4085                             << Base.getSourceRange(),
4086                           Context.getTypeDeclType(ClassDecl));
4087 
4088     MarkFunctionReferenced(Location, Dtor);
4089     DiagnoseUseOfDecl(Dtor, Location);
4090   }
4091 
4092   // Virtual bases.
4093   for (const auto &VBase : ClassDecl->vbases()) {
4094     // Bases are always records in a well-formed non-dependent class.
4095     const RecordType *RT = VBase.getType()->castAs<RecordType>();
4096 
4097     // Ignore direct virtual bases.
4098     if (DirectVirtualBases.count(RT))
4099       continue;
4100 
4101     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4102     // If our base class is invalid, we probably can't get its dtor anyway.
4103     if (BaseClassDecl->isInvalidDecl())
4104       continue;
4105     if (BaseClassDecl->hasIrrelevantDestructor())
4106       continue;
4107 
4108     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4109     assert(Dtor && "No dtor found for BaseClassDecl!");
4110     if (CheckDestructorAccess(
4111             ClassDecl->getLocation(), Dtor,
4112             PDiag(diag::err_access_dtor_vbase)
4113                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
4114             Context.getTypeDeclType(ClassDecl)) ==
4115         AR_accessible) {
4116       CheckDerivedToBaseConversion(
4117           Context.getTypeDeclType(ClassDecl), VBase.getType(),
4118           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4119           SourceRange(), DeclarationName(), nullptr);
4120     }
4121 
4122     MarkFunctionReferenced(Location, Dtor);
4123     DiagnoseUseOfDecl(Dtor, Location);
4124   }
4125 }
4126 
4127 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
4128   if (!CDtorDecl)
4129     return;
4130 
4131   if (CXXConstructorDecl *Constructor
4132       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
4133     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
4134     DiagnoseUninitializedFields(*this, Constructor);
4135   }
4136 }
4137 
4138 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4139                                   unsigned DiagID, AbstractDiagSelID SelID) {
4140   class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4141     unsigned DiagID;
4142     AbstractDiagSelID SelID;
4143 
4144   public:
4145     NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4146       : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
4147 
4148     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
4149       if (Suppressed) return;
4150       if (SelID == -1)
4151         S.Diag(Loc, DiagID) << T;
4152       else
4153         S.Diag(Loc, DiagID) << SelID << T;
4154     }
4155   } Diagnoser(DiagID, SelID);
4156 
4157   return RequireNonAbstractType(Loc, T, Diagnoser);
4158 }
4159 
4160 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4161                                   TypeDiagnoser &Diagnoser) {
4162   if (!getLangOpts().CPlusPlus)
4163     return false;
4164 
4165   if (const ArrayType *AT = Context.getAsArrayType(T))
4166     return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4167 
4168   if (const PointerType *PT = T->getAs<PointerType>()) {
4169     // Find the innermost pointer type.
4170     while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
4171       PT = T;
4172 
4173     if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
4174       return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4175   }
4176 
4177   const RecordType *RT = T->getAs<RecordType>();
4178   if (!RT)
4179     return false;
4180 
4181   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4182 
4183   // We can't answer whether something is abstract until it has a
4184   // definition.  If it's currently being defined, we'll walk back
4185   // over all the declarations when we have a full definition.
4186   const CXXRecordDecl *Def = RD->getDefinition();
4187   if (!Def || Def->isBeingDefined())
4188     return false;
4189 
4190   if (!RD->isAbstract())
4191     return false;
4192 
4193   Diagnoser.diagnose(*this, Loc, T);
4194   DiagnoseAbstractType(RD);
4195 
4196   return true;
4197 }
4198 
4199 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4200   // Check if we've already emitted the list of pure virtual functions
4201   // for this class.
4202   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
4203     return;
4204 
4205   // If the diagnostic is suppressed, don't emit the notes. We're only
4206   // going to emit them once, so try to attach them to a diagnostic we're
4207   // actually going to show.
4208   if (Diags.isLastDiagnosticIgnored())
4209     return;
4210 
4211   CXXFinalOverriderMap FinalOverriders;
4212   RD->getFinalOverriders(FinalOverriders);
4213 
4214   // Keep a set of seen pure methods so we won't diagnose the same method
4215   // more than once.
4216   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4217 
4218   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4219                                    MEnd = FinalOverriders.end();
4220        M != MEnd;
4221        ++M) {
4222     for (OverridingMethods::iterator SO = M->second.begin(),
4223                                   SOEnd = M->second.end();
4224          SO != SOEnd; ++SO) {
4225       // C++ [class.abstract]p4:
4226       //   A class is abstract if it contains or inherits at least one
4227       //   pure virtual function for which the final overrider is pure
4228       //   virtual.
4229 
4230       //
4231       if (SO->second.size() != 1)
4232         continue;
4233 
4234       if (!SO->second.front().Method->isPure())
4235         continue;
4236 
4237       if (!SeenPureMethods.insert(SO->second.front().Method))
4238         continue;
4239 
4240       Diag(SO->second.front().Method->getLocation(),
4241            diag::note_pure_virtual_function)
4242         << SO->second.front().Method->getDeclName() << RD->getDeclName();
4243     }
4244   }
4245 
4246   if (!PureVirtualClassDiagSet)
4247     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4248   PureVirtualClassDiagSet->insert(RD);
4249 }
4250 
4251 namespace {
4252 struct AbstractUsageInfo {
4253   Sema &S;
4254   CXXRecordDecl *Record;
4255   CanQualType AbstractType;
4256   bool Invalid;
4257 
4258   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4259     : S(S), Record(Record),
4260       AbstractType(S.Context.getCanonicalType(
4261                    S.Context.getTypeDeclType(Record))),
4262       Invalid(false) {}
4263 
4264   void DiagnoseAbstractType() {
4265     if (Invalid) return;
4266     S.DiagnoseAbstractType(Record);
4267     Invalid = true;
4268   }
4269 
4270   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4271 };
4272 
4273 struct CheckAbstractUsage {
4274   AbstractUsageInfo &Info;
4275   const NamedDecl *Ctx;
4276 
4277   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4278     : Info(Info), Ctx(Ctx) {}
4279 
4280   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4281     switch (TL.getTypeLocClass()) {
4282 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4283 #define TYPELOC(CLASS, PARENT) \
4284     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
4285 #include "clang/AST/TypeLocNodes.def"
4286     }
4287   }
4288 
4289   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4290     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
4291     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4292       if (!TL.getParam(I))
4293         continue;
4294 
4295       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
4296       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
4297     }
4298   }
4299 
4300   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4301     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4302   }
4303 
4304   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4305     // Visit the type parameters from a permissive context.
4306     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4307       TemplateArgumentLoc TAL = TL.getArgLoc(I);
4308       if (TAL.getArgument().getKind() == TemplateArgument::Type)
4309         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4310           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4311       // TODO: other template argument types?
4312     }
4313   }
4314 
4315   // Visit pointee types from a permissive context.
4316 #define CheckPolymorphic(Type) \
4317   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4318     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4319   }
4320   CheckPolymorphic(PointerTypeLoc)
4321   CheckPolymorphic(ReferenceTypeLoc)
4322   CheckPolymorphic(MemberPointerTypeLoc)
4323   CheckPolymorphic(BlockPointerTypeLoc)
4324   CheckPolymorphic(AtomicTypeLoc)
4325 
4326   /// Handle all the types we haven't given a more specific
4327   /// implementation for above.
4328   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4329     // Every other kind of type that we haven't called out already
4330     // that has an inner type is either (1) sugar or (2) contains that
4331     // inner type in some way as a subobject.
4332     if (TypeLoc Next = TL.getNextTypeLoc())
4333       return Visit(Next, Sel);
4334 
4335     // If there's no inner type and we're in a permissive context,
4336     // don't diagnose.
4337     if (Sel == Sema::AbstractNone) return;
4338 
4339     // Check whether the type matches the abstract type.
4340     QualType T = TL.getType();
4341     if (T->isArrayType()) {
4342       Sel = Sema::AbstractArrayType;
4343       T = Info.S.Context.getBaseElementType(T);
4344     }
4345     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4346     if (CT != Info.AbstractType) return;
4347 
4348     // It matched; do some magic.
4349     if (Sel == Sema::AbstractArrayType) {
4350       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4351         << T << TL.getSourceRange();
4352     } else {
4353       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4354         << Sel << T << TL.getSourceRange();
4355     }
4356     Info.DiagnoseAbstractType();
4357   }
4358 };
4359 
4360 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4361                                   Sema::AbstractDiagSelID Sel) {
4362   CheckAbstractUsage(*this, D).Visit(TL, Sel);
4363 }
4364 
4365 }
4366 
4367 /// Check for invalid uses of an abstract type in a method declaration.
4368 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4369                                     CXXMethodDecl *MD) {
4370   // No need to do the check on definitions, which require that
4371   // the return/param types be complete.
4372   if (MD->doesThisDeclarationHaveABody())
4373     return;
4374 
4375   // For safety's sake, just ignore it if we don't have type source
4376   // information.  This should never happen for non-implicit methods,
4377   // but...
4378   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4379     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4380 }
4381 
4382 /// Check for invalid uses of an abstract type within a class definition.
4383 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4384                                     CXXRecordDecl *RD) {
4385   for (auto *D : RD->decls()) {
4386     if (D->isImplicit()) continue;
4387 
4388     // Methods and method templates.
4389     if (isa<CXXMethodDecl>(D)) {
4390       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4391     } else if (isa<FunctionTemplateDecl>(D)) {
4392       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4393       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4394 
4395     // Fields and static variables.
4396     } else if (isa<FieldDecl>(D)) {
4397       FieldDecl *FD = cast<FieldDecl>(D);
4398       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4399         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4400     } else if (isa<VarDecl>(D)) {
4401       VarDecl *VD = cast<VarDecl>(D);
4402       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4403         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4404 
4405     // Nested classes and class templates.
4406     } else if (isa<CXXRecordDecl>(D)) {
4407       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4408     } else if (isa<ClassTemplateDecl>(D)) {
4409       CheckAbstractClassUsage(Info,
4410                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4411     }
4412   }
4413 }
4414 
4415 /// \brief Check class-level dllimport/dllexport attribute.
4416 static void checkDLLAttribute(Sema &S, CXXRecordDecl *Class) {
4417   Attr *ClassAttr = getDLLAttr(Class);
4418   if (!ClassAttr)
4419     return;
4420 
4421   bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4422 
4423   // Force declaration of implicit members so they can inherit the attribute.
4424   S.ForceDeclarationOfImplicitMembers(Class);
4425 
4426   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4427   // seem to be true in practice?
4428 
4429   for (Decl *Member : Class->decls()) {
4430     VarDecl *VD = dyn_cast<VarDecl>(Member);
4431     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4432 
4433     // Only methods and static fields inherit the attributes.
4434     if (!VD && !MD)
4435       continue;
4436 
4437     // Don't process deleted methods.
4438     if (MD && MD->isDeleted())
4439       continue;
4440 
4441     if (MD && MD->isMoveAssignmentOperator() && !ClassExported &&
4442         MD->isInlined()) {
4443       // Current MSVC versions don't export the move assignment operators, so
4444       // don't attempt to import them if we have a definition.
4445       continue;
4446     }
4447 
4448     if (InheritableAttr *MemberAttr = getDLLAttr(Member)) {
4449       if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4450           !MemberAttr->isInherited() && !ClassAttr->isInherited()) {
4451         S.Diag(MemberAttr->getLocation(),
4452                diag::err_attribute_dll_member_of_dll_class)
4453             << MemberAttr << ClassAttr;
4454         S.Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
4455         Member->setInvalidDecl();
4456         continue;
4457       }
4458     } else {
4459       auto *NewAttr =
4460           cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
4461       NewAttr->setInherited(true);
4462       Member->addAttr(NewAttr);
4463     }
4464 
4465     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) {
4466       if (ClassExported) {
4467         if (MD->isUserProvided()) {
4468           // Instantiate non-default methods.
4469           S.MarkFunctionReferenced(Class->getLocation(), MD);
4470         } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4471                    MD->isCopyAssignmentOperator() ||
4472                    MD->isMoveAssignmentOperator()) {
4473           // Instantiate non-trivial or explicitly defaulted methods, and the
4474           // copy assignment / move assignment operators.
4475           S.MarkFunctionReferenced(Class->getLocation(), MD);
4476           // Resolve its exception specification; CodeGen needs it.
4477           auto *FPT = MD->getType()->getAs<FunctionProtoType>();
4478           S.ResolveExceptionSpec(Class->getLocation(), FPT);
4479           S.ActOnFinishInlineMethodDef(MD);
4480         }
4481       }
4482     }
4483   }
4484 }
4485 
4486 /// \brief Perform semantic checks on a class definition that has been
4487 /// completing, introducing implicitly-declared members, checking for
4488 /// abstract types, etc.
4489 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
4490   if (!Record)
4491     return;
4492 
4493   if (Record->isAbstract() && !Record->isInvalidDecl()) {
4494     AbstractUsageInfo Info(*this, Record);
4495     CheckAbstractClassUsage(Info, Record);
4496   }
4497 
4498   // If this is not an aggregate type and has no user-declared constructor,
4499   // complain about any non-static data members of reference or const scalar
4500   // type, since they will never get initializers.
4501   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
4502       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4503       !Record->isLambda()) {
4504     bool Complained = false;
4505     for (const auto *F : Record->fields()) {
4506       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
4507         continue;
4508 
4509       if (F->getType()->isReferenceType() ||
4510           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
4511         if (!Complained) {
4512           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4513             << Record->getTagKind() << Record;
4514           Complained = true;
4515         }
4516 
4517         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4518           << F->getType()->isReferenceType()
4519           << F->getDeclName();
4520       }
4521     }
4522   }
4523 
4524   if (Record->isDynamicClass() && !Record->isDependentType())
4525     DynamicClasses.push_back(Record);
4526 
4527   if (Record->getIdentifier()) {
4528     // C++ [class.mem]p13:
4529     //   If T is the name of a class, then each of the following shall have a
4530     //   name different from T:
4531     //     - every member of every anonymous union that is a member of class T.
4532     //
4533     // C++ [class.mem]p14:
4534     //   In addition, if class T has a user-declared constructor (12.1), every
4535     //   non-static data member of class T shall have a name different from T.
4536     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4537     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4538          ++I) {
4539       NamedDecl *D = *I;
4540       if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4541           isa<IndirectFieldDecl>(D)) {
4542         Diag(D->getLocation(), diag::err_member_name_of_class)
4543           << D->getDeclName();
4544         break;
4545       }
4546     }
4547   }
4548 
4549   // Warn if the class has virtual methods but non-virtual public destructor.
4550   if (Record->isPolymorphic() && !Record->isDependentType()) {
4551     CXXDestructorDecl *dtor = Record->getDestructor();
4552     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4553         !Record->hasAttr<FinalAttr>())
4554       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4555            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4556   }
4557 
4558   if (Record->isAbstract()) {
4559     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4560       Diag(Record->getLocation(), diag::warn_abstract_final_class)
4561         << FA->isSpelledAsSealed();
4562       DiagnoseAbstractType(Record);
4563     }
4564   }
4565 
4566   if (!Record->isDependentType()) {
4567     for (auto *M : Record->methods()) {
4568       // See if a method overloads virtual methods in a base
4569       // class without overriding any.
4570       if (!M->isStatic())
4571         DiagnoseHiddenVirtualMethods(M);
4572 
4573       // Check whether the explicitly-defaulted special members are valid.
4574       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4575         CheckExplicitlyDefaultedSpecialMember(M);
4576 
4577       // For an explicitly defaulted or deleted special member, we defer
4578       // determining triviality until the class is complete. That time is now!
4579       if (!M->isImplicit() && !M->isUserProvided()) {
4580         CXXSpecialMember CSM = getSpecialMember(M);
4581         if (CSM != CXXInvalid) {
4582           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
4583 
4584           // Inform the class that we've finished declaring this member.
4585           Record->finishedDefaultedOrDeletedMember(M);
4586         }
4587       }
4588     }
4589   }
4590 
4591   // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4592   // function that is not a constructor declares that member function to be
4593   // const. [...] The class of which that function is a member shall be
4594   // a literal type.
4595   //
4596   // If the class has virtual bases, any constexpr members will already have
4597   // been diagnosed by the checks performed on the member declaration, so
4598   // suppress this (less useful) diagnostic.
4599   //
4600   // We delay this until we know whether an explicitly-defaulted (or deleted)
4601   // destructor for the class is trivial.
4602   if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
4603       !Record->isLiteral() && !Record->getNumVBases()) {
4604     for (const auto *M : Record->methods()) {
4605       if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) {
4606         switch (Record->getTemplateSpecializationKind()) {
4607         case TSK_ImplicitInstantiation:
4608         case TSK_ExplicitInstantiationDeclaration:
4609         case TSK_ExplicitInstantiationDefinition:
4610           // If a template instantiates to a non-literal type, but its members
4611           // instantiate to constexpr functions, the template is technically
4612           // ill-formed, but we allow it for sanity.
4613           continue;
4614 
4615         case TSK_Undeclared:
4616         case TSK_ExplicitSpecialization:
4617           RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4618                              diag::err_constexpr_method_non_literal);
4619           break;
4620         }
4621 
4622         // Only produce one error per class.
4623         break;
4624       }
4625     }
4626   }
4627 
4628   // ms_struct is a request to use the same ABI rules as MSVC.  Check
4629   // whether this class uses any C++ features that are implemented
4630   // completely differently in MSVC, and if so, emit a diagnostic.
4631   // That diagnostic defaults to an error, but we allow projects to
4632   // map it down to a warning (or ignore it).  It's a fairly common
4633   // practice among users of the ms_struct pragma to mass-annotate
4634   // headers, sweeping up a bunch of types that the project doesn't
4635   // really rely on MSVC-compatible layout for.  We must therefore
4636   // support "ms_struct except for C++ stuff" as a secondary ABI.
4637   if (Record->isMsStruct(Context) &&
4638       (Record->isPolymorphic() || Record->getNumBases())) {
4639     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
4640   }
4641 
4642   // Declare inheriting constructors. We do this eagerly here because:
4643   // - The standard requires an eager diagnostic for conflicting inheriting
4644   //   constructors from different classes.
4645   // - The lazy declaration of the other implicit constructors is so as to not
4646   //   waste space and performance on classes that are not meant to be
4647   //   instantiated (e.g. meta-functions). This doesn't apply to classes that
4648   //   have inheriting constructors.
4649   DeclareInheritingConstructors(Record);
4650 
4651   checkDLLAttribute(*this, Record);
4652 }
4653 
4654 /// Look up the special member function that would be called by a special
4655 /// member function for a subobject of class type.
4656 ///
4657 /// \param Class The class type of the subobject.
4658 /// \param CSM The kind of special member function.
4659 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4660 /// \param ConstRHS True if this is a copy operation with a const object
4661 ///        on its RHS, that is, if the argument to the outer special member
4662 ///        function is 'const' and this is not a field marked 'mutable'.
4663 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
4664     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
4665     unsigned FieldQuals, bool ConstRHS) {
4666   unsigned LHSQuals = 0;
4667   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
4668     LHSQuals = FieldQuals;
4669 
4670   unsigned RHSQuals = FieldQuals;
4671   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4672     RHSQuals = 0;
4673   else if (ConstRHS)
4674     RHSQuals |= Qualifiers::Const;
4675 
4676   return S.LookupSpecialMember(Class, CSM,
4677                                RHSQuals & Qualifiers::Const,
4678                                RHSQuals & Qualifiers::Volatile,
4679                                false,
4680                                LHSQuals & Qualifiers::Const,
4681                                LHSQuals & Qualifiers::Volatile);
4682 }
4683 
4684 /// Is the special member function which would be selected to perform the
4685 /// specified operation on the specified class type a constexpr constructor?
4686 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4687                                      Sema::CXXSpecialMember CSM,
4688                                      unsigned Quals, bool ConstRHS) {
4689   Sema::SpecialMemberOverloadResult *SMOR =
4690       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
4691   if (!SMOR || !SMOR->getMethod())
4692     // A constructor we wouldn't select can't be "involved in initializing"
4693     // anything.
4694     return true;
4695   return SMOR->getMethod()->isConstexpr();
4696 }
4697 
4698 /// Determine whether the specified special member function would be constexpr
4699 /// if it were implicitly defined.
4700 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4701                                               Sema::CXXSpecialMember CSM,
4702                                               bool ConstArg) {
4703   if (!S.getLangOpts().CPlusPlus11)
4704     return false;
4705 
4706   // C++11 [dcl.constexpr]p4:
4707   // In the definition of a constexpr constructor [...]
4708   bool Ctor = true;
4709   switch (CSM) {
4710   case Sema::CXXDefaultConstructor:
4711     // Since default constructor lookup is essentially trivial (and cannot
4712     // involve, for instance, template instantiation), we compute whether a
4713     // defaulted default constructor is constexpr directly within CXXRecordDecl.
4714     //
4715     // This is important for performance; we need to know whether the default
4716     // constructor is constexpr to determine whether the type is a literal type.
4717     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4718 
4719   case Sema::CXXCopyConstructor:
4720   case Sema::CXXMoveConstructor:
4721     // For copy or move constructors, we need to perform overload resolution.
4722     break;
4723 
4724   case Sema::CXXCopyAssignment:
4725   case Sema::CXXMoveAssignment:
4726     if (!S.getLangOpts().CPlusPlus1y)
4727       return false;
4728     // In C++1y, we need to perform overload resolution.
4729     Ctor = false;
4730     break;
4731 
4732   case Sema::CXXDestructor:
4733   case Sema::CXXInvalid:
4734     return false;
4735   }
4736 
4737   //   -- if the class is a non-empty union, or for each non-empty anonymous
4738   //      union member of a non-union class, exactly one non-static data member
4739   //      shall be initialized; [DR1359]
4740   //
4741   // If we squint, this is guaranteed, since exactly one non-static data member
4742   // will be initialized (if the constructor isn't deleted), we just don't know
4743   // which one.
4744   if (Ctor && ClassDecl->isUnion())
4745     return true;
4746 
4747   //   -- the class shall not have any virtual base classes;
4748   if (Ctor && ClassDecl->getNumVBases())
4749     return false;
4750 
4751   // C++1y [class.copy]p26:
4752   //   -- [the class] is a literal type, and
4753   if (!Ctor && !ClassDecl->isLiteral())
4754     return false;
4755 
4756   //   -- every constructor involved in initializing [...] base class
4757   //      sub-objects shall be a constexpr constructor;
4758   //   -- the assignment operator selected to copy/move each direct base
4759   //      class is a constexpr function, and
4760   for (const auto &B : ClassDecl->bases()) {
4761     const RecordType *BaseType = B.getType()->getAs<RecordType>();
4762     if (!BaseType) continue;
4763 
4764     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4765     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
4766       return false;
4767   }
4768 
4769   //   -- every constructor involved in initializing non-static data members
4770   //      [...] shall be a constexpr constructor;
4771   //   -- every non-static data member and base class sub-object shall be
4772   //      initialized
4773   //   -- for each non-static data member of X that is of class type (or array
4774   //      thereof), the assignment operator selected to copy/move that member is
4775   //      a constexpr function
4776   for (const auto *F : ClassDecl->fields()) {
4777     if (F->isInvalidDecl())
4778       continue;
4779     QualType BaseType = S.Context.getBaseElementType(F->getType());
4780     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
4781       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4782       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
4783                                     BaseType.getCVRQualifiers(),
4784                                     ConstArg && !F->isMutable()))
4785         return false;
4786     }
4787   }
4788 
4789   // All OK, it's constexpr!
4790   return true;
4791 }
4792 
4793 static Sema::ImplicitExceptionSpecification
4794 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4795   switch (S.getSpecialMember(MD)) {
4796   case Sema::CXXDefaultConstructor:
4797     return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4798   case Sema::CXXCopyConstructor:
4799     return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4800   case Sema::CXXCopyAssignment:
4801     return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4802   case Sema::CXXMoveConstructor:
4803     return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4804   case Sema::CXXMoveAssignment:
4805     return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4806   case Sema::CXXDestructor:
4807     return S.ComputeDefaultedDtorExceptionSpec(MD);
4808   case Sema::CXXInvalid:
4809     break;
4810   }
4811   assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4812          "only special members have implicit exception specs");
4813   return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
4814 }
4815 
4816 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4817                                                             CXXMethodDecl *MD) {
4818   FunctionProtoType::ExtProtoInfo EPI;
4819 
4820   // Build an exception specification pointing back at this member.
4821   EPI.ExceptionSpecType = EST_Unevaluated;
4822   EPI.ExceptionSpecDecl = MD;
4823 
4824   // Set the calling convention to the default for C++ instance methods.
4825   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4826       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4827                                             /*IsCXXMethod=*/true));
4828   return EPI;
4829 }
4830 
4831 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4832   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4833   if (FPT->getExceptionSpecType() != EST_Unevaluated)
4834     return;
4835 
4836   // Evaluate the exception specification.
4837   ImplicitExceptionSpecification ExceptSpec =
4838       computeImplicitExceptionSpec(*this, Loc, MD);
4839 
4840   FunctionProtoType::ExtProtoInfo EPI;
4841   ExceptSpec.getEPI(EPI);
4842 
4843   // Update the type of the special member to use it.
4844   UpdateExceptionSpec(MD, EPI);
4845 
4846   // A user-provided destructor can be defined outside the class. When that
4847   // happens, be sure to update the exception specification on both
4848   // declarations.
4849   const FunctionProtoType *CanonicalFPT =
4850     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4851   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4852     UpdateExceptionSpec(MD->getCanonicalDecl(), EPI);
4853 }
4854 
4855 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4856   CXXRecordDecl *RD = MD->getParent();
4857   CXXSpecialMember CSM = getSpecialMember(MD);
4858 
4859   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4860          "not an explicitly-defaulted special member");
4861 
4862   // Whether this was the first-declared instance of the constructor.
4863   // This affects whether we implicitly add an exception spec and constexpr.
4864   bool First = MD == MD->getCanonicalDecl();
4865 
4866   bool HadError = false;
4867 
4868   // C++11 [dcl.fct.def.default]p1:
4869   //   A function that is explicitly defaulted shall
4870   //     -- be a special member function (checked elsewhere),
4871   //     -- have the same type (except for ref-qualifiers, and except that a
4872   //        copy operation can take a non-const reference) as an implicit
4873   //        declaration, and
4874   //     -- not have default arguments.
4875   unsigned ExpectedParams = 1;
4876   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4877     ExpectedParams = 0;
4878   if (MD->getNumParams() != ExpectedParams) {
4879     // This also checks for default arguments: a copy or move constructor with a
4880     // default argument is classified as a default constructor, and assignment
4881     // operations and destructors can't have default arguments.
4882     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4883       << CSM << MD->getSourceRange();
4884     HadError = true;
4885   } else if (MD->isVariadic()) {
4886     Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4887       << CSM << MD->getSourceRange();
4888     HadError = true;
4889   }
4890 
4891   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
4892 
4893   bool CanHaveConstParam = false;
4894   if (CSM == CXXCopyConstructor)
4895     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
4896   else if (CSM == CXXCopyAssignment)
4897     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
4898 
4899   QualType ReturnType = Context.VoidTy;
4900   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4901     // Check for return type matching.
4902     ReturnType = Type->getReturnType();
4903     QualType ExpectedReturnType =
4904         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4905     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4906       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4907         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4908       HadError = true;
4909     }
4910 
4911     // A defaulted special member cannot have cv-qualifiers.
4912     if (Type->getTypeQuals()) {
4913       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4914         << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
4915       HadError = true;
4916     }
4917   }
4918 
4919   // Check for parameter type matching.
4920   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
4921   bool HasConstParam = false;
4922   if (ExpectedParams && ArgType->isReferenceType()) {
4923     // Argument must be reference to possibly-const T.
4924     QualType ReferentType = ArgType->getPointeeType();
4925     HasConstParam = ReferentType.isConstQualified();
4926 
4927     if (ReferentType.isVolatileQualified()) {
4928       Diag(MD->getLocation(),
4929            diag::err_defaulted_special_member_volatile_param) << CSM;
4930       HadError = true;
4931     }
4932 
4933     if (HasConstParam && !CanHaveConstParam) {
4934       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4935         Diag(MD->getLocation(),
4936              diag::err_defaulted_special_member_copy_const_param)
4937           << (CSM == CXXCopyAssignment);
4938         // FIXME: Explain why this special member can't be const.
4939       } else {
4940         Diag(MD->getLocation(),
4941              diag::err_defaulted_special_member_move_const_param)
4942           << (CSM == CXXMoveAssignment);
4943       }
4944       HadError = true;
4945     }
4946   } else if (ExpectedParams) {
4947     // A copy assignment operator can take its argument by value, but a
4948     // defaulted one cannot.
4949     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
4950     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
4951     HadError = true;
4952   }
4953 
4954   // C++11 [dcl.fct.def.default]p2:
4955   //   An explicitly-defaulted function may be declared constexpr only if it
4956   //   would have been implicitly declared as constexpr,
4957   // Do not apply this rule to members of class templates, since core issue 1358
4958   // makes such functions always instantiate to constexpr functions. For
4959   // functions which cannot be constexpr (for non-constructors in C++11 and for
4960   // destructors in C++1y), this is checked elsewhere.
4961   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4962                                                      HasConstParam);
4963   if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4964                                  : isa<CXXConstructorDecl>(MD)) &&
4965       MD->isConstexpr() && !Constexpr &&
4966       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4967     Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
4968     // FIXME: Explain why the special member can't be constexpr.
4969     HadError = true;
4970   }
4971 
4972   //   and may have an explicit exception-specification only if it is compatible
4973   //   with the exception-specification on the implicit declaration.
4974   if (Type->hasExceptionSpec()) {
4975     // Delay the check if this is the first declaration of the special member,
4976     // since we may not have parsed some necessary in-class initializers yet.
4977     if (First) {
4978       // If the exception specification needs to be instantiated, do so now,
4979       // before we clobber it with an EST_Unevaluated specification below.
4980       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4981         InstantiateExceptionSpec(MD->getLocStart(), MD);
4982         Type = MD->getType()->getAs<FunctionProtoType>();
4983       }
4984       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
4985     } else
4986       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4987   }
4988 
4989   //   If a function is explicitly defaulted on its first declaration,
4990   if (First) {
4991     //  -- it is implicitly considered to be constexpr if the implicit
4992     //     definition would be,
4993     MD->setConstexpr(Constexpr);
4994 
4995     //  -- it is implicitly considered to have the same exception-specification
4996     //     as if it had been implicitly declared,
4997     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4998     EPI.ExceptionSpecType = EST_Unevaluated;
4999     EPI.ExceptionSpecDecl = MD;
5000     MD->setType(Context.getFunctionType(ReturnType,
5001                                         ArrayRef<QualType>(&ArgType,
5002                                                            ExpectedParams),
5003                                         EPI));
5004   }
5005 
5006   if (ShouldDeleteSpecialMember(MD, CSM)) {
5007     if (First) {
5008       SetDeclDeleted(MD, MD->getLocation());
5009     } else {
5010       // C++11 [dcl.fct.def.default]p4:
5011       //   [For a] user-provided explicitly-defaulted function [...] if such a
5012       //   function is implicitly defined as deleted, the program is ill-formed.
5013       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
5014       ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
5015       HadError = true;
5016     }
5017   }
5018 
5019   if (HadError)
5020     MD->setInvalidDecl();
5021 }
5022 
5023 /// Check whether the exception specification provided for an
5024 /// explicitly-defaulted special member matches the exception specification
5025 /// that would have been generated for an implicit special member, per
5026 /// C++11 [dcl.fct.def.default]p2.
5027 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
5028     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
5029   // Compute the implicit exception specification.
5030   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5031                                                        /*IsCXXMethod=*/true);
5032   FunctionProtoType::ExtProtoInfo EPI(CC);
5033   computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
5034   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
5035     Context.getFunctionType(Context.VoidTy, None, EPI));
5036 
5037   // Ensure that it matches.
5038   CheckEquivalentExceptionSpec(
5039     PDiag(diag::err_incorrect_defaulted_exception_spec)
5040       << getSpecialMember(MD), PDiag(),
5041     ImplicitType, SourceLocation(),
5042     SpecifiedType, MD->getLocation());
5043 }
5044 
5045 void Sema::CheckDelayedMemberExceptionSpecs() {
5046   SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
5047               2> Checks;
5048   SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
5049 
5050   std::swap(Checks, DelayedDestructorExceptionSpecChecks);
5051   std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
5052 
5053   // Perform any deferred checking of exception specifications for virtual
5054   // destructors.
5055   for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
5056     const CXXDestructorDecl *Dtor = Checks[i].first;
5057     assert(!Dtor->getParent()->isDependentType() &&
5058            "Should not ever add destructors of templates into the list.");
5059     CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
5060   }
5061 
5062   // Check that any explicitly-defaulted methods have exception specifications
5063   // compatible with their implicit exception specifications.
5064   for (unsigned I = 0, N = Specs.size(); I != N; ++I)
5065     CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
5066                                                 Specs[I].second);
5067 }
5068 
5069 namespace {
5070 struct SpecialMemberDeletionInfo {
5071   Sema &S;
5072   CXXMethodDecl *MD;
5073   Sema::CXXSpecialMember CSM;
5074   bool Diagnose;
5075 
5076   // Properties of the special member, computed for convenience.
5077   bool IsConstructor, IsAssignment, IsMove, ConstArg;
5078   SourceLocation Loc;
5079 
5080   bool AllFieldsAreConst;
5081 
5082   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
5083                             Sema::CXXSpecialMember CSM, bool Diagnose)
5084     : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
5085       IsConstructor(false), IsAssignment(false), IsMove(false),
5086       ConstArg(false), Loc(MD->getLocation()),
5087       AllFieldsAreConst(true) {
5088     switch (CSM) {
5089       case Sema::CXXDefaultConstructor:
5090       case Sema::CXXCopyConstructor:
5091         IsConstructor = true;
5092         break;
5093       case Sema::CXXMoveConstructor:
5094         IsConstructor = true;
5095         IsMove = true;
5096         break;
5097       case Sema::CXXCopyAssignment:
5098         IsAssignment = true;
5099         break;
5100       case Sema::CXXMoveAssignment:
5101         IsAssignment = true;
5102         IsMove = true;
5103         break;
5104       case Sema::CXXDestructor:
5105         break;
5106       case Sema::CXXInvalid:
5107         llvm_unreachable("invalid special member kind");
5108     }
5109 
5110     if (MD->getNumParams()) {
5111       if (const ReferenceType *RT =
5112               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5113         ConstArg = RT->getPointeeType().isConstQualified();
5114     }
5115   }
5116 
5117   bool inUnion() const { return MD->getParent()->isUnion(); }
5118 
5119   /// Look up the corresponding special member in the given class.
5120   Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
5121                                               unsigned Quals, bool IsMutable) {
5122     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5123                                        ConstArg && !IsMutable);
5124   }
5125 
5126   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
5127 
5128   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
5129   bool shouldDeleteForField(FieldDecl *FD);
5130   bool shouldDeleteForAllConstMembers();
5131 
5132   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5133                                      unsigned Quals);
5134   bool shouldDeleteForSubobjectCall(Subobject Subobj,
5135                                     Sema::SpecialMemberOverloadResult *SMOR,
5136                                     bool IsDtorCallInCtor);
5137 
5138   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
5139 };
5140 }
5141 
5142 /// Is the given special member inaccessible when used on the given
5143 /// sub-object.
5144 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5145                                              CXXMethodDecl *target) {
5146   /// If we're operating on a base class, the object type is the
5147   /// type of this special member.
5148   QualType objectTy;
5149   AccessSpecifier access = target->getAccess();
5150   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5151     objectTy = S.Context.getTypeDeclType(MD->getParent());
5152     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5153 
5154   // If we're operating on a field, the object type is the type of the field.
5155   } else {
5156     objectTy = S.Context.getTypeDeclType(target->getParent());
5157   }
5158 
5159   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5160 }
5161 
5162 /// Check whether we should delete a special member due to the implicit
5163 /// definition containing a call to a special member of a subobject.
5164 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5165     Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5166     bool IsDtorCallInCtor) {
5167   CXXMethodDecl *Decl = SMOR->getMethod();
5168   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5169 
5170   int DiagKind = -1;
5171 
5172   if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5173     DiagKind = !Decl ? 0 : 1;
5174   else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5175     DiagKind = 2;
5176   else if (!isAccessible(Subobj, Decl))
5177     DiagKind = 3;
5178   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5179            !Decl->isTrivial()) {
5180     // A member of a union must have a trivial corresponding special member.
5181     // As a weird special case, a destructor call from a union's constructor
5182     // must be accessible and non-deleted, but need not be trivial. Such a
5183     // destructor is never actually called, but is semantically checked as
5184     // if it were.
5185     DiagKind = 4;
5186   }
5187 
5188   if (DiagKind == -1)
5189     return false;
5190 
5191   if (Diagnose) {
5192     if (Field) {
5193       S.Diag(Field->getLocation(),
5194              diag::note_deleted_special_member_class_subobject)
5195         << CSM << MD->getParent() << /*IsField*/true
5196         << Field << DiagKind << IsDtorCallInCtor;
5197     } else {
5198       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5199       S.Diag(Base->getLocStart(),
5200              diag::note_deleted_special_member_class_subobject)
5201         << CSM << MD->getParent() << /*IsField*/false
5202         << Base->getType() << DiagKind << IsDtorCallInCtor;
5203     }
5204 
5205     if (DiagKind == 1)
5206       S.NoteDeletedFunction(Decl);
5207     // FIXME: Explain inaccessibility if DiagKind == 3.
5208   }
5209 
5210   return true;
5211 }
5212 
5213 /// Check whether we should delete a special member function due to having a
5214 /// direct or virtual base class or non-static data member of class type M.
5215 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
5216     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
5217   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5218   bool IsMutable = Field && Field->isMutable();
5219 
5220   // C++11 [class.ctor]p5:
5221   // -- any direct or virtual base class, or non-static data member with no
5222   //    brace-or-equal-initializer, has class type M (or array thereof) and
5223   //    either M has no default constructor or overload resolution as applied
5224   //    to M's default constructor results in an ambiguity or in a function
5225   //    that is deleted or inaccessible
5226   // C++11 [class.copy]p11, C++11 [class.copy]p23:
5227   // -- a direct or virtual base class B that cannot be copied/moved because
5228   //    overload resolution, as applied to B's corresponding special member,
5229   //    results in an ambiguity or a function that is deleted or inaccessible
5230   //    from the defaulted special member
5231   // C++11 [class.dtor]p5:
5232   // -- any direct or virtual base class [...] has a type with a destructor
5233   //    that is deleted or inaccessible
5234   if (!(CSM == Sema::CXXDefaultConstructor &&
5235         Field && Field->hasInClassInitializer()) &&
5236       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5237                                    false))
5238     return true;
5239 
5240   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5241   // -- any direct or virtual base class or non-static data member has a
5242   //    type with a destructor that is deleted or inaccessible
5243   if (IsConstructor) {
5244     Sema::SpecialMemberOverloadResult *SMOR =
5245         S.LookupSpecialMember(Class, Sema::CXXDestructor,
5246                               false, false, false, false, false);
5247     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5248       return true;
5249   }
5250 
5251   return false;
5252 }
5253 
5254 /// Check whether we should delete a special member function due to the class
5255 /// having a particular direct or virtual base class.
5256 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
5257   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
5258   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
5259 }
5260 
5261 /// Check whether we should delete a special member function due to the class
5262 /// having a particular non-static data member.
5263 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5264   QualType FieldType = S.Context.getBaseElementType(FD->getType());
5265   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5266 
5267   if (CSM == Sema::CXXDefaultConstructor) {
5268     // For a default constructor, all references must be initialized in-class
5269     // and, if a union, it must have a non-const member.
5270     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5271       if (Diagnose)
5272         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5273           << MD->getParent() << FD << FieldType << /*Reference*/0;
5274       return true;
5275     }
5276     // C++11 [class.ctor]p5: any non-variant non-static data member of
5277     // const-qualified type (or array thereof) with no
5278     // brace-or-equal-initializer does not have a user-provided default
5279     // constructor.
5280     if (!inUnion() && FieldType.isConstQualified() &&
5281         !FD->hasInClassInitializer() &&
5282         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5283       if (Diagnose)
5284         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5285           << MD->getParent() << FD << FD->getType() << /*Const*/1;
5286       return true;
5287     }
5288 
5289     if (inUnion() && !FieldType.isConstQualified())
5290       AllFieldsAreConst = false;
5291   } else if (CSM == Sema::CXXCopyConstructor) {
5292     // For a copy constructor, data members must not be of rvalue reference
5293     // type.
5294     if (FieldType->isRValueReferenceType()) {
5295       if (Diagnose)
5296         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5297           << MD->getParent() << FD << FieldType;
5298       return true;
5299     }
5300   } else if (IsAssignment) {
5301     // For an assignment operator, data members must not be of reference type.
5302     if (FieldType->isReferenceType()) {
5303       if (Diagnose)
5304         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5305           << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
5306       return true;
5307     }
5308     if (!FieldRecord && FieldType.isConstQualified()) {
5309       // C++11 [class.copy]p23:
5310       // -- a non-static data member of const non-class type (or array thereof)
5311       if (Diagnose)
5312         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5313           << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
5314       return true;
5315     }
5316   }
5317 
5318   if (FieldRecord) {
5319     // Some additional restrictions exist on the variant members.
5320     if (!inUnion() && FieldRecord->isUnion() &&
5321         FieldRecord->isAnonymousStructOrUnion()) {
5322       bool AllVariantFieldsAreConst = true;
5323 
5324       // FIXME: Handle anonymous unions declared within anonymous unions.
5325       for (auto *UI : FieldRecord->fields()) {
5326         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
5327 
5328         if (!UnionFieldType.isConstQualified())
5329           AllVariantFieldsAreConst = false;
5330 
5331         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5332         if (UnionFieldRecord &&
5333             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
5334                                           UnionFieldType.getCVRQualifiers()))
5335           return true;
5336       }
5337 
5338       // At least one member in each anonymous union must be non-const
5339       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
5340           !FieldRecord->field_empty()) {
5341         if (Diagnose)
5342           S.Diag(FieldRecord->getLocation(),
5343                  diag::note_deleted_default_ctor_all_const)
5344             << MD->getParent() << /*anonymous union*/1;
5345         return true;
5346       }
5347 
5348       // Don't check the implicit member of the anonymous union type.
5349       // This is technically non-conformant, but sanity demands it.
5350       return false;
5351     }
5352 
5353     if (shouldDeleteForClassSubobject(FieldRecord, FD,
5354                                       FieldType.getCVRQualifiers()))
5355       return true;
5356   }
5357 
5358   return false;
5359 }
5360 
5361 /// C++11 [class.ctor] p5:
5362 ///   A defaulted default constructor for a class X is defined as deleted if
5363 /// X is a union and all of its variant members are of const-qualified type.
5364 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
5365   // This is a silly definition, because it gives an empty union a deleted
5366   // default constructor. Don't do that.
5367   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5368       !MD->getParent()->field_empty()) {
5369     if (Diagnose)
5370       S.Diag(MD->getParent()->getLocation(),
5371              diag::note_deleted_default_ctor_all_const)
5372         << MD->getParent() << /*not anonymous union*/0;
5373     return true;
5374   }
5375   return false;
5376 }
5377 
5378 /// Determine whether a defaulted special member function should be defined as
5379 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5380 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
5381 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5382                                      bool Diagnose) {
5383   if (MD->isInvalidDecl())
5384     return false;
5385   CXXRecordDecl *RD = MD->getParent();
5386   assert(!RD->isDependentType() && "do deletion after instantiation");
5387   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
5388     return false;
5389 
5390   // C++11 [expr.lambda.prim]p19:
5391   //   The closure type associated with a lambda-expression has a
5392   //   deleted (8.4.3) default constructor and a deleted copy
5393   //   assignment operator.
5394   if (RD->isLambda() &&
5395       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5396     if (Diagnose)
5397       Diag(RD->getLocation(), diag::note_lambda_decl);
5398     return true;
5399   }
5400 
5401   // For an anonymous struct or union, the copy and assignment special members
5402   // will never be used, so skip the check. For an anonymous union declared at
5403   // namespace scope, the constructor and destructor are used.
5404   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5405       RD->isAnonymousStructOrUnion())
5406     return false;
5407 
5408   // C++11 [class.copy]p7, p18:
5409   //   If the class definition declares a move constructor or move assignment
5410   //   operator, an implicitly declared copy constructor or copy assignment
5411   //   operator is defined as deleted.
5412   if (MD->isImplicit() &&
5413       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5414     CXXMethodDecl *UserDeclaredMove = nullptr;
5415 
5416     // In Microsoft mode, a user-declared move only causes the deletion of the
5417     // corresponding copy operation, not both copy operations.
5418     if (RD->hasUserDeclaredMoveConstructor() &&
5419         (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
5420       if (!Diagnose) return true;
5421 
5422       // Find any user-declared move constructor.
5423       for (auto *I : RD->ctors()) {
5424         if (I->isMoveConstructor()) {
5425           UserDeclaredMove = I;
5426           break;
5427         }
5428       }
5429       assert(UserDeclaredMove);
5430     } else if (RD->hasUserDeclaredMoveAssignment() &&
5431                (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
5432       if (!Diagnose) return true;
5433 
5434       // Find any user-declared move assignment operator.
5435       for (auto *I : RD->methods()) {
5436         if (I->isMoveAssignmentOperator()) {
5437           UserDeclaredMove = I;
5438           break;
5439         }
5440       }
5441       assert(UserDeclaredMove);
5442     }
5443 
5444     if (UserDeclaredMove) {
5445       Diag(UserDeclaredMove->getLocation(),
5446            diag::note_deleted_copy_user_declared_move)
5447         << (CSM == CXXCopyAssignment) << RD
5448         << UserDeclaredMove->isMoveAssignmentOperator();
5449       return true;
5450     }
5451   }
5452 
5453   // Do access control from the special member function
5454   ContextRAII MethodContext(*this, MD);
5455 
5456   // C++11 [class.dtor]p5:
5457   // -- for a virtual destructor, lookup of the non-array deallocation function
5458   //    results in an ambiguity or in a function that is deleted or inaccessible
5459   if (CSM == CXXDestructor && MD->isVirtual()) {
5460     FunctionDecl *OperatorDelete = nullptr;
5461     DeclarationName Name =
5462       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5463     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
5464                                  OperatorDelete, false)) {
5465       if (Diagnose)
5466         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
5467       return true;
5468     }
5469   }
5470 
5471   SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
5472 
5473   for (auto &BI : RD->bases())
5474     if (!BI.isVirtual() &&
5475         SMI.shouldDeleteForBase(&BI))
5476       return true;
5477 
5478   // Per DR1611, do not consider virtual bases of constructors of abstract
5479   // classes, since we are not going to construct them.
5480   if (!RD->isAbstract() || !SMI.IsConstructor) {
5481     for (auto &BI : RD->vbases())
5482       if (SMI.shouldDeleteForBase(&BI))
5483         return true;
5484   }
5485 
5486   for (auto *FI : RD->fields())
5487     if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
5488         SMI.shouldDeleteForField(FI))
5489       return true;
5490 
5491   if (SMI.shouldDeleteForAllConstMembers())
5492     return true;
5493 
5494   return false;
5495 }
5496 
5497 /// Perform lookup for a special member of the specified kind, and determine
5498 /// whether it is trivial. If the triviality can be determined without the
5499 /// lookup, skip it. This is intended for use when determining whether a
5500 /// special member of a containing object is trivial, and thus does not ever
5501 /// perform overload resolution for default constructors.
5502 ///
5503 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5504 /// member that was most likely to be intended to be trivial, if any.
5505 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5506                                      Sema::CXXSpecialMember CSM, unsigned Quals,
5507                                      bool ConstRHS, CXXMethodDecl **Selected) {
5508   if (Selected)
5509     *Selected = nullptr;
5510 
5511   switch (CSM) {
5512   case Sema::CXXInvalid:
5513     llvm_unreachable("not a special member");
5514 
5515   case Sema::CXXDefaultConstructor:
5516     // C++11 [class.ctor]p5:
5517     //   A default constructor is trivial if:
5518     //    - all the [direct subobjects] have trivial default constructors
5519     //
5520     // Note, no overload resolution is performed in this case.
5521     if (RD->hasTrivialDefaultConstructor())
5522       return true;
5523 
5524     if (Selected) {
5525       // If there's a default constructor which could have been trivial, dig it
5526       // out. Otherwise, if there's any user-provided default constructor, point
5527       // to that as an example of why there's not a trivial one.
5528       CXXConstructorDecl *DefCtor = nullptr;
5529       if (RD->needsImplicitDefaultConstructor())
5530         S.DeclareImplicitDefaultConstructor(RD);
5531       for (auto *CI : RD->ctors()) {
5532         if (!CI->isDefaultConstructor())
5533           continue;
5534         DefCtor = CI;
5535         if (!DefCtor->isUserProvided())
5536           break;
5537       }
5538 
5539       *Selected = DefCtor;
5540     }
5541 
5542     return false;
5543 
5544   case Sema::CXXDestructor:
5545     // C++11 [class.dtor]p5:
5546     //   A destructor is trivial if:
5547     //    - all the direct [subobjects] have trivial destructors
5548     if (RD->hasTrivialDestructor())
5549       return true;
5550 
5551     if (Selected) {
5552       if (RD->needsImplicitDestructor())
5553         S.DeclareImplicitDestructor(RD);
5554       *Selected = RD->getDestructor();
5555     }
5556 
5557     return false;
5558 
5559   case Sema::CXXCopyConstructor:
5560     // C++11 [class.copy]p12:
5561     //   A copy constructor is trivial if:
5562     //    - the constructor selected to copy each direct [subobject] is trivial
5563     if (RD->hasTrivialCopyConstructor()) {
5564       if (Quals == Qualifiers::Const)
5565         // We must either select the trivial copy constructor or reach an
5566         // ambiguity; no need to actually perform overload resolution.
5567         return true;
5568     } else if (!Selected) {
5569       return false;
5570     }
5571     // In C++98, we are not supposed to perform overload resolution here, but we
5572     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5573     // cases like B as having a non-trivial copy constructor:
5574     //   struct A { template<typename T> A(T&); };
5575     //   struct B { mutable A a; };
5576     goto NeedOverloadResolution;
5577 
5578   case Sema::CXXCopyAssignment:
5579     // C++11 [class.copy]p25:
5580     //   A copy assignment operator is trivial if:
5581     //    - the assignment operator selected to copy each direct [subobject] is
5582     //      trivial
5583     if (RD->hasTrivialCopyAssignment()) {
5584       if (Quals == Qualifiers::Const)
5585         return true;
5586     } else if (!Selected) {
5587       return false;
5588     }
5589     // In C++98, we are not supposed to perform overload resolution here, but we
5590     // treat that as a language defect.
5591     goto NeedOverloadResolution;
5592 
5593   case Sema::CXXMoveConstructor:
5594   case Sema::CXXMoveAssignment:
5595   NeedOverloadResolution:
5596     Sema::SpecialMemberOverloadResult *SMOR =
5597         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
5598 
5599     // The standard doesn't describe how to behave if the lookup is ambiguous.
5600     // We treat it as not making the member non-trivial, just like the standard
5601     // mandates for the default constructor. This should rarely matter, because
5602     // the member will also be deleted.
5603     if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5604       return true;
5605 
5606     if (!SMOR->getMethod()) {
5607       assert(SMOR->getKind() ==
5608              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5609       return false;
5610     }
5611 
5612     // We deliberately don't check if we found a deleted special member. We're
5613     // not supposed to!
5614     if (Selected)
5615       *Selected = SMOR->getMethod();
5616     return SMOR->getMethod()->isTrivial();
5617   }
5618 
5619   llvm_unreachable("unknown special method kind");
5620 }
5621 
5622 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
5623   for (auto *CI : RD->ctors())
5624     if (!CI->isImplicit())
5625       return CI;
5626 
5627   // Look for constructor templates.
5628   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5629   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5630     if (CXXConstructorDecl *CD =
5631           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5632       return CD;
5633   }
5634 
5635   return nullptr;
5636 }
5637 
5638 /// The kind of subobject we are checking for triviality. The values of this
5639 /// enumeration are used in diagnostics.
5640 enum TrivialSubobjectKind {
5641   /// The subobject is a base class.
5642   TSK_BaseClass,
5643   /// The subobject is a non-static data member.
5644   TSK_Field,
5645   /// The object is actually the complete object.
5646   TSK_CompleteObject
5647 };
5648 
5649 /// Check whether the special member selected for a given type would be trivial.
5650 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5651                                       QualType SubType, bool ConstRHS,
5652                                       Sema::CXXSpecialMember CSM,
5653                                       TrivialSubobjectKind Kind,
5654                                       bool Diagnose) {
5655   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5656   if (!SubRD)
5657     return true;
5658 
5659   CXXMethodDecl *Selected;
5660   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5661                                ConstRHS, Diagnose ? &Selected : nullptr))
5662     return true;
5663 
5664   if (Diagnose) {
5665     if (ConstRHS)
5666       SubType.addConst();
5667 
5668     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5669       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5670         << Kind << SubType.getUnqualifiedType();
5671       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5672         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5673     } else if (!Selected)
5674       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5675         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5676     else if (Selected->isUserProvided()) {
5677       if (Kind == TSK_CompleteObject)
5678         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5679           << Kind << SubType.getUnqualifiedType() << CSM;
5680       else {
5681         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5682           << Kind << SubType.getUnqualifiedType() << CSM;
5683         S.Diag(Selected->getLocation(), diag::note_declared_at);
5684       }
5685     } else {
5686       if (Kind != TSK_CompleteObject)
5687         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5688           << Kind << SubType.getUnqualifiedType() << CSM;
5689 
5690       // Explain why the defaulted or deleted special member isn't trivial.
5691       S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5692     }
5693   }
5694 
5695   return false;
5696 }
5697 
5698 /// Check whether the members of a class type allow a special member to be
5699 /// trivial.
5700 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5701                                      Sema::CXXSpecialMember CSM,
5702                                      bool ConstArg, bool Diagnose) {
5703   for (const auto *FI : RD->fields()) {
5704     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5705       continue;
5706 
5707     QualType FieldType = S.Context.getBaseElementType(FI->getType());
5708 
5709     // Pretend anonymous struct or union members are members of this class.
5710     if (FI->isAnonymousStructOrUnion()) {
5711       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5712                                     CSM, ConstArg, Diagnose))
5713         return false;
5714       continue;
5715     }
5716 
5717     // C++11 [class.ctor]p5:
5718     //   A default constructor is trivial if [...]
5719     //    -- no non-static data member of its class has a
5720     //       brace-or-equal-initializer
5721     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5722       if (Diagnose)
5723         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
5724       return false;
5725     }
5726 
5727     // Objective C ARC 4.3.5:
5728     //   [...] nontrivally ownership-qualified types are [...] not trivially
5729     //   default constructible, copy constructible, move constructible, copy
5730     //   assignable, move assignable, or destructible [...]
5731     if (S.getLangOpts().ObjCAutoRefCount &&
5732         FieldType.hasNonTrivialObjCLifetime()) {
5733       if (Diagnose)
5734         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5735           << RD << FieldType.getObjCLifetime();
5736       return false;
5737     }
5738 
5739     bool ConstRHS = ConstArg && !FI->isMutable();
5740     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
5741                                    CSM, TSK_Field, Diagnose))
5742       return false;
5743   }
5744 
5745   return true;
5746 }
5747 
5748 /// Diagnose why the specified class does not have a trivial special member of
5749 /// the given kind.
5750 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5751   QualType Ty = Context.getRecordType(RD);
5752 
5753   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
5754   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
5755                             TSK_CompleteObject, /*Diagnose*/true);
5756 }
5757 
5758 /// Determine whether a defaulted or deleted special member function is trivial,
5759 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5760 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5761 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5762                                   bool Diagnose) {
5763   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5764 
5765   CXXRecordDecl *RD = MD->getParent();
5766 
5767   bool ConstArg = false;
5768 
5769   // C++11 [class.copy]p12, p25: [DR1593]
5770   //   A [special member] is trivial if [...] its parameter-type-list is
5771   //   equivalent to the parameter-type-list of an implicit declaration [...]
5772   switch (CSM) {
5773   case CXXDefaultConstructor:
5774   case CXXDestructor:
5775     // Trivial default constructors and destructors cannot have parameters.
5776     break;
5777 
5778   case CXXCopyConstructor:
5779   case CXXCopyAssignment: {
5780     // Trivial copy operations always have const, non-volatile parameter types.
5781     ConstArg = true;
5782     const ParmVarDecl *Param0 = MD->getParamDecl(0);
5783     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5784     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5785       if (Diagnose)
5786         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5787           << Param0->getSourceRange() << Param0->getType()
5788           << Context.getLValueReferenceType(
5789                Context.getRecordType(RD).withConst());
5790       return false;
5791     }
5792     break;
5793   }
5794 
5795   case CXXMoveConstructor:
5796   case CXXMoveAssignment: {
5797     // Trivial move operations always have non-cv-qualified parameters.
5798     const ParmVarDecl *Param0 = MD->getParamDecl(0);
5799     const RValueReferenceType *RT =
5800       Param0->getType()->getAs<RValueReferenceType>();
5801     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5802       if (Diagnose)
5803         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5804           << Param0->getSourceRange() << Param0->getType()
5805           << Context.getRValueReferenceType(Context.getRecordType(RD));
5806       return false;
5807     }
5808     break;
5809   }
5810 
5811   case CXXInvalid:
5812     llvm_unreachable("not a special member");
5813   }
5814 
5815   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5816     if (Diagnose)
5817       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5818            diag::note_nontrivial_default_arg)
5819         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5820     return false;
5821   }
5822   if (MD->isVariadic()) {
5823     if (Diagnose)
5824       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5825     return false;
5826   }
5827 
5828   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5829   //   A copy/move [constructor or assignment operator] is trivial if
5830   //    -- the [member] selected to copy/move each direct base class subobject
5831   //       is trivial
5832   //
5833   // C++11 [class.copy]p12, C++11 [class.copy]p25:
5834   //   A [default constructor or destructor] is trivial if
5835   //    -- all the direct base classes have trivial [default constructors or
5836   //       destructors]
5837   for (const auto &BI : RD->bases())
5838     if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
5839                                    ConstArg, CSM, TSK_BaseClass, Diagnose))
5840       return false;
5841 
5842   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5843   //   A copy/move [constructor or assignment operator] for a class X is
5844   //   trivial if
5845   //    -- for each non-static data member of X that is of class type (or array
5846   //       thereof), the constructor selected to copy/move that member is
5847   //       trivial
5848   //
5849   // C++11 [class.copy]p12, C++11 [class.copy]p25:
5850   //   A [default constructor or destructor] is trivial if
5851   //    -- for all of the non-static data members of its class that are of class
5852   //       type (or array thereof), each such class has a trivial [default
5853   //       constructor or destructor]
5854   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5855     return false;
5856 
5857   // C++11 [class.dtor]p5:
5858   //   A destructor is trivial if [...]
5859   //    -- the destructor is not virtual
5860   if (CSM == CXXDestructor && MD->isVirtual()) {
5861     if (Diagnose)
5862       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5863     return false;
5864   }
5865 
5866   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5867   //   A [special member] for class X is trivial if [...]
5868   //    -- class X has no virtual functions and no virtual base classes
5869   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5870     if (!Diagnose)
5871       return false;
5872 
5873     if (RD->getNumVBases()) {
5874       // Check for virtual bases. We already know that the corresponding
5875       // member in all bases is trivial, so vbases must all be direct.
5876       CXXBaseSpecifier &BS = *RD->vbases_begin();
5877       assert(BS.isVirtual());
5878       Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5879       return false;
5880     }
5881 
5882     // Must have a virtual method.
5883     for (const auto *MI : RD->methods()) {
5884       if (MI->isVirtual()) {
5885         SourceLocation MLoc = MI->getLocStart();
5886         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5887         return false;
5888       }
5889     }
5890 
5891     llvm_unreachable("dynamic class with no vbases and no virtual functions");
5892   }
5893 
5894   // Looks like it's trivial!
5895   return true;
5896 }
5897 
5898 /// \brief Data used with FindHiddenVirtualMethod
5899 namespace {
5900   struct FindHiddenVirtualMethodData {
5901     Sema *S;
5902     CXXMethodDecl *Method;
5903     llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
5904     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5905   };
5906 }
5907 
5908 /// \brief Check whether any most overriden method from MD in Methods
5909 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5910                    const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5911   if (MD->size_overridden_methods() == 0)
5912     return Methods.count(MD->getCanonicalDecl());
5913   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5914                                       E = MD->end_overridden_methods();
5915        I != E; ++I)
5916     if (CheckMostOverridenMethods(*I, Methods))
5917       return true;
5918   return false;
5919 }
5920 
5921 /// \brief Member lookup function that determines whether a given C++
5922 /// method overloads virtual methods in a base class without overriding any,
5923 /// to be used with CXXRecordDecl::lookupInBases().
5924 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5925                                     CXXBasePath &Path,
5926                                     void *UserData) {
5927   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5928 
5929   FindHiddenVirtualMethodData &Data
5930     = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5931 
5932   DeclarationName Name = Data.Method->getDeclName();
5933   assert(Name.getNameKind() == DeclarationName::Identifier);
5934 
5935   bool foundSameNameMethod = false;
5936   SmallVector<CXXMethodDecl *, 8> overloadedMethods;
5937   for (Path.Decls = BaseRecord->lookup(Name);
5938        !Path.Decls.empty();
5939        Path.Decls = Path.Decls.slice(1)) {
5940     NamedDecl *D = Path.Decls.front();
5941     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5942       MD = MD->getCanonicalDecl();
5943       foundSameNameMethod = true;
5944       // Interested only in hidden virtual methods.
5945       if (!MD->isVirtual())
5946         continue;
5947       // If the method we are checking overrides a method from its base
5948       // don't warn about the other overloaded methods.
5949       if (!Data.S->IsOverload(Data.Method, MD, false))
5950         return true;
5951       // Collect the overload only if its hidden.
5952       if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
5953         overloadedMethods.push_back(MD);
5954     }
5955   }
5956 
5957   if (foundSameNameMethod)
5958     Data.OverloadedMethods.append(overloadedMethods.begin(),
5959                                    overloadedMethods.end());
5960   return foundSameNameMethod;
5961 }
5962 
5963 /// \brief Add the most overriden methods from MD to Methods
5964 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5965                          llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5966   if (MD->size_overridden_methods() == 0)
5967     Methods.insert(MD->getCanonicalDecl());
5968   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5969                                       E = MD->end_overridden_methods();
5970        I != E; ++I)
5971     AddMostOverridenMethods(*I, Methods);
5972 }
5973 
5974 /// \brief Check if a method overloads virtual methods in a base class without
5975 /// overriding any.
5976 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
5977                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
5978   if (!MD->getDeclName().isIdentifier())
5979     return;
5980 
5981   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5982                      /*bool RecordPaths=*/false,
5983                      /*bool DetectVirtual=*/false);
5984   FindHiddenVirtualMethodData Data;
5985   Data.Method = MD;
5986   Data.S = this;
5987 
5988   // Keep the base methods that were overriden or introduced in the subclass
5989   // by 'using' in a set. A base method not in this set is hidden.
5990   CXXRecordDecl *DC = MD->getParent();
5991   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5992   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5993     NamedDecl *ND = *I;
5994     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
5995       ND = shad->getTargetDecl();
5996     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5997       AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
5998   }
5999 
6000   if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
6001     OverloadedMethods = Data.OverloadedMethods;
6002 }
6003 
6004 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6005                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6006   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
6007     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
6008     PartialDiagnostic PD = PDiag(
6009          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
6010     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
6011     Diag(overloadedMD->getLocation(), PD);
6012   }
6013 }
6014 
6015 /// \brief Diagnose methods which overload virtual methods in a base class
6016 /// without overriding any.
6017 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
6018   if (MD->isInvalidDecl())
6019     return;
6020 
6021   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
6022     return;
6023 
6024   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6025   FindHiddenVirtualMethods(MD, OverloadedMethods);
6026   if (!OverloadedMethods.empty()) {
6027     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
6028       << MD << (OverloadedMethods.size() > 1);
6029 
6030     NoteHiddenVirtualMethods(MD, OverloadedMethods);
6031   }
6032 }
6033 
6034 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
6035                                              Decl *TagDecl,
6036                                              SourceLocation LBrac,
6037                                              SourceLocation RBrac,
6038                                              AttributeList *AttrList) {
6039   if (!TagDecl)
6040     return;
6041 
6042   AdjustDeclIfTemplate(TagDecl);
6043 
6044   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6045     if (l->getKind() != AttributeList::AT_Visibility)
6046       continue;
6047     l->setInvalid();
6048     Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
6049       l->getName();
6050   }
6051 
6052   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
6053               // strict aliasing violation!
6054               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
6055               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
6056 
6057   CheckCompletedCXXClass(
6058                         dyn_cast_or_null<CXXRecordDecl>(TagDecl));
6059 }
6060 
6061 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6062 /// special functions, such as the default constructor, copy
6063 /// constructor, or destructor, to the given C++ class (C++
6064 /// [special]p1).  This routine can only be executed just before the
6065 /// definition of the class is complete.
6066 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
6067   if (!ClassDecl->hasUserDeclaredConstructor())
6068     ++ASTContext::NumImplicitDefaultConstructors;
6069 
6070   if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
6071     ++ASTContext::NumImplicitCopyConstructors;
6072 
6073     // If the properties or semantics of the copy constructor couldn't be
6074     // determined while the class was being declared, force a declaration
6075     // of it now.
6076     if (ClassDecl->needsOverloadResolutionForCopyConstructor())
6077       DeclareImplicitCopyConstructor(ClassDecl);
6078   }
6079 
6080   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
6081     ++ASTContext::NumImplicitMoveConstructors;
6082 
6083     if (ClassDecl->needsOverloadResolutionForMoveConstructor())
6084       DeclareImplicitMoveConstructor(ClassDecl);
6085   }
6086 
6087   if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6088     ++ASTContext::NumImplicitCopyAssignmentOperators;
6089 
6090     // If we have a dynamic class, then the copy assignment operator may be
6091     // virtual, so we have to declare it immediately. This ensures that, e.g.,
6092     // it shows up in the right place in the vtable and that we diagnose
6093     // problems with the implicit exception specification.
6094     if (ClassDecl->isDynamicClass() ||
6095         ClassDecl->needsOverloadResolutionForCopyAssignment())
6096       DeclareImplicitCopyAssignment(ClassDecl);
6097   }
6098 
6099   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
6100     ++ASTContext::NumImplicitMoveAssignmentOperators;
6101 
6102     // Likewise for the move assignment operator.
6103     if (ClassDecl->isDynamicClass() ||
6104         ClassDecl->needsOverloadResolutionForMoveAssignment())
6105       DeclareImplicitMoveAssignment(ClassDecl);
6106   }
6107 
6108   if (!ClassDecl->hasUserDeclaredDestructor()) {
6109     ++ASTContext::NumImplicitDestructors;
6110 
6111     // If we have a dynamic class, then the destructor may be virtual, so we
6112     // have to declare the destructor immediately. This ensures that, e.g., it
6113     // shows up in the right place in the vtable and that we diagnose problems
6114     // with the implicit exception specification.
6115     if (ClassDecl->isDynamicClass() ||
6116         ClassDecl->needsOverloadResolutionForDestructor())
6117       DeclareImplicitDestructor(ClassDecl);
6118   }
6119 }
6120 
6121 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
6122   if (!D)
6123     return 0;
6124 
6125   // The order of template parameters is not important here. All names
6126   // get added to the same scope.
6127   SmallVector<TemplateParameterList *, 4> ParameterLists;
6128 
6129   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6130     D = TD->getTemplatedDecl();
6131 
6132   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6133     ParameterLists.push_back(PSD->getTemplateParameters());
6134 
6135   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6136     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6137       ParameterLists.push_back(DD->getTemplateParameterList(i));
6138 
6139     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6140       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6141         ParameterLists.push_back(FTD->getTemplateParameters());
6142     }
6143   }
6144 
6145   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6146     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6147       ParameterLists.push_back(TD->getTemplateParameterList(i));
6148 
6149     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6150       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6151         ParameterLists.push_back(CTD->getTemplateParameters());
6152     }
6153   }
6154 
6155   unsigned Count = 0;
6156   for (TemplateParameterList *Params : ParameterLists) {
6157     if (Params->size() > 0)
6158       // Ignore explicit specializations; they don't contribute to the template
6159       // depth.
6160       ++Count;
6161     for (NamedDecl *Param : *Params) {
6162       if (Param->getDeclName()) {
6163         S->AddDecl(Param);
6164         IdResolver.AddDecl(Param);
6165       }
6166     }
6167   }
6168 
6169   return Count;
6170 }
6171 
6172 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6173   if (!RecordD) return;
6174   AdjustDeclIfTemplate(RecordD);
6175   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
6176   PushDeclContext(S, Record);
6177 }
6178 
6179 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6180   if (!RecordD) return;
6181   PopDeclContext();
6182 }
6183 
6184 /// This is used to implement the constant expression evaluation part of the
6185 /// attribute enable_if extension. There is nothing in standard C++ which would
6186 /// require reentering parameters.
6187 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6188   if (!Param)
6189     return;
6190 
6191   S->AddDecl(Param);
6192   if (Param->getDeclName())
6193     IdResolver.AddDecl(Param);
6194 }
6195 
6196 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
6197 /// parsing a top-level (non-nested) C++ class, and we are now
6198 /// parsing those parts of the given Method declaration that could
6199 /// not be parsed earlier (C++ [class.mem]p2), such as default
6200 /// arguments. This action should enter the scope of the given
6201 /// Method declaration as if we had just parsed the qualified method
6202 /// name. However, it should not bring the parameters into scope;
6203 /// that will be performed by ActOnDelayedCXXMethodParameter.
6204 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6205 }
6206 
6207 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
6208 /// C++ method declaration. We're (re-)introducing the given
6209 /// function parameter into scope for use in parsing later parts of
6210 /// the method declaration. For example, we could see an
6211 /// ActOnParamDefaultArgument event for this parameter.
6212 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
6213   if (!ParamD)
6214     return;
6215 
6216   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
6217 
6218   // If this parameter has an unparsed default argument, clear it out
6219   // to make way for the parsed default argument.
6220   if (Param->hasUnparsedDefaultArg())
6221     Param->setDefaultArg(nullptr);
6222 
6223   S->AddDecl(Param);
6224   if (Param->getDeclName())
6225     IdResolver.AddDecl(Param);
6226 }
6227 
6228 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6229 /// processing the delayed method declaration for Method. The method
6230 /// declaration is now considered finished. There may be a separate
6231 /// ActOnStartOfFunctionDef action later (not necessarily
6232 /// immediately!) for this method, if it was also defined inside the
6233 /// class body.
6234 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6235   if (!MethodD)
6236     return;
6237 
6238   AdjustDeclIfTemplate(MethodD);
6239 
6240   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
6241 
6242   // Now that we have our default arguments, check the constructor
6243   // again. It could produce additional diagnostics or affect whether
6244   // the class has implicitly-declared destructors, among other
6245   // things.
6246   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6247     CheckConstructor(Constructor);
6248 
6249   // Check the default arguments, which we may have added.
6250   if (!Method->isInvalidDecl())
6251     CheckCXXDefaultArguments(Method);
6252 }
6253 
6254 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
6255 /// the well-formedness of the constructor declarator @p D with type @p
6256 /// R. If there are any errors in the declarator, this routine will
6257 /// emit diagnostics and set the invalid bit to true.  In any case, the type
6258 /// will be updated to reflect a well-formed type for the constructor and
6259 /// returned.
6260 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
6261                                           StorageClass &SC) {
6262   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6263 
6264   // C++ [class.ctor]p3:
6265   //   A constructor shall not be virtual (10.3) or static (9.4). A
6266   //   constructor can be invoked for a const, volatile or const
6267   //   volatile object. A constructor shall not be declared const,
6268   //   volatile, or const volatile (9.3.2).
6269   if (isVirtual) {
6270     if (!D.isInvalidType())
6271       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6272         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6273         << SourceRange(D.getIdentifierLoc());
6274     D.setInvalidType();
6275   }
6276   if (SC == SC_Static) {
6277     if (!D.isInvalidType())
6278       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6279         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6280         << SourceRange(D.getIdentifierLoc());
6281     D.setInvalidType();
6282     SC = SC_None;
6283   }
6284 
6285   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6286     diagnoseIgnoredQualifiers(
6287         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
6288         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
6289         D.getDeclSpec().getRestrictSpecLoc(),
6290         D.getDeclSpec().getAtomicSpecLoc());
6291     D.setInvalidType();
6292   }
6293 
6294   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6295   if (FTI.TypeQuals != 0) {
6296     if (FTI.TypeQuals & Qualifiers::Const)
6297       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6298         << "const" << SourceRange(D.getIdentifierLoc());
6299     if (FTI.TypeQuals & Qualifiers::Volatile)
6300       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6301         << "volatile" << SourceRange(D.getIdentifierLoc());
6302     if (FTI.TypeQuals & Qualifiers::Restrict)
6303       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6304         << "restrict" << SourceRange(D.getIdentifierLoc());
6305     D.setInvalidType();
6306   }
6307 
6308   // C++0x [class.ctor]p4:
6309   //   A constructor shall not be declared with a ref-qualifier.
6310   if (FTI.hasRefQualifier()) {
6311     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6312       << FTI.RefQualifierIsLValueRef
6313       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6314     D.setInvalidType();
6315   }
6316 
6317   // Rebuild the function type "R" without any type qualifiers (in
6318   // case any of the errors above fired) and with "void" as the
6319   // return type, since constructors don't have return types.
6320   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6321   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
6322     return R;
6323 
6324   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6325   EPI.TypeQuals = 0;
6326   EPI.RefQualifier = RQ_None;
6327 
6328   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
6329 }
6330 
6331 /// CheckConstructor - Checks a fully-formed constructor for
6332 /// well-formedness, issuing any diagnostics required. Returns true if
6333 /// the constructor declarator is invalid.
6334 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
6335   CXXRecordDecl *ClassDecl
6336     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6337   if (!ClassDecl)
6338     return Constructor->setInvalidDecl();
6339 
6340   // C++ [class.copy]p3:
6341   //   A declaration of a constructor for a class X is ill-formed if
6342   //   its first parameter is of type (optionally cv-qualified) X and
6343   //   either there are no other parameters or else all other
6344   //   parameters have default arguments.
6345   if (!Constructor->isInvalidDecl() &&
6346       ((Constructor->getNumParams() == 1) ||
6347        (Constructor->getNumParams() > 1 &&
6348         Constructor->getParamDecl(1)->hasDefaultArg())) &&
6349       Constructor->getTemplateSpecializationKind()
6350                                               != TSK_ImplicitInstantiation) {
6351     QualType ParamType = Constructor->getParamDecl(0)->getType();
6352     QualType ClassTy = Context.getTagDeclType(ClassDecl);
6353     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
6354       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
6355       const char *ConstRef
6356         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6357                                                         : " const &";
6358       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
6359         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
6360 
6361       // FIXME: Rather that making the constructor invalid, we should endeavor
6362       // to fix the type.
6363       Constructor->setInvalidDecl();
6364     }
6365   }
6366 }
6367 
6368 /// CheckDestructor - Checks a fully-formed destructor definition for
6369 /// well-formedness, issuing any diagnostics required.  Returns true
6370 /// on error.
6371 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
6372   CXXRecordDecl *RD = Destructor->getParent();
6373 
6374   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
6375     SourceLocation Loc;
6376 
6377     if (!Destructor->isImplicit())
6378       Loc = Destructor->getLocation();
6379     else
6380       Loc = RD->getLocation();
6381 
6382     // If we have a virtual destructor, look up the deallocation function
6383     FunctionDecl *OperatorDelete = nullptr;
6384     DeclarationName Name =
6385     Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6386     if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
6387       return true;
6388     // If there's no class-specific operator delete, look up the global
6389     // non-array delete.
6390     if (!OperatorDelete)
6391       OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
6392 
6393     MarkFunctionReferenced(Loc, OperatorDelete);
6394 
6395     Destructor->setOperatorDelete(OperatorDelete);
6396   }
6397 
6398   return false;
6399 }
6400 
6401 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6402 /// the well-formednes of the destructor declarator @p D with type @p
6403 /// R. If there are any errors in the declarator, this routine will
6404 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
6405 /// will be updated to reflect a well-formed type for the destructor and
6406 /// returned.
6407 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
6408                                          StorageClass& SC) {
6409   // C++ [class.dtor]p1:
6410   //   [...] A typedef-name that names a class is a class-name
6411   //   (7.1.3); however, a typedef-name that names a class shall not
6412   //   be used as the identifier in the declarator for a destructor
6413   //   declaration.
6414   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
6415   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
6416     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6417       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
6418   else if (const TemplateSpecializationType *TST =
6419              DeclaratorType->getAs<TemplateSpecializationType>())
6420     if (TST->isTypeAlias())
6421       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6422         << DeclaratorType << 1;
6423 
6424   // C++ [class.dtor]p2:
6425   //   A destructor is used to destroy objects of its class type. A
6426   //   destructor takes no parameters, and no return type can be
6427   //   specified for it (not even void). The address of a destructor
6428   //   shall not be taken. A destructor shall not be static. A
6429   //   destructor can be invoked for a const, volatile or const
6430   //   volatile object. A destructor shall not be declared const,
6431   //   volatile or const volatile (9.3.2).
6432   if (SC == SC_Static) {
6433     if (!D.isInvalidType())
6434       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6435         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6436         << SourceRange(D.getIdentifierLoc())
6437         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6438 
6439     SC = SC_None;
6440   }
6441   if (!D.isInvalidType()) {
6442     // Destructors don't have return types, but the parser will
6443     // happily parse something like:
6444     //
6445     //   class X {
6446     //     float ~X();
6447     //   };
6448     //
6449     // The return type will be eliminated later.
6450     if (D.getDeclSpec().hasTypeSpecifier())
6451       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6452         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6453         << SourceRange(D.getIdentifierLoc());
6454     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6455       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
6456                                 SourceLocation(),
6457                                 D.getDeclSpec().getConstSpecLoc(),
6458                                 D.getDeclSpec().getVolatileSpecLoc(),
6459                                 D.getDeclSpec().getRestrictSpecLoc(),
6460                                 D.getDeclSpec().getAtomicSpecLoc());
6461       D.setInvalidType();
6462     }
6463   }
6464 
6465   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6466   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
6467     if (FTI.TypeQuals & Qualifiers::Const)
6468       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6469         << "const" << SourceRange(D.getIdentifierLoc());
6470     if (FTI.TypeQuals & Qualifiers::Volatile)
6471       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6472         << "volatile" << SourceRange(D.getIdentifierLoc());
6473     if (FTI.TypeQuals & Qualifiers::Restrict)
6474       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6475         << "restrict" << SourceRange(D.getIdentifierLoc());
6476     D.setInvalidType();
6477   }
6478 
6479   // C++0x [class.dtor]p2:
6480   //   A destructor shall not be declared with a ref-qualifier.
6481   if (FTI.hasRefQualifier()) {
6482     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6483       << FTI.RefQualifierIsLValueRef
6484       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6485     D.setInvalidType();
6486   }
6487 
6488   // Make sure we don't have any parameters.
6489   if (FTIHasNonVoidParameters(FTI)) {
6490     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6491 
6492     // Delete the parameters.
6493     FTI.freeParams();
6494     D.setInvalidType();
6495   }
6496 
6497   // Make sure the destructor isn't variadic.
6498   if (FTI.isVariadic) {
6499     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
6500     D.setInvalidType();
6501   }
6502 
6503   // Rebuild the function type "R" without any type qualifiers or
6504   // parameters (in case any of the errors above fired) and with
6505   // "void" as the return type, since destructors don't have return
6506   // types.
6507   if (!D.isInvalidType())
6508     return R;
6509 
6510   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6511   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6512   EPI.Variadic = false;
6513   EPI.TypeQuals = 0;
6514   EPI.RefQualifier = RQ_None;
6515   return Context.getFunctionType(Context.VoidTy, None, EPI);
6516 }
6517 
6518 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6519 /// well-formednes of the conversion function declarator @p D with
6520 /// type @p R. If there are any errors in the declarator, this routine
6521 /// will emit diagnostics and return true. Otherwise, it will return
6522 /// false. Either way, the type @p R will be updated to reflect a
6523 /// well-formed type for the conversion operator.
6524 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
6525                                      StorageClass& SC) {
6526   // C++ [class.conv.fct]p1:
6527   //   Neither parameter types nor return type can be specified. The
6528   //   type of a conversion function (8.3.5) is "function taking no
6529   //   parameter returning conversion-type-id."
6530   if (SC == SC_Static) {
6531     if (!D.isInvalidType())
6532       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
6533         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6534         << D.getName().getSourceRange();
6535     D.setInvalidType();
6536     SC = SC_None;
6537   }
6538 
6539   QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6540 
6541   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
6542     // Conversion functions don't have return types, but the parser will
6543     // happily parse something like:
6544     //
6545     //   class X {
6546     //     float operator bool();
6547     //   };
6548     //
6549     // The return type will be changed later anyway.
6550     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6551       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6552       << SourceRange(D.getIdentifierLoc());
6553     D.setInvalidType();
6554   }
6555 
6556   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6557 
6558   // Make sure we don't have any parameters.
6559   if (Proto->getNumParams() > 0) {
6560     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6561 
6562     // Delete the parameters.
6563     D.getFunctionTypeInfo().freeParams();
6564     D.setInvalidType();
6565   } else if (Proto->isVariadic()) {
6566     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
6567     D.setInvalidType();
6568   }
6569 
6570   // Diagnose "&operator bool()" and other such nonsense.  This
6571   // is actually a gcc extension which we don't support.
6572   if (Proto->getReturnType() != ConvType) {
6573     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6574         << Proto->getReturnType();
6575     D.setInvalidType();
6576     ConvType = Proto->getReturnType();
6577   }
6578 
6579   // C++ [class.conv.fct]p4:
6580   //   The conversion-type-id shall not represent a function type nor
6581   //   an array type.
6582   if (ConvType->isArrayType()) {
6583     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6584     ConvType = Context.getPointerType(ConvType);
6585     D.setInvalidType();
6586   } else if (ConvType->isFunctionType()) {
6587     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6588     ConvType = Context.getPointerType(ConvType);
6589     D.setInvalidType();
6590   }
6591 
6592   // Rebuild the function type "R" without any parameters (in case any
6593   // of the errors above fired) and with the conversion type as the
6594   // return type.
6595   if (D.isInvalidType())
6596     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
6597 
6598   // C++0x explicit conversion operators.
6599   if (D.getDeclSpec().isExplicitSpecified())
6600     Diag(D.getDeclSpec().getExplicitSpecLoc(),
6601          getLangOpts().CPlusPlus11 ?
6602            diag::warn_cxx98_compat_explicit_conversion_functions :
6603            diag::ext_explicit_conversion_functions)
6604       << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
6605 }
6606 
6607 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6608 /// the declaration of the given C++ conversion function. This routine
6609 /// is responsible for recording the conversion function in the C++
6610 /// class, if possible.
6611 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
6612   assert(Conversion && "Expected to receive a conversion function declaration");
6613 
6614   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
6615 
6616   // Make sure we aren't redeclaring the conversion function.
6617   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
6618 
6619   // C++ [class.conv.fct]p1:
6620   //   [...] A conversion function is never used to convert a
6621   //   (possibly cv-qualified) object to the (possibly cv-qualified)
6622   //   same object type (or a reference to it), to a (possibly
6623   //   cv-qualified) base class of that type (or a reference to it),
6624   //   or to (possibly cv-qualified) void.
6625   // FIXME: Suppress this warning if the conversion function ends up being a
6626   // virtual function that overrides a virtual function in a base class.
6627   QualType ClassType
6628     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6629   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
6630     ConvType = ConvTypeRef->getPointeeType();
6631   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6632       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
6633     /* Suppress diagnostics for instantiations. */;
6634   else if (ConvType->isRecordType()) {
6635     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6636     if (ConvType == ClassType)
6637       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
6638         << ClassType;
6639     else if (IsDerivedFrom(ClassType, ConvType))
6640       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
6641         <<  ClassType << ConvType;
6642   } else if (ConvType->isVoidType()) {
6643     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
6644       << ClassType << ConvType;
6645   }
6646 
6647   if (FunctionTemplateDecl *ConversionTemplate
6648                                 = Conversion->getDescribedFunctionTemplate())
6649     return ConversionTemplate;
6650 
6651   return Conversion;
6652 }
6653 
6654 //===----------------------------------------------------------------------===//
6655 // Namespace Handling
6656 //===----------------------------------------------------------------------===//
6657 
6658 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6659 /// reopened.
6660 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6661                                             SourceLocation Loc,
6662                                             IdentifierInfo *II, bool *IsInline,
6663                                             NamespaceDecl *PrevNS) {
6664   assert(*IsInline != PrevNS->isInline());
6665 
6666   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6667   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6668   // inline namespaces, with the intention of bringing names into namespace std.
6669   //
6670   // We support this just well enough to get that case working; this is not
6671   // sufficient to support reopening namespaces as inline in general.
6672   if (*IsInline && II && II->getName().startswith("__atomic") &&
6673       S.getSourceManager().isInSystemHeader(Loc)) {
6674     // Mark all prior declarations of the namespace as inline.
6675     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6676          NS = NS->getPreviousDecl())
6677       NS->setInline(*IsInline);
6678     // Patch up the lookup table for the containing namespace. This isn't really
6679     // correct, but it's good enough for this particular case.
6680     for (auto *I : PrevNS->decls())
6681       if (auto *ND = dyn_cast<NamedDecl>(I))
6682         PrevNS->getParent()->makeDeclVisibleInContext(ND);
6683     return;
6684   }
6685 
6686   if (PrevNS->isInline())
6687     // The user probably just forgot the 'inline', so suggest that it
6688     // be added back.
6689     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6690       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6691   else
6692     S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
6693 
6694   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6695   *IsInline = PrevNS->isInline();
6696 }
6697 
6698 /// ActOnStartNamespaceDef - This is called at the start of a namespace
6699 /// definition.
6700 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
6701                                    SourceLocation InlineLoc,
6702                                    SourceLocation NamespaceLoc,
6703                                    SourceLocation IdentLoc,
6704                                    IdentifierInfo *II,
6705                                    SourceLocation LBrace,
6706                                    AttributeList *AttrList) {
6707   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6708   // For anonymous namespace, take the location of the left brace.
6709   SourceLocation Loc = II ? IdentLoc : LBrace;
6710   bool IsInline = InlineLoc.isValid();
6711   bool IsInvalid = false;
6712   bool IsStd = false;
6713   bool AddToKnown = false;
6714   Scope *DeclRegionScope = NamespcScope->getParent();
6715 
6716   NamespaceDecl *PrevNS = nullptr;
6717   if (II) {
6718     // C++ [namespace.def]p2:
6719     //   The identifier in an original-namespace-definition shall not
6720     //   have been previously defined in the declarative region in
6721     //   which the original-namespace-definition appears. The
6722     //   identifier in an original-namespace-definition is the name of
6723     //   the namespace. Subsequently in that declarative region, it is
6724     //   treated as an original-namespace-name.
6725     //
6726     // Since namespace names are unique in their scope, and we don't
6727     // look through using directives, just look for any ordinary names.
6728 
6729     const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
6730     Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6731     Decl::IDNS_Namespace;
6732     NamedDecl *PrevDecl = nullptr;
6733     DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6734     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6735          ++I) {
6736       if ((*I)->getIdentifierNamespace() & IDNS) {
6737         PrevDecl = *I;
6738         break;
6739       }
6740     }
6741 
6742     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6743 
6744     if (PrevNS) {
6745       // This is an extended namespace definition.
6746       if (IsInline != PrevNS->isInline())
6747         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6748                                         &IsInline, PrevNS);
6749     } else if (PrevDecl) {
6750       // This is an invalid name redefinition.
6751       Diag(Loc, diag::err_redefinition_different_kind)
6752         << II;
6753       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6754       IsInvalid = true;
6755       // Continue on to push Namespc as current DeclContext and return it.
6756     } else if (II->isStr("std") &&
6757                CurContext->getRedeclContext()->isTranslationUnit()) {
6758       // This is the first "real" definition of the namespace "std", so update
6759       // our cache of the "std" namespace to point at this definition.
6760       PrevNS = getStdNamespace();
6761       IsStd = true;
6762       AddToKnown = !IsInline;
6763     } else {
6764       // We've seen this namespace for the first time.
6765       AddToKnown = !IsInline;
6766     }
6767   } else {
6768     // Anonymous namespaces.
6769 
6770     // Determine whether the parent already has an anonymous namespace.
6771     DeclContext *Parent = CurContext->getRedeclContext();
6772     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6773       PrevNS = TU->getAnonymousNamespace();
6774     } else {
6775       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
6776       PrevNS = ND->getAnonymousNamespace();
6777     }
6778 
6779     if (PrevNS && IsInline != PrevNS->isInline())
6780       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6781                                       &IsInline, PrevNS);
6782   }
6783 
6784   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6785                                                  StartLoc, Loc, II, PrevNS);
6786   if (IsInvalid)
6787     Namespc->setInvalidDecl();
6788 
6789   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
6790 
6791   // FIXME: Should we be merging attributes?
6792   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
6793     PushNamespaceVisibilityAttr(Attr, Loc);
6794 
6795   if (IsStd)
6796     StdNamespace = Namespc;
6797   if (AddToKnown)
6798     KnownNamespaces[Namespc] = false;
6799 
6800   if (II) {
6801     PushOnScopeChains(Namespc, DeclRegionScope);
6802   } else {
6803     // Link the anonymous namespace into its parent.
6804     DeclContext *Parent = CurContext->getRedeclContext();
6805     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6806       TU->setAnonymousNamespace(Namespc);
6807     } else {
6808       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
6809     }
6810 
6811     CurContext->addDecl(Namespc);
6812 
6813     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
6814     //   behaves as if it were replaced by
6815     //     namespace unique { /* empty body */ }
6816     //     using namespace unique;
6817     //     namespace unique { namespace-body }
6818     //   where all occurrences of 'unique' in a translation unit are
6819     //   replaced by the same identifier and this identifier differs
6820     //   from all other identifiers in the entire program.
6821 
6822     // We just create the namespace with an empty name and then add an
6823     // implicit using declaration, just like the standard suggests.
6824     //
6825     // CodeGen enforces the "universally unique" aspect by giving all
6826     // declarations semantically contained within an anonymous
6827     // namespace internal linkage.
6828 
6829     if (!PrevNS) {
6830       UsingDirectiveDecl* UD
6831         = UsingDirectiveDecl::Create(Context, Parent,
6832                                      /* 'using' */ LBrace,
6833                                      /* 'namespace' */ SourceLocation(),
6834                                      /* qualifier */ NestedNameSpecifierLoc(),
6835                                      /* identifier */ SourceLocation(),
6836                                      Namespc,
6837                                      /* Ancestor */ Parent);
6838       UD->setImplicit();
6839       Parent->addDecl(UD);
6840     }
6841   }
6842 
6843   ActOnDocumentableDecl(Namespc);
6844 
6845   // Although we could have an invalid decl (i.e. the namespace name is a
6846   // redefinition), push it as current DeclContext and try to continue parsing.
6847   // FIXME: We should be able to push Namespc here, so that the each DeclContext
6848   // for the namespace has the declarations that showed up in that particular
6849   // namespace definition.
6850   PushDeclContext(NamespcScope, Namespc);
6851   return Namespc;
6852 }
6853 
6854 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6855 /// is a namespace alias, returns the namespace it points to.
6856 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6857   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6858     return AD->getNamespace();
6859   return dyn_cast_or_null<NamespaceDecl>(D);
6860 }
6861 
6862 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
6863 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
6864 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
6865   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6866   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
6867   Namespc->setRBraceLoc(RBrace);
6868   PopDeclContext();
6869   if (Namespc->hasAttr<VisibilityAttr>())
6870     PopPragmaVisibility(true, RBrace);
6871 }
6872 
6873 CXXRecordDecl *Sema::getStdBadAlloc() const {
6874   return cast_or_null<CXXRecordDecl>(
6875                                   StdBadAlloc.get(Context.getExternalSource()));
6876 }
6877 
6878 NamespaceDecl *Sema::getStdNamespace() const {
6879   return cast_or_null<NamespaceDecl>(
6880                                  StdNamespace.get(Context.getExternalSource()));
6881 }
6882 
6883 /// \brief Retrieve the special "std" namespace, which may require us to
6884 /// implicitly define the namespace.
6885 NamespaceDecl *Sema::getOrCreateStdNamespace() {
6886   if (!StdNamespace) {
6887     // The "std" namespace has not yet been defined, so build one implicitly.
6888     StdNamespace = NamespaceDecl::Create(Context,
6889                                          Context.getTranslationUnitDecl(),
6890                                          /*Inline=*/false,
6891                                          SourceLocation(), SourceLocation(),
6892                                          &PP.getIdentifierTable().get("std"),
6893                                          /*PrevDecl=*/nullptr);
6894     getStdNamespace()->setImplicit(true);
6895   }
6896 
6897   return getStdNamespace();
6898 }
6899 
6900 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
6901   assert(getLangOpts().CPlusPlus &&
6902          "Looking for std::initializer_list outside of C++.");
6903 
6904   // We're looking for implicit instantiations of
6905   // template <typename E> class std::initializer_list.
6906 
6907   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6908     return false;
6909 
6910   ClassTemplateDecl *Template = nullptr;
6911   const TemplateArgument *Arguments = nullptr;
6912 
6913   if (const RecordType *RT = Ty->getAs<RecordType>()) {
6914 
6915     ClassTemplateSpecializationDecl *Specialization =
6916         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6917     if (!Specialization)
6918       return false;
6919 
6920     Template = Specialization->getSpecializedTemplate();
6921     Arguments = Specialization->getTemplateArgs().data();
6922   } else if (const TemplateSpecializationType *TST =
6923                  Ty->getAs<TemplateSpecializationType>()) {
6924     Template = dyn_cast_or_null<ClassTemplateDecl>(
6925         TST->getTemplateName().getAsTemplateDecl());
6926     Arguments = TST->getArgs();
6927   }
6928   if (!Template)
6929     return false;
6930 
6931   if (!StdInitializerList) {
6932     // Haven't recognized std::initializer_list yet, maybe this is it.
6933     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6934     if (TemplateClass->getIdentifier() !=
6935             &PP.getIdentifierTable().get("initializer_list") ||
6936         !getStdNamespace()->InEnclosingNamespaceSetOf(
6937             TemplateClass->getDeclContext()))
6938       return false;
6939     // This is a template called std::initializer_list, but is it the right
6940     // template?
6941     TemplateParameterList *Params = Template->getTemplateParameters();
6942     if (Params->getMinRequiredArguments() != 1)
6943       return false;
6944     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6945       return false;
6946 
6947     // It's the right template.
6948     StdInitializerList = Template;
6949   }
6950 
6951   if (Template != StdInitializerList)
6952     return false;
6953 
6954   // This is an instance of std::initializer_list. Find the argument type.
6955   if (Element)
6956     *Element = Arguments[0].getAsType();
6957   return true;
6958 }
6959 
6960 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6961   NamespaceDecl *Std = S.getStdNamespace();
6962   if (!Std) {
6963     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6964     return nullptr;
6965   }
6966 
6967   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6968                       Loc, Sema::LookupOrdinaryName);
6969   if (!S.LookupQualifiedName(Result, Std)) {
6970     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6971     return nullptr;
6972   }
6973   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6974   if (!Template) {
6975     Result.suppressDiagnostics();
6976     // We found something weird. Complain about the first thing we found.
6977     NamedDecl *Found = *Result.begin();
6978     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6979     return nullptr;
6980   }
6981 
6982   // We found some template called std::initializer_list. Now verify that it's
6983   // correct.
6984   TemplateParameterList *Params = Template->getTemplateParameters();
6985   if (Params->getMinRequiredArguments() != 1 ||
6986       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6987     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6988     return nullptr;
6989   }
6990 
6991   return Template;
6992 }
6993 
6994 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6995   if (!StdInitializerList) {
6996     StdInitializerList = LookupStdInitializerList(*this, Loc);
6997     if (!StdInitializerList)
6998       return QualType();
6999   }
7000 
7001   TemplateArgumentListInfo Args(Loc, Loc);
7002   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
7003                                        Context.getTrivialTypeSourceInfo(Element,
7004                                                                         Loc)));
7005   return Context.getCanonicalType(
7006       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
7007 }
7008 
7009 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
7010   // C++ [dcl.init.list]p2:
7011   //   A constructor is an initializer-list constructor if its first parameter
7012   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
7013   //   std::initializer_list<E> for some type E, and either there are no other
7014   //   parameters or else all other parameters have default arguments.
7015   if (Ctor->getNumParams() < 1 ||
7016       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
7017     return false;
7018 
7019   QualType ArgType = Ctor->getParamDecl(0)->getType();
7020   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
7021     ArgType = RT->getPointeeType().getUnqualifiedType();
7022 
7023   return isStdInitializerList(ArgType, nullptr);
7024 }
7025 
7026 /// \brief Determine whether a using statement is in a context where it will be
7027 /// apply in all contexts.
7028 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
7029   switch (CurContext->getDeclKind()) {
7030     case Decl::TranslationUnit:
7031       return true;
7032     case Decl::LinkageSpec:
7033       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
7034     default:
7035       return false;
7036   }
7037 }
7038 
7039 namespace {
7040 
7041 // Callback to only accept typo corrections that are namespaces.
7042 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
7043 public:
7044   bool ValidateCandidate(const TypoCorrection &candidate) override {
7045     if (NamedDecl *ND = candidate.getCorrectionDecl())
7046       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
7047     return false;
7048   }
7049 };
7050 
7051 }
7052 
7053 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
7054                                        CXXScopeSpec &SS,
7055                                        SourceLocation IdentLoc,
7056                                        IdentifierInfo *Ident) {
7057   NamespaceValidatorCCC Validator;
7058   R.clear();
7059   if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
7060                                                R.getLookupKind(), Sc, &SS,
7061                                                Validator,
7062                                                Sema::CTK_ErrorRecovery)) {
7063     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
7064       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
7065       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
7066                               Ident->getName().equals(CorrectedStr);
7067       S.diagnoseTypo(Corrected,
7068                      S.PDiag(diag::err_using_directive_member_suggest)
7069                        << Ident << DC << DroppedSpecifier << SS.getRange(),
7070                      S.PDiag(diag::note_namespace_defined_here));
7071     } else {
7072       S.diagnoseTypo(Corrected,
7073                      S.PDiag(diag::err_using_directive_suggest) << Ident,
7074                      S.PDiag(diag::note_namespace_defined_here));
7075     }
7076     R.addDecl(Corrected.getCorrectionDecl());
7077     return true;
7078   }
7079   return false;
7080 }
7081 
7082 Decl *Sema::ActOnUsingDirective(Scope *S,
7083                                           SourceLocation UsingLoc,
7084                                           SourceLocation NamespcLoc,
7085                                           CXXScopeSpec &SS,
7086                                           SourceLocation IdentLoc,
7087                                           IdentifierInfo *NamespcName,
7088                                           AttributeList *AttrList) {
7089   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7090   assert(NamespcName && "Invalid NamespcName.");
7091   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
7092 
7093   // This can only happen along a recovery path.
7094   while (S->getFlags() & Scope::TemplateParamScope)
7095     S = S->getParent();
7096   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7097 
7098   UsingDirectiveDecl *UDir = nullptr;
7099   NestedNameSpecifier *Qualifier = nullptr;
7100   if (SS.isSet())
7101     Qualifier = SS.getScopeRep();
7102 
7103   // Lookup namespace name.
7104   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7105   LookupParsedName(R, S, &SS);
7106   if (R.isAmbiguous())
7107     return nullptr;
7108 
7109   if (R.empty()) {
7110     R.clear();
7111     // Allow "using namespace std;" or "using namespace ::std;" even if
7112     // "std" hasn't been defined yet, for GCC compatibility.
7113     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7114         NamespcName->isStr("std")) {
7115       Diag(IdentLoc, diag::ext_using_undefined_std);
7116       R.addDecl(getOrCreateStdNamespace());
7117       R.resolveKind();
7118     }
7119     // Otherwise, attempt typo correction.
7120     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
7121   }
7122 
7123   if (!R.empty()) {
7124     NamedDecl *Named = R.getFoundDecl();
7125     assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
7126         && "expected namespace decl");
7127     // C++ [namespace.udir]p1:
7128     //   A using-directive specifies that the names in the nominated
7129     //   namespace can be used in the scope in which the
7130     //   using-directive appears after the using-directive. During
7131     //   unqualified name lookup (3.4.1), the names appear as if they
7132     //   were declared in the nearest enclosing namespace which
7133     //   contains both the using-directive and the nominated
7134     //   namespace. [Note: in this context, "contains" means "contains
7135     //   directly or indirectly". ]
7136 
7137     // Find enclosing context containing both using-directive and
7138     // nominated namespace.
7139     NamespaceDecl *NS = getNamespaceDecl(Named);
7140     DeclContext *CommonAncestor = cast<DeclContext>(NS);
7141     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7142       CommonAncestor = CommonAncestor->getParent();
7143 
7144     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
7145                                       SS.getWithLocInContext(Context),
7146                                       IdentLoc, Named, CommonAncestor);
7147 
7148     if (IsUsingDirectiveInToplevelContext(CurContext) &&
7149         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
7150       Diag(IdentLoc, diag::warn_using_directive_in_header);
7151     }
7152 
7153     PushUsingDirective(S, UDir);
7154   } else {
7155     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
7156   }
7157 
7158   if (UDir)
7159     ProcessDeclAttributeList(S, UDir, AttrList);
7160 
7161   return UDir;
7162 }
7163 
7164 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
7165   // If the scope has an associated entity and the using directive is at
7166   // namespace or translation unit scope, add the UsingDirectiveDecl into
7167   // its lookup structure so qualified name lookup can find it.
7168   DeclContext *Ctx = S->getEntity();
7169   if (Ctx && !Ctx->isFunctionOrMethod())
7170     Ctx->addDecl(UDir);
7171   else
7172     // Otherwise, it is at block scope. The using-directives will affect lookup
7173     // only to the end of the scope.
7174     S->PushUsingDirective(UDir);
7175 }
7176 
7177 
7178 Decl *Sema::ActOnUsingDeclaration(Scope *S,
7179                                   AccessSpecifier AS,
7180                                   bool HasUsingKeyword,
7181                                   SourceLocation UsingLoc,
7182                                   CXXScopeSpec &SS,
7183                                   UnqualifiedId &Name,
7184                                   AttributeList *AttrList,
7185                                   bool HasTypenameKeyword,
7186                                   SourceLocation TypenameLoc) {
7187   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7188 
7189   switch (Name.getKind()) {
7190   case UnqualifiedId::IK_ImplicitSelfParam:
7191   case UnqualifiedId::IK_Identifier:
7192   case UnqualifiedId::IK_OperatorFunctionId:
7193   case UnqualifiedId::IK_LiteralOperatorId:
7194   case UnqualifiedId::IK_ConversionFunctionId:
7195     break;
7196 
7197   case UnqualifiedId::IK_ConstructorName:
7198   case UnqualifiedId::IK_ConstructorTemplateId:
7199     // C++11 inheriting constructors.
7200     Diag(Name.getLocStart(),
7201          getLangOpts().CPlusPlus11 ?
7202            diag::warn_cxx98_compat_using_decl_constructor :
7203            diag::err_using_decl_constructor)
7204       << SS.getRange();
7205 
7206     if (getLangOpts().CPlusPlus11) break;
7207 
7208     return nullptr;
7209 
7210   case UnqualifiedId::IK_DestructorName:
7211     Diag(Name.getLocStart(), diag::err_using_decl_destructor)
7212       << SS.getRange();
7213     return nullptr;
7214 
7215   case UnqualifiedId::IK_TemplateId:
7216     Diag(Name.getLocStart(), diag::err_using_decl_template_id)
7217       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
7218     return nullptr;
7219   }
7220 
7221   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7222   DeclarationName TargetName = TargetNameInfo.getName();
7223   if (!TargetName)
7224     return nullptr;
7225 
7226   // Warn about access declarations.
7227   if (!HasUsingKeyword) {
7228     Diag(Name.getLocStart(),
7229          getLangOpts().CPlusPlus11 ? diag::err_access_decl
7230                                    : diag::warn_access_decl_deprecated)
7231       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
7232   }
7233 
7234   if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7235       DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7236     return nullptr;
7237 
7238   NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
7239                                         TargetNameInfo, AttrList,
7240                                         /* IsInstantiation */ false,
7241                                         HasTypenameKeyword, TypenameLoc);
7242   if (UD)
7243     PushOnScopeChains(UD, S, /*AddToContext*/ false);
7244 
7245   return UD;
7246 }
7247 
7248 /// \brief Determine whether a using declaration considers the given
7249 /// declarations as "equivalent", e.g., if they are redeclarations of
7250 /// the same entity or are both typedefs of the same type.
7251 static bool
7252 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7253   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
7254     return true;
7255 
7256   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
7257     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
7258       return Context.hasSameType(TD1->getUnderlyingType(),
7259                                  TD2->getUnderlyingType());
7260 
7261   return false;
7262 }
7263 
7264 
7265 /// Determines whether to create a using shadow decl for a particular
7266 /// decl, given the set of decls existing prior to this using lookup.
7267 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
7268                                 const LookupResult &Previous,
7269                                 UsingShadowDecl *&PrevShadow) {
7270   // Diagnose finding a decl which is not from a base class of the
7271   // current class.  We do this now because there are cases where this
7272   // function will silently decide not to build a shadow decl, which
7273   // will pre-empt further diagnostics.
7274   //
7275   // We don't need to do this in C++0x because we do the check once on
7276   // the qualifier.
7277   //
7278   // FIXME: diagnose the following if we care enough:
7279   //   struct A { int foo; };
7280   //   struct B : A { using A::foo; };
7281   //   template <class T> struct C : A {};
7282   //   template <class T> struct D : C<T> { using B::foo; } // <---
7283   // This is invalid (during instantiation) in C++03 because B::foo
7284   // resolves to the using decl in B, which is not a base class of D<T>.
7285   // We can't diagnose it immediately because C<T> is an unknown
7286   // specialization.  The UsingShadowDecl in D<T> then points directly
7287   // to A::foo, which will look well-formed when we instantiate.
7288   // The right solution is to not collapse the shadow-decl chain.
7289   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
7290     DeclContext *OrigDC = Orig->getDeclContext();
7291 
7292     // Handle enums and anonymous structs.
7293     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7294     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7295     while (OrigRec->isAnonymousStructOrUnion())
7296       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7297 
7298     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7299       if (OrigDC == CurContext) {
7300         Diag(Using->getLocation(),
7301              diag::err_using_decl_nested_name_specifier_is_current_class)
7302           << Using->getQualifierLoc().getSourceRange();
7303         Diag(Orig->getLocation(), diag::note_using_decl_target);
7304         return true;
7305       }
7306 
7307       Diag(Using->getQualifierLoc().getBeginLoc(),
7308            diag::err_using_decl_nested_name_specifier_is_not_base_class)
7309         << Using->getQualifier()
7310         << cast<CXXRecordDecl>(CurContext)
7311         << Using->getQualifierLoc().getSourceRange();
7312       Diag(Orig->getLocation(), diag::note_using_decl_target);
7313       return true;
7314     }
7315   }
7316 
7317   if (Previous.empty()) return false;
7318 
7319   NamedDecl *Target = Orig;
7320   if (isa<UsingShadowDecl>(Target))
7321     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7322 
7323   // If the target happens to be one of the previous declarations, we
7324   // don't have a conflict.
7325   //
7326   // FIXME: but we might be increasing its access, in which case we
7327   // should redeclare it.
7328   NamedDecl *NonTag = nullptr, *Tag = nullptr;
7329   bool FoundEquivalentDecl = false;
7330   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7331          I != E; ++I) {
7332     NamedDecl *D = (*I)->getUnderlyingDecl();
7333     if (IsEquivalentForUsingDecl(Context, D, Target)) {
7334       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7335         PrevShadow = Shadow;
7336       FoundEquivalentDecl = true;
7337     }
7338 
7339     (isa<TagDecl>(D) ? Tag : NonTag) = D;
7340   }
7341 
7342   if (FoundEquivalentDecl)
7343     return false;
7344 
7345   if (FunctionDecl *FD = Target->getAsFunction()) {
7346     NamedDecl *OldDecl = nullptr;
7347     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7348                           /*IsForUsingDecl*/ true)) {
7349     case Ovl_Overload:
7350       return false;
7351 
7352     case Ovl_NonFunction:
7353       Diag(Using->getLocation(), diag::err_using_decl_conflict);
7354       break;
7355 
7356     // We found a decl with the exact signature.
7357     case Ovl_Match:
7358       // If we're in a record, we want to hide the target, so we
7359       // return true (without a diagnostic) to tell the caller not to
7360       // build a shadow decl.
7361       if (CurContext->isRecord())
7362         return true;
7363 
7364       // If we're not in a record, this is an error.
7365       Diag(Using->getLocation(), diag::err_using_decl_conflict);
7366       break;
7367     }
7368 
7369     Diag(Target->getLocation(), diag::note_using_decl_target);
7370     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7371     return true;
7372   }
7373 
7374   // Target is not a function.
7375 
7376   if (isa<TagDecl>(Target)) {
7377     // No conflict between a tag and a non-tag.
7378     if (!Tag) return false;
7379 
7380     Diag(Using->getLocation(), diag::err_using_decl_conflict);
7381     Diag(Target->getLocation(), diag::note_using_decl_target);
7382     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7383     return true;
7384   }
7385 
7386   // No conflict between a tag and a non-tag.
7387   if (!NonTag) return false;
7388 
7389   Diag(Using->getLocation(), diag::err_using_decl_conflict);
7390   Diag(Target->getLocation(), diag::note_using_decl_target);
7391   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7392   return true;
7393 }
7394 
7395 /// Builds a shadow declaration corresponding to a 'using' declaration.
7396 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
7397                                             UsingDecl *UD,
7398                                             NamedDecl *Orig,
7399                                             UsingShadowDecl *PrevDecl) {
7400 
7401   // If we resolved to another shadow declaration, just coalesce them.
7402   NamedDecl *Target = Orig;
7403   if (isa<UsingShadowDecl>(Target)) {
7404     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7405     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
7406   }
7407 
7408   UsingShadowDecl *Shadow
7409     = UsingShadowDecl::Create(Context, CurContext,
7410                               UD->getLocation(), UD, Target);
7411   UD->addShadowDecl(Shadow);
7412 
7413   Shadow->setAccess(UD->getAccess());
7414   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7415     Shadow->setInvalidDecl();
7416 
7417   Shadow->setPreviousDecl(PrevDecl);
7418 
7419   if (S)
7420     PushOnScopeChains(Shadow, S);
7421   else
7422     CurContext->addDecl(Shadow);
7423 
7424 
7425   return Shadow;
7426 }
7427 
7428 /// Hides a using shadow declaration.  This is required by the current
7429 /// using-decl implementation when a resolvable using declaration in a
7430 /// class is followed by a declaration which would hide or override
7431 /// one or more of the using decl's targets; for example:
7432 ///
7433 ///   struct Base { void foo(int); };
7434 ///   struct Derived : Base {
7435 ///     using Base::foo;
7436 ///     void foo(int);
7437 ///   };
7438 ///
7439 /// The governing language is C++03 [namespace.udecl]p12:
7440 ///
7441 ///   When a using-declaration brings names from a base class into a
7442 ///   derived class scope, member functions in the derived class
7443 ///   override and/or hide member functions with the same name and
7444 ///   parameter types in a base class (rather than conflicting).
7445 ///
7446 /// There are two ways to implement this:
7447 ///   (1) optimistically create shadow decls when they're not hidden
7448 ///       by existing declarations, or
7449 ///   (2) don't create any shadow decls (or at least don't make them
7450 ///       visible) until we've fully parsed/instantiated the class.
7451 /// The problem with (1) is that we might have to retroactively remove
7452 /// a shadow decl, which requires several O(n) operations because the
7453 /// decl structures are (very reasonably) not designed for removal.
7454 /// (2) avoids this but is very fiddly and phase-dependent.
7455 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
7456   if (Shadow->getDeclName().getNameKind() ==
7457         DeclarationName::CXXConversionFunctionName)
7458     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7459 
7460   // Remove it from the DeclContext...
7461   Shadow->getDeclContext()->removeDecl(Shadow);
7462 
7463   // ...and the scope, if applicable...
7464   if (S) {
7465     S->RemoveDecl(Shadow);
7466     IdResolver.RemoveDecl(Shadow);
7467   }
7468 
7469   // ...and the using decl.
7470   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7471 
7472   // TODO: complain somehow if Shadow was used.  It shouldn't
7473   // be possible for this to happen, because...?
7474 }
7475 
7476 /// Find the base specifier for a base class with the given type.
7477 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7478                                                 QualType DesiredBase,
7479                                                 bool &AnyDependentBases) {
7480   // Check whether the named type is a direct base class.
7481   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7482   for (auto &Base : Derived->bases()) {
7483     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7484     if (CanonicalDesiredBase == BaseType)
7485       return &Base;
7486     if (BaseType->isDependentType())
7487       AnyDependentBases = true;
7488   }
7489   return nullptr;
7490 }
7491 
7492 namespace {
7493 class UsingValidatorCCC : public CorrectionCandidateCallback {
7494 public:
7495   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
7496                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
7497       : HasTypenameKeyword(HasTypenameKeyword),
7498         IsInstantiation(IsInstantiation), OldNNS(NNS),
7499         RequireMemberOf(RequireMemberOf) {}
7500 
7501   bool ValidateCandidate(const TypoCorrection &Candidate) override {
7502     NamedDecl *ND = Candidate.getCorrectionDecl();
7503 
7504     // Keywords are not valid here.
7505     if (!ND || isa<NamespaceDecl>(ND))
7506       return false;
7507 
7508     // Completely unqualified names are invalid for a 'using' declaration.
7509     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7510       return false;
7511 
7512     if (RequireMemberOf) {
7513       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
7514       if (FoundRecord && FoundRecord->isInjectedClassName()) {
7515         // No-one ever wants a using-declaration to name an injected-class-name
7516         // of a base class, unless they're declaring an inheriting constructor.
7517         ASTContext &Ctx = ND->getASTContext();
7518         if (!Ctx.getLangOpts().CPlusPlus11)
7519           return false;
7520         QualType FoundType = Ctx.getRecordType(FoundRecord);
7521 
7522         // Check that the injected-class-name is named as a member of its own
7523         // type; we don't want to suggest 'using Derived::Base;', since that
7524         // means something else.
7525         NestedNameSpecifier *Specifier =
7526             Candidate.WillReplaceSpecifier()
7527                 ? Candidate.getCorrectionSpecifier()
7528                 : OldNNS;
7529         if (!Specifier->getAsType() ||
7530             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
7531           return false;
7532 
7533         // Check that this inheriting constructor declaration actually names a
7534         // direct base class of the current class.
7535         bool AnyDependentBases = false;
7536         if (!findDirectBaseWithType(RequireMemberOf,
7537                                     Ctx.getRecordType(FoundRecord),
7538                                     AnyDependentBases) &&
7539             !AnyDependentBases)
7540           return false;
7541       } else {
7542         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
7543         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
7544           return false;
7545 
7546         // FIXME: Check that the base class member is accessible?
7547       }
7548     }
7549 
7550     if (isa<TypeDecl>(ND))
7551       return HasTypenameKeyword || !IsInstantiation;
7552 
7553     return !HasTypenameKeyword;
7554   }
7555 
7556 private:
7557   bool HasTypenameKeyword;
7558   bool IsInstantiation;
7559   NestedNameSpecifier *OldNNS;
7560   CXXRecordDecl *RequireMemberOf;
7561 };
7562 } // end anonymous namespace
7563 
7564 /// Builds a using declaration.
7565 ///
7566 /// \param IsInstantiation - Whether this call arises from an
7567 ///   instantiation of an unresolved using declaration.  We treat
7568 ///   the lookup differently for these declarations.
7569 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7570                                        SourceLocation UsingLoc,
7571                                        CXXScopeSpec &SS,
7572                                        DeclarationNameInfo NameInfo,
7573                                        AttributeList *AttrList,
7574                                        bool IsInstantiation,
7575                                        bool HasTypenameKeyword,
7576                                        SourceLocation TypenameLoc) {
7577   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7578   SourceLocation IdentLoc = NameInfo.getLoc();
7579   assert(IdentLoc.isValid() && "Invalid TargetName location.");
7580 
7581   // FIXME: We ignore attributes for now.
7582 
7583   if (SS.isEmpty()) {
7584     Diag(IdentLoc, diag::err_using_requires_qualname);
7585     return nullptr;
7586   }
7587 
7588   // Do the redeclaration lookup in the current scope.
7589   LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
7590                         ForRedeclaration);
7591   Previous.setHideTags(false);
7592   if (S) {
7593     LookupName(Previous, S);
7594 
7595     // It is really dumb that we have to do this.
7596     LookupResult::Filter F = Previous.makeFilter();
7597     while (F.hasNext()) {
7598       NamedDecl *D = F.next();
7599       if (!isDeclInScope(D, CurContext, S))
7600         F.erase();
7601       // If we found a local extern declaration that's not ordinarily visible,
7602       // and this declaration is being added to a non-block scope, ignore it.
7603       // We're only checking for scope conflicts here, not also for violations
7604       // of the linkage rules.
7605       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
7606                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
7607         F.erase();
7608     }
7609     F.done();
7610   } else {
7611     assert(IsInstantiation && "no scope in non-instantiation");
7612     assert(CurContext->isRecord() && "scope not record in instantiation");
7613     LookupQualifiedName(Previous, CurContext);
7614   }
7615 
7616   // Check for invalid redeclarations.
7617   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7618                                   SS, IdentLoc, Previous))
7619     return nullptr;
7620 
7621   // Check for bad qualifiers.
7622   if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
7623     return nullptr;
7624 
7625   DeclContext *LookupContext = computeDeclContext(SS);
7626   NamedDecl *D;
7627   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
7628   if (!LookupContext) {
7629     if (HasTypenameKeyword) {
7630       // FIXME: not all declaration name kinds are legal here
7631       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7632                                               UsingLoc, TypenameLoc,
7633                                               QualifierLoc,
7634                                               IdentLoc, NameInfo.getName());
7635     } else {
7636       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7637                                            QualifierLoc, NameInfo);
7638     }
7639     D->setAccess(AS);
7640     CurContext->addDecl(D);
7641     return D;
7642   }
7643 
7644   auto Build = [&](bool Invalid) {
7645     UsingDecl *UD =
7646         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
7647                           HasTypenameKeyword);
7648     UD->setAccess(AS);
7649     CurContext->addDecl(UD);
7650     UD->setInvalidDecl(Invalid);
7651     return UD;
7652   };
7653   auto BuildInvalid = [&]{ return Build(true); };
7654   auto BuildValid = [&]{ return Build(false); };
7655 
7656   if (RequireCompleteDeclContext(SS, LookupContext))
7657     return BuildInvalid();
7658 
7659   // The normal rules do not apply to inheriting constructor declarations.
7660   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
7661     UsingDecl *UD = BuildValid();
7662     CheckInheritingConstructorUsingDecl(UD);
7663     return UD;
7664   }
7665 
7666   // Otherwise, look up the target name.
7667 
7668   LookupResult R(*this, NameInfo, LookupOrdinaryName);
7669 
7670   // Unlike most lookups, we don't always want to hide tag
7671   // declarations: tag names are visible through the using declaration
7672   // even if hidden by ordinary names, *except* in a dependent context
7673   // where it's important for the sanity of two-phase lookup.
7674   if (!IsInstantiation)
7675     R.setHideTags(false);
7676 
7677   // For the purposes of this lookup, we have a base object type
7678   // equal to that of the current context.
7679   if (CurContext->isRecord()) {
7680     R.setBaseObjectType(
7681                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7682   }
7683 
7684   LookupQualifiedName(R, LookupContext);
7685 
7686   // Try to correct typos if possible.
7687   if (R.empty()) {
7688     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
7689                           dyn_cast<CXXRecordDecl>(CurContext));
7690     if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
7691                                                R.getLookupKind(), S, &SS, CCC,
7692                                                CTK_ErrorRecovery)){
7693       // We reject any correction for which ND would be NULL.
7694       NamedDecl *ND = Corrected.getCorrectionDecl();
7695 
7696       // We reject candidates where DroppedSpecifier == true, hence the
7697       // literal '0' below.
7698       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7699                                 << NameInfo.getName() << LookupContext << 0
7700                                 << SS.getRange());
7701 
7702       // If we corrected to an inheriting constructor, handle it as one.
7703       auto *RD = dyn_cast<CXXRecordDecl>(ND);
7704       if (RD && RD->isInjectedClassName()) {
7705         // Fix up the information we'll use to build the using declaration.
7706         if (Corrected.WillReplaceSpecifier()) {
7707           NestedNameSpecifierLocBuilder Builder;
7708           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
7709                               QualifierLoc.getSourceRange());
7710           QualifierLoc = Builder.getWithLocInContext(Context);
7711         }
7712 
7713         NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
7714             Context.getCanonicalType(Context.getRecordType(RD))));
7715         NameInfo.setNamedTypeInfo(nullptr);
7716 
7717         // Build it and process it as an inheriting constructor.
7718         UsingDecl *UD = BuildValid();
7719         CheckInheritingConstructorUsingDecl(UD);
7720         return UD;
7721       }
7722 
7723       // FIXME: Pick up all the declarations if we found an overloaded function.
7724       R.setLookupName(Corrected.getCorrection());
7725       R.addDecl(ND);
7726     } else {
7727       Diag(IdentLoc, diag::err_no_member)
7728         << NameInfo.getName() << LookupContext << SS.getRange();
7729       return BuildInvalid();
7730     }
7731   }
7732 
7733   if (R.isAmbiguous())
7734     return BuildInvalid();
7735 
7736   if (HasTypenameKeyword) {
7737     // If we asked for a typename and got a non-type decl, error out.
7738     if (!R.getAsSingle<TypeDecl>()) {
7739       Diag(IdentLoc, diag::err_using_typename_non_type);
7740       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7741         Diag((*I)->getUnderlyingDecl()->getLocation(),
7742              diag::note_using_decl_target);
7743       return BuildInvalid();
7744     }
7745   } else {
7746     // If we asked for a non-typename and we got a type, error out,
7747     // but only if this is an instantiation of an unresolved using
7748     // decl.  Otherwise just silently find the type name.
7749     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
7750       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7751       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
7752       return BuildInvalid();
7753     }
7754   }
7755 
7756   // C++0x N2914 [namespace.udecl]p6:
7757   // A using-declaration shall not name a namespace.
7758   if (R.getAsSingle<NamespaceDecl>()) {
7759     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7760       << SS.getRange();
7761     return BuildInvalid();
7762   }
7763 
7764   UsingDecl *UD = BuildValid();
7765   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7766     UsingShadowDecl *PrevDecl = nullptr;
7767     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
7768       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
7769   }
7770 
7771   return UD;
7772 }
7773 
7774 /// Additional checks for a using declaration referring to a constructor name.
7775 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
7776   assert(!UD->hasTypename() && "expecting a constructor name");
7777 
7778   const Type *SourceType = UD->getQualifier()->getAsType();
7779   assert(SourceType &&
7780          "Using decl naming constructor doesn't have type in scope spec.");
7781   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7782 
7783   // Check whether the named type is a direct base class.
7784   bool AnyDependentBases = false;
7785   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
7786                                       AnyDependentBases);
7787   if (!Base && !AnyDependentBases) {
7788     Diag(UD->getUsingLoc(),
7789          diag::err_using_decl_constructor_not_in_direct_base)
7790       << UD->getNameInfo().getSourceRange()
7791       << QualType(SourceType, 0) << TargetClass;
7792     UD->setInvalidDecl();
7793     return true;
7794   }
7795 
7796   if (Base)
7797     Base->setInheritConstructors();
7798 
7799   return false;
7800 }
7801 
7802 /// Checks that the given using declaration is not an invalid
7803 /// redeclaration.  Note that this is checking only for the using decl
7804 /// itself, not for any ill-formedness among the UsingShadowDecls.
7805 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7806                                        bool HasTypenameKeyword,
7807                                        const CXXScopeSpec &SS,
7808                                        SourceLocation NameLoc,
7809                                        const LookupResult &Prev) {
7810   // C++03 [namespace.udecl]p8:
7811   // C++0x [namespace.udecl]p10:
7812   //   A using-declaration is a declaration and can therefore be used
7813   //   repeatedly where (and only where) multiple declarations are
7814   //   allowed.
7815   //
7816   // That's in non-member contexts.
7817   if (!CurContext->getRedeclContext()->isRecord())
7818     return false;
7819 
7820   NestedNameSpecifier *Qual = SS.getScopeRep();
7821 
7822   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7823     NamedDecl *D = *I;
7824 
7825     bool DTypename;
7826     NestedNameSpecifier *DQual;
7827     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7828       DTypename = UD->hasTypename();
7829       DQual = UD->getQualifier();
7830     } else if (UnresolvedUsingValueDecl *UD
7831                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7832       DTypename = false;
7833       DQual = UD->getQualifier();
7834     } else if (UnresolvedUsingTypenameDecl *UD
7835                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7836       DTypename = true;
7837       DQual = UD->getQualifier();
7838     } else continue;
7839 
7840     // using decls differ if one says 'typename' and the other doesn't.
7841     // FIXME: non-dependent using decls?
7842     if (HasTypenameKeyword != DTypename) continue;
7843 
7844     // using decls differ if they name different scopes (but note that
7845     // template instantiation can cause this check to trigger when it
7846     // didn't before instantiation).
7847     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7848         Context.getCanonicalNestedNameSpecifier(DQual))
7849       continue;
7850 
7851     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
7852     Diag(D->getLocation(), diag::note_using_decl) << 1;
7853     return true;
7854   }
7855 
7856   return false;
7857 }
7858 
7859 
7860 /// Checks that the given nested-name qualifier used in a using decl
7861 /// in the current context is appropriately related to the current
7862 /// scope.  If an error is found, diagnoses it and returns true.
7863 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7864                                    const CXXScopeSpec &SS,
7865                                    const DeclarationNameInfo &NameInfo,
7866                                    SourceLocation NameLoc) {
7867   DeclContext *NamedContext = computeDeclContext(SS);
7868 
7869   if (!CurContext->isRecord()) {
7870     // C++03 [namespace.udecl]p3:
7871     // C++0x [namespace.udecl]p8:
7872     //   A using-declaration for a class member shall be a member-declaration.
7873 
7874     // If we weren't able to compute a valid scope, it must be a
7875     // dependent class scope.
7876     if (!NamedContext || NamedContext->isRecord()) {
7877       auto *RD = dyn_cast<CXXRecordDecl>(NamedContext);
7878       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
7879         RD = nullptr;
7880 
7881       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7882         << SS.getRange();
7883 
7884       // If we have a complete, non-dependent source type, try to suggest a
7885       // way to get the same effect.
7886       if (!RD)
7887         return true;
7888 
7889       // Find what this using-declaration was referring to.
7890       LookupResult R(*this, NameInfo, LookupOrdinaryName);
7891       R.setHideTags(false);
7892       R.suppressDiagnostics();
7893       LookupQualifiedName(R, RD);
7894 
7895       if (R.getAsSingle<TypeDecl>()) {
7896         if (getLangOpts().CPlusPlus11) {
7897           // Convert 'using X::Y;' to 'using Y = X::Y;'.
7898           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
7899             << 0 // alias declaration
7900             << FixItHint::CreateInsertion(SS.getBeginLoc(),
7901                                           NameInfo.getName().getAsString() +
7902                                               " = ");
7903         } else {
7904           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
7905           SourceLocation InsertLoc =
7906               PP.getLocForEndOfToken(NameInfo.getLocEnd());
7907           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
7908             << 1 // typedef declaration
7909             << FixItHint::CreateReplacement(UsingLoc, "typedef")
7910             << FixItHint::CreateInsertion(
7911                    InsertLoc, " " + NameInfo.getName().getAsString());
7912         }
7913       } else if (R.getAsSingle<VarDecl>()) {
7914         // Don't provide a fixit outside C++11 mode; we don't want to suggest
7915         // repeating the type of the static data member here.
7916         FixItHint FixIt;
7917         if (getLangOpts().CPlusPlus11) {
7918           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
7919           FixIt = FixItHint::CreateReplacement(
7920               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
7921         }
7922 
7923         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
7924           << 2 // reference declaration
7925           << FixIt;
7926       }
7927       return true;
7928     }
7929 
7930     // Otherwise, everything is known to be fine.
7931     return false;
7932   }
7933 
7934   // The current scope is a record.
7935 
7936   // If the named context is dependent, we can't decide much.
7937   if (!NamedContext) {
7938     // FIXME: in C++0x, we can diagnose if we can prove that the
7939     // nested-name-specifier does not refer to a base class, which is
7940     // still possible in some cases.
7941 
7942     // Otherwise we have to conservatively report that things might be
7943     // okay.
7944     return false;
7945   }
7946 
7947   if (!NamedContext->isRecord()) {
7948     // Ideally this would point at the last name in the specifier,
7949     // but we don't have that level of source info.
7950     Diag(SS.getRange().getBegin(),
7951          diag::err_using_decl_nested_name_specifier_is_not_class)
7952       << SS.getScopeRep() << SS.getRange();
7953     return true;
7954   }
7955 
7956   if (!NamedContext->isDependentContext() &&
7957       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7958     return true;
7959 
7960   if (getLangOpts().CPlusPlus11) {
7961     // C++0x [namespace.udecl]p3:
7962     //   In a using-declaration used as a member-declaration, the
7963     //   nested-name-specifier shall name a base class of the class
7964     //   being defined.
7965 
7966     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7967                                  cast<CXXRecordDecl>(NamedContext))) {
7968       if (CurContext == NamedContext) {
7969         Diag(NameLoc,
7970              diag::err_using_decl_nested_name_specifier_is_current_class)
7971           << SS.getRange();
7972         return true;
7973       }
7974 
7975       Diag(SS.getRange().getBegin(),
7976            diag::err_using_decl_nested_name_specifier_is_not_base_class)
7977         << SS.getScopeRep()
7978         << cast<CXXRecordDecl>(CurContext)
7979         << SS.getRange();
7980       return true;
7981     }
7982 
7983     return false;
7984   }
7985 
7986   // C++03 [namespace.udecl]p4:
7987   //   A using-declaration used as a member-declaration shall refer
7988   //   to a member of a base class of the class being defined [etc.].
7989 
7990   // Salient point: SS doesn't have to name a base class as long as
7991   // lookup only finds members from base classes.  Therefore we can
7992   // diagnose here only if we can prove that that can't happen,
7993   // i.e. if the class hierarchies provably don't intersect.
7994 
7995   // TODO: it would be nice if "definitely valid" results were cached
7996   // in the UsingDecl and UsingShadowDecl so that these checks didn't
7997   // need to be repeated.
7998 
7999   struct UserData {
8000     llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
8001 
8002     static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
8003       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8004       Data->Bases.insert(Base);
8005       return true;
8006     }
8007 
8008     bool hasDependentBases(const CXXRecordDecl *Class) {
8009       return !Class->forallBases(collect, this);
8010     }
8011 
8012     /// Returns true if the base is dependent or is one of the
8013     /// accumulated base classes.
8014     static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
8015       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8016       return !Data->Bases.count(Base);
8017     }
8018 
8019     bool mightShareBases(const CXXRecordDecl *Class) {
8020       return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
8021     }
8022   };
8023 
8024   UserData Data;
8025 
8026   // Returns false if we find a dependent base.
8027   if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
8028     return false;
8029 
8030   // Returns false if the class has a dependent base or if it or one
8031   // of its bases is present in the base set of the current context.
8032   if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
8033     return false;
8034 
8035   Diag(SS.getRange().getBegin(),
8036        diag::err_using_decl_nested_name_specifier_is_not_base_class)
8037     << SS.getScopeRep()
8038     << cast<CXXRecordDecl>(CurContext)
8039     << SS.getRange();
8040 
8041   return true;
8042 }
8043 
8044 Decl *Sema::ActOnAliasDeclaration(Scope *S,
8045                                   AccessSpecifier AS,
8046                                   MultiTemplateParamsArg TemplateParamLists,
8047                                   SourceLocation UsingLoc,
8048                                   UnqualifiedId &Name,
8049                                   AttributeList *AttrList,
8050                                   TypeResult Type) {
8051   // Skip up to the relevant declaration scope.
8052   while (S->getFlags() & Scope::TemplateParamScope)
8053     S = S->getParent();
8054   assert((S->getFlags() & Scope::DeclScope) &&
8055          "got alias-declaration outside of declaration scope");
8056 
8057   if (Type.isInvalid())
8058     return nullptr;
8059 
8060   bool Invalid = false;
8061   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
8062   TypeSourceInfo *TInfo = nullptr;
8063   GetTypeFromParser(Type.get(), &TInfo);
8064 
8065   if (DiagnoseClassNameShadow(CurContext, NameInfo))
8066     return nullptr;
8067 
8068   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
8069                                       UPPC_DeclarationType)) {
8070     Invalid = true;
8071     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8072                                              TInfo->getTypeLoc().getBeginLoc());
8073   }
8074 
8075   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
8076   LookupName(Previous, S);
8077 
8078   // Warn about shadowing the name of a template parameter.
8079   if (Previous.isSingleResult() &&
8080       Previous.getFoundDecl()->isTemplateParameter()) {
8081     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
8082     Previous.clear();
8083   }
8084 
8085   assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8086          "name in alias declaration must be an identifier");
8087   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
8088                                                Name.StartLocation,
8089                                                Name.Identifier, TInfo);
8090 
8091   NewTD->setAccess(AS);
8092 
8093   if (Invalid)
8094     NewTD->setInvalidDecl();
8095 
8096   ProcessDeclAttributeList(S, NewTD, AttrList);
8097 
8098   CheckTypedefForVariablyModifiedType(S, NewTD);
8099   Invalid |= NewTD->isInvalidDecl();
8100 
8101   bool Redeclaration = false;
8102 
8103   NamedDecl *NewND;
8104   if (TemplateParamLists.size()) {
8105     TypeAliasTemplateDecl *OldDecl = nullptr;
8106     TemplateParameterList *OldTemplateParams = nullptr;
8107 
8108     if (TemplateParamLists.size() != 1) {
8109       Diag(UsingLoc, diag::err_alias_template_extra_headers)
8110         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8111          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
8112     }
8113     TemplateParameterList *TemplateParams = TemplateParamLists[0];
8114 
8115     // Only consider previous declarations in the same scope.
8116     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8117                          /*ExplicitInstantiationOrSpecialization*/false);
8118     if (!Previous.empty()) {
8119       Redeclaration = true;
8120 
8121       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8122       if (!OldDecl && !Invalid) {
8123         Diag(UsingLoc, diag::err_redefinition_different_kind)
8124           << Name.Identifier;
8125 
8126         NamedDecl *OldD = Previous.getRepresentativeDecl();
8127         if (OldD->getLocation().isValid())
8128           Diag(OldD->getLocation(), diag::note_previous_definition);
8129 
8130         Invalid = true;
8131       }
8132 
8133       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8134         if (TemplateParameterListsAreEqual(TemplateParams,
8135                                            OldDecl->getTemplateParameters(),
8136                                            /*Complain=*/true,
8137                                            TPL_TemplateMatch))
8138           OldTemplateParams = OldDecl->getTemplateParameters();
8139         else
8140           Invalid = true;
8141 
8142         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8143         if (!Invalid &&
8144             !Context.hasSameType(OldTD->getUnderlyingType(),
8145                                  NewTD->getUnderlyingType())) {
8146           // FIXME: The C++0x standard does not clearly say this is ill-formed,
8147           // but we can't reasonably accept it.
8148           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8149             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8150           if (OldTD->getLocation().isValid())
8151             Diag(OldTD->getLocation(), diag::note_previous_definition);
8152           Invalid = true;
8153         }
8154       }
8155     }
8156 
8157     // Merge any previous default template arguments into our parameters,
8158     // and check the parameter list.
8159     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8160                                    TPC_TypeAliasTemplate))
8161       return nullptr;
8162 
8163     TypeAliasTemplateDecl *NewDecl =
8164       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8165                                     Name.Identifier, TemplateParams,
8166                                     NewTD);
8167 
8168     NewDecl->setAccess(AS);
8169 
8170     if (Invalid)
8171       NewDecl->setInvalidDecl();
8172     else if (OldDecl)
8173       NewDecl->setPreviousDecl(OldDecl);
8174 
8175     NewND = NewDecl;
8176   } else {
8177     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8178     NewND = NewTD;
8179   }
8180 
8181   if (!Redeclaration)
8182     PushOnScopeChains(NewND, S);
8183 
8184   ActOnDocumentableDecl(NewND);
8185   return NewND;
8186 }
8187 
8188 Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
8189                                              SourceLocation NamespaceLoc,
8190                                              SourceLocation AliasLoc,
8191                                              IdentifierInfo *Alias,
8192                                              CXXScopeSpec &SS,
8193                                              SourceLocation IdentLoc,
8194                                              IdentifierInfo *Ident) {
8195 
8196   // Lookup the namespace name.
8197   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8198   LookupParsedName(R, S, &SS);
8199 
8200   // Check if we have a previous declaration with the same name.
8201   NamedDecl *PrevDecl
8202     = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
8203                        ForRedeclaration);
8204   if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
8205     PrevDecl = nullptr;
8206 
8207   if (PrevDecl) {
8208     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
8209       // We already have an alias with the same name that points to the same
8210       // namespace, so don't create a new one.
8211       // FIXME: At some point, we'll want to create the (redundant)
8212       // declaration to maintain better source information.
8213       if (!R.isAmbiguous() && !R.empty() &&
8214           AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
8215         return nullptr;
8216     }
8217 
8218     unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
8219       diag::err_redefinition_different_kind;
8220     Diag(AliasLoc, DiagID) << Alias;
8221     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8222     return nullptr;
8223   }
8224 
8225   if (R.isAmbiguous())
8226     return nullptr;
8227 
8228   if (R.empty()) {
8229     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
8230       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
8231       return nullptr;
8232     }
8233   }
8234 
8235   NamespaceAliasDecl *AliasDecl =
8236     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
8237                                Alias, SS.getWithLocInContext(Context),
8238                                IdentLoc, R.getFoundDecl());
8239 
8240   PushOnScopeChains(AliasDecl, S);
8241   return AliasDecl;
8242 }
8243 
8244 Sema::ImplicitExceptionSpecification
8245 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8246                                                CXXMethodDecl *MD) {
8247   CXXRecordDecl *ClassDecl = MD->getParent();
8248 
8249   // C++ [except.spec]p14:
8250   //   An implicitly declared special member function (Clause 12) shall have an
8251   //   exception-specification. [...]
8252   ImplicitExceptionSpecification ExceptSpec(*this);
8253   if (ClassDecl->isInvalidDecl())
8254     return ExceptSpec;
8255 
8256   // Direct base-class constructors.
8257   for (const auto &B : ClassDecl->bases()) {
8258     if (B.isVirtual()) // Handled below.
8259       continue;
8260 
8261     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8262       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8263       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8264       // If this is a deleted function, add it anyway. This might be conformant
8265       // with the standard. This might not. I'm not sure. It might not matter.
8266       if (Constructor)
8267         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8268     }
8269   }
8270 
8271   // Virtual base-class constructors.
8272   for (const auto &B : ClassDecl->vbases()) {
8273     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8274       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8275       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8276       // If this is a deleted function, add it anyway. This might be conformant
8277       // with the standard. This might not. I'm not sure. It might not matter.
8278       if (Constructor)
8279         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8280     }
8281   }
8282 
8283   // Field constructors.
8284   for (const auto *F : ClassDecl->fields()) {
8285     if (F->hasInClassInitializer()) {
8286       if (Expr *E = F->getInClassInitializer())
8287         ExceptSpec.CalledExpr(E);
8288       else if (!F->isInvalidDecl())
8289         // DR1351:
8290         //   If the brace-or-equal-initializer of a non-static data member
8291         //   invokes a defaulted default constructor of its class or of an
8292         //   enclosing class in a potentially evaluated subexpression, the
8293         //   program is ill-formed.
8294         //
8295         // This resolution is unworkable: the exception specification of the
8296         // default constructor can be needed in an unevaluated context, in
8297         // particular, in the operand of a noexcept-expression, and we can be
8298         // unable to compute an exception specification for an enclosed class.
8299         //
8300         // We do not allow an in-class initializer to require the evaluation
8301         // of the exception specification for any in-class initializer whose
8302         // definition is not lexically complete.
8303         Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
8304     } else if (const RecordType *RecordTy
8305               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8306       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8307       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8308       // If this is a deleted function, add it anyway. This might be conformant
8309       // with the standard. This might not. I'm not sure. It might not matter.
8310       // In particular, the problem is that this function never gets called. It
8311       // might just be ill-formed because this function attempts to refer to
8312       // a deleted function here.
8313       if (Constructor)
8314         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8315     }
8316   }
8317 
8318   return ExceptSpec;
8319 }
8320 
8321 Sema::ImplicitExceptionSpecification
8322 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8323   CXXRecordDecl *ClassDecl = CD->getParent();
8324 
8325   // C++ [except.spec]p14:
8326   //   An inheriting constructor [...] shall have an exception-specification. [...]
8327   ImplicitExceptionSpecification ExceptSpec(*this);
8328   if (ClassDecl->isInvalidDecl())
8329     return ExceptSpec;
8330 
8331   // Inherited constructor.
8332   const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8333   const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8334   // FIXME: Copying or moving the parameters could add extra exceptions to the
8335   // set, as could the default arguments for the inherited constructor. This
8336   // will be addressed when we implement the resolution of core issue 1351.
8337   ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8338 
8339   // Direct base-class constructors.
8340   for (const auto &B : ClassDecl->bases()) {
8341     if (B.isVirtual()) // Handled below.
8342       continue;
8343 
8344     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8345       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8346       if (BaseClassDecl == InheritedDecl)
8347         continue;
8348       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8349       if (Constructor)
8350         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8351     }
8352   }
8353 
8354   // Virtual base-class constructors.
8355   for (const auto &B : ClassDecl->vbases()) {
8356     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8357       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8358       if (BaseClassDecl == InheritedDecl)
8359         continue;
8360       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8361       if (Constructor)
8362         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8363     }
8364   }
8365 
8366   // Field constructors.
8367   for (const auto *F : ClassDecl->fields()) {
8368     if (F->hasInClassInitializer()) {
8369       if (Expr *E = F->getInClassInitializer())
8370         ExceptSpec.CalledExpr(E);
8371       else if (!F->isInvalidDecl())
8372         Diag(CD->getLocation(),
8373              diag::err_in_class_initializer_references_def_ctor) << CD;
8374     } else if (const RecordType *RecordTy
8375               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8376       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8377       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8378       if (Constructor)
8379         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8380     }
8381   }
8382 
8383   return ExceptSpec;
8384 }
8385 
8386 namespace {
8387 /// RAII object to register a special member as being currently declared.
8388 struct DeclaringSpecialMember {
8389   Sema &S;
8390   Sema::SpecialMemberDecl D;
8391   bool WasAlreadyBeingDeclared;
8392 
8393   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8394     : S(S), D(RD, CSM) {
8395     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8396     if (WasAlreadyBeingDeclared)
8397       // This almost never happens, but if it does, ensure that our cache
8398       // doesn't contain a stale result.
8399       S.SpecialMemberCache.clear();
8400 
8401     // FIXME: Register a note to be produced if we encounter an error while
8402     // declaring the special member.
8403   }
8404   ~DeclaringSpecialMember() {
8405     if (!WasAlreadyBeingDeclared)
8406       S.SpecialMembersBeingDeclared.erase(D);
8407   }
8408 
8409   /// \brief Are we already trying to declare this special member?
8410   bool isAlreadyBeingDeclared() const {
8411     return WasAlreadyBeingDeclared;
8412   }
8413 };
8414 }
8415 
8416 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8417                                                      CXXRecordDecl *ClassDecl) {
8418   // C++ [class.ctor]p5:
8419   //   A default constructor for a class X is a constructor of class X
8420   //   that can be called without an argument. If there is no
8421   //   user-declared constructor for class X, a default constructor is
8422   //   implicitly declared. An implicitly-declared default constructor
8423   //   is an inline public member of its class.
8424   assert(ClassDecl->needsImplicitDefaultConstructor() &&
8425          "Should not build implicit default constructor!");
8426 
8427   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8428   if (DSM.isAlreadyBeingDeclared())
8429     return nullptr;
8430 
8431   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8432                                                      CXXDefaultConstructor,
8433                                                      false);
8434 
8435   // Create the actual constructor declaration.
8436   CanQualType ClassType
8437     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8438   SourceLocation ClassLoc = ClassDecl->getLocation();
8439   DeclarationName Name
8440     = Context.DeclarationNames.getCXXConstructorName(ClassType);
8441   DeclarationNameInfo NameInfo(Name, ClassLoc);
8442   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
8443       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8444       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8445       /*isImplicitlyDeclared=*/true, Constexpr);
8446   DefaultCon->setAccess(AS_public);
8447   DefaultCon->setDefaulted();
8448   DefaultCon->setImplicit();
8449 
8450   // Build an exception specification pointing back at this constructor.
8451   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
8452   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8453 
8454   // We don't need to use SpecialMemberIsTrivial here; triviality for default
8455   // constructors is easy to compute.
8456   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8457 
8458   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
8459     SetDeclDeleted(DefaultCon, ClassLoc);
8460 
8461   // Note that we have declared this constructor.
8462   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
8463 
8464   if (Scope *S = getScopeForContext(ClassDecl))
8465     PushOnScopeChains(DefaultCon, S, false);
8466   ClassDecl->addDecl(DefaultCon);
8467 
8468   return DefaultCon;
8469 }
8470 
8471 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8472                                             CXXConstructorDecl *Constructor) {
8473   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
8474           !Constructor->doesThisDeclarationHaveABody() &&
8475           !Constructor->isDeleted()) &&
8476     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
8477 
8478   CXXRecordDecl *ClassDecl = Constructor->getParent();
8479   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
8480 
8481   SynthesizedFunctionScope Scope(*this, Constructor);
8482   DiagnosticErrorTrap Trap(Diags);
8483   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8484       Trap.hasErrorOccurred()) {
8485     Diag(CurrentLocation, diag::note_member_synthesized_at)
8486       << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
8487     Constructor->setInvalidDecl();
8488     return;
8489   }
8490 
8491   SourceLocation Loc = Constructor->getLocEnd().isValid()
8492                            ? Constructor->getLocEnd()
8493                            : Constructor->getLocation();
8494   Constructor->setBody(new (Context) CompoundStmt(Loc));
8495 
8496   Constructor->markUsed(Context);
8497   MarkVTableUsed(CurrentLocation, ClassDecl);
8498 
8499   if (ASTMutationListener *L = getASTMutationListener()) {
8500     L->CompletedImplicitDefinition(Constructor);
8501   }
8502 
8503   DiagnoseUninitializedFields(*this, Constructor);
8504 }
8505 
8506 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
8507   // Perform any delayed checks on exception specifications.
8508   CheckDelayedMemberExceptionSpecs();
8509 }
8510 
8511 namespace {
8512 /// Information on inheriting constructors to declare.
8513 class InheritingConstructorInfo {
8514 public:
8515   InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8516       : SemaRef(SemaRef), Derived(Derived) {
8517     // Mark the constructors that we already have in the derived class.
8518     //
8519     // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8520     //   unless there is a user-declared constructor with the same signature in
8521     //   the class where the using-declaration appears.
8522     visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8523   }
8524 
8525   void inheritAll(CXXRecordDecl *RD) {
8526     visitAll(RD, &InheritingConstructorInfo::inherit);
8527   }
8528 
8529 private:
8530   /// Information about an inheriting constructor.
8531   struct InheritingConstructor {
8532     InheritingConstructor()
8533       : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
8534 
8535     /// If \c true, a constructor with this signature is already declared
8536     /// in the derived class.
8537     bool DeclaredInDerived;
8538 
8539     /// The constructor which is inherited.
8540     const CXXConstructorDecl *BaseCtor;
8541 
8542     /// The derived constructor we declared.
8543     CXXConstructorDecl *DerivedCtor;
8544   };
8545 
8546   /// Inheriting constructors with a given canonical type. There can be at
8547   /// most one such non-template constructor, and any number of templated
8548   /// constructors.
8549   struct InheritingConstructorsForType {
8550     InheritingConstructor NonTemplate;
8551     SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8552         Templates;
8553 
8554     InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8555       if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8556         TemplateParameterList *ParamList = FTD->getTemplateParameters();
8557         for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8558           if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8559                                                false, S.TPL_TemplateMatch))
8560             return Templates[I].second;
8561         Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8562         return Templates.back().second;
8563       }
8564 
8565       return NonTemplate;
8566     }
8567   };
8568 
8569   /// Get or create the inheriting constructor record for a constructor.
8570   InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8571                                   QualType CtorType) {
8572     return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8573         .getEntry(SemaRef, Ctor);
8574   }
8575 
8576   typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8577 
8578   /// Process all constructors for a class.
8579   void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
8580     for (const auto *Ctor : RD->ctors())
8581       (this->*Callback)(Ctor);
8582     for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8583              I(RD->decls_begin()), E(RD->decls_end());
8584          I != E; ++I) {
8585       const FunctionDecl *FD = (*I)->getTemplatedDecl();
8586       if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8587         (this->*Callback)(CD);
8588     }
8589   }
8590 
8591   /// Note that a constructor (or constructor template) was declared in Derived.
8592   void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8593     getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8594   }
8595 
8596   /// Inherit a single constructor.
8597   void inherit(const CXXConstructorDecl *Ctor) {
8598     const FunctionProtoType *CtorType =
8599         Ctor->getType()->castAs<FunctionProtoType>();
8600     ArrayRef<QualType> ArgTypes(CtorType->getParamTypes());
8601     FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8602 
8603     SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8604 
8605     // Core issue (no number yet): the ellipsis is always discarded.
8606     if (EPI.Variadic) {
8607       SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8608       SemaRef.Diag(Ctor->getLocation(),
8609                    diag::note_using_decl_constructor_ellipsis);
8610       EPI.Variadic = false;
8611     }
8612 
8613     // Declare a constructor for each number of parameters.
8614     //
8615     // C++11 [class.inhctor]p1:
8616     //   The candidate set of inherited constructors from the class X named in
8617     //   the using-declaration consists of [... modulo defects ...] for each
8618     //   constructor or constructor template of X, the set of constructors or
8619     //   constructor templates that results from omitting any ellipsis parameter
8620     //   specification and successively omitting parameters with a default
8621     //   argument from the end of the parameter-type-list
8622     unsigned MinParams = minParamsToInherit(Ctor);
8623     unsigned Params = Ctor->getNumParams();
8624     if (Params >= MinParams) {
8625       do
8626         declareCtor(UsingLoc, Ctor,
8627                     SemaRef.Context.getFunctionType(
8628                         Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
8629       while (Params > MinParams &&
8630              Ctor->getParamDecl(--Params)->hasDefaultArg());
8631     }
8632   }
8633 
8634   /// Find the using-declaration which specified that we should inherit the
8635   /// constructors of \p Base.
8636   SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8637     // No fancy lookup required; just look for the base constructor name
8638     // directly within the derived class.
8639     ASTContext &Context = SemaRef.Context;
8640     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8641         Context.getCanonicalType(Context.getRecordType(Base)));
8642     DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8643     return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8644   }
8645 
8646   unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8647     // C++11 [class.inhctor]p3:
8648     //   [F]or each constructor template in the candidate set of inherited
8649     //   constructors, a constructor template is implicitly declared
8650     if (Ctor->getDescribedFunctionTemplate())
8651       return 0;
8652 
8653     //   For each non-template constructor in the candidate set of inherited
8654     //   constructors other than a constructor having no parameters or a
8655     //   copy/move constructor having a single parameter, a constructor is
8656     //   implicitly declared [...]
8657     if (Ctor->getNumParams() == 0)
8658       return 1;
8659     if (Ctor->isCopyOrMoveConstructor())
8660       return 2;
8661 
8662     // Per discussion on core reflector, never inherit a constructor which
8663     // would become a default, copy, or move constructor of Derived either.
8664     const ParmVarDecl *PD = Ctor->getParamDecl(0);
8665     const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8666     return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8667   }
8668 
8669   /// Declare a single inheriting constructor, inheriting the specified
8670   /// constructor, with the given type.
8671   void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8672                    QualType DerivedType) {
8673     InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8674 
8675     // C++11 [class.inhctor]p3:
8676     //   ... a constructor is implicitly declared with the same constructor
8677     //   characteristics unless there is a user-declared constructor with
8678     //   the same signature in the class where the using-declaration appears
8679     if (Entry.DeclaredInDerived)
8680       return;
8681 
8682     // C++11 [class.inhctor]p7:
8683     //   If two using-declarations declare inheriting constructors with the
8684     //   same signature, the program is ill-formed
8685     if (Entry.DerivedCtor) {
8686       if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8687         // Only diagnose this once per constructor.
8688         if (Entry.DerivedCtor->isInvalidDecl())
8689           return;
8690         Entry.DerivedCtor->setInvalidDecl();
8691 
8692         SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8693         SemaRef.Diag(BaseCtor->getLocation(),
8694                      diag::note_using_decl_constructor_conflict_current_ctor);
8695         SemaRef.Diag(Entry.BaseCtor->getLocation(),
8696                      diag::note_using_decl_constructor_conflict_previous_ctor);
8697         SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8698                      diag::note_using_decl_constructor_conflict_previous_using);
8699       } else {
8700         // Core issue (no number): if the same inheriting constructor is
8701         // produced by multiple base class constructors from the same base
8702         // class, the inheriting constructor is defined as deleted.
8703         SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8704       }
8705 
8706       return;
8707     }
8708 
8709     ASTContext &Context = SemaRef.Context;
8710     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8711         Context.getCanonicalType(Context.getRecordType(Derived)));
8712     DeclarationNameInfo NameInfo(Name, UsingLoc);
8713 
8714     TemplateParameterList *TemplateParams = nullptr;
8715     if (const FunctionTemplateDecl *FTD =
8716             BaseCtor->getDescribedFunctionTemplate()) {
8717       TemplateParams = FTD->getTemplateParameters();
8718       // We're reusing template parameters from a different DeclContext. This
8719       // is questionable at best, but works out because the template depth in
8720       // both places is guaranteed to be 0.
8721       // FIXME: Rebuild the template parameters in the new context, and
8722       // transform the function type to refer to them.
8723     }
8724 
8725     // Build type source info pointing at the using-declaration. This is
8726     // required by template instantiation.
8727     TypeSourceInfo *TInfo =
8728         Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8729     FunctionProtoTypeLoc ProtoLoc =
8730         TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8731 
8732     CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8733         Context, Derived, UsingLoc, NameInfo, DerivedType,
8734         TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8735         /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8736 
8737     // Build an unevaluated exception specification for this constructor.
8738     const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8739     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8740     EPI.ExceptionSpecType = EST_Unevaluated;
8741     EPI.ExceptionSpecDecl = DerivedCtor;
8742     DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
8743                                                  FPT->getParamTypes(), EPI));
8744 
8745     // Build the parameter declarations.
8746     SmallVector<ParmVarDecl *, 16> ParamDecls;
8747     for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
8748       TypeSourceInfo *TInfo =
8749           Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
8750       ParmVarDecl *PD = ParmVarDecl::Create(
8751           Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
8752           FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
8753       PD->setScopeInfo(0, I);
8754       PD->setImplicit();
8755       ParamDecls.push_back(PD);
8756       ProtoLoc.setParam(I, PD);
8757     }
8758 
8759     // Set up the new constructor.
8760     DerivedCtor->setAccess(BaseCtor->getAccess());
8761     DerivedCtor->setParams(ParamDecls);
8762     DerivedCtor->setInheritedConstructor(BaseCtor);
8763     if (BaseCtor->isDeleted())
8764       SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8765 
8766     // If this is a constructor template, build the template declaration.
8767     if (TemplateParams) {
8768       FunctionTemplateDecl *DerivedTemplate =
8769           FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8770                                        TemplateParams, DerivedCtor);
8771       DerivedTemplate->setAccess(BaseCtor->getAccess());
8772       DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8773       Derived->addDecl(DerivedTemplate);
8774     } else {
8775       Derived->addDecl(DerivedCtor);
8776     }
8777 
8778     Entry.BaseCtor = BaseCtor;
8779     Entry.DerivedCtor = DerivedCtor;
8780   }
8781 
8782   Sema &SemaRef;
8783   CXXRecordDecl *Derived;
8784   typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8785   MapType Map;
8786 };
8787 }
8788 
8789 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8790   // Defer declaring the inheriting constructors until the class is
8791   // instantiated.
8792   if (ClassDecl->isDependentContext())
8793     return;
8794 
8795   // Find base classes from which we might inherit constructors.
8796   SmallVector<CXXRecordDecl*, 4> InheritedBases;
8797   for (const auto &BaseIt : ClassDecl->bases())
8798     if (BaseIt.getInheritConstructors())
8799       InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
8800 
8801   // Go no further if we're not inheriting any constructors.
8802   if (InheritedBases.empty())
8803     return;
8804 
8805   // Declare the inherited constructors.
8806   InheritingConstructorInfo ICI(*this, ClassDecl);
8807   for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8808     ICI.inheritAll(InheritedBases[I]);
8809 }
8810 
8811 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8812                                        CXXConstructorDecl *Constructor) {
8813   CXXRecordDecl *ClassDecl = Constructor->getParent();
8814   assert(Constructor->getInheritedConstructor() &&
8815          !Constructor->doesThisDeclarationHaveABody() &&
8816          !Constructor->isDeleted());
8817 
8818   SynthesizedFunctionScope Scope(*this, Constructor);
8819   DiagnosticErrorTrap Trap(Diags);
8820   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8821       Trap.hasErrorOccurred()) {
8822     Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8823       << Context.getTagDeclType(ClassDecl);
8824     Constructor->setInvalidDecl();
8825     return;
8826   }
8827 
8828   SourceLocation Loc = Constructor->getLocation();
8829   Constructor->setBody(new (Context) CompoundStmt(Loc));
8830 
8831   Constructor->markUsed(Context);
8832   MarkVTableUsed(CurrentLocation, ClassDecl);
8833 
8834   if (ASTMutationListener *L = getASTMutationListener()) {
8835     L->CompletedImplicitDefinition(Constructor);
8836   }
8837 }
8838 
8839 
8840 Sema::ImplicitExceptionSpecification
8841 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8842   CXXRecordDecl *ClassDecl = MD->getParent();
8843 
8844   // C++ [except.spec]p14:
8845   //   An implicitly declared special member function (Clause 12) shall have
8846   //   an exception-specification.
8847   ImplicitExceptionSpecification ExceptSpec(*this);
8848   if (ClassDecl->isInvalidDecl())
8849     return ExceptSpec;
8850 
8851   // Direct base-class destructors.
8852   for (const auto &B : ClassDecl->bases()) {
8853     if (B.isVirtual()) // Handled below.
8854       continue;
8855 
8856     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8857       ExceptSpec.CalledDecl(B.getLocStart(),
8858                    LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
8859   }
8860 
8861   // Virtual base-class destructors.
8862   for (const auto &B : ClassDecl->vbases()) {
8863     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8864       ExceptSpec.CalledDecl(B.getLocStart(),
8865                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
8866   }
8867 
8868   // Field destructors.
8869   for (const auto *F : ClassDecl->fields()) {
8870     if (const RecordType *RecordTy
8871         = Context.getBaseElementType(F->getType())->getAs<RecordType>())
8872       ExceptSpec.CalledDecl(F->getLocation(),
8873                   LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
8874   }
8875 
8876   return ExceptSpec;
8877 }
8878 
8879 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8880   // C++ [class.dtor]p2:
8881   //   If a class has no user-declared destructor, a destructor is
8882   //   declared implicitly. An implicitly-declared destructor is an
8883   //   inline public member of its class.
8884   assert(ClassDecl->needsImplicitDestructor());
8885 
8886   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8887   if (DSM.isAlreadyBeingDeclared())
8888     return nullptr;
8889 
8890   // Create the actual destructor declaration.
8891   CanQualType ClassType
8892     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8893   SourceLocation ClassLoc = ClassDecl->getLocation();
8894   DeclarationName Name
8895     = Context.DeclarationNames.getCXXDestructorName(ClassType);
8896   DeclarationNameInfo NameInfo(Name, ClassLoc);
8897   CXXDestructorDecl *Destructor
8898       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8899                                   QualType(), nullptr, /*isInline=*/true,
8900                                   /*isImplicitlyDeclared=*/true);
8901   Destructor->setAccess(AS_public);
8902   Destructor->setDefaulted();
8903   Destructor->setImplicit();
8904 
8905   // Build an exception specification pointing back at this destructor.
8906   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
8907   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8908 
8909   AddOverriddenMethods(ClassDecl, Destructor);
8910 
8911   // We don't need to use SpecialMemberIsTrivial here; triviality for
8912   // destructors is easy to compute.
8913   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8914 
8915   if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
8916     SetDeclDeleted(Destructor, ClassLoc);
8917 
8918   // Note that we have declared this destructor.
8919   ++ASTContext::NumImplicitDestructorsDeclared;
8920 
8921   // Introduce this destructor into its scope.
8922   if (Scope *S = getScopeForContext(ClassDecl))
8923     PushOnScopeChains(Destructor, S, false);
8924   ClassDecl->addDecl(Destructor);
8925 
8926   return Destructor;
8927 }
8928 
8929 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
8930                                     CXXDestructorDecl *Destructor) {
8931   assert((Destructor->isDefaulted() &&
8932           !Destructor->doesThisDeclarationHaveABody() &&
8933           !Destructor->isDeleted()) &&
8934          "DefineImplicitDestructor - call it for implicit default dtor");
8935   CXXRecordDecl *ClassDecl = Destructor->getParent();
8936   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
8937 
8938   if (Destructor->isInvalidDecl())
8939     return;
8940 
8941   SynthesizedFunctionScope Scope(*this, Destructor);
8942 
8943   DiagnosticErrorTrap Trap(Diags);
8944   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8945                                          Destructor->getParent());
8946 
8947   if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
8948     Diag(CurrentLocation, diag::note_member_synthesized_at)
8949       << CXXDestructor << Context.getTagDeclType(ClassDecl);
8950 
8951     Destructor->setInvalidDecl();
8952     return;
8953   }
8954 
8955   SourceLocation Loc = Destructor->getLocEnd().isValid()
8956                            ? Destructor->getLocEnd()
8957                            : Destructor->getLocation();
8958   Destructor->setBody(new (Context) CompoundStmt(Loc));
8959   Destructor->markUsed(Context);
8960   MarkVTableUsed(CurrentLocation, ClassDecl);
8961 
8962   if (ASTMutationListener *L = getASTMutationListener()) {
8963     L->CompletedImplicitDefinition(Destructor);
8964   }
8965 }
8966 
8967 /// \brief Perform any semantic analysis which needs to be delayed until all
8968 /// pending class member declarations have been parsed.
8969 void Sema::ActOnFinishCXXMemberDecls() {
8970   // If the context is an invalid C++ class, just suppress these checks.
8971   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8972     if (Record->isInvalidDecl()) {
8973       DelayedDefaultedMemberExceptionSpecs.clear();
8974       DelayedDestructorExceptionSpecChecks.clear();
8975       return;
8976     }
8977   }
8978 }
8979 
8980 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8981                                          CXXDestructorDecl *Destructor) {
8982   assert(getLangOpts().CPlusPlus11 &&
8983          "adjusting dtor exception specs was introduced in c++11");
8984 
8985   // C++11 [class.dtor]p3:
8986   //   A declaration of a destructor that does not have an exception-
8987   //   specification is implicitly considered to have the same exception-
8988   //   specification as an implicit declaration.
8989   const FunctionProtoType *DtorType = Destructor->getType()->
8990                                         getAs<FunctionProtoType>();
8991   if (DtorType->hasExceptionSpec())
8992     return;
8993 
8994   // Replace the destructor's type, building off the existing one. Fortunately,
8995   // the only thing of interest in the destructor type is its extended info.
8996   // The return and arguments are fixed.
8997   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8998   EPI.ExceptionSpecType = EST_Unevaluated;
8999   EPI.ExceptionSpecDecl = Destructor;
9000   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9001 
9002   // FIXME: If the destructor has a body that could throw, and the newly created
9003   // spec doesn't allow exceptions, we should emit a warning, because this
9004   // change in behavior can break conforming C++03 programs at runtime.
9005   // However, we don't have a body or an exception specification yet, so it
9006   // needs to be done somewhere else.
9007 }
9008 
9009 namespace {
9010 /// \brief An abstract base class for all helper classes used in building the
9011 //  copy/move operators. These classes serve as factory functions and help us
9012 //  avoid using the same Expr* in the AST twice.
9013 class ExprBuilder {
9014   ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
9015   ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
9016 
9017 protected:
9018   static Expr *assertNotNull(Expr *E) {
9019     assert(E && "Expression construction must not fail.");
9020     return E;
9021   }
9022 
9023 public:
9024   ExprBuilder() {}
9025   virtual ~ExprBuilder() {}
9026 
9027   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
9028 };
9029 
9030 class RefBuilder: public ExprBuilder {
9031   VarDecl *Var;
9032   QualType VarType;
9033 
9034 public:
9035   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9036     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
9037   }
9038 
9039   RefBuilder(VarDecl *Var, QualType VarType)
9040       : Var(Var), VarType(VarType) {}
9041 };
9042 
9043 class ThisBuilder: public ExprBuilder {
9044 public:
9045   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9046     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
9047   }
9048 };
9049 
9050 class CastBuilder: public ExprBuilder {
9051   const ExprBuilder &Builder;
9052   QualType Type;
9053   ExprValueKind Kind;
9054   const CXXCastPath &Path;
9055 
9056 public:
9057   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9058     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
9059                                              CK_UncheckedDerivedToBase, Kind,
9060                                              &Path).get());
9061   }
9062 
9063   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
9064               const CXXCastPath &Path)
9065       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
9066 };
9067 
9068 class DerefBuilder: public ExprBuilder {
9069   const ExprBuilder &Builder;
9070 
9071 public:
9072   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9073     return assertNotNull(
9074         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
9075   }
9076 
9077   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9078 };
9079 
9080 class MemberBuilder: public ExprBuilder {
9081   const ExprBuilder &Builder;
9082   QualType Type;
9083   CXXScopeSpec SS;
9084   bool IsArrow;
9085   LookupResult &MemberLookup;
9086 
9087 public:
9088   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9089     return assertNotNull(S.BuildMemberReferenceExpr(
9090         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
9091         nullptr, MemberLookup, nullptr).get());
9092   }
9093 
9094   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9095                 LookupResult &MemberLookup)
9096       : Builder(Builder), Type(Type), IsArrow(IsArrow),
9097         MemberLookup(MemberLookup) {}
9098 };
9099 
9100 class MoveCastBuilder: public ExprBuilder {
9101   const ExprBuilder &Builder;
9102 
9103 public:
9104   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9105     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9106   }
9107 
9108   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9109 };
9110 
9111 class LvalueConvBuilder: public ExprBuilder {
9112   const ExprBuilder &Builder;
9113 
9114 public:
9115   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9116     return assertNotNull(
9117         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
9118   }
9119 
9120   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9121 };
9122 
9123 class SubscriptBuilder: public ExprBuilder {
9124   const ExprBuilder &Base;
9125   const ExprBuilder &Index;
9126 
9127 public:
9128   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9129     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
9130         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
9131   }
9132 
9133   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9134       : Base(Base), Index(Index) {}
9135 };
9136 
9137 } // end anonymous namespace
9138 
9139 /// When generating a defaulted copy or move assignment operator, if a field
9140 /// should be copied with __builtin_memcpy rather than via explicit assignments,
9141 /// do so. This optimization only applies for arrays of scalars, and for arrays
9142 /// of class type where the selected copy/move-assignment operator is trivial.
9143 static StmtResult
9144 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
9145                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
9146   // Compute the size of the memory buffer to be copied.
9147   QualType SizeType = S.Context.getSizeType();
9148   llvm::APInt Size(S.Context.getTypeSize(SizeType),
9149                    S.Context.getTypeSizeInChars(T).getQuantity());
9150 
9151   // Take the address of the field references for "from" and "to". We
9152   // directly construct UnaryOperators here because semantic analysis
9153   // does not permit us to take the address of an xvalue.
9154   Expr *From = FromB.build(S, Loc);
9155   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9156                          S.Context.getPointerType(From->getType()),
9157                          VK_RValue, OK_Ordinary, Loc);
9158   Expr *To = ToB.build(S, Loc);
9159   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9160                        S.Context.getPointerType(To->getType()),
9161                        VK_RValue, OK_Ordinary, Loc);
9162 
9163   const Type *E = T->getBaseElementTypeUnsafe();
9164   bool NeedsCollectableMemCpy =
9165     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9166 
9167   // Create a reference to the __builtin_objc_memmove_collectable function
9168   StringRef MemCpyName = NeedsCollectableMemCpy ?
9169     "__builtin_objc_memmove_collectable" :
9170     "__builtin_memcpy";
9171   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9172                  Sema::LookupOrdinaryName);
9173   S.LookupName(R, S.TUScope, true);
9174 
9175   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9176   if (!MemCpy)
9177     // Something went horribly wrong earlier, and we will have complained
9178     // about it.
9179     return StmtError();
9180 
9181   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
9182                                             VK_RValue, Loc, nullptr);
9183   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9184 
9185   Expr *CallArgs[] = {
9186     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9187   };
9188   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
9189                                     Loc, CallArgs, Loc);
9190 
9191   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
9192   return Call.getAs<Stmt>();
9193 }
9194 
9195 /// \brief Builds a statement that copies/moves the given entity from \p From to
9196 /// \c To.
9197 ///
9198 /// This routine is used to copy/move the members of a class with an
9199 /// implicitly-declared copy/move assignment operator. When the entities being
9200 /// copied are arrays, this routine builds for loops to copy them.
9201 ///
9202 /// \param S The Sema object used for type-checking.
9203 ///
9204 /// \param Loc The location where the implicit copy/move is being generated.
9205 ///
9206 /// \param T The type of the expressions being copied/moved. Both expressions
9207 /// must have this type.
9208 ///
9209 /// \param To The expression we are copying/moving to.
9210 ///
9211 /// \param From The expression we are copying/moving from.
9212 ///
9213 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
9214 /// Otherwise, it's a non-static member subobject.
9215 ///
9216 /// \param Copying Whether we're copying or moving.
9217 ///
9218 /// \param Depth Internal parameter recording the depth of the recursion.
9219 ///
9220 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9221 /// if a memcpy should be used instead.
9222 static StmtResult
9223 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
9224                                  const ExprBuilder &To, const ExprBuilder &From,
9225                                  bool CopyingBaseSubobject, bool Copying,
9226                                  unsigned Depth = 0) {
9227   // C++11 [class.copy]p28:
9228   //   Each subobject is assigned in the manner appropriate to its type:
9229   //
9230   //     - if the subobject is of class type, as if by a call to operator= with
9231   //       the subobject as the object expression and the corresponding
9232   //       subobject of x as a single function argument (as if by explicit
9233   //       qualification; that is, ignoring any possible virtual overriding
9234   //       functions in more derived classes);
9235   //
9236   // C++03 [class.copy]p13:
9237   //     - if the subobject is of class type, the copy assignment operator for
9238   //       the class is used (as if by explicit qualification; that is,
9239   //       ignoring any possible virtual overriding functions in more derived
9240   //       classes);
9241   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9242     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9243 
9244     // Look for operator=.
9245     DeclarationName Name
9246       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9247     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9248     S.LookupQualifiedName(OpLookup, ClassDecl, false);
9249 
9250     // Prior to C++11, filter out any result that isn't a copy/move-assignment
9251     // operator.
9252     if (!S.getLangOpts().CPlusPlus11) {
9253       LookupResult::Filter F = OpLookup.makeFilter();
9254       while (F.hasNext()) {
9255         NamedDecl *D = F.next();
9256         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9257           if (Method->isCopyAssignmentOperator() ||
9258               (!Copying && Method->isMoveAssignmentOperator()))
9259             continue;
9260 
9261         F.erase();
9262       }
9263       F.done();
9264     }
9265 
9266     // Suppress the protected check (C++ [class.protected]) for each of the
9267     // assignment operators we found. This strange dance is required when
9268     // we're assigning via a base classes's copy-assignment operator. To
9269     // ensure that we're getting the right base class subobject (without
9270     // ambiguities), we need to cast "this" to that subobject type; to
9271     // ensure that we don't go through the virtual call mechanism, we need
9272     // to qualify the operator= name with the base class (see below). However,
9273     // this means that if the base class has a protected copy assignment
9274     // operator, the protected member access check will fail. So, we
9275     // rewrite "protected" access to "public" access in this case, since we
9276     // know by construction that we're calling from a derived class.
9277     if (CopyingBaseSubobject) {
9278       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9279            L != LEnd; ++L) {
9280         if (L.getAccess() == AS_protected)
9281           L.setAccess(AS_public);
9282       }
9283     }
9284 
9285     // Create the nested-name-specifier that will be used to qualify the
9286     // reference to operator=; this is required to suppress the virtual
9287     // call mechanism.
9288     CXXScopeSpec SS;
9289     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
9290     SS.MakeTrivial(S.Context,
9291                    NestedNameSpecifier::Create(S.Context, nullptr, false,
9292                                                CanonicalT),
9293                    Loc);
9294 
9295     // Create the reference to operator=.
9296     ExprResult OpEqualRef
9297       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9298                                    SS, /*TemplateKWLoc=*/SourceLocation(),
9299                                    /*FirstQualifierInScope=*/nullptr,
9300                                    OpLookup,
9301                                    /*TemplateArgs=*/nullptr,
9302                                    /*SuppressQualifierCheck=*/true);
9303     if (OpEqualRef.isInvalid())
9304       return StmtError();
9305 
9306     // Build the call to the assignment operator.
9307 
9308     Expr *FromInst = From.build(S, Loc);
9309     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
9310                                                   OpEqualRef.getAs<Expr>(),
9311                                                   Loc, FromInst, Loc);
9312     if (Call.isInvalid())
9313       return StmtError();
9314 
9315     // If we built a call to a trivial 'operator=' while copying an array,
9316     // bail out. We'll replace the whole shebang with a memcpy.
9317     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9318     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9319       return StmtResult((Stmt*)nullptr);
9320 
9321     // Convert to an expression-statement, and clean up any produced
9322     // temporaries.
9323     return S.ActOnExprStmt(Call);
9324   }
9325 
9326   //     - if the subobject is of scalar type, the built-in assignment
9327   //       operator is used.
9328   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
9329   if (!ArrayTy) {
9330     ExprResult Assignment = S.CreateBuiltinBinOp(
9331         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
9332     if (Assignment.isInvalid())
9333       return StmtError();
9334     return S.ActOnExprStmt(Assignment);
9335   }
9336 
9337   //     - if the subobject is an array, each element is assigned, in the
9338   //       manner appropriate to the element type;
9339 
9340   // Construct a loop over the array bounds, e.g.,
9341   //
9342   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9343   //
9344   // that will copy each of the array elements.
9345   QualType SizeType = S.Context.getSizeType();
9346 
9347   // Create the iteration variable.
9348   IdentifierInfo *IterationVarName = nullptr;
9349   {
9350     SmallString<8> Str;
9351     llvm::raw_svector_ostream OS(Str);
9352     OS << "__i" << Depth;
9353     IterationVarName = &S.Context.Idents.get(OS.str());
9354   }
9355   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
9356                                           IterationVarName, SizeType,
9357                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
9358                                           SC_None);
9359 
9360   // Initialize the iteration variable to zero.
9361   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
9362   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
9363 
9364   // Creates a reference to the iteration variable.
9365   RefBuilder IterationVarRef(IterationVar, SizeType);
9366   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
9367 
9368   // Create the DeclStmt that holds the iteration variable.
9369   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
9370 
9371   // Subscript the "from" and "to" expressions with the iteration variable.
9372   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9373   MoveCastBuilder FromIndexMove(FromIndexCopy);
9374   const ExprBuilder *FromIndex;
9375   if (Copying)
9376     FromIndex = &FromIndexCopy;
9377   else
9378     FromIndex = &FromIndexMove;
9379 
9380   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
9381 
9382   // Build the copy/move for an individual element of the array.
9383   StmtResult Copy =
9384     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
9385                                      ToIndex, *FromIndex, CopyingBaseSubobject,
9386                                      Copying, Depth + 1);
9387   // Bail out if copying fails or if we determined that we should use memcpy.
9388   if (Copy.isInvalid() || !Copy.get())
9389     return Copy;
9390 
9391   // Create the comparison against the array bound.
9392   llvm::APInt Upper
9393     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9394   Expr *Comparison
9395     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
9396                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9397                                      BO_NE, S.Context.BoolTy,
9398                                      VK_RValue, OK_Ordinary, Loc, false);
9399 
9400   // Create the pre-increment of the iteration variable.
9401   Expr *Increment
9402     = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9403                                     SizeType, VK_LValue, OK_Ordinary, Loc);
9404 
9405   // Construct the loop that copies all elements of this array.
9406   return S.ActOnForStmt(Loc, Loc, InitStmt,
9407                         S.MakeFullExpr(Comparison),
9408                         nullptr, S.MakeFullDiscardedValueExpr(Increment),
9409                         Loc, Copy.get());
9410 }
9411 
9412 static StmtResult
9413 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
9414                       const ExprBuilder &To, const ExprBuilder &From,
9415                       bool CopyingBaseSubobject, bool Copying) {
9416   // Maybe we should use a memcpy?
9417   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9418       T.isTriviallyCopyableType(S.Context))
9419     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9420 
9421   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9422                                                      CopyingBaseSubobject,
9423                                                      Copying, 0));
9424 
9425   // If we ended up picking a trivial assignment operator for an array of a
9426   // non-trivially-copyable class type, just emit a memcpy.
9427   if (!Result.isInvalid() && !Result.get())
9428     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9429 
9430   return Result;
9431 }
9432 
9433 Sema::ImplicitExceptionSpecification
9434 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9435   CXXRecordDecl *ClassDecl = MD->getParent();
9436 
9437   ImplicitExceptionSpecification ExceptSpec(*this);
9438   if (ClassDecl->isInvalidDecl())
9439     return ExceptSpec;
9440 
9441   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9442   assert(T->getNumParams() == 1 && "not a copy assignment op");
9443   unsigned ArgQuals =
9444       T->getParamType(0).getNonReferenceType().getCVRQualifiers();
9445 
9446   // C++ [except.spec]p14:
9447   //   An implicitly declared special member function (Clause 12) shall have an
9448   //   exception-specification. [...]
9449 
9450   // It is unspecified whether or not an implicit copy assignment operator
9451   // attempts to deduplicate calls to assignment operators of virtual bases are
9452   // made. As such, this exception specification is effectively unspecified.
9453   // Based on a similar decision made for constness in C++0x, we're erring on
9454   // the side of assuming such calls to be made regardless of whether they
9455   // actually happen.
9456   for (const auto &Base : ClassDecl->bases()) {
9457     if (Base.isVirtual())
9458       continue;
9459 
9460     CXXRecordDecl *BaseClassDecl
9461       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9462     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9463                                                             ArgQuals, false, 0))
9464       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
9465   }
9466 
9467   for (const auto &Base : ClassDecl->vbases()) {
9468     CXXRecordDecl *BaseClassDecl
9469       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9470     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9471                                                             ArgQuals, false, 0))
9472       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
9473   }
9474 
9475   for (const auto *Field : ClassDecl->fields()) {
9476     QualType FieldType = Context.getBaseElementType(Field->getType());
9477     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9478       if (CXXMethodDecl *CopyAssign =
9479           LookupCopyingAssignment(FieldClassDecl,
9480                                   ArgQuals | FieldType.getCVRQualifiers(),
9481                                   false, 0))
9482         ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
9483     }
9484   }
9485 
9486   return ExceptSpec;
9487 }
9488 
9489 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9490   // Note: The following rules are largely analoguous to the copy
9491   // constructor rules. Note that virtual bases are not taken into account
9492   // for determining the argument type of the operator. Note also that
9493   // operators taking an object instead of a reference are allowed.
9494   assert(ClassDecl->needsImplicitCopyAssignment());
9495 
9496   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9497   if (DSM.isAlreadyBeingDeclared())
9498     return nullptr;
9499 
9500   QualType ArgType = Context.getTypeDeclType(ClassDecl);
9501   QualType RetType = Context.getLValueReferenceType(ArgType);
9502   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9503   if (Const)
9504     ArgType = ArgType.withConst();
9505   ArgType = Context.getLValueReferenceType(ArgType);
9506 
9507   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9508                                                      CXXCopyAssignment,
9509                                                      Const);
9510 
9511   //   An implicitly-declared copy assignment operator is an inline public
9512   //   member of its class.
9513   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9514   SourceLocation ClassLoc = ClassDecl->getLocation();
9515   DeclarationNameInfo NameInfo(Name, ClassLoc);
9516   CXXMethodDecl *CopyAssignment =
9517       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9518                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
9519                             /*isInline=*/true, Constexpr, SourceLocation());
9520   CopyAssignment->setAccess(AS_public);
9521   CopyAssignment->setDefaulted();
9522   CopyAssignment->setImplicit();
9523 
9524   // Build an exception specification pointing back at this member.
9525   FunctionProtoType::ExtProtoInfo EPI =
9526       getImplicitMethodEPI(*this, CopyAssignment);
9527   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
9528 
9529   // Add the parameter to the operator.
9530   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
9531                                                ClassLoc, ClassLoc,
9532                                                /*Id=*/nullptr, ArgType,
9533                                                /*TInfo=*/nullptr, SC_None,
9534                                                nullptr);
9535   CopyAssignment->setParams(FromParam);
9536 
9537   AddOverriddenMethods(ClassDecl, CopyAssignment);
9538 
9539   CopyAssignment->setTrivial(
9540     ClassDecl->needsOverloadResolutionForCopyAssignment()
9541       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9542       : ClassDecl->hasTrivialCopyAssignment());
9543 
9544   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
9545     SetDeclDeleted(CopyAssignment, ClassLoc);
9546 
9547   // Note that we have added this copy-assignment operator.
9548   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9549 
9550   if (Scope *S = getScopeForContext(ClassDecl))
9551     PushOnScopeChains(CopyAssignment, S, false);
9552   ClassDecl->addDecl(CopyAssignment);
9553 
9554   return CopyAssignment;
9555 }
9556 
9557 /// Diagnose an implicit copy operation for a class which is odr-used, but
9558 /// which is deprecated because the class has a user-declared copy constructor,
9559 /// copy assignment operator, or destructor.
9560 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9561                                             SourceLocation UseLoc) {
9562   assert(CopyOp->isImplicit());
9563 
9564   CXXRecordDecl *RD = CopyOp->getParent();
9565   CXXMethodDecl *UserDeclaredOperation = nullptr;
9566 
9567   // In Microsoft mode, assignment operations don't affect constructors and
9568   // vice versa.
9569   if (RD->hasUserDeclaredDestructor()) {
9570     UserDeclaredOperation = RD->getDestructor();
9571   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9572              RD->hasUserDeclaredCopyConstructor() &&
9573              !S.getLangOpts().MSVCCompat) {
9574     // Find any user-declared copy constructor.
9575     for (auto *I : RD->ctors()) {
9576       if (I->isCopyConstructor()) {
9577         UserDeclaredOperation = I;
9578         break;
9579       }
9580     }
9581     assert(UserDeclaredOperation);
9582   } else if (isa<CXXConstructorDecl>(CopyOp) &&
9583              RD->hasUserDeclaredCopyAssignment() &&
9584              !S.getLangOpts().MSVCCompat) {
9585     // Find any user-declared move assignment operator.
9586     for (auto *I : RD->methods()) {
9587       if (I->isCopyAssignmentOperator()) {
9588         UserDeclaredOperation = I;
9589         break;
9590       }
9591     }
9592     assert(UserDeclaredOperation);
9593   }
9594 
9595   if (UserDeclaredOperation) {
9596     S.Diag(UserDeclaredOperation->getLocation(),
9597          diag::warn_deprecated_copy_operation)
9598       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9599       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9600     S.Diag(UseLoc, diag::note_member_synthesized_at)
9601       << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9602                                           : Sema::CXXCopyAssignment)
9603       << RD;
9604   }
9605 }
9606 
9607 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9608                                         CXXMethodDecl *CopyAssignOperator) {
9609   assert((CopyAssignOperator->isDefaulted() &&
9610           CopyAssignOperator->isOverloadedOperator() &&
9611           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
9612           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9613           !CopyAssignOperator->isDeleted()) &&
9614          "DefineImplicitCopyAssignment called for wrong function");
9615 
9616   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9617 
9618   if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9619     CopyAssignOperator->setInvalidDecl();
9620     return;
9621   }
9622 
9623   // C++11 [class.copy]p18:
9624   //   The [definition of an implicitly declared copy assignment operator] is
9625   //   deprecated if the class has a user-declared copy constructor or a
9626   //   user-declared destructor.
9627   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9628     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9629 
9630   CopyAssignOperator->markUsed(Context);
9631 
9632   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
9633   DiagnosticErrorTrap Trap(Diags);
9634 
9635   // C++0x [class.copy]p30:
9636   //   The implicitly-defined or explicitly-defaulted copy assignment operator
9637   //   for a non-union class X performs memberwise copy assignment of its
9638   //   subobjects. The direct base classes of X are assigned first, in the
9639   //   order of their declaration in the base-specifier-list, and then the
9640   //   immediate non-static data members of X are assigned, in the order in
9641   //   which they were declared in the class definition.
9642 
9643   // The statements that form the synthesized function body.
9644   SmallVector<Stmt*, 8> Statements;
9645 
9646   // The parameter for the "other" object, which we are copying from.
9647   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9648   Qualifiers OtherQuals = Other->getType().getQualifiers();
9649   QualType OtherRefType = Other->getType();
9650   if (const LValueReferenceType *OtherRef
9651                                 = OtherRefType->getAs<LValueReferenceType>()) {
9652     OtherRefType = OtherRef->getPointeeType();
9653     OtherQuals = OtherRefType.getQualifiers();
9654   }
9655 
9656   // Our location for everything implicitly-generated.
9657   SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
9658                            ? CopyAssignOperator->getLocEnd()
9659                            : CopyAssignOperator->getLocation();
9660 
9661   // Builds a DeclRefExpr for the "other" object.
9662   RefBuilder OtherRef(Other, OtherRefType);
9663 
9664   // Builds the "this" pointer.
9665   ThisBuilder This;
9666 
9667   // Assign base classes.
9668   bool Invalid = false;
9669   for (auto &Base : ClassDecl->bases()) {
9670     // Form the assignment:
9671     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
9672     QualType BaseType = Base.getType().getUnqualifiedType();
9673     if (!BaseType->isRecordType()) {
9674       Invalid = true;
9675       continue;
9676     }
9677 
9678     CXXCastPath BasePath;
9679     BasePath.push_back(&Base);
9680 
9681     // Construct the "from" expression, which is an implicit cast to the
9682     // appropriately-qualified base type.
9683     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9684                      VK_LValue, BasePath);
9685 
9686     // Dereference "this".
9687     DerefBuilder DerefThis(This);
9688     CastBuilder To(DerefThis,
9689                    Context.getCVRQualifiedType(
9690                        BaseType, CopyAssignOperator->getTypeQualifiers()),
9691                    VK_LValue, BasePath);
9692 
9693     // Build the copy.
9694     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
9695                                             To, From,
9696                                             /*CopyingBaseSubobject=*/true,
9697                                             /*Copying=*/true);
9698     if (Copy.isInvalid()) {
9699       Diag(CurrentLocation, diag::note_member_synthesized_at)
9700         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9701       CopyAssignOperator->setInvalidDecl();
9702       return;
9703     }
9704 
9705     // Success! Record the copy.
9706     Statements.push_back(Copy.getAs<Expr>());
9707   }
9708 
9709   // Assign non-static members.
9710   for (auto *Field : ClassDecl->fields()) {
9711     if (Field->isUnnamedBitfield())
9712       continue;
9713 
9714     if (Field->isInvalidDecl()) {
9715       Invalid = true;
9716       continue;
9717     }
9718 
9719     // Check for members of reference type; we can't copy those.
9720     if (Field->getType()->isReferenceType()) {
9721       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9722         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9723       Diag(Field->getLocation(), diag::note_declared_at);
9724       Diag(CurrentLocation, diag::note_member_synthesized_at)
9725         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9726       Invalid = true;
9727       continue;
9728     }
9729 
9730     // Check for members of const-qualified, non-class type.
9731     QualType BaseType = Context.getBaseElementType(Field->getType());
9732     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9733       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9734         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9735       Diag(Field->getLocation(), diag::note_declared_at);
9736       Diag(CurrentLocation, diag::note_member_synthesized_at)
9737         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9738       Invalid = true;
9739       continue;
9740     }
9741 
9742     // Suppress assigning zero-width bitfields.
9743     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9744       continue;
9745 
9746     QualType FieldType = Field->getType().getNonReferenceType();
9747     if (FieldType->isIncompleteArrayType()) {
9748       assert(ClassDecl->hasFlexibleArrayMember() &&
9749              "Incomplete array type is not valid");
9750       continue;
9751     }
9752 
9753     // Build references to the field in the object we're copying from and to.
9754     CXXScopeSpec SS; // Intentionally empty
9755     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9756                               LookupMemberName);
9757     MemberLookup.addDecl(Field);
9758     MemberLookup.resolveKind();
9759 
9760     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9761 
9762     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
9763 
9764     // Build the copy of this field.
9765     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
9766                                             To, From,
9767                                             /*CopyingBaseSubobject=*/false,
9768                                             /*Copying=*/true);
9769     if (Copy.isInvalid()) {
9770       Diag(CurrentLocation, diag::note_member_synthesized_at)
9771         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9772       CopyAssignOperator->setInvalidDecl();
9773       return;
9774     }
9775 
9776     // Success! Record the copy.
9777     Statements.push_back(Copy.getAs<Stmt>());
9778   }
9779 
9780   if (!Invalid) {
9781     // Add a "return *this;"
9782     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
9783 
9784     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
9785     if (Return.isInvalid())
9786       Invalid = true;
9787     else {
9788       Statements.push_back(Return.getAs<Stmt>());
9789 
9790       if (Trap.hasErrorOccurred()) {
9791         Diag(CurrentLocation, diag::note_member_synthesized_at)
9792           << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9793         Invalid = true;
9794       }
9795     }
9796   }
9797 
9798   if (Invalid) {
9799     CopyAssignOperator->setInvalidDecl();
9800     return;
9801   }
9802 
9803   StmtResult Body;
9804   {
9805     CompoundScopeRAII CompoundScope(*this);
9806     Body = ActOnCompoundStmt(Loc, Loc, Statements,
9807                              /*isStmtExpr=*/false);
9808     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9809   }
9810   CopyAssignOperator->setBody(Body.getAs<Stmt>());
9811 
9812   if (ASTMutationListener *L = getASTMutationListener()) {
9813     L->CompletedImplicitDefinition(CopyAssignOperator);
9814   }
9815 }
9816 
9817 Sema::ImplicitExceptionSpecification
9818 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9819   CXXRecordDecl *ClassDecl = MD->getParent();
9820 
9821   ImplicitExceptionSpecification ExceptSpec(*this);
9822   if (ClassDecl->isInvalidDecl())
9823     return ExceptSpec;
9824 
9825   // C++0x [except.spec]p14:
9826   //   An implicitly declared special member function (Clause 12) shall have an
9827   //   exception-specification. [...]
9828 
9829   // It is unspecified whether or not an implicit move assignment operator
9830   // attempts to deduplicate calls to assignment operators of virtual bases are
9831   // made. As such, this exception specification is effectively unspecified.
9832   // Based on a similar decision made for constness in C++0x, we're erring on
9833   // the side of assuming such calls to be made regardless of whether they
9834   // actually happen.
9835   // Note that a move constructor is not implicitly declared when there are
9836   // virtual bases, but it can still be user-declared and explicitly defaulted.
9837   for (const auto &Base : ClassDecl->bases()) {
9838     if (Base.isVirtual())
9839       continue;
9840 
9841     CXXRecordDecl *BaseClassDecl
9842       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9843     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
9844                                                            0, false, 0))
9845       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
9846   }
9847 
9848   for (const auto &Base : ClassDecl->vbases()) {
9849     CXXRecordDecl *BaseClassDecl
9850       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9851     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
9852                                                            0, false, 0))
9853       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
9854   }
9855 
9856   for (const auto *Field : ClassDecl->fields()) {
9857     QualType FieldType = Context.getBaseElementType(Field->getType());
9858     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9859       if (CXXMethodDecl *MoveAssign =
9860               LookupMovingAssignment(FieldClassDecl,
9861                                      FieldType.getCVRQualifiers(),
9862                                      false, 0))
9863         ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
9864     }
9865   }
9866 
9867   return ExceptSpec;
9868 }
9869 
9870 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
9871   assert(ClassDecl->needsImplicitMoveAssignment());
9872 
9873   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9874   if (DSM.isAlreadyBeingDeclared())
9875     return nullptr;
9876 
9877   // Note: The following rules are largely analoguous to the move
9878   // constructor rules.
9879 
9880   QualType ArgType = Context.getTypeDeclType(ClassDecl);
9881   QualType RetType = Context.getLValueReferenceType(ArgType);
9882   ArgType = Context.getRValueReferenceType(ArgType);
9883 
9884   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9885                                                      CXXMoveAssignment,
9886                                                      false);
9887 
9888   //   An implicitly-declared move assignment operator is an inline public
9889   //   member of its class.
9890   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9891   SourceLocation ClassLoc = ClassDecl->getLocation();
9892   DeclarationNameInfo NameInfo(Name, ClassLoc);
9893   CXXMethodDecl *MoveAssignment =
9894       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9895                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
9896                             /*isInline=*/true, Constexpr, SourceLocation());
9897   MoveAssignment->setAccess(AS_public);
9898   MoveAssignment->setDefaulted();
9899   MoveAssignment->setImplicit();
9900 
9901   // Build an exception specification pointing back at this member.
9902   FunctionProtoType::ExtProtoInfo EPI =
9903       getImplicitMethodEPI(*this, MoveAssignment);
9904   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
9905 
9906   // Add the parameter to the operator.
9907   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9908                                                ClassLoc, ClassLoc,
9909                                                /*Id=*/nullptr, ArgType,
9910                                                /*TInfo=*/nullptr, SC_None,
9911                                                nullptr);
9912   MoveAssignment->setParams(FromParam);
9913 
9914   AddOverriddenMethods(ClassDecl, MoveAssignment);
9915 
9916   MoveAssignment->setTrivial(
9917     ClassDecl->needsOverloadResolutionForMoveAssignment()
9918       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9919       : ClassDecl->hasTrivialMoveAssignment());
9920 
9921   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
9922     ClassDecl->setImplicitMoveAssignmentIsDeleted();
9923     SetDeclDeleted(MoveAssignment, ClassLoc);
9924   }
9925 
9926   // Note that we have added this copy-assignment operator.
9927   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9928 
9929   if (Scope *S = getScopeForContext(ClassDecl))
9930     PushOnScopeChains(MoveAssignment, S, false);
9931   ClassDecl->addDecl(MoveAssignment);
9932 
9933   return MoveAssignment;
9934 }
9935 
9936 /// Check if we're implicitly defining a move assignment operator for a class
9937 /// with virtual bases. Such a move assignment might move-assign the virtual
9938 /// base multiple times.
9939 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
9940                                                SourceLocation CurrentLocation) {
9941   assert(!Class->isDependentContext() && "should not define dependent move");
9942 
9943   // Only a virtual base could get implicitly move-assigned multiple times.
9944   // Only a non-trivial move assignment can observe this. We only want to
9945   // diagnose if we implicitly define an assignment operator that assigns
9946   // two base classes, both of which move-assign the same virtual base.
9947   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
9948       Class->getNumBases() < 2)
9949     return;
9950 
9951   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
9952   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
9953   VBaseMap VBases;
9954 
9955   for (auto &BI : Class->bases()) {
9956     Worklist.push_back(&BI);
9957     while (!Worklist.empty()) {
9958       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
9959       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
9960 
9961       // If the base has no non-trivial move assignment operators,
9962       // we don't care about moves from it.
9963       if (!Base->hasNonTrivialMoveAssignment())
9964         continue;
9965 
9966       // If there's nothing virtual here, skip it.
9967       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
9968         continue;
9969 
9970       // If we're not actually going to call a move assignment for this base,
9971       // or the selected move assignment is trivial, skip it.
9972       Sema::SpecialMemberOverloadResult *SMOR =
9973         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
9974                               /*ConstArg*/false, /*VolatileArg*/false,
9975                               /*RValueThis*/true, /*ConstThis*/false,
9976                               /*VolatileThis*/false);
9977       if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
9978           !SMOR->getMethod()->isMoveAssignmentOperator())
9979         continue;
9980 
9981       if (BaseSpec->isVirtual()) {
9982         // We're going to move-assign this virtual base, and its move
9983         // assignment operator is not trivial. If this can happen for
9984         // multiple distinct direct bases of Class, diagnose it. (If it
9985         // only happens in one base, we'll diagnose it when synthesizing
9986         // that base class's move assignment operator.)
9987         CXXBaseSpecifier *&Existing =
9988             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
9989                 .first->second;
9990         if (Existing && Existing != &BI) {
9991           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
9992             << Class << Base;
9993           S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
9994             << (Base->getCanonicalDecl() ==
9995                 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9996             << Base << Existing->getType() << Existing->getSourceRange();
9997           S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
9998             << (Base->getCanonicalDecl() ==
9999                 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10000             << Base << BI.getType() << BaseSpec->getSourceRange();
10001 
10002           // Only diagnose each vbase once.
10003           Existing = nullptr;
10004         }
10005       } else {
10006         // Only walk over bases that have defaulted move assignment operators.
10007         // We assume that any user-provided move assignment operator handles
10008         // the multiple-moves-of-vbase case itself somehow.
10009         if (!SMOR->getMethod()->isDefaulted())
10010           continue;
10011 
10012         // We're going to move the base classes of Base. Add them to the list.
10013         for (auto &BI : Base->bases())
10014           Worklist.push_back(&BI);
10015       }
10016     }
10017   }
10018 }
10019 
10020 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
10021                                         CXXMethodDecl *MoveAssignOperator) {
10022   assert((MoveAssignOperator->isDefaulted() &&
10023           MoveAssignOperator->isOverloadedOperator() &&
10024           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
10025           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
10026           !MoveAssignOperator->isDeleted()) &&
10027          "DefineImplicitMoveAssignment called for wrong function");
10028 
10029   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
10030 
10031   if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
10032     MoveAssignOperator->setInvalidDecl();
10033     return;
10034   }
10035 
10036   MoveAssignOperator->markUsed(Context);
10037 
10038   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
10039   DiagnosticErrorTrap Trap(Diags);
10040 
10041   // C++0x [class.copy]p28:
10042   //   The implicitly-defined or move assignment operator for a non-union class
10043   //   X performs memberwise move assignment of its subobjects. The direct base
10044   //   classes of X are assigned first, in the order of their declaration in the
10045   //   base-specifier-list, and then the immediate non-static data members of X
10046   //   are assigned, in the order in which they were declared in the class
10047   //   definition.
10048 
10049   // Issue a warning if our implicit move assignment operator will move
10050   // from a virtual base more than once.
10051   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
10052 
10053   // The statements that form the synthesized function body.
10054   SmallVector<Stmt*, 8> Statements;
10055 
10056   // The parameter for the "other" object, which we are move from.
10057   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
10058   QualType OtherRefType = Other->getType()->
10059       getAs<RValueReferenceType>()->getPointeeType();
10060   assert(!OtherRefType.getQualifiers() &&
10061          "Bad argument type of defaulted move assignment");
10062 
10063   // Our location for everything implicitly-generated.
10064   SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
10065                            ? MoveAssignOperator->getLocEnd()
10066                            : MoveAssignOperator->getLocation();
10067 
10068   // Builds a reference to the "other" object.
10069   RefBuilder OtherRef(Other, OtherRefType);
10070   // Cast to rvalue.
10071   MoveCastBuilder MoveOther(OtherRef);
10072 
10073   // Builds the "this" pointer.
10074   ThisBuilder This;
10075 
10076   // Assign base classes.
10077   bool Invalid = false;
10078   for (auto &Base : ClassDecl->bases()) {
10079     // C++11 [class.copy]p28:
10080     //   It is unspecified whether subobjects representing virtual base classes
10081     //   are assigned more than once by the implicitly-defined copy assignment
10082     //   operator.
10083     // FIXME: Do not assign to a vbase that will be assigned by some other base
10084     // class. For a move-assignment, this can result in the vbase being moved
10085     // multiple times.
10086 
10087     // Form the assignment:
10088     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
10089     QualType BaseType = Base.getType().getUnqualifiedType();
10090     if (!BaseType->isRecordType()) {
10091       Invalid = true;
10092       continue;
10093     }
10094 
10095     CXXCastPath BasePath;
10096     BasePath.push_back(&Base);
10097 
10098     // Construct the "from" expression, which is an implicit cast to the
10099     // appropriately-qualified base type.
10100     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
10101 
10102     // Dereference "this".
10103     DerefBuilder DerefThis(This);
10104 
10105     // Implicitly cast "this" to the appropriately-qualified base type.
10106     CastBuilder To(DerefThis,
10107                    Context.getCVRQualifiedType(
10108                        BaseType, MoveAssignOperator->getTypeQualifiers()),
10109                    VK_LValue, BasePath);
10110 
10111     // Build the move.
10112     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
10113                                             To, From,
10114                                             /*CopyingBaseSubobject=*/true,
10115                                             /*Copying=*/false);
10116     if (Move.isInvalid()) {
10117       Diag(CurrentLocation, diag::note_member_synthesized_at)
10118         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10119       MoveAssignOperator->setInvalidDecl();
10120       return;
10121     }
10122 
10123     // Success! Record the move.
10124     Statements.push_back(Move.getAs<Expr>());
10125   }
10126 
10127   // Assign non-static members.
10128   for (auto *Field : ClassDecl->fields()) {
10129     if (Field->isUnnamedBitfield())
10130       continue;
10131 
10132     if (Field->isInvalidDecl()) {
10133       Invalid = true;
10134       continue;
10135     }
10136 
10137     // Check for members of reference type; we can't move those.
10138     if (Field->getType()->isReferenceType()) {
10139       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10140         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10141       Diag(Field->getLocation(), diag::note_declared_at);
10142       Diag(CurrentLocation, diag::note_member_synthesized_at)
10143         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10144       Invalid = true;
10145       continue;
10146     }
10147 
10148     // Check for members of const-qualified, non-class type.
10149     QualType BaseType = Context.getBaseElementType(Field->getType());
10150     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10151       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10152         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10153       Diag(Field->getLocation(), diag::note_declared_at);
10154       Diag(CurrentLocation, diag::note_member_synthesized_at)
10155         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10156       Invalid = true;
10157       continue;
10158     }
10159 
10160     // Suppress assigning zero-width bitfields.
10161     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10162       continue;
10163 
10164     QualType FieldType = Field->getType().getNonReferenceType();
10165     if (FieldType->isIncompleteArrayType()) {
10166       assert(ClassDecl->hasFlexibleArrayMember() &&
10167              "Incomplete array type is not valid");
10168       continue;
10169     }
10170 
10171     // Build references to the field in the object we're copying from and to.
10172     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10173                               LookupMemberName);
10174     MemberLookup.addDecl(Field);
10175     MemberLookup.resolveKind();
10176     MemberBuilder From(MoveOther, OtherRefType,
10177                        /*IsArrow=*/false, MemberLookup);
10178     MemberBuilder To(This, getCurrentThisType(),
10179                      /*IsArrow=*/true, MemberLookup);
10180 
10181     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
10182         "Member reference with rvalue base must be rvalue except for reference "
10183         "members, which aren't allowed for move assignment.");
10184 
10185     // Build the move of this field.
10186     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
10187                                             To, From,
10188                                             /*CopyingBaseSubobject=*/false,
10189                                             /*Copying=*/false);
10190     if (Move.isInvalid()) {
10191       Diag(CurrentLocation, diag::note_member_synthesized_at)
10192         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10193       MoveAssignOperator->setInvalidDecl();
10194       return;
10195     }
10196 
10197     // Success! Record the copy.
10198     Statements.push_back(Move.getAs<Stmt>());
10199   }
10200 
10201   if (!Invalid) {
10202     // Add a "return *this;"
10203     ExprResult ThisObj =
10204         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10205 
10206     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
10207     if (Return.isInvalid())
10208       Invalid = true;
10209     else {
10210       Statements.push_back(Return.getAs<Stmt>());
10211 
10212       if (Trap.hasErrorOccurred()) {
10213         Diag(CurrentLocation, diag::note_member_synthesized_at)
10214           << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10215         Invalid = true;
10216       }
10217     }
10218   }
10219 
10220   if (Invalid) {
10221     MoveAssignOperator->setInvalidDecl();
10222     return;
10223   }
10224 
10225   StmtResult Body;
10226   {
10227     CompoundScopeRAII CompoundScope(*this);
10228     Body = ActOnCompoundStmt(Loc, Loc, Statements,
10229                              /*isStmtExpr=*/false);
10230     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10231   }
10232   MoveAssignOperator->setBody(Body.getAs<Stmt>());
10233 
10234   if (ASTMutationListener *L = getASTMutationListener()) {
10235     L->CompletedImplicitDefinition(MoveAssignOperator);
10236   }
10237 }
10238 
10239 Sema::ImplicitExceptionSpecification
10240 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10241   CXXRecordDecl *ClassDecl = MD->getParent();
10242 
10243   ImplicitExceptionSpecification ExceptSpec(*this);
10244   if (ClassDecl->isInvalidDecl())
10245     return ExceptSpec;
10246 
10247   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
10248   assert(T->getNumParams() >= 1 && "not a copy ctor");
10249   unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
10250 
10251   // C++ [except.spec]p14:
10252   //   An implicitly declared special member function (Clause 12) shall have an
10253   //   exception-specification. [...]
10254   for (const auto &Base : ClassDecl->bases()) {
10255     // Virtual bases are handled below.
10256     if (Base.isVirtual())
10257       continue;
10258 
10259     CXXRecordDecl *BaseClassDecl
10260       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10261     if (CXXConstructorDecl *CopyConstructor =
10262           LookupCopyingConstructor(BaseClassDecl, Quals))
10263       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10264   }
10265   for (const auto &Base : ClassDecl->vbases()) {
10266     CXXRecordDecl *BaseClassDecl
10267       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10268     if (CXXConstructorDecl *CopyConstructor =
10269           LookupCopyingConstructor(BaseClassDecl, Quals))
10270       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10271   }
10272   for (const auto *Field : ClassDecl->fields()) {
10273     QualType FieldType = Context.getBaseElementType(Field->getType());
10274     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10275       if (CXXConstructorDecl *CopyConstructor =
10276               LookupCopyingConstructor(FieldClassDecl,
10277                                        Quals | FieldType.getCVRQualifiers()))
10278       ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
10279     }
10280   }
10281 
10282   return ExceptSpec;
10283 }
10284 
10285 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10286                                                     CXXRecordDecl *ClassDecl) {
10287   // C++ [class.copy]p4:
10288   //   If the class definition does not explicitly declare a copy
10289   //   constructor, one is declared implicitly.
10290   assert(ClassDecl->needsImplicitCopyConstructor());
10291 
10292   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10293   if (DSM.isAlreadyBeingDeclared())
10294     return nullptr;
10295 
10296   QualType ClassType = Context.getTypeDeclType(ClassDecl);
10297   QualType ArgType = ClassType;
10298   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
10299   if (Const)
10300     ArgType = ArgType.withConst();
10301   ArgType = Context.getLValueReferenceType(ArgType);
10302 
10303   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10304                                                      CXXCopyConstructor,
10305                                                      Const);
10306 
10307   DeclarationName Name
10308     = Context.DeclarationNames.getCXXConstructorName(
10309                                            Context.getCanonicalType(ClassType));
10310   SourceLocation ClassLoc = ClassDecl->getLocation();
10311   DeclarationNameInfo NameInfo(Name, ClassLoc);
10312 
10313   //   An implicitly-declared copy constructor is an inline public
10314   //   member of its class.
10315   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
10316       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
10317       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10318       Constexpr);
10319   CopyConstructor->setAccess(AS_public);
10320   CopyConstructor->setDefaulted();
10321 
10322   // Build an exception specification pointing back at this member.
10323   FunctionProtoType::ExtProtoInfo EPI =
10324       getImplicitMethodEPI(*this, CopyConstructor);
10325   CopyConstructor->setType(
10326       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10327 
10328   // Add the parameter to the constructor.
10329   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
10330                                                ClassLoc, ClassLoc,
10331                                                /*IdentifierInfo=*/nullptr,
10332                                                ArgType, /*TInfo=*/nullptr,
10333                                                SC_None, nullptr);
10334   CopyConstructor->setParams(FromParam);
10335 
10336   CopyConstructor->setTrivial(
10337     ClassDecl->needsOverloadResolutionForCopyConstructor()
10338       ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10339       : ClassDecl->hasTrivialCopyConstructor());
10340 
10341   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
10342     SetDeclDeleted(CopyConstructor, ClassLoc);
10343 
10344   // Note that we have declared this constructor.
10345   ++ASTContext::NumImplicitCopyConstructorsDeclared;
10346 
10347   if (Scope *S = getScopeForContext(ClassDecl))
10348     PushOnScopeChains(CopyConstructor, S, false);
10349   ClassDecl->addDecl(CopyConstructor);
10350 
10351   return CopyConstructor;
10352 }
10353 
10354 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
10355                                    CXXConstructorDecl *CopyConstructor) {
10356   assert((CopyConstructor->isDefaulted() &&
10357           CopyConstructor->isCopyConstructor() &&
10358           !CopyConstructor->doesThisDeclarationHaveABody() &&
10359           !CopyConstructor->isDeleted()) &&
10360          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
10361 
10362   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
10363   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
10364 
10365   // C++11 [class.copy]p7:
10366   //   The [definition of an implicitly declared copy constructor] is
10367   //   deprecated if the class has a user-declared copy assignment operator
10368   //   or a user-declared destructor.
10369   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10370     diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10371 
10372   SynthesizedFunctionScope Scope(*this, CopyConstructor);
10373   DiagnosticErrorTrap Trap(Diags);
10374 
10375   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
10376       Trap.hasErrorOccurred()) {
10377     Diag(CurrentLocation, diag::note_member_synthesized_at)
10378       << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
10379     CopyConstructor->setInvalidDecl();
10380   }  else {
10381     SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
10382                              ? CopyConstructor->getLocEnd()
10383                              : CopyConstructor->getLocation();
10384     Sema::CompoundScopeRAII CompoundScope(*this);
10385     CopyConstructor->setBody(
10386         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
10387   }
10388 
10389   CopyConstructor->markUsed(Context);
10390   MarkVTableUsed(CurrentLocation, ClassDecl);
10391 
10392   if (ASTMutationListener *L = getASTMutationListener()) {
10393     L->CompletedImplicitDefinition(CopyConstructor);
10394   }
10395 }
10396 
10397 Sema::ImplicitExceptionSpecification
10398 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10399   CXXRecordDecl *ClassDecl = MD->getParent();
10400 
10401   // C++ [except.spec]p14:
10402   //   An implicitly declared special member function (Clause 12) shall have an
10403   //   exception-specification. [...]
10404   ImplicitExceptionSpecification ExceptSpec(*this);
10405   if (ClassDecl->isInvalidDecl())
10406     return ExceptSpec;
10407 
10408   // Direct base-class constructors.
10409   for (const auto &B : ClassDecl->bases()) {
10410     if (B.isVirtual()) // Handled below.
10411       continue;
10412 
10413     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
10414       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10415       CXXConstructorDecl *Constructor =
10416           LookupMovingConstructor(BaseClassDecl, 0);
10417       // If this is a deleted function, add it anyway. This might be conformant
10418       // with the standard. This might not. I'm not sure. It might not matter.
10419       if (Constructor)
10420         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
10421     }
10422   }
10423 
10424   // Virtual base-class constructors.
10425   for (const auto &B : ClassDecl->vbases()) {
10426     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
10427       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10428       CXXConstructorDecl *Constructor =
10429           LookupMovingConstructor(BaseClassDecl, 0);
10430       // If this is a deleted function, add it anyway. This might be conformant
10431       // with the standard. This might not. I'm not sure. It might not matter.
10432       if (Constructor)
10433         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
10434     }
10435   }
10436 
10437   // Field constructors.
10438   for (const auto *F : ClassDecl->fields()) {
10439     QualType FieldType = Context.getBaseElementType(F->getType());
10440     if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10441       CXXConstructorDecl *Constructor =
10442           LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
10443       // If this is a deleted function, add it anyway. This might be conformant
10444       // with the standard. This might not. I'm not sure. It might not matter.
10445       // In particular, the problem is that this function never gets called. It
10446       // might just be ill-formed because this function attempts to refer to
10447       // a deleted function here.
10448       if (Constructor)
10449         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
10450     }
10451   }
10452 
10453   return ExceptSpec;
10454 }
10455 
10456 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10457                                                     CXXRecordDecl *ClassDecl) {
10458   assert(ClassDecl->needsImplicitMoveConstructor());
10459 
10460   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10461   if (DSM.isAlreadyBeingDeclared())
10462     return nullptr;
10463 
10464   QualType ClassType = Context.getTypeDeclType(ClassDecl);
10465   QualType ArgType = Context.getRValueReferenceType(ClassType);
10466 
10467   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10468                                                      CXXMoveConstructor,
10469                                                      false);
10470 
10471   DeclarationName Name
10472     = Context.DeclarationNames.getCXXConstructorName(
10473                                            Context.getCanonicalType(ClassType));
10474   SourceLocation ClassLoc = ClassDecl->getLocation();
10475   DeclarationNameInfo NameInfo(Name, ClassLoc);
10476 
10477   // C++11 [class.copy]p11:
10478   //   An implicitly-declared copy/move constructor is an inline public
10479   //   member of its class.
10480   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
10481       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
10482       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10483       Constexpr);
10484   MoveConstructor->setAccess(AS_public);
10485   MoveConstructor->setDefaulted();
10486 
10487   // Build an exception specification pointing back at this member.
10488   FunctionProtoType::ExtProtoInfo EPI =
10489       getImplicitMethodEPI(*this, MoveConstructor);
10490   MoveConstructor->setType(
10491       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10492 
10493   // Add the parameter to the constructor.
10494   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10495                                                ClassLoc, ClassLoc,
10496                                                /*IdentifierInfo=*/nullptr,
10497                                                ArgType, /*TInfo=*/nullptr,
10498                                                SC_None, nullptr);
10499   MoveConstructor->setParams(FromParam);
10500 
10501   MoveConstructor->setTrivial(
10502     ClassDecl->needsOverloadResolutionForMoveConstructor()
10503       ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10504       : ClassDecl->hasTrivialMoveConstructor());
10505 
10506   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
10507     ClassDecl->setImplicitMoveConstructorIsDeleted();
10508     SetDeclDeleted(MoveConstructor, ClassLoc);
10509   }
10510 
10511   // Note that we have declared this constructor.
10512   ++ASTContext::NumImplicitMoveConstructorsDeclared;
10513 
10514   if (Scope *S = getScopeForContext(ClassDecl))
10515     PushOnScopeChains(MoveConstructor, S, false);
10516   ClassDecl->addDecl(MoveConstructor);
10517 
10518   return MoveConstructor;
10519 }
10520 
10521 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10522                                    CXXConstructorDecl *MoveConstructor) {
10523   assert((MoveConstructor->isDefaulted() &&
10524           MoveConstructor->isMoveConstructor() &&
10525           !MoveConstructor->doesThisDeclarationHaveABody() &&
10526           !MoveConstructor->isDeleted()) &&
10527          "DefineImplicitMoveConstructor - call it for implicit move ctor");
10528 
10529   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10530   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10531 
10532   SynthesizedFunctionScope Scope(*this, MoveConstructor);
10533   DiagnosticErrorTrap Trap(Diags);
10534 
10535   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
10536       Trap.hasErrorOccurred()) {
10537     Diag(CurrentLocation, diag::note_member_synthesized_at)
10538       << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10539     MoveConstructor->setInvalidDecl();
10540   }  else {
10541     SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
10542                              ? MoveConstructor->getLocEnd()
10543                              : MoveConstructor->getLocation();
10544     Sema::CompoundScopeRAII CompoundScope(*this);
10545     MoveConstructor->setBody(ActOnCompoundStmt(
10546         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
10547   }
10548 
10549   MoveConstructor->markUsed(Context);
10550   MarkVTableUsed(CurrentLocation, ClassDecl);
10551 
10552   if (ASTMutationListener *L = getASTMutationListener()) {
10553     L->CompletedImplicitDefinition(MoveConstructor);
10554   }
10555 }
10556 
10557 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
10558   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
10559 }
10560 
10561 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
10562                             SourceLocation CurrentLocation,
10563                             CXXConversionDecl *Conv) {
10564   CXXRecordDecl *Lambda = Conv->getParent();
10565   CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10566   // If we are defining a specialization of a conversion to function-ptr
10567   // cache the deduced template arguments for this specialization
10568   // so that we can use them to retrieve the corresponding call-operator
10569   // and static-invoker.
10570   const TemplateArgumentList *DeducedTemplateArgs = nullptr;
10571 
10572   // Retrieve the corresponding call-operator specialization.
10573   if (Lambda->isGenericLambda()) {
10574     assert(Conv->isFunctionTemplateSpecialization());
10575     FunctionTemplateDecl *CallOpTemplate =
10576         CallOp->getDescribedFunctionTemplate();
10577     DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
10578     void *InsertPos = nullptr;
10579     FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
10580                                                 DeducedTemplateArgs->asArray(),
10581                                                 InsertPos);
10582     assert(CallOpSpec &&
10583           "Conversion operator must have a corresponding call operator");
10584     CallOp = cast<CXXMethodDecl>(CallOpSpec);
10585   }
10586   // Mark the call operator referenced (and add to pending instantiations
10587   // if necessary).
10588   // For both the conversion and static-invoker template specializations
10589   // we construct their body's in this function, so no need to add them
10590   // to the PendingInstantiations.
10591   MarkFunctionReferenced(CurrentLocation, CallOp);
10592 
10593   SynthesizedFunctionScope Scope(*this, Conv);
10594   DiagnosticErrorTrap Trap(Diags);
10595 
10596   // Retrieve the static invoker...
10597   CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10598   // ... and get the corresponding specialization for a generic lambda.
10599   if (Lambda->isGenericLambda()) {
10600     assert(DeducedTemplateArgs &&
10601       "Must have deduced template arguments from Conversion Operator");
10602     FunctionTemplateDecl *InvokeTemplate =
10603                           Invoker->getDescribedFunctionTemplate();
10604     void *InsertPos = nullptr;
10605     FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
10606                                                 DeducedTemplateArgs->asArray(),
10607                                                 InsertPos);
10608     assert(InvokeSpec &&
10609       "Must have a corresponding static invoker specialization");
10610     Invoker = cast<CXXMethodDecl>(InvokeSpec);
10611   }
10612   // Construct the body of the conversion function { return __invoke; }.
10613   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
10614                                         VK_LValue, Conv->getLocation()).get();
10615    assert(FunctionRef && "Can't refer to __invoke function?");
10616    Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
10617    Conv->setBody(new (Context) CompoundStmt(Context, Return,
10618                                             Conv->getLocation(),
10619                                             Conv->getLocation()));
10620 
10621   Conv->markUsed(Context);
10622   Conv->setReferenced();
10623 
10624   // Fill in the __invoke function with a dummy implementation. IR generation
10625   // will fill in the actual details.
10626   Invoker->markUsed(Context);
10627   Invoker->setReferenced();
10628   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10629 
10630   if (ASTMutationListener *L = getASTMutationListener()) {
10631     L->CompletedImplicitDefinition(Conv);
10632     L->CompletedImplicitDefinition(Invoker);
10633    }
10634 }
10635 
10636 
10637 
10638 void Sema::DefineImplicitLambdaToBlockPointerConversion(
10639        SourceLocation CurrentLocation,
10640        CXXConversionDecl *Conv)
10641 {
10642   assert(!Conv->getParent()->isGenericLambda());
10643 
10644   Conv->markUsed(Context);
10645 
10646   SynthesizedFunctionScope Scope(*this, Conv);
10647   DiagnosticErrorTrap Trap(Diags);
10648 
10649   // Copy-initialize the lambda object as needed to capture it.
10650   Expr *This = ActOnCXXThis(CurrentLocation).get();
10651   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
10652 
10653   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10654                                                         Conv->getLocation(),
10655                                                         Conv, DerefThis);
10656 
10657   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10658   // behavior.  Note that only the general conversion function does this
10659   // (since it's unusable otherwise); in the case where we inline the
10660   // block literal, it has block literal lifetime semantics.
10661   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
10662     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10663                                           CK_CopyAndAutoreleaseBlockObject,
10664                                           BuildBlock.get(), nullptr, VK_RValue);
10665 
10666   if (BuildBlock.isInvalid()) {
10667     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10668     Conv->setInvalidDecl();
10669     return;
10670   }
10671 
10672   // Create the return statement that returns the block from the conversion
10673   // function.
10674   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
10675   if (Return.isInvalid()) {
10676     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10677     Conv->setInvalidDecl();
10678     return;
10679   }
10680 
10681   // Set the body of the conversion function.
10682   Stmt *ReturnS = Return.get();
10683   Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
10684                                            Conv->getLocation(),
10685                                            Conv->getLocation()));
10686 
10687   // We're done; notify the mutation listener, if any.
10688   if (ASTMutationListener *L = getASTMutationListener()) {
10689     L->CompletedImplicitDefinition(Conv);
10690   }
10691 }
10692 
10693 /// \brief Determine whether the given list arguments contains exactly one
10694 /// "real" (non-default) argument.
10695 static bool hasOneRealArgument(MultiExprArg Args) {
10696   switch (Args.size()) {
10697   case 0:
10698     return false;
10699 
10700   default:
10701     if (!Args[1]->isDefaultArgument())
10702       return false;
10703 
10704     // fall through
10705   case 1:
10706     return !Args[0]->isDefaultArgument();
10707   }
10708 
10709   return false;
10710 }
10711 
10712 ExprResult
10713 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10714                             CXXConstructorDecl *Constructor,
10715                             MultiExprArg ExprArgs,
10716                             bool HadMultipleCandidates,
10717                             bool IsListInitialization,
10718                             bool IsStdInitListInitialization,
10719                             bool RequiresZeroInit,
10720                             unsigned ConstructKind,
10721                             SourceRange ParenRange) {
10722   bool Elidable = false;
10723 
10724   // C++0x [class.copy]p34:
10725   //   When certain criteria are met, an implementation is allowed to
10726   //   omit the copy/move construction of a class object, even if the
10727   //   copy/move constructor and/or destructor for the object have
10728   //   side effects. [...]
10729   //     - when a temporary class object that has not been bound to a
10730   //       reference (12.2) would be copied/moved to a class object
10731   //       with the same cv-unqualified type, the copy/move operation
10732   //       can be omitted by constructing the temporary object
10733   //       directly into the target of the omitted copy/move
10734   if (ConstructKind == CXXConstructExpr::CK_Complete &&
10735       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
10736     Expr *SubExpr = ExprArgs[0];
10737     Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
10738   }
10739 
10740   return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
10741                                Elidable, ExprArgs, HadMultipleCandidates,
10742                                IsListInitialization,
10743                                IsStdInitListInitialization, RequiresZeroInit,
10744                                ConstructKind, ParenRange);
10745 }
10746 
10747 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
10748 /// including handling of its default argument expressions.
10749 ExprResult
10750 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10751                             CXXConstructorDecl *Constructor, bool Elidable,
10752                             MultiExprArg ExprArgs,
10753                             bool HadMultipleCandidates,
10754                             bool IsListInitialization,
10755                             bool IsStdInitListInitialization,
10756                             bool RequiresZeroInit,
10757                             unsigned ConstructKind,
10758                             SourceRange ParenRange) {
10759   MarkFunctionReferenced(ConstructLoc, Constructor);
10760   return CXXConstructExpr::Create(
10761       Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
10762       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
10763       RequiresZeroInit,
10764       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10765       ParenRange);
10766 }
10767 
10768 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
10769   if (VD->isInvalidDecl()) return;
10770 
10771   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
10772   if (ClassDecl->isInvalidDecl()) return;
10773   if (ClassDecl->hasIrrelevantDestructor()) return;
10774   if (ClassDecl->isDependentContext()) return;
10775 
10776   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10777   MarkFunctionReferenced(VD->getLocation(), Destructor);
10778   CheckDestructorAccess(VD->getLocation(), Destructor,
10779                         PDiag(diag::err_access_dtor_var)
10780                         << VD->getDeclName()
10781                         << VD->getType());
10782   DiagnoseUseOfDecl(Destructor, VD->getLocation());
10783 
10784   if (Destructor->isTrivial()) return;
10785   if (!VD->hasGlobalStorage()) return;
10786 
10787   // Emit warning for non-trivial dtor in global scope (a real global,
10788   // class-static, function-static).
10789   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10790 
10791   // TODO: this should be re-enabled for static locals by !CXAAtExit
10792   if (!VD->isStaticLocal())
10793     Diag(VD->getLocation(), diag::warn_global_destructor);
10794 }
10795 
10796 /// \brief Given a constructor and the set of arguments provided for the
10797 /// constructor, convert the arguments and add any required default arguments
10798 /// to form a proper call to this constructor.
10799 ///
10800 /// \returns true if an error occurred, false otherwise.
10801 bool
10802 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10803                               MultiExprArg ArgsPtr,
10804                               SourceLocation Loc,
10805                               SmallVectorImpl<Expr*> &ConvertedArgs,
10806                               bool AllowExplicit,
10807                               bool IsListInitialization) {
10808   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10809   unsigned NumArgs = ArgsPtr.size();
10810   Expr **Args = ArgsPtr.data();
10811 
10812   const FunctionProtoType *Proto
10813     = Constructor->getType()->getAs<FunctionProtoType>();
10814   assert(Proto && "Constructor without a prototype?");
10815   unsigned NumParams = Proto->getNumParams();
10816 
10817   // If too few arguments are available, we'll fill in the rest with defaults.
10818   if (NumArgs < NumParams)
10819     ConvertedArgs.reserve(NumParams);
10820   else
10821     ConvertedArgs.reserve(NumArgs);
10822 
10823   VariadicCallType CallType =
10824     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
10825   SmallVector<Expr *, 8> AllArgs;
10826   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
10827                                         Proto, 0,
10828                                         llvm::makeArrayRef(Args, NumArgs),
10829                                         AllArgs,
10830                                         CallType, AllowExplicit,
10831                                         IsListInitialization);
10832   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
10833 
10834   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
10835 
10836   CheckConstructorCall(Constructor,
10837                        llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10838                                                         AllArgs.size()),
10839                        Proto, Loc);
10840 
10841   return Invalid;
10842 }
10843 
10844 static inline bool
10845 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10846                                        const FunctionDecl *FnDecl) {
10847   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
10848   if (isa<NamespaceDecl>(DC)) {
10849     return SemaRef.Diag(FnDecl->getLocation(),
10850                         diag::err_operator_new_delete_declared_in_namespace)
10851       << FnDecl->getDeclName();
10852   }
10853 
10854   if (isa<TranslationUnitDecl>(DC) &&
10855       FnDecl->getStorageClass() == SC_Static) {
10856     return SemaRef.Diag(FnDecl->getLocation(),
10857                         diag::err_operator_new_delete_declared_static)
10858       << FnDecl->getDeclName();
10859   }
10860 
10861   return false;
10862 }
10863 
10864 static inline bool
10865 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10866                             CanQualType ExpectedResultType,
10867                             CanQualType ExpectedFirstParamType,
10868                             unsigned DependentParamTypeDiag,
10869                             unsigned InvalidParamTypeDiag) {
10870   QualType ResultType =
10871       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
10872 
10873   // Check that the result type is not dependent.
10874   if (ResultType->isDependentType())
10875     return SemaRef.Diag(FnDecl->getLocation(),
10876                         diag::err_operator_new_delete_dependent_result_type)
10877     << FnDecl->getDeclName() << ExpectedResultType;
10878 
10879   // Check that the result type is what we expect.
10880   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10881     return SemaRef.Diag(FnDecl->getLocation(),
10882                         diag::err_operator_new_delete_invalid_result_type)
10883     << FnDecl->getDeclName() << ExpectedResultType;
10884 
10885   // A function template must have at least 2 parameters.
10886   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10887     return SemaRef.Diag(FnDecl->getLocation(),
10888                       diag::err_operator_new_delete_template_too_few_parameters)
10889         << FnDecl->getDeclName();
10890 
10891   // The function decl must have at least 1 parameter.
10892   if (FnDecl->getNumParams() == 0)
10893     return SemaRef.Diag(FnDecl->getLocation(),
10894                         diag::err_operator_new_delete_too_few_parameters)
10895       << FnDecl->getDeclName();
10896 
10897   // Check the first parameter type is not dependent.
10898   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10899   if (FirstParamType->isDependentType())
10900     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10901       << FnDecl->getDeclName() << ExpectedFirstParamType;
10902 
10903   // Check that the first parameter type is what we expect.
10904   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
10905       ExpectedFirstParamType)
10906     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10907     << FnDecl->getDeclName() << ExpectedFirstParamType;
10908 
10909   return false;
10910 }
10911 
10912 static bool
10913 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
10914   // C++ [basic.stc.dynamic.allocation]p1:
10915   //   A program is ill-formed if an allocation function is declared in a
10916   //   namespace scope other than global scope or declared static in global
10917   //   scope.
10918   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10919     return true;
10920 
10921   CanQualType SizeTy =
10922     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10923 
10924   // C++ [basic.stc.dynamic.allocation]p1:
10925   //  The return type shall be void*. The first parameter shall have type
10926   //  std::size_t.
10927   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10928                                   SizeTy,
10929                                   diag::err_operator_new_dependent_param_type,
10930                                   diag::err_operator_new_param_type))
10931     return true;
10932 
10933   // C++ [basic.stc.dynamic.allocation]p1:
10934   //  The first parameter shall not have an associated default argument.
10935   if (FnDecl->getParamDecl(0)->hasDefaultArg())
10936     return SemaRef.Diag(FnDecl->getLocation(),
10937                         diag::err_operator_new_default_arg)
10938       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10939 
10940   return false;
10941 }
10942 
10943 static bool
10944 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
10945   // C++ [basic.stc.dynamic.deallocation]p1:
10946   //   A program is ill-formed if deallocation functions are declared in a
10947   //   namespace scope other than global scope or declared static in global
10948   //   scope.
10949   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10950     return true;
10951 
10952   // C++ [basic.stc.dynamic.deallocation]p2:
10953   //   Each deallocation function shall return void and its first parameter
10954   //   shall be void*.
10955   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10956                                   SemaRef.Context.VoidPtrTy,
10957                                  diag::err_operator_delete_dependent_param_type,
10958                                  diag::err_operator_delete_param_type))
10959     return true;
10960 
10961   return false;
10962 }
10963 
10964 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
10965 /// of this overloaded operator is well-formed. If so, returns false;
10966 /// otherwise, emits appropriate diagnostics and returns true.
10967 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
10968   assert(FnDecl && FnDecl->isOverloadedOperator() &&
10969          "Expected an overloaded operator declaration");
10970 
10971   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10972 
10973   // C++ [over.oper]p5:
10974   //   The allocation and deallocation functions, operator new,
10975   //   operator new[], operator delete and operator delete[], are
10976   //   described completely in 3.7.3. The attributes and restrictions
10977   //   found in the rest of this subclause do not apply to them unless
10978   //   explicitly stated in 3.7.3.
10979   if (Op == OO_Delete || Op == OO_Array_Delete)
10980     return CheckOperatorDeleteDeclaration(*this, FnDecl);
10981 
10982   if (Op == OO_New || Op == OO_Array_New)
10983     return CheckOperatorNewDeclaration(*this, FnDecl);
10984 
10985   // C++ [over.oper]p6:
10986   //   An operator function shall either be a non-static member
10987   //   function or be a non-member function and have at least one
10988   //   parameter whose type is a class, a reference to a class, an
10989   //   enumeration, or a reference to an enumeration.
10990   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10991     if (MethodDecl->isStatic())
10992       return Diag(FnDecl->getLocation(),
10993                   diag::err_operator_overload_static) << FnDecl->getDeclName();
10994   } else {
10995     bool ClassOrEnumParam = false;
10996     for (auto Param : FnDecl->params()) {
10997       QualType ParamType = Param->getType().getNonReferenceType();
10998       if (ParamType->isDependentType() || ParamType->isRecordType() ||
10999           ParamType->isEnumeralType()) {
11000         ClassOrEnumParam = true;
11001         break;
11002       }
11003     }
11004 
11005     if (!ClassOrEnumParam)
11006       return Diag(FnDecl->getLocation(),
11007                   diag::err_operator_overload_needs_class_or_enum)
11008         << FnDecl->getDeclName();
11009   }
11010 
11011   // C++ [over.oper]p8:
11012   //   An operator function cannot have default arguments (8.3.6),
11013   //   except where explicitly stated below.
11014   //
11015   // Only the function-call operator allows default arguments
11016   // (C++ [over.call]p1).
11017   if (Op != OO_Call) {
11018     for (auto Param : FnDecl->params()) {
11019       if (Param->hasDefaultArg())
11020         return Diag(Param->getLocation(),
11021                     diag::err_operator_overload_default_arg)
11022           << FnDecl->getDeclName() << Param->getDefaultArgRange();
11023     }
11024   }
11025 
11026   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
11027     { false, false, false }
11028 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11029     , { Unary, Binary, MemberOnly }
11030 #include "clang/Basic/OperatorKinds.def"
11031   };
11032 
11033   bool CanBeUnaryOperator = OperatorUses[Op][0];
11034   bool CanBeBinaryOperator = OperatorUses[Op][1];
11035   bool MustBeMemberOperator = OperatorUses[Op][2];
11036 
11037   // C++ [over.oper]p8:
11038   //   [...] Operator functions cannot have more or fewer parameters
11039   //   than the number required for the corresponding operator, as
11040   //   described in the rest of this subclause.
11041   unsigned NumParams = FnDecl->getNumParams()
11042                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
11043   if (Op != OO_Call &&
11044       ((NumParams == 1 && !CanBeUnaryOperator) ||
11045        (NumParams == 2 && !CanBeBinaryOperator) ||
11046        (NumParams < 1) || (NumParams > 2))) {
11047     // We have the wrong number of parameters.
11048     unsigned ErrorKind;
11049     if (CanBeUnaryOperator && CanBeBinaryOperator) {
11050       ErrorKind = 2;  // 2 -> unary or binary.
11051     } else if (CanBeUnaryOperator) {
11052       ErrorKind = 0;  // 0 -> unary
11053     } else {
11054       assert(CanBeBinaryOperator &&
11055              "All non-call overloaded operators are unary or binary!");
11056       ErrorKind = 1;  // 1 -> binary
11057     }
11058 
11059     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
11060       << FnDecl->getDeclName() << NumParams << ErrorKind;
11061   }
11062 
11063   // Overloaded operators other than operator() cannot be variadic.
11064   if (Op != OO_Call &&
11065       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
11066     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
11067       << FnDecl->getDeclName();
11068   }
11069 
11070   // Some operators must be non-static member functions.
11071   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
11072     return Diag(FnDecl->getLocation(),
11073                 diag::err_operator_overload_must_be_member)
11074       << FnDecl->getDeclName();
11075   }
11076 
11077   // C++ [over.inc]p1:
11078   //   The user-defined function called operator++ implements the
11079   //   prefix and postfix ++ operator. If this function is a member
11080   //   function with no parameters, or a non-member function with one
11081   //   parameter of class or enumeration type, it defines the prefix
11082   //   increment operator ++ for objects of that type. If the function
11083   //   is a member function with one parameter (which shall be of type
11084   //   int) or a non-member function with two parameters (the second
11085   //   of which shall be of type int), it defines the postfix
11086   //   increment operator ++ for objects of that type.
11087   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11088     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
11089     QualType ParamType = LastParam->getType();
11090 
11091     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11092         !ParamType->isDependentType())
11093       return Diag(LastParam->getLocation(),
11094                   diag::err_operator_overload_post_incdec_must_be_int)
11095         << LastParam->getType() << (Op == OO_MinusMinus);
11096   }
11097 
11098   return false;
11099 }
11100 
11101 /// CheckLiteralOperatorDeclaration - Check whether the declaration
11102 /// of this literal operator function is well-formed. If so, returns
11103 /// false; otherwise, emits appropriate diagnostics and returns true.
11104 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
11105   if (isa<CXXMethodDecl>(FnDecl)) {
11106     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11107       << FnDecl->getDeclName();
11108     return true;
11109   }
11110 
11111   if (FnDecl->isExternC()) {
11112     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11113     return true;
11114   }
11115 
11116   bool Valid = false;
11117 
11118   // This might be the definition of a literal operator template.
11119   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11120   // This might be a specialization of a literal operator template.
11121   if (!TpDecl)
11122     TpDecl = FnDecl->getPrimaryTemplate();
11123 
11124   // template <char...> type operator "" name() and
11125   // template <class T, T...> type operator "" name() are the only valid
11126   // template signatures, and the only valid signatures with no parameters.
11127   if (TpDecl) {
11128     if (FnDecl->param_size() == 0) {
11129       // Must have one or two template parameters
11130       TemplateParameterList *Params = TpDecl->getTemplateParameters();
11131       if (Params->size() == 1) {
11132         NonTypeTemplateParmDecl *PmDecl =
11133           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
11134 
11135         // The template parameter must be a char parameter pack.
11136         if (PmDecl && PmDecl->isTemplateParameterPack() &&
11137             Context.hasSameType(PmDecl->getType(), Context.CharTy))
11138           Valid = true;
11139       } else if (Params->size() == 2) {
11140         TemplateTypeParmDecl *PmType =
11141           dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
11142         NonTypeTemplateParmDecl *PmArgs =
11143           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
11144 
11145         // The second template parameter must be a parameter pack with the
11146         // first template parameter as its type.
11147         if (PmType && PmArgs &&
11148             !PmType->isTemplateParameterPack() &&
11149             PmArgs->isTemplateParameterPack()) {
11150           const TemplateTypeParmType *TArgs =
11151             PmArgs->getType()->getAs<TemplateTypeParmType>();
11152           if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11153               TArgs->getIndex() == PmType->getIndex()) {
11154             Valid = true;
11155             if (ActiveTemplateInstantiations.empty())
11156               Diag(FnDecl->getLocation(),
11157                    diag::ext_string_literal_operator_template);
11158           }
11159         }
11160       }
11161     }
11162   } else if (FnDecl->param_size()) {
11163     // Check the first parameter
11164     FunctionDecl::param_iterator Param = FnDecl->param_begin();
11165 
11166     QualType T = (*Param)->getType().getUnqualifiedType();
11167 
11168     // unsigned long long int, long double, and any character type are allowed
11169     // as the only parameters.
11170     if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
11171         Context.hasSameType(T, Context.LongDoubleTy) ||
11172         Context.hasSameType(T, Context.CharTy) ||
11173         Context.hasSameType(T, Context.WideCharTy) ||
11174         Context.hasSameType(T, Context.Char16Ty) ||
11175         Context.hasSameType(T, Context.Char32Ty)) {
11176       if (++Param == FnDecl->param_end())
11177         Valid = true;
11178       goto FinishedParams;
11179     }
11180 
11181     // Otherwise it must be a pointer to const; let's strip those qualifiers.
11182     const PointerType *PT = T->getAs<PointerType>();
11183     if (!PT)
11184       goto FinishedParams;
11185     T = PT->getPointeeType();
11186     if (!T.isConstQualified() || T.isVolatileQualified())
11187       goto FinishedParams;
11188     T = T.getUnqualifiedType();
11189 
11190     // Move on to the second parameter;
11191     ++Param;
11192 
11193     // If there is no second parameter, the first must be a const char *
11194     if (Param == FnDecl->param_end()) {
11195       if (Context.hasSameType(T, Context.CharTy))
11196         Valid = true;
11197       goto FinishedParams;
11198     }
11199 
11200     // const char *, const wchar_t*, const char16_t*, and const char32_t*
11201     // are allowed as the first parameter to a two-parameter function
11202     if (!(Context.hasSameType(T, Context.CharTy) ||
11203           Context.hasSameType(T, Context.WideCharTy) ||
11204           Context.hasSameType(T, Context.Char16Ty) ||
11205           Context.hasSameType(T, Context.Char32Ty)))
11206       goto FinishedParams;
11207 
11208     // The second and final parameter must be an std::size_t
11209     T = (*Param)->getType().getUnqualifiedType();
11210     if (Context.hasSameType(T, Context.getSizeType()) &&
11211         ++Param == FnDecl->param_end())
11212       Valid = true;
11213   }
11214 
11215   // FIXME: This diagnostic is absolutely terrible.
11216 FinishedParams:
11217   if (!Valid) {
11218     Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11219       << FnDecl->getDeclName();
11220     return true;
11221   }
11222 
11223   // A parameter-declaration-clause containing a default argument is not
11224   // equivalent to any of the permitted forms.
11225   for (auto Param : FnDecl->params()) {
11226     if (Param->hasDefaultArg()) {
11227       Diag(Param->getDefaultArgRange().getBegin(),
11228            diag::err_literal_operator_default_argument)
11229         << Param->getDefaultArgRange();
11230       break;
11231     }
11232   }
11233 
11234   StringRef LiteralName
11235     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11236   if (LiteralName[0] != '_') {
11237     // C++11 [usrlit.suffix]p1:
11238     //   Literal suffix identifiers that do not start with an underscore
11239     //   are reserved for future standardization.
11240     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11241       << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
11242   }
11243 
11244   return false;
11245 }
11246 
11247 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11248 /// linkage specification, including the language and (if present)
11249 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
11250 /// language string literal. LBraceLoc, if valid, provides the location of
11251 /// the '{' brace. Otherwise, this linkage specification does not
11252 /// have any braces.
11253 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
11254                                            Expr *LangStr,
11255                                            SourceLocation LBraceLoc) {
11256   StringLiteral *Lit = cast<StringLiteral>(LangStr);
11257   if (!Lit->isAscii()) {
11258     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11259       << LangStr->getSourceRange();
11260     return nullptr;
11261   }
11262 
11263   StringRef Lang = Lit->getString();
11264   LinkageSpecDecl::LanguageIDs Language;
11265   if (Lang == "C")
11266     Language = LinkageSpecDecl::lang_c;
11267   else if (Lang == "C++")
11268     Language = LinkageSpecDecl::lang_cxx;
11269   else {
11270     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11271       << LangStr->getSourceRange();
11272     return nullptr;
11273   }
11274 
11275   // FIXME: Add all the various semantics of linkage specifications
11276 
11277   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11278                                                LangStr->getExprLoc(), Language,
11279                                                LBraceLoc.isValid());
11280   CurContext->addDecl(D);
11281   PushDeclContext(S, D);
11282   return D;
11283 }
11284 
11285 /// ActOnFinishLinkageSpecification - Complete the definition of
11286 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
11287 /// valid, it's the position of the closing '}' brace in a linkage
11288 /// specification that uses braces.
11289 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
11290                                             Decl *LinkageSpec,
11291                                             SourceLocation RBraceLoc) {
11292   if (RBraceLoc.isValid()) {
11293     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11294     LSDecl->setRBraceLoc(RBraceLoc);
11295   }
11296   PopDeclContext();
11297   return LinkageSpec;
11298 }
11299 
11300 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11301                                   AttributeList *AttrList,
11302                                   SourceLocation SemiLoc) {
11303   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11304   // Attribute declarations appertain to empty declaration so we handle
11305   // them here.
11306   if (AttrList)
11307     ProcessDeclAttributeList(S, ED, AttrList);
11308 
11309   CurContext->addDecl(ED);
11310   return ED;
11311 }
11312 
11313 /// \brief Perform semantic analysis for the variable declaration that
11314 /// occurs within a C++ catch clause, returning the newly-created
11315 /// variable.
11316 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
11317                                          TypeSourceInfo *TInfo,
11318                                          SourceLocation StartLoc,
11319                                          SourceLocation Loc,
11320                                          IdentifierInfo *Name) {
11321   bool Invalid = false;
11322   QualType ExDeclType = TInfo->getType();
11323 
11324   // Arrays and functions decay.
11325   if (ExDeclType->isArrayType())
11326     ExDeclType = Context.getArrayDecayedType(ExDeclType);
11327   else if (ExDeclType->isFunctionType())
11328     ExDeclType = Context.getPointerType(ExDeclType);
11329 
11330   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11331   // The exception-declaration shall not denote a pointer or reference to an
11332   // incomplete type, other than [cv] void*.
11333   // N2844 forbids rvalue references.
11334   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
11335     Diag(Loc, diag::err_catch_rvalue_ref);
11336     Invalid = true;
11337   }
11338 
11339   QualType BaseType = ExDeclType;
11340   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
11341   unsigned DK = diag::err_catch_incomplete;
11342   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
11343     BaseType = Ptr->getPointeeType();
11344     Mode = 1;
11345     DK = diag::err_catch_incomplete_ptr;
11346   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
11347     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
11348     BaseType = Ref->getPointeeType();
11349     Mode = 2;
11350     DK = diag::err_catch_incomplete_ref;
11351   }
11352   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
11353       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
11354     Invalid = true;
11355 
11356   if (!Invalid && !ExDeclType->isDependentType() &&
11357       RequireNonAbstractType(Loc, ExDeclType,
11358                              diag::err_abstract_type_in_decl,
11359                              AbstractVariableType))
11360     Invalid = true;
11361 
11362   // Only the non-fragile NeXT runtime currently supports C++ catches
11363   // of ObjC types, and no runtime supports catching ObjC types by value.
11364   if (!Invalid && getLangOpts().ObjC1) {
11365     QualType T = ExDeclType;
11366     if (const ReferenceType *RT = T->getAs<ReferenceType>())
11367       T = RT->getPointeeType();
11368 
11369     if (T->isObjCObjectType()) {
11370       Diag(Loc, diag::err_objc_object_catch);
11371       Invalid = true;
11372     } else if (T->isObjCObjectPointerType()) {
11373       // FIXME: should this be a test for macosx-fragile specifically?
11374       if (getLangOpts().ObjCRuntime.isFragile())
11375         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
11376     }
11377   }
11378 
11379   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
11380                                     ExDeclType, TInfo, SC_None);
11381   ExDecl->setExceptionVariable(true);
11382 
11383   // In ARC, infer 'retaining' for variables of retainable type.
11384   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
11385     Invalid = true;
11386 
11387   if (!Invalid && !ExDeclType->isDependentType()) {
11388     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
11389       // Insulate this from anything else we might currently be parsing.
11390       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11391 
11392       // C++ [except.handle]p16:
11393       //   The object declared in an exception-declaration or, if the
11394       //   exception-declaration does not specify a name, a temporary (12.2) is
11395       //   copy-initialized (8.5) from the exception object. [...]
11396       //   The object is destroyed when the handler exits, after the destruction
11397       //   of any automatic objects initialized within the handler.
11398       //
11399       // We just pretend to initialize the object with itself, then make sure
11400       // it can be destroyed later.
11401       QualType initType = ExDeclType;
11402 
11403       InitializedEntity entity =
11404         InitializedEntity::InitializeVariable(ExDecl);
11405       InitializationKind initKind =
11406         InitializationKind::CreateCopy(Loc, SourceLocation());
11407 
11408       Expr *opaqueValue =
11409         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
11410       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11411       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
11412       if (result.isInvalid())
11413         Invalid = true;
11414       else {
11415         // If the constructor used was non-trivial, set this as the
11416         // "initializer".
11417         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
11418         if (!construct->getConstructor()->isTrivial()) {
11419           Expr *init = MaybeCreateExprWithCleanups(construct);
11420           ExDecl->setInit(init);
11421         }
11422 
11423         // And make sure it's destructable.
11424         FinalizeVarWithDestructor(ExDecl, recordType);
11425       }
11426     }
11427   }
11428 
11429   if (Invalid)
11430     ExDecl->setInvalidDecl();
11431 
11432   return ExDecl;
11433 }
11434 
11435 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11436 /// handler.
11437 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
11438   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11439   bool Invalid = D.isInvalidType();
11440 
11441   // Check for unexpanded parameter packs.
11442   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11443                                       UPPC_ExceptionType)) {
11444     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11445                                              D.getIdentifierLoc());
11446     Invalid = true;
11447   }
11448 
11449   IdentifierInfo *II = D.getIdentifier();
11450   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
11451                                              LookupOrdinaryName,
11452                                              ForRedeclaration)) {
11453     // The scope should be freshly made just for us. There is just no way
11454     // it contains any previous declaration, except for function parameters in
11455     // a function-try-block's catch statement.
11456     assert(!S->isDeclScope(PrevDecl));
11457     if (isDeclInScope(PrevDecl, CurContext, S)) {
11458       Diag(D.getIdentifierLoc(), diag::err_redefinition)
11459         << D.getIdentifier();
11460       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11461       Invalid = true;
11462     } else if (PrevDecl->isTemplateParameter())
11463       // Maybe we will complain about the shadowed template parameter.
11464       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11465   }
11466 
11467   if (D.getCXXScopeSpec().isSet() && !Invalid) {
11468     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11469       << D.getCXXScopeSpec().getRange();
11470     Invalid = true;
11471   }
11472 
11473   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
11474                                               D.getLocStart(),
11475                                               D.getIdentifierLoc(),
11476                                               D.getIdentifier());
11477   if (Invalid)
11478     ExDecl->setInvalidDecl();
11479 
11480   // Add the exception declaration into this scope.
11481   if (II)
11482     PushOnScopeChains(ExDecl, S);
11483   else
11484     CurContext->addDecl(ExDecl);
11485 
11486   ProcessDeclAttributes(S, ExDecl, D);
11487   return ExDecl;
11488 }
11489 
11490 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11491                                          Expr *AssertExpr,
11492                                          Expr *AssertMessageExpr,
11493                                          SourceLocation RParenLoc) {
11494   StringLiteral *AssertMessage =
11495       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
11496 
11497   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
11498     return nullptr;
11499 
11500   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11501                                       AssertMessage, RParenLoc, false);
11502 }
11503 
11504 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11505                                          Expr *AssertExpr,
11506                                          StringLiteral *AssertMessage,
11507                                          SourceLocation RParenLoc,
11508                                          bool Failed) {
11509   assert(AssertExpr != nullptr && "Expected non-null condition");
11510   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11511       !Failed) {
11512     // In a static_assert-declaration, the constant-expression shall be a
11513     // constant expression that can be contextually converted to bool.
11514     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11515     if (Converted.isInvalid())
11516       Failed = true;
11517 
11518     llvm::APSInt Cond;
11519     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
11520           diag::err_static_assert_expression_is_not_constant,
11521           /*AllowFold=*/false).isInvalid())
11522       Failed = true;
11523 
11524     if (!Failed && !Cond) {
11525       SmallString<256> MsgBuffer;
11526       llvm::raw_svector_ostream Msg(MsgBuffer);
11527       if (AssertMessage)
11528         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
11529       Diag(StaticAssertLoc, diag::err_static_assert_failed)
11530         << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
11531       Failed = true;
11532     }
11533   }
11534 
11535   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
11536                                         AssertExpr, AssertMessage, RParenLoc,
11537                                         Failed);
11538 
11539   CurContext->addDecl(Decl);
11540   return Decl;
11541 }
11542 
11543 /// \brief Perform semantic analysis of the given friend type declaration.
11544 ///
11545 /// \returns A friend declaration that.
11546 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
11547                                       SourceLocation FriendLoc,
11548                                       TypeSourceInfo *TSInfo) {
11549   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11550 
11551   QualType T = TSInfo->getType();
11552   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
11553 
11554   // C++03 [class.friend]p2:
11555   //   An elaborated-type-specifier shall be used in a friend declaration
11556   //   for a class.*
11557   //
11558   //   * The class-key of the elaborated-type-specifier is required.
11559   if (!ActiveTemplateInstantiations.empty()) {
11560     // Do not complain about the form of friend template types during
11561     // template instantiation; we will already have complained when the
11562     // template was declared.
11563   } else {
11564     if (!T->isElaboratedTypeSpecifier()) {
11565       // If we evaluated the type to a record type, suggest putting
11566       // a tag in front.
11567       if (const RecordType *RT = T->getAs<RecordType>()) {
11568         RecordDecl *RD = RT->getDecl();
11569 
11570         SmallString<16> InsertionText(" ");
11571         InsertionText += RD->getKindName();
11572 
11573         Diag(TypeRange.getBegin(),
11574              getLangOpts().CPlusPlus11 ?
11575                diag::warn_cxx98_compat_unelaborated_friend_type :
11576                diag::ext_unelaborated_friend_type)
11577           << (unsigned) RD->getTagKind()
11578           << T
11579           << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11580                                         InsertionText);
11581       } else {
11582         Diag(FriendLoc,
11583              getLangOpts().CPlusPlus11 ?
11584                diag::warn_cxx98_compat_nonclass_type_friend :
11585                diag::ext_nonclass_type_friend)
11586           << T
11587           << TypeRange;
11588       }
11589     } else if (T->getAs<EnumType>()) {
11590       Diag(FriendLoc,
11591            getLangOpts().CPlusPlus11 ?
11592              diag::warn_cxx98_compat_enum_friend :
11593              diag::ext_enum_friend)
11594         << T
11595         << TypeRange;
11596     }
11597 
11598     // C++11 [class.friend]p3:
11599     //   A friend declaration that does not declare a function shall have one
11600     //   of the following forms:
11601     //     friend elaborated-type-specifier ;
11602     //     friend simple-type-specifier ;
11603     //     friend typename-specifier ;
11604     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11605       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11606   }
11607 
11608   //   If the type specifier in a friend declaration designates a (possibly
11609   //   cv-qualified) class type, that class is declared as a friend; otherwise,
11610   //   the friend declaration is ignored.
11611   return FriendDecl::Create(Context, CurContext,
11612                             TSInfo->getTypeLoc().getLocStart(), TSInfo,
11613                             FriendLoc);
11614 }
11615 
11616 /// Handle a friend tag declaration where the scope specifier was
11617 /// templated.
11618 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11619                                     unsigned TagSpec, SourceLocation TagLoc,
11620                                     CXXScopeSpec &SS,
11621                                     IdentifierInfo *Name,
11622                                     SourceLocation NameLoc,
11623                                     AttributeList *Attr,
11624                                     MultiTemplateParamsArg TempParamLists) {
11625   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11626 
11627   bool isExplicitSpecialization = false;
11628   bool Invalid = false;
11629 
11630   if (TemplateParameterList *TemplateParams =
11631           MatchTemplateParametersToScopeSpecifier(
11632               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
11633               isExplicitSpecialization, Invalid)) {
11634     if (TemplateParams->size() > 0) {
11635       // This is a declaration of a class template.
11636       if (Invalid)
11637         return nullptr;
11638 
11639       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
11640                                 NameLoc, Attr, TemplateParams, AS_public,
11641                                 /*ModulePrivateLoc=*/SourceLocation(),
11642                                 FriendLoc, TempParamLists.size() - 1,
11643                                 TempParamLists.data()).get();
11644     } else {
11645       // The "template<>" header is extraneous.
11646       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11647         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11648       isExplicitSpecialization = true;
11649     }
11650   }
11651 
11652   if (Invalid) return nullptr;
11653 
11654   bool isAllExplicitSpecializations = true;
11655   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
11656     if (TempParamLists[I]->size()) {
11657       isAllExplicitSpecializations = false;
11658       break;
11659     }
11660   }
11661 
11662   // FIXME: don't ignore attributes.
11663 
11664   // If it's explicit specializations all the way down, just forget
11665   // about the template header and build an appropriate non-templated
11666   // friend.  TODO: for source fidelity, remember the headers.
11667   if (isAllExplicitSpecializations) {
11668     if (SS.isEmpty()) {
11669       bool Owned = false;
11670       bool IsDependent = false;
11671       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
11672                       Attr, AS_public,
11673                       /*ModulePrivateLoc=*/SourceLocation(),
11674                       MultiTemplateParamsArg(), Owned, IsDependent,
11675                       /*ScopedEnumKWLoc=*/SourceLocation(),
11676                       /*ScopedEnumUsesClassTag=*/false,
11677                       /*UnderlyingType=*/TypeResult(),
11678                       /*IsTypeSpecifier=*/false);
11679     }
11680 
11681     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11682     ElaboratedTypeKeyword Keyword
11683       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11684     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
11685                                    *Name, NameLoc);
11686     if (T.isNull())
11687       return nullptr;
11688 
11689     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11690     if (isa<DependentNameType>(T)) {
11691       DependentNameTypeLoc TL =
11692           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
11693       TL.setElaboratedKeywordLoc(TagLoc);
11694       TL.setQualifierLoc(QualifierLoc);
11695       TL.setNameLoc(NameLoc);
11696     } else {
11697       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
11698       TL.setElaboratedKeywordLoc(TagLoc);
11699       TL.setQualifierLoc(QualifierLoc);
11700       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
11701     }
11702 
11703     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
11704                                             TSI, FriendLoc, TempParamLists);
11705     Friend->setAccess(AS_public);
11706     CurContext->addDecl(Friend);
11707     return Friend;
11708   }
11709 
11710   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11711 
11712 
11713 
11714   // Handle the case of a templated-scope friend class.  e.g.
11715   //   template <class T> class A<T>::B;
11716   // FIXME: we don't support these right now.
11717   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
11718     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
11719   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11720   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11721   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11722   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
11723   TL.setElaboratedKeywordLoc(TagLoc);
11724   TL.setQualifierLoc(SS.getWithLocInContext(Context));
11725   TL.setNameLoc(NameLoc);
11726 
11727   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
11728                                           TSI, FriendLoc, TempParamLists);
11729   Friend->setAccess(AS_public);
11730   Friend->setUnsupportedFriend(true);
11731   CurContext->addDecl(Friend);
11732   return Friend;
11733 }
11734 
11735 
11736 /// Handle a friend type declaration.  This works in tandem with
11737 /// ActOnTag.
11738 ///
11739 /// Notes on friend class templates:
11740 ///
11741 /// We generally treat friend class declarations as if they were
11742 /// declaring a class.  So, for example, the elaborated type specifier
11743 /// in a friend declaration is required to obey the restrictions of a
11744 /// class-head (i.e. no typedefs in the scope chain), template
11745 /// parameters are required to match up with simple template-ids, &c.
11746 /// However, unlike when declaring a template specialization, it's
11747 /// okay to refer to a template specialization without an empty
11748 /// template parameter declaration, e.g.
11749 ///   friend class A<T>::B<unsigned>;
11750 /// We permit this as a special case; if there are any template
11751 /// parameters present at all, require proper matching, i.e.
11752 ///   template <> template \<class T> friend class A<int>::B;
11753 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
11754                                 MultiTemplateParamsArg TempParams) {
11755   SourceLocation Loc = DS.getLocStart();
11756 
11757   assert(DS.isFriendSpecified());
11758   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11759 
11760   // Try to convert the decl specifier to a type.  This works for
11761   // friend templates because ActOnTag never produces a ClassTemplateDecl
11762   // for a TUK_Friend.
11763   Declarator TheDeclarator(DS, Declarator::MemberContext);
11764   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11765   QualType T = TSI->getType();
11766   if (TheDeclarator.isInvalidType())
11767     return nullptr;
11768 
11769   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11770     return nullptr;
11771 
11772   // This is definitely an error in C++98.  It's probably meant to
11773   // be forbidden in C++0x, too, but the specification is just
11774   // poorly written.
11775   //
11776   // The problem is with declarations like the following:
11777   //   template <T> friend A<T>::foo;
11778   // where deciding whether a class C is a friend or not now hinges
11779   // on whether there exists an instantiation of A that causes
11780   // 'foo' to equal C.  There are restrictions on class-heads
11781   // (which we declare (by fiat) elaborated friend declarations to
11782   // be) that makes this tractable.
11783   //
11784   // FIXME: handle "template <> friend class A<T>;", which
11785   // is possibly well-formed?  Who even knows?
11786   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
11787     Diag(Loc, diag::err_tagless_friend_type_template)
11788       << DS.getSourceRange();
11789     return nullptr;
11790   }
11791 
11792   // C++98 [class.friend]p1: A friend of a class is a function
11793   //   or class that is not a member of the class . . .
11794   // This is fixed in DR77, which just barely didn't make the C++03
11795   // deadline.  It's also a very silly restriction that seriously
11796   // affects inner classes and which nobody else seems to implement;
11797   // thus we never diagnose it, not even in -pedantic.
11798   //
11799   // But note that we could warn about it: it's always useless to
11800   // friend one of your own members (it's not, however, worthless to
11801   // friend a member of an arbitrary specialization of your template).
11802 
11803   Decl *D;
11804   if (unsigned NumTempParamLists = TempParams.size())
11805     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
11806                                    NumTempParamLists,
11807                                    TempParams.data(),
11808                                    TSI,
11809                                    DS.getFriendSpecLoc());
11810   else
11811     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
11812 
11813   if (!D)
11814     return nullptr;
11815 
11816   D->setAccess(AS_public);
11817   CurContext->addDecl(D);
11818 
11819   return D;
11820 }
11821 
11822 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11823                                         MultiTemplateParamsArg TemplateParams) {
11824   const DeclSpec &DS = D.getDeclSpec();
11825 
11826   assert(DS.isFriendSpecified());
11827   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11828 
11829   SourceLocation Loc = D.getIdentifierLoc();
11830   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11831 
11832   // C++ [class.friend]p1
11833   //   A friend of a class is a function or class....
11834   // Note that this sees through typedefs, which is intended.
11835   // It *doesn't* see through dependent types, which is correct
11836   // according to [temp.arg.type]p3:
11837   //   If a declaration acquires a function type through a
11838   //   type dependent on a template-parameter and this causes
11839   //   a declaration that does not use the syntactic form of a
11840   //   function declarator to have a function type, the program
11841   //   is ill-formed.
11842   if (!TInfo->getType()->isFunctionType()) {
11843     Diag(Loc, diag::err_unexpected_friend);
11844 
11845     // It might be worthwhile to try to recover by creating an
11846     // appropriate declaration.
11847     return nullptr;
11848   }
11849 
11850   // C++ [namespace.memdef]p3
11851   //  - If a friend declaration in a non-local class first declares a
11852   //    class or function, the friend class or function is a member
11853   //    of the innermost enclosing namespace.
11854   //  - The name of the friend is not found by simple name lookup
11855   //    until a matching declaration is provided in that namespace
11856   //    scope (either before or after the class declaration granting
11857   //    friendship).
11858   //  - If a friend function is called, its name may be found by the
11859   //    name lookup that considers functions from namespaces and
11860   //    classes associated with the types of the function arguments.
11861   //  - When looking for a prior declaration of a class or a function
11862   //    declared as a friend, scopes outside the innermost enclosing
11863   //    namespace scope are not considered.
11864 
11865   CXXScopeSpec &SS = D.getCXXScopeSpec();
11866   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11867   DeclarationName Name = NameInfo.getName();
11868   assert(Name);
11869 
11870   // Check for unexpanded parameter packs.
11871   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11872       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11873       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11874     return nullptr;
11875 
11876   // The context we found the declaration in, or in which we should
11877   // create the declaration.
11878   DeclContext *DC;
11879   Scope *DCScope = S;
11880   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
11881                         ForRedeclaration);
11882 
11883   // There are five cases here.
11884   //   - There's no scope specifier and we're in a local class. Only look
11885   //     for functions declared in the immediately-enclosing block scope.
11886   // We recover from invalid scope qualifiers as if they just weren't there.
11887   FunctionDecl *FunctionContainingLocalClass = nullptr;
11888   if ((SS.isInvalid() || !SS.isSet()) &&
11889       (FunctionContainingLocalClass =
11890            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11891     // C++11 [class.friend]p11:
11892     //   If a friend declaration appears in a local class and the name
11893     //   specified is an unqualified name, a prior declaration is
11894     //   looked up without considering scopes that are outside the
11895     //   innermost enclosing non-class scope. For a friend function
11896     //   declaration, if there is no prior declaration, the program is
11897     //   ill-formed.
11898 
11899     // Find the innermost enclosing non-class scope. This is the block
11900     // scope containing the local class definition (or for a nested class,
11901     // the outer local class).
11902     DCScope = S->getFnParent();
11903 
11904     // Look up the function name in the scope.
11905     Previous.clear(LookupLocalFriendName);
11906     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11907 
11908     if (!Previous.empty()) {
11909       // All possible previous declarations must have the same context:
11910       // either they were declared at block scope or they are members of
11911       // one of the enclosing local classes.
11912       DC = Previous.getRepresentativeDecl()->getDeclContext();
11913     } else {
11914       // This is ill-formed, but provide the context that we would have
11915       // declared the function in, if we were permitted to, for error recovery.
11916       DC = FunctionContainingLocalClass;
11917     }
11918     adjustContextForLocalExternDecl(DC);
11919 
11920     // C++ [class.friend]p6:
11921     //   A function can be defined in a friend declaration of a class if and
11922     //   only if the class is a non-local class (9.8), the function name is
11923     //   unqualified, and the function has namespace scope.
11924     if (D.isFunctionDefinition()) {
11925       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11926     }
11927 
11928   //   - There's no scope specifier, in which case we just go to the
11929   //     appropriate scope and look for a function or function template
11930   //     there as appropriate.
11931   } else if (SS.isInvalid() || !SS.isSet()) {
11932     // C++11 [namespace.memdef]p3:
11933     //   If the name in a friend declaration is neither qualified nor
11934     //   a template-id and the declaration is a function or an
11935     //   elaborated-type-specifier, the lookup to determine whether
11936     //   the entity has been previously declared shall not consider
11937     //   any scopes outside the innermost enclosing namespace.
11938     bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
11939 
11940     // Find the appropriate context according to the above.
11941     DC = CurContext;
11942 
11943     // Skip class contexts.  If someone can cite chapter and verse
11944     // for this behavior, that would be nice --- it's what GCC and
11945     // EDG do, and it seems like a reasonable intent, but the spec
11946     // really only says that checks for unqualified existing
11947     // declarations should stop at the nearest enclosing namespace,
11948     // not that they should only consider the nearest enclosing
11949     // namespace.
11950     while (DC->isRecord())
11951       DC = DC->getParent();
11952 
11953     DeclContext *LookupDC = DC;
11954     while (LookupDC->isTransparentContext())
11955       LookupDC = LookupDC->getParent();
11956 
11957     while (true) {
11958       LookupQualifiedName(Previous, LookupDC);
11959 
11960       if (!Previous.empty()) {
11961         DC = LookupDC;
11962         break;
11963       }
11964 
11965       if (isTemplateId) {
11966         if (isa<TranslationUnitDecl>(LookupDC)) break;
11967       } else {
11968         if (LookupDC->isFileContext()) break;
11969       }
11970       LookupDC = LookupDC->getParent();
11971     }
11972 
11973     DCScope = getScopeForDeclContext(S, DC);
11974 
11975   //   - There's a non-dependent scope specifier, in which case we
11976   //     compute it and do a previous lookup there for a function
11977   //     or function template.
11978   } else if (!SS.getScopeRep()->isDependent()) {
11979     DC = computeDeclContext(SS);
11980     if (!DC) return nullptr;
11981 
11982     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
11983 
11984     LookupQualifiedName(Previous, DC);
11985 
11986     // Ignore things found implicitly in the wrong scope.
11987     // TODO: better diagnostics for this case.  Suggesting the right
11988     // qualified scope would be nice...
11989     LookupResult::Filter F = Previous.makeFilter();
11990     while (F.hasNext()) {
11991       NamedDecl *D = F.next();
11992       if (!DC->InEnclosingNamespaceSetOf(
11993               D->getDeclContext()->getRedeclContext()))
11994         F.erase();
11995     }
11996     F.done();
11997 
11998     if (Previous.empty()) {
11999       D.setInvalidType();
12000       Diag(Loc, diag::err_qualified_friend_not_found)
12001           << Name << TInfo->getType();
12002       return nullptr;
12003     }
12004 
12005     // C++ [class.friend]p1: A friend of a class is a function or
12006     //   class that is not a member of the class . . .
12007     if (DC->Equals(CurContext))
12008       Diag(DS.getFriendSpecLoc(),
12009            getLangOpts().CPlusPlus11 ?
12010              diag::warn_cxx98_compat_friend_is_member :
12011              diag::err_friend_is_member);
12012 
12013     if (D.isFunctionDefinition()) {
12014       // C++ [class.friend]p6:
12015       //   A function can be defined in a friend declaration of a class if and
12016       //   only if the class is a non-local class (9.8), the function name is
12017       //   unqualified, and the function has namespace scope.
12018       SemaDiagnosticBuilder DB
12019         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
12020 
12021       DB << SS.getScopeRep();
12022       if (DC->isFileContext())
12023         DB << FixItHint::CreateRemoval(SS.getRange());
12024       SS.clear();
12025     }
12026 
12027   //   - There's a scope specifier that does not match any template
12028   //     parameter lists, in which case we use some arbitrary context,
12029   //     create a method or method template, and wait for instantiation.
12030   //   - There's a scope specifier that does match some template
12031   //     parameter lists, which we don't handle right now.
12032   } else {
12033     if (D.isFunctionDefinition()) {
12034       // C++ [class.friend]p6:
12035       //   A function can be defined in a friend declaration of a class if and
12036       //   only if the class is a non-local class (9.8), the function name is
12037       //   unqualified, and the function has namespace scope.
12038       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
12039         << SS.getScopeRep();
12040     }
12041 
12042     DC = CurContext;
12043     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
12044   }
12045 
12046   if (!DC->isRecord()) {
12047     // This implies that it has to be an operator or function.
12048     if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
12049         D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
12050         D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
12051       Diag(Loc, diag::err_introducing_special_friend) <<
12052         (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
12053          D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
12054       return nullptr;
12055     }
12056   }
12057 
12058   // FIXME: This is an egregious hack to cope with cases where the scope stack
12059   // does not contain the declaration context, i.e., in an out-of-line
12060   // definition of a class.
12061   Scope FakeDCScope(S, Scope::DeclScope, Diags);
12062   if (!DCScope) {
12063     FakeDCScope.setEntity(DC);
12064     DCScope = &FakeDCScope;
12065   }
12066 
12067   bool AddToScope = true;
12068   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
12069                                           TemplateParams, AddToScope);
12070   if (!ND) return nullptr;
12071 
12072   assert(ND->getLexicalDeclContext() == CurContext);
12073 
12074   // If we performed typo correction, we might have added a scope specifier
12075   // and changed the decl context.
12076   DC = ND->getDeclContext();
12077 
12078   // Add the function declaration to the appropriate lookup tables,
12079   // adjusting the redeclarations list as necessary.  We don't
12080   // want to do this yet if the friending class is dependent.
12081   //
12082   // Also update the scope-based lookup if the target context's
12083   // lookup context is in lexical scope.
12084   if (!CurContext->isDependentContext()) {
12085     DC = DC->getRedeclContext();
12086     DC->makeDeclVisibleInContext(ND);
12087     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
12088       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
12089   }
12090 
12091   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
12092                                        D.getIdentifierLoc(), ND,
12093                                        DS.getFriendSpecLoc());
12094   FrD->setAccess(AS_public);
12095   CurContext->addDecl(FrD);
12096 
12097   if (ND->isInvalidDecl()) {
12098     FrD->setInvalidDecl();
12099   } else {
12100     if (DC->isRecord()) CheckFriendAccess(ND);
12101 
12102     FunctionDecl *FD;
12103     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12104       FD = FTD->getTemplatedDecl();
12105     else
12106       FD = cast<FunctionDecl>(ND);
12107 
12108     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12109     // default argument expression, that declaration shall be a definition
12110     // and shall be the only declaration of the function or function
12111     // template in the translation unit.
12112     if (functionDeclHasDefaultArgument(FD)) {
12113       if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12114         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12115         Diag(OldFD->getLocation(), diag::note_previous_declaration);
12116       } else if (!D.isFunctionDefinition())
12117         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12118     }
12119 
12120     // Mark templated-scope function declarations as unsupported.
12121     if (FD->getNumTemplateParameterLists())
12122       FrD->setUnsupportedFriend(true);
12123   }
12124 
12125   return ND;
12126 }
12127 
12128 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12129   AdjustDeclIfTemplate(Dcl);
12130 
12131   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
12132   if (!Fn) {
12133     Diag(DelLoc, diag::err_deleted_non_function);
12134     return;
12135   }
12136 
12137   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
12138     // Don't consider the implicit declaration we generate for explicit
12139     // specializations. FIXME: Do not generate these implicit declarations.
12140     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12141          Prev->getPreviousDecl()) &&
12142         !Prev->isDefined()) {
12143       Diag(DelLoc, diag::err_deleted_decl_not_first);
12144       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12145            Prev->isImplicit() ? diag::note_previous_implicit_declaration
12146                               : diag::note_previous_declaration);
12147     }
12148     // If the declaration wasn't the first, we delete the function anyway for
12149     // recovery.
12150     Fn = Fn->getCanonicalDecl();
12151   }
12152 
12153   // dllimport/dllexport cannot be deleted.
12154   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12155     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12156     Fn->setInvalidDecl();
12157   }
12158 
12159   if (Fn->isDeleted())
12160     return;
12161 
12162   // See if we're deleting a function which is already known to override a
12163   // non-deleted virtual function.
12164   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
12165     bool IssuedDiagnostic = false;
12166     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
12167                                         E = MD->end_overridden_methods();
12168          I != E; ++I) {
12169       if (!(*MD->begin_overridden_methods())->isDeleted()) {
12170         if (!IssuedDiagnostic) {
12171           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
12172           IssuedDiagnostic = true;
12173         }
12174         Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
12175       }
12176     }
12177   }
12178 
12179   // C++11 [basic.start.main]p3:
12180   //   A program that defines main as deleted [...] is ill-formed.
12181   if (Fn->isMain())
12182     Diag(DelLoc, diag::err_deleted_main);
12183 
12184   Fn->setDeletedAsWritten();
12185 }
12186 
12187 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
12188   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
12189 
12190   if (MD) {
12191     if (MD->getParent()->isDependentType()) {
12192       MD->setDefaulted();
12193       MD->setExplicitlyDefaulted();
12194       return;
12195     }
12196 
12197     CXXSpecialMember Member = getSpecialMember(MD);
12198     if (Member == CXXInvalid) {
12199       if (!MD->isInvalidDecl())
12200         Diag(DefaultLoc, diag::err_default_special_members);
12201       return;
12202     }
12203 
12204     MD->setDefaulted();
12205     MD->setExplicitlyDefaulted();
12206 
12207     // If this definition appears within the record, do the checking when
12208     // the record is complete.
12209     const FunctionDecl *Primary = MD;
12210     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
12211       // Find the uninstantiated declaration that actually had the '= default'
12212       // on it.
12213       Pattern->isDefined(Primary);
12214 
12215     // If the method was defaulted on its first declaration, we will have
12216     // already performed the checking in CheckCompletedCXXClass. Such a
12217     // declaration doesn't trigger an implicit definition.
12218     if (Primary == Primary->getCanonicalDecl())
12219       return;
12220 
12221     CheckExplicitlyDefaultedSpecialMember(MD);
12222 
12223     // The exception specification is needed because we are defining the
12224     // function.
12225     ResolveExceptionSpec(DefaultLoc,
12226                          MD->getType()->castAs<FunctionProtoType>());
12227 
12228     if (MD->isInvalidDecl())
12229       return;
12230 
12231     switch (Member) {
12232     case CXXDefaultConstructor:
12233       DefineImplicitDefaultConstructor(DefaultLoc,
12234                                        cast<CXXConstructorDecl>(MD));
12235       break;
12236     case CXXCopyConstructor:
12237       DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
12238       break;
12239     case CXXCopyAssignment:
12240       DefineImplicitCopyAssignment(DefaultLoc, MD);
12241       break;
12242     case CXXDestructor:
12243       DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
12244       break;
12245     case CXXMoveConstructor:
12246       DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
12247       break;
12248     case CXXMoveAssignment:
12249       DefineImplicitMoveAssignment(DefaultLoc, MD);
12250       break;
12251     case CXXInvalid:
12252       llvm_unreachable("Invalid special member.");
12253     }
12254   } else {
12255     Diag(DefaultLoc, diag::err_default_special_members);
12256   }
12257 }
12258 
12259 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
12260   for (Stmt::child_range CI = S->children(); CI; ++CI) {
12261     Stmt *SubStmt = *CI;
12262     if (!SubStmt)
12263       continue;
12264     if (isa<ReturnStmt>(SubStmt))
12265       Self.Diag(SubStmt->getLocStart(),
12266            diag::err_return_in_constructor_handler);
12267     if (!isa<Expr>(SubStmt))
12268       SearchForReturnInStmt(Self, SubStmt);
12269   }
12270 }
12271 
12272 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12273   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12274     CXXCatchStmt *Handler = TryBlock->getHandler(I);
12275     SearchForReturnInStmt(*this, Handler);
12276   }
12277 }
12278 
12279 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
12280                                              const CXXMethodDecl *Old) {
12281   const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12282   const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12283 
12284   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12285 
12286   // If the calling conventions match, everything is fine
12287   if (NewCC == OldCC)
12288     return false;
12289 
12290   // If the calling conventions mismatch because the new function is static,
12291   // suppress the calling convention mismatch error; the error about static
12292   // function override (err_static_overrides_virtual from
12293   // Sema::CheckFunctionDeclaration) is more clear.
12294   if (New->getStorageClass() == SC_Static)
12295     return false;
12296 
12297   Diag(New->getLocation(),
12298        diag::err_conflicting_overriding_cc_attributes)
12299     << New->getDeclName() << New->getType() << Old->getType();
12300   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12301   return true;
12302 }
12303 
12304 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
12305                                              const CXXMethodDecl *Old) {
12306   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12307   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
12308 
12309   if (Context.hasSameType(NewTy, OldTy) ||
12310       NewTy->isDependentType() || OldTy->isDependentType())
12311     return false;
12312 
12313   // Check if the return types are covariant
12314   QualType NewClassTy, OldClassTy;
12315 
12316   /// Both types must be pointers or references to classes.
12317   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12318     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
12319       NewClassTy = NewPT->getPointeeType();
12320       OldClassTy = OldPT->getPointeeType();
12321     }
12322   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12323     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12324       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12325         NewClassTy = NewRT->getPointeeType();
12326         OldClassTy = OldRT->getPointeeType();
12327       }
12328     }
12329   }
12330 
12331   // The return types aren't either both pointers or references to a class type.
12332   if (NewClassTy.isNull()) {
12333     Diag(New->getLocation(),
12334          diag::err_different_return_type_for_overriding_virtual_function)
12335         << New->getDeclName() << NewTy << OldTy
12336         << New->getReturnTypeSourceRange();
12337     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12338         << Old->getReturnTypeSourceRange();
12339 
12340     return true;
12341   }
12342 
12343   // C++ [class.virtual]p6:
12344   //   If the return type of D::f differs from the return type of B::f, the
12345   //   class type in the return type of D::f shall be complete at the point of
12346   //   declaration of D::f or shall be the class type D.
12347   if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12348     if (!RT->isBeingDefined() &&
12349         RequireCompleteType(New->getLocation(), NewClassTy,
12350                             diag::err_covariant_return_incomplete,
12351                             New->getDeclName()))
12352     return true;
12353   }
12354 
12355   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
12356     // Check if the new class derives from the old class.
12357     if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12358       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
12359           << New->getDeclName() << NewTy << OldTy
12360           << New->getReturnTypeSourceRange();
12361       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12362           << Old->getReturnTypeSourceRange();
12363       return true;
12364     }
12365 
12366     // Check if we the conversion from derived to base is valid.
12367     if (CheckDerivedToBaseConversion(
12368             NewClassTy, OldClassTy,
12369             diag::err_covariant_return_inaccessible_base,
12370             diag::err_covariant_return_ambiguous_derived_to_base_conv,
12371             New->getLocation(), New->getReturnTypeSourceRange(),
12372             New->getDeclName(), nullptr)) {
12373       // FIXME: this note won't trigger for delayed access control
12374       // diagnostics, and it's impossible to get an undelayed error
12375       // here from access control during the original parse because
12376       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
12377       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12378           << Old->getReturnTypeSourceRange();
12379       return true;
12380     }
12381   }
12382 
12383   // The qualifiers of the return types must be the same.
12384   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
12385     Diag(New->getLocation(),
12386          diag::err_covariant_return_type_different_qualifications)
12387         << New->getDeclName() << NewTy << OldTy
12388         << New->getReturnTypeSourceRange();
12389     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12390         << Old->getReturnTypeSourceRange();
12391     return true;
12392   };
12393 
12394 
12395   // The new class type must have the same or less qualifiers as the old type.
12396   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12397     Diag(New->getLocation(),
12398          diag::err_covariant_return_type_class_type_more_qualified)
12399         << New->getDeclName() << NewTy << OldTy
12400         << New->getReturnTypeSourceRange();
12401     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12402         << Old->getReturnTypeSourceRange();
12403     return true;
12404   };
12405 
12406   return false;
12407 }
12408 
12409 /// \brief Mark the given method pure.
12410 ///
12411 /// \param Method the method to be marked pure.
12412 ///
12413 /// \param InitRange the source range that covers the "0" initializer.
12414 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
12415   SourceLocation EndLoc = InitRange.getEnd();
12416   if (EndLoc.isValid())
12417     Method->setRangeEnd(EndLoc);
12418 
12419   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12420     Method->setPure();
12421     return false;
12422   }
12423 
12424   if (!Method->isInvalidDecl())
12425     Diag(Method->getLocation(), diag::err_non_virtual_pure)
12426       << Method->getDeclName() << InitRange;
12427   return true;
12428 }
12429 
12430 /// \brief Determine whether the given declaration is a static data member.
12431 static bool isStaticDataMember(const Decl *D) {
12432   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12433     return Var->isStaticDataMember();
12434 
12435   return false;
12436 }
12437 
12438 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12439 /// an initializer for the out-of-line declaration 'Dcl'.  The scope
12440 /// is a fresh scope pushed for just this purpose.
12441 ///
12442 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12443 /// static data member of class X, names should be looked up in the scope of
12444 /// class X.
12445 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
12446   // If there is no declaration, there was an error parsing it.
12447   if (!D || D->isInvalidDecl())
12448     return;
12449 
12450   // We will always have a nested name specifier here, but this declaration
12451   // might not be out of line if the specifier names the current namespace:
12452   //   extern int n;
12453   //   int ::n = 0;
12454   if (D->isOutOfLine())
12455     EnterDeclaratorContext(S, D->getDeclContext());
12456 
12457   // If we are parsing the initializer for a static data member, push a
12458   // new expression evaluation context that is associated with this static
12459   // data member.
12460   if (isStaticDataMember(D))
12461     PushExpressionEvaluationContext(PotentiallyEvaluated, D);
12462 }
12463 
12464 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
12465 /// initializer for the out-of-line declaration 'D'.
12466 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
12467   // If there is no declaration, there was an error parsing it.
12468   if (!D || D->isInvalidDecl())
12469     return;
12470 
12471   if (isStaticDataMember(D))
12472     PopExpressionEvaluationContext();
12473 
12474   if (D->isOutOfLine())
12475     ExitDeclaratorContext(S);
12476 }
12477 
12478 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12479 /// C++ if/switch/while/for statement.
12480 /// e.g: "if (int x = f()) {...}"
12481 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
12482   // C++ 6.4p2:
12483   // The declarator shall not specify a function or an array.
12484   // The type-specifier-seq shall not contain typedef and shall not declare a
12485   // new class or enumeration.
12486   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12487          "Parser allowed 'typedef' as storage class of condition decl.");
12488 
12489   Decl *Dcl = ActOnDeclarator(S, D);
12490   if (!Dcl)
12491     return true;
12492 
12493   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12494     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
12495       << D.getSourceRange();
12496     return true;
12497   }
12498 
12499   return Dcl;
12500 }
12501 
12502 void Sema::LoadExternalVTableUses() {
12503   if (!ExternalSource)
12504     return;
12505 
12506   SmallVector<ExternalVTableUse, 4> VTables;
12507   ExternalSource->ReadUsedVTables(VTables);
12508   SmallVector<VTableUse, 4> NewUses;
12509   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12510     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12511       = VTablesUsed.find(VTables[I].Record);
12512     // Even if a definition wasn't required before, it may be required now.
12513     if (Pos != VTablesUsed.end()) {
12514       if (!Pos->second && VTables[I].DefinitionRequired)
12515         Pos->second = true;
12516       continue;
12517     }
12518 
12519     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12520     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12521   }
12522 
12523   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12524 }
12525 
12526 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12527                           bool DefinitionRequired) {
12528   // Ignore any vtable uses in unevaluated operands or for classes that do
12529   // not have a vtable.
12530   if (!Class->isDynamicClass() || Class->isDependentContext() ||
12531       CurContext->isDependentContext() || isUnevaluatedContext())
12532     return;
12533 
12534   // Try to insert this class into the map.
12535   LoadExternalVTableUses();
12536   Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12537   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12538     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12539   if (!Pos.second) {
12540     // If we already had an entry, check to see if we are promoting this vtable
12541     // to required a definition. If so, we need to reappend to the VTableUses
12542     // list, since we may have already processed the first entry.
12543     if (DefinitionRequired && !Pos.first->second) {
12544       Pos.first->second = true;
12545     } else {
12546       // Otherwise, we can early exit.
12547       return;
12548     }
12549   } else {
12550     // The Microsoft ABI requires that we perform the destructor body
12551     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
12552     // the deleting destructor is emitted with the vtable, not with the
12553     // destructor definition as in the Itanium ABI.
12554     // If it has a definition, we do the check at that point instead.
12555     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12556         Class->hasUserDeclaredDestructor() &&
12557         !Class->getDestructor()->isDefined() &&
12558         !Class->getDestructor()->isDeleted()) {
12559       CXXDestructorDecl *DD = Class->getDestructor();
12560       ContextRAII SavedContext(*this, DD);
12561       CheckDestructor(DD);
12562     }
12563   }
12564 
12565   // Local classes need to have their virtual members marked
12566   // immediately. For all other classes, we mark their virtual members
12567   // at the end of the translation unit.
12568   if (Class->isLocalClass())
12569     MarkVirtualMembersReferenced(Loc, Class);
12570   else
12571     VTableUses.push_back(std::make_pair(Class, Loc));
12572 }
12573 
12574 bool Sema::DefineUsedVTables() {
12575   LoadExternalVTableUses();
12576   if (VTableUses.empty())
12577     return false;
12578 
12579   // Note: The VTableUses vector could grow as a result of marking
12580   // the members of a class as "used", so we check the size each
12581   // time through the loop and prefer indices (which are stable) to
12582   // iterators (which are not).
12583   bool DefinedAnything = false;
12584   for (unsigned I = 0; I != VTableUses.size(); ++I) {
12585     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
12586     if (!Class)
12587       continue;
12588 
12589     SourceLocation Loc = VTableUses[I].second;
12590 
12591     bool DefineVTable = true;
12592 
12593     // If this class has a key function, but that key function is
12594     // defined in another translation unit, we don't need to emit the
12595     // vtable even though we're using it.
12596     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
12597     if (KeyFunction && !KeyFunction->hasBody()) {
12598       // The key function is in another translation unit.
12599       DefineVTable = false;
12600       TemplateSpecializationKind TSK =
12601           KeyFunction->getTemplateSpecializationKind();
12602       assert(TSK != TSK_ExplicitInstantiationDefinition &&
12603              TSK != TSK_ImplicitInstantiation &&
12604              "Instantiations don't have key functions");
12605       (void)TSK;
12606     } else if (!KeyFunction) {
12607       // If we have a class with no key function that is the subject
12608       // of an explicit instantiation declaration, suppress the
12609       // vtable; it will live with the explicit instantiation
12610       // definition.
12611       bool IsExplicitInstantiationDeclaration
12612         = Class->getTemplateSpecializationKind()
12613                                       == TSK_ExplicitInstantiationDeclaration;
12614       for (auto R : Class->redecls()) {
12615         TemplateSpecializationKind TSK
12616           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
12617         if (TSK == TSK_ExplicitInstantiationDeclaration)
12618           IsExplicitInstantiationDeclaration = true;
12619         else if (TSK == TSK_ExplicitInstantiationDefinition) {
12620           IsExplicitInstantiationDeclaration = false;
12621           break;
12622         }
12623       }
12624 
12625       if (IsExplicitInstantiationDeclaration)
12626         DefineVTable = false;
12627     }
12628 
12629     // The exception specifications for all virtual members may be needed even
12630     // if we are not providing an authoritative form of the vtable in this TU.
12631     // We may choose to emit it available_externally anyway.
12632     if (!DefineVTable) {
12633       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12634       continue;
12635     }
12636 
12637     // Mark all of the virtual members of this class as referenced, so
12638     // that we can build a vtable. Then, tell the AST consumer that a
12639     // vtable for this class is required.
12640     DefinedAnything = true;
12641     MarkVirtualMembersReferenced(Loc, Class);
12642     CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12643     Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12644 
12645     // Optionally warn if we're emitting a weak vtable.
12646     if (Class->isExternallyVisible() &&
12647         Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
12648       const FunctionDecl *KeyFunctionDef = nullptr;
12649       if (!KeyFunction ||
12650           (KeyFunction->hasBody(KeyFunctionDef) &&
12651            KeyFunctionDef->isInlined()))
12652         Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12653              TSK_ExplicitInstantiationDefinition
12654              ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12655           << Class;
12656     }
12657   }
12658   VTableUses.clear();
12659 
12660   return DefinedAnything;
12661 }
12662 
12663 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12664                                                  const CXXRecordDecl *RD) {
12665   for (const auto *I : RD->methods())
12666     if (I->isVirtual() && !I->isPure())
12667       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
12668 }
12669 
12670 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12671                                         const CXXRecordDecl *RD) {
12672   // Mark all functions which will appear in RD's vtable as used.
12673   CXXFinalOverriderMap FinalOverriders;
12674   RD->getFinalOverriders(FinalOverriders);
12675   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12676                                             E = FinalOverriders.end();
12677        I != E; ++I) {
12678     for (OverridingMethods::const_iterator OI = I->second.begin(),
12679                                            OE = I->second.end();
12680          OI != OE; ++OI) {
12681       assert(OI->second.size() > 0 && "no final overrider");
12682       CXXMethodDecl *Overrider = OI->second.front().Method;
12683 
12684       // C++ [basic.def.odr]p2:
12685       //   [...] A virtual member function is used if it is not pure. [...]
12686       if (!Overrider->isPure())
12687         MarkFunctionReferenced(Loc, Overrider);
12688     }
12689   }
12690 
12691   // Only classes that have virtual bases need a VTT.
12692   if (RD->getNumVBases() == 0)
12693     return;
12694 
12695   for (const auto &I : RD->bases()) {
12696     const CXXRecordDecl *Base =
12697         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
12698     if (Base->getNumVBases() == 0)
12699       continue;
12700     MarkVirtualMembersReferenced(Loc, Base);
12701   }
12702 }
12703 
12704 /// SetIvarInitializers - This routine builds initialization ASTs for the
12705 /// Objective-C implementation whose ivars need be initialized.
12706 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
12707   if (!getLangOpts().CPlusPlus)
12708     return;
12709   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
12710     SmallVector<ObjCIvarDecl*, 8> ivars;
12711     CollectIvarsToConstructOrDestruct(OID, ivars);
12712     if (ivars.empty())
12713       return;
12714     SmallVector<CXXCtorInitializer*, 32> AllToInit;
12715     for (unsigned i = 0; i < ivars.size(); i++) {
12716       FieldDecl *Field = ivars[i];
12717       if (Field->isInvalidDecl())
12718         continue;
12719 
12720       CXXCtorInitializer *Member;
12721       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12722       InitializationKind InitKind =
12723         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
12724 
12725       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12726       ExprResult MemberInit =
12727         InitSeq.Perform(*this, InitEntity, InitKind, None);
12728       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
12729       // Note, MemberInit could actually come back empty if no initialization
12730       // is required (e.g., because it would call a trivial default constructor)
12731       if (!MemberInit.get() || MemberInit.isInvalid())
12732         continue;
12733 
12734       Member =
12735         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12736                                          SourceLocation(),
12737                                          MemberInit.getAs<Expr>(),
12738                                          SourceLocation());
12739       AllToInit.push_back(Member);
12740 
12741       // Be sure that the destructor is accessible and is marked as referenced.
12742       if (const RecordType *RecordTy
12743                   = Context.getBaseElementType(Field->getType())
12744                                                         ->getAs<RecordType>()) {
12745                     CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
12746         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
12747           MarkFunctionReferenced(Field->getLocation(), Destructor);
12748           CheckDestructorAccess(Field->getLocation(), Destructor,
12749                             PDiag(diag::err_access_dtor_ivar)
12750                               << Context.getBaseElementType(Field->getType()));
12751         }
12752       }
12753     }
12754     ObjCImplementation->setIvarInitializers(Context,
12755                                             AllToInit.data(), AllToInit.size());
12756   }
12757 }
12758 
12759 static
12760 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12761                            llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12762                            llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12763                            llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12764                            Sema &S) {
12765   if (Ctor->isInvalidDecl())
12766     return;
12767 
12768   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12769 
12770   // Target may not be determinable yet, for instance if this is a dependent
12771   // call in an uninstantiated template.
12772   if (Target) {
12773     const FunctionDecl *FNTarget = nullptr;
12774     (void)Target->hasBody(FNTarget);
12775     Target = const_cast<CXXConstructorDecl*>(
12776       cast_or_null<CXXConstructorDecl>(FNTarget));
12777   }
12778 
12779   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12780                      // Avoid dereferencing a null pointer here.
12781                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
12782 
12783   if (!Current.insert(Canonical))
12784     return;
12785 
12786   // We know that beyond here, we aren't chaining into a cycle.
12787   if (!Target || !Target->isDelegatingConstructor() ||
12788       Target->isInvalidDecl() || Valid.count(TCanonical)) {
12789     Valid.insert(Current.begin(), Current.end());
12790     Current.clear();
12791   // We've hit a cycle.
12792   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12793              Current.count(TCanonical)) {
12794     // If we haven't diagnosed this cycle yet, do so now.
12795     if (!Invalid.count(TCanonical)) {
12796       S.Diag((*Ctor->init_begin())->getSourceLocation(),
12797              diag::warn_delegating_ctor_cycle)
12798         << Ctor;
12799 
12800       // Don't add a note for a function delegating directly to itself.
12801       if (TCanonical != Canonical)
12802         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12803 
12804       CXXConstructorDecl *C = Target;
12805       while (C->getCanonicalDecl() != Canonical) {
12806         const FunctionDecl *FNTarget = nullptr;
12807         (void)C->getTargetConstructor()->hasBody(FNTarget);
12808         assert(FNTarget && "Ctor cycle through bodiless function");
12809 
12810         C = const_cast<CXXConstructorDecl*>(
12811           cast<CXXConstructorDecl>(FNTarget));
12812         S.Diag(C->getLocation(), diag::note_which_delegates_to);
12813       }
12814     }
12815 
12816     Invalid.insert(Current.begin(), Current.end());
12817     Current.clear();
12818   } else {
12819     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12820   }
12821 }
12822 
12823 
12824 void Sema::CheckDelegatingCtorCycles() {
12825   llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12826 
12827   for (DelegatingCtorDeclsType::iterator
12828          I = DelegatingCtorDecls.begin(ExternalSource),
12829          E = DelegatingCtorDecls.end();
12830        I != E; ++I)
12831     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
12832 
12833   for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12834                                                          CE = Invalid.end();
12835        CI != CE; ++CI)
12836     (*CI)->setInvalidDecl();
12837 }
12838 
12839 namespace {
12840   /// \brief AST visitor that finds references to the 'this' expression.
12841   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12842     Sema &S;
12843 
12844   public:
12845     explicit FindCXXThisExpr(Sema &S) : S(S) { }
12846 
12847     bool VisitCXXThisExpr(CXXThisExpr *E) {
12848       S.Diag(E->getLocation(), diag::err_this_static_member_func)
12849         << E->isImplicit();
12850       return false;
12851     }
12852   };
12853 }
12854 
12855 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12856   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12857   if (!TSInfo)
12858     return false;
12859 
12860   TypeLoc TL = TSInfo->getTypeLoc();
12861   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
12862   if (!ProtoTL)
12863     return false;
12864 
12865   // C++11 [expr.prim.general]p3:
12866   //   [The expression this] shall not appear before the optional
12867   //   cv-qualifier-seq and it shall not appear within the declaration of a
12868   //   static member function (although its type and value category are defined
12869   //   within a static member function as they are within a non-static member
12870   //   function). [ Note: this is because declaration matching does not occur
12871   //  until the complete declarator is known. - end note ]
12872   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
12873   FindCXXThisExpr Finder(*this);
12874 
12875   // If the return type came after the cv-qualifier-seq, check it now.
12876   if (Proto->hasTrailingReturn() &&
12877       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
12878     return true;
12879 
12880   // Check the exception specification.
12881   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12882     return true;
12883 
12884   return checkThisInStaticMemberFunctionAttributes(Method);
12885 }
12886 
12887 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12888   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12889   if (!TSInfo)
12890     return false;
12891 
12892   TypeLoc TL = TSInfo->getTypeLoc();
12893   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
12894   if (!ProtoTL)
12895     return false;
12896 
12897   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
12898   FindCXXThisExpr Finder(*this);
12899 
12900   switch (Proto->getExceptionSpecType()) {
12901   case EST_Uninstantiated:
12902   case EST_Unevaluated:
12903   case EST_BasicNoexcept:
12904   case EST_DynamicNone:
12905   case EST_MSAny:
12906   case EST_None:
12907     break;
12908 
12909   case EST_ComputedNoexcept:
12910     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12911       return true;
12912 
12913   case EST_Dynamic:
12914     for (const auto &E : Proto->exceptions()) {
12915       if (!Finder.TraverseType(E))
12916         return true;
12917     }
12918     break;
12919   }
12920 
12921   return false;
12922 }
12923 
12924 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12925   FindCXXThisExpr Finder(*this);
12926 
12927   // Check attributes.
12928   for (const auto *A : Method->attrs()) {
12929     // FIXME: This should be emitted by tblgen.
12930     Expr *Arg = nullptr;
12931     ArrayRef<Expr *> Args;
12932     if (const auto *G = dyn_cast<GuardedByAttr>(A))
12933       Arg = G->getArg();
12934     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
12935       Arg = G->getArg();
12936     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
12937       Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12938     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
12939       Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12940     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
12941       Arg = ETLF->getSuccessValue();
12942       Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12943     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
12944       Arg = STLF->getSuccessValue();
12945       Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12946     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
12947       Arg = LR->getArg();
12948     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
12949       Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12950     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
12951       Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
12952     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
12953       Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
12954     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
12955       Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
12956     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
12957       Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
12958 
12959     if (Arg && !Finder.TraverseStmt(Arg))
12960       return true;
12961 
12962     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12963       if (!Finder.TraverseStmt(Args[I]))
12964         return true;
12965     }
12966   }
12967 
12968   return false;
12969 }
12970 
12971 void
12972 Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12973                                   ArrayRef<ParsedType> DynamicExceptions,
12974                                   ArrayRef<SourceRange> DynamicExceptionRanges,
12975                                   Expr *NoexceptExpr,
12976                                   SmallVectorImpl<QualType> &Exceptions,
12977                                   FunctionProtoType::ExtProtoInfo &EPI) {
12978   Exceptions.clear();
12979   EPI.ExceptionSpecType = EST;
12980   if (EST == EST_Dynamic) {
12981     Exceptions.reserve(DynamicExceptions.size());
12982     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12983       // FIXME: Preserve type source info.
12984       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12985 
12986       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12987       collectUnexpandedParameterPacks(ET, Unexpanded);
12988       if (!Unexpanded.empty()) {
12989         DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12990                                          UPPC_ExceptionType,
12991                                          Unexpanded);
12992         continue;
12993       }
12994 
12995       // Check that the type is valid for an exception spec, and
12996       // drop it if not.
12997       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12998         Exceptions.push_back(ET);
12999     }
13000     EPI.NumExceptions = Exceptions.size();
13001     EPI.Exceptions = Exceptions.data();
13002     return;
13003   }
13004 
13005   if (EST == EST_ComputedNoexcept) {
13006     // If an error occurred, there's no expression here.
13007     if (NoexceptExpr) {
13008       assert((NoexceptExpr->isTypeDependent() ||
13009               NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
13010               Context.BoolTy) &&
13011              "Parser should have made sure that the expression is boolean");
13012       if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
13013         EPI.ExceptionSpecType = EST_BasicNoexcept;
13014         return;
13015       }
13016 
13017       if (!NoexceptExpr->isValueDependent())
13018         NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
13019                          diag::err_noexcept_needs_constant_expression,
13020                          /*AllowFold*/ false).get();
13021       EPI.NoexceptExpr = NoexceptExpr;
13022     }
13023     return;
13024   }
13025 }
13026 
13027 /// IdentifyCUDATarget - Determine the CUDA compilation target for this function
13028 Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
13029   // Implicitly declared functions (e.g. copy constructors) are
13030   // __host__ __device__
13031   if (D->isImplicit())
13032     return CFT_HostDevice;
13033 
13034   if (D->hasAttr<CUDAGlobalAttr>())
13035     return CFT_Global;
13036 
13037   if (D->hasAttr<CUDADeviceAttr>()) {
13038     if (D->hasAttr<CUDAHostAttr>())
13039       return CFT_HostDevice;
13040     return CFT_Device;
13041   }
13042 
13043   return CFT_Host;
13044 }
13045 
13046 bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
13047                            CUDAFunctionTarget CalleeTarget) {
13048   // CUDA B.1.1 "The __device__ qualifier declares a function that is...
13049   // Callable from the device only."
13050   if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
13051     return true;
13052 
13053   // CUDA B.1.2 "The __global__ qualifier declares a function that is...
13054   // Callable from the host only."
13055   // CUDA B.1.3 "The __host__ qualifier declares a function that is...
13056   // Callable from the host only."
13057   if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
13058       (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
13059     return true;
13060 
13061   if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
13062     return true;
13063 
13064   return false;
13065 }
13066 
13067 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
13068 ///
13069 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
13070                                        SourceLocation DeclStart,
13071                                        Declarator &D, Expr *BitWidth,
13072                                        InClassInitStyle InitStyle,
13073                                        AccessSpecifier AS,
13074                                        AttributeList *MSPropertyAttr) {
13075   IdentifierInfo *II = D.getIdentifier();
13076   if (!II) {
13077     Diag(DeclStart, diag::err_anonymous_property);
13078     return nullptr;
13079   }
13080   SourceLocation Loc = D.getIdentifierLoc();
13081 
13082   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13083   QualType T = TInfo->getType();
13084   if (getLangOpts().CPlusPlus) {
13085     CheckExtraCXXDefaultArguments(D);
13086 
13087     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13088                                         UPPC_DataMemberType)) {
13089       D.setInvalidType();
13090       T = Context.IntTy;
13091       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13092     }
13093   }
13094 
13095   DiagnoseFunctionSpecifiers(D.getDeclSpec());
13096 
13097   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13098     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13099          diag::err_invalid_thread)
13100       << DeclSpec::getSpecifierName(TSCS);
13101 
13102   // Check to see if this name was declared as a member previously
13103   NamedDecl *PrevDecl = nullptr;
13104   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13105   LookupName(Previous, S);
13106   switch (Previous.getResultKind()) {
13107   case LookupResult::Found:
13108   case LookupResult::FoundUnresolvedValue:
13109     PrevDecl = Previous.getAsSingle<NamedDecl>();
13110     break;
13111 
13112   case LookupResult::FoundOverloaded:
13113     PrevDecl = Previous.getRepresentativeDecl();
13114     break;
13115 
13116   case LookupResult::NotFound:
13117   case LookupResult::NotFoundInCurrentInstantiation:
13118   case LookupResult::Ambiguous:
13119     break;
13120   }
13121 
13122   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13123     // Maybe we will complain about the shadowed template parameter.
13124     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13125     // Just pretend that we didn't see the previous declaration.
13126     PrevDecl = nullptr;
13127   }
13128 
13129   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13130     PrevDecl = nullptr;
13131 
13132   SourceLocation TSSL = D.getLocStart();
13133   const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
13134   MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13135       Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
13136   ProcessDeclAttributes(TUScope, NewPD, D);
13137   NewPD->setAccess(AS);
13138 
13139   if (NewPD->isInvalidDecl())
13140     Record->setInvalidDecl();
13141 
13142   if (D.getDeclSpec().isModulePrivateSpecified())
13143     NewPD->setModulePrivate();
13144 
13145   if (NewPD->isInvalidDecl() && PrevDecl) {
13146     // Don't introduce NewFD into scope; there's already something
13147     // with the same name in the same scope.
13148   } else if (II) {
13149     PushOnScopeChains(NewPD, S);
13150   } else
13151     Record->addDecl(NewPD);
13152 
13153   return NewPD;
13154 }
13155