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   if (!param)
349     return;
350 
351   ParmVarDecl *Param = cast<ParmVarDecl>(param);
352   Param->setInvalidDecl();
353   UnparsedDefaultArgLocs.erase(Param);
354 }
355 
356 /// CheckExtraCXXDefaultArguments - Check for any extra default
357 /// arguments in the declarator, which is not a function declaration
358 /// or definition and therefore is not permitted to have default
359 /// arguments. This routine should be invoked for every declarator
360 /// that is not a function declaration or definition.
361 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
362   // C++ [dcl.fct.default]p3
363   //   A default argument expression shall be specified only in the
364   //   parameter-declaration-clause of a function declaration or in a
365   //   template-parameter (14.1). It shall not be specified for a
366   //   parameter pack. If it is specified in a
367   //   parameter-declaration-clause, it shall not occur within a
368   //   declarator or abstract-declarator of a parameter-declaration.
369   bool MightBeFunction = D.isFunctionDeclarationContext();
370   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
371     DeclaratorChunk &chunk = D.getTypeObject(i);
372     if (chunk.Kind == DeclaratorChunk::Function) {
373       if (MightBeFunction) {
374         // This is a function declaration. It can have default arguments, but
375         // keep looking in case its return type is a function type with default
376         // arguments.
377         MightBeFunction = false;
378         continue;
379       }
380       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
381            ++argIdx) {
382         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
383         if (Param->hasUnparsedDefaultArg()) {
384           CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
385           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
386             << SourceRange((*Toks)[1].getLocation(),
387                            Toks->back().getLocation());
388           delete Toks;
389           chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
390         } else if (Param->getDefaultArg()) {
391           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
392             << Param->getDefaultArg()->getSourceRange();
393           Param->setDefaultArg(nullptr);
394         }
395       }
396     } else if (chunk.Kind != DeclaratorChunk::Paren) {
397       MightBeFunction = false;
398     }
399   }
400 }
401 
402 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
403   for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
404     const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
405     if (!PVD->hasDefaultArg())
406       return false;
407     if (!PVD->hasInheritedDefaultArg())
408       return true;
409   }
410   return false;
411 }
412 
413 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
414 /// function, once we already know that they have the same
415 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
416 /// error, false otherwise.
417 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
418                                 Scope *S) {
419   bool Invalid = false;
420 
421   // C++ [dcl.fct.default]p4:
422   //   For non-template functions, default arguments can be added in
423   //   later declarations of a function in the same
424   //   scope. Declarations in different scopes have completely
425   //   distinct sets of default arguments. That is, declarations in
426   //   inner scopes do not acquire default arguments from
427   //   declarations in outer scopes, and vice versa. In a given
428   //   function declaration, all parameters subsequent to a
429   //   parameter with a default argument shall have default
430   //   arguments supplied in this or previous declarations. A
431   //   default argument shall not be redefined by a later
432   //   declaration (not even to the same value).
433   //
434   // C++ [dcl.fct.default]p6:
435   //   Except for member functions of class templates, the default arguments
436   //   in a member function definition that appears outside of the class
437   //   definition are added to the set of default arguments provided by the
438   //   member function declaration in the class definition.
439   for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
440     ParmVarDecl *OldParam = Old->getParamDecl(p);
441     ParmVarDecl *NewParam = New->getParamDecl(p);
442 
443     bool OldParamHasDfl = OldParam->hasDefaultArg();
444     bool NewParamHasDfl = NewParam->hasDefaultArg();
445 
446     NamedDecl *ND = Old;
447 
448     // The declaration context corresponding to the scope is the semantic
449     // parent, unless this is a local function declaration, in which case
450     // it is that surrounding function.
451     DeclContext *ScopeDC = New->getLexicalDeclContext();
452     if (!ScopeDC->isFunctionOrMethod())
453       ScopeDC = New->getDeclContext();
454     if (S && !isDeclInScope(ND, ScopeDC, S) &&
455         !New->getDeclContext()->isRecord())
456       // Ignore default parameters of old decl if they are not in
457       // the same scope and this is not an out-of-line definition of
458       // a member function.
459       OldParamHasDfl = false;
460 
461     if (OldParamHasDfl && NewParamHasDfl) {
462 
463       unsigned DiagDefaultParamID =
464         diag::err_param_default_argument_redefinition;
465 
466       // MSVC accepts that default parameters be redefined for member functions
467       // of template class. The new default parameter's value is ignored.
468       Invalid = true;
469       if (getLangOpts().MicrosoftExt) {
470         CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
471         if (MD && MD->getParent()->getDescribedClassTemplate()) {
472           // Merge the old default argument into the new parameter.
473           NewParam->setHasInheritedDefaultArg();
474           if (OldParam->hasUninstantiatedDefaultArg())
475             NewParam->setUninstantiatedDefaultArg(
476                                       OldParam->getUninstantiatedDefaultArg());
477           else
478             NewParam->setDefaultArg(OldParam->getInit());
479           DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
480           Invalid = false;
481         }
482       }
483 
484       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
485       // hint here. Alternatively, we could walk the type-source information
486       // for NewParam to find the last source location in the type... but it
487       // isn't worth the effort right now. This is the kind of test case that
488       // is hard to get right:
489       //   int f(int);
490       //   void g(int (*fp)(int) = f);
491       //   void g(int (*fp)(int) = &f);
492       Diag(NewParam->getLocation(), DiagDefaultParamID)
493         << NewParam->getDefaultArgRange();
494 
495       // Look for the function declaration where the default argument was
496       // actually written, which may be a declaration prior to Old.
497       for (FunctionDecl *Older = Old->getPreviousDecl();
498            Older; Older = Older->getPreviousDecl()) {
499         if (!Older->getParamDecl(p)->hasDefaultArg())
500           break;
501 
502         OldParam = Older->getParamDecl(p);
503       }
504 
505       Diag(OldParam->getLocation(), diag::note_previous_definition)
506         << OldParam->getDefaultArgRange();
507     } else if (OldParamHasDfl) {
508       // Merge the old default argument into the new parameter.
509       // It's important to use getInit() here;  getDefaultArg()
510       // strips off any top-level ExprWithCleanups.
511       NewParam->setHasInheritedDefaultArg();
512       if (OldParam->hasUninstantiatedDefaultArg())
513         NewParam->setUninstantiatedDefaultArg(
514                                       OldParam->getUninstantiatedDefaultArg());
515       else
516         NewParam->setDefaultArg(OldParam->getInit());
517     } else if (NewParamHasDfl) {
518       if (New->getDescribedFunctionTemplate()) {
519         // Paragraph 4, quoted above, only applies to non-template functions.
520         Diag(NewParam->getLocation(),
521              diag::err_param_default_argument_template_redecl)
522           << NewParam->getDefaultArgRange();
523         Diag(Old->getLocation(), diag::note_template_prev_declaration)
524           << false;
525       } else if (New->getTemplateSpecializationKind()
526                    != TSK_ImplicitInstantiation &&
527                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
528         // C++ [temp.expr.spec]p21:
529         //   Default function arguments shall not be specified in a declaration
530         //   or a definition for one of the following explicit specializations:
531         //     - the explicit specialization of a function template;
532         //     - the explicit specialization of a member function template;
533         //     - the explicit specialization of a member function of a class
534         //       template where the class template specialization to which the
535         //       member function specialization belongs is implicitly
536         //       instantiated.
537         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
538           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
539           << New->getDeclName()
540           << NewParam->getDefaultArgRange();
541       } else if (New->getDeclContext()->isDependentContext()) {
542         // C++ [dcl.fct.default]p6 (DR217):
543         //   Default arguments for a member function of a class template shall
544         //   be specified on the initial declaration of the member function
545         //   within the class template.
546         //
547         // Reading the tea leaves a bit in DR217 and its reference to DR205
548         // leads me to the conclusion that one cannot add default function
549         // arguments for an out-of-line definition of a member function of a
550         // dependent type.
551         int WhichKind = 2;
552         if (CXXRecordDecl *Record
553               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
554           if (Record->getDescribedClassTemplate())
555             WhichKind = 0;
556           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
557             WhichKind = 1;
558           else
559             WhichKind = 2;
560         }
561 
562         Diag(NewParam->getLocation(),
563              diag::err_param_default_argument_member_template_redecl)
564           << WhichKind
565           << NewParam->getDefaultArgRange();
566       }
567     }
568   }
569 
570   // DR1344: If a default argument is added outside a class definition and that
571   // default argument makes the function a special member function, the program
572   // is ill-formed. This can only happen for constructors.
573   if (isa<CXXConstructorDecl>(New) &&
574       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
575     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
576                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
577     if (NewSM != OldSM) {
578       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
579       assert(NewParam->hasDefaultArg());
580       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
581         << NewParam->getDefaultArgRange() << NewSM;
582       Diag(Old->getLocation(), diag::note_previous_declaration);
583     }
584   }
585 
586   const FunctionDecl *Def;
587   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
588   // template has a constexpr specifier then all its declarations shall
589   // contain the constexpr specifier.
590   if (New->isConstexpr() != Old->isConstexpr()) {
591     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
592       << New << New->isConstexpr();
593     Diag(Old->getLocation(), diag::note_previous_declaration);
594     Invalid = true;
595   } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) {
596     // C++11 [dcl.fcn.spec]p4:
597     //   If the definition of a function appears in a translation unit before its
598     //   first declaration as inline, the program is ill-formed.
599     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
600     Diag(Def->getLocation(), diag::note_previous_definition);
601     Invalid = true;
602   }
603 
604   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
605   // argument expression, that declaration shall be a definition and shall be
606   // the only declaration of the function or function template in the
607   // translation unit.
608   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
609       functionDeclHasDefaultArgument(Old)) {
610     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
611     Diag(Old->getLocation(), diag::note_previous_declaration);
612     Invalid = true;
613   }
614 
615   if (CheckEquivalentExceptionSpec(Old, New))
616     Invalid = true;
617 
618   return Invalid;
619 }
620 
621 /// \brief Merge the exception specifications of two variable declarations.
622 ///
623 /// This is called when there's a redeclaration of a VarDecl. The function
624 /// checks if the redeclaration might have an exception specification and
625 /// validates compatibility and merges the specs if necessary.
626 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
627   // Shortcut if exceptions are disabled.
628   if (!getLangOpts().CXXExceptions)
629     return;
630 
631   assert(Context.hasSameType(New->getType(), Old->getType()) &&
632          "Should only be called if types are otherwise the same.");
633 
634   QualType NewType = New->getType();
635   QualType OldType = Old->getType();
636 
637   // We're only interested in pointers and references to functions, as well
638   // as pointers to member functions.
639   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
640     NewType = R->getPointeeType();
641     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
642   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
643     NewType = P->getPointeeType();
644     OldType = OldType->getAs<PointerType>()->getPointeeType();
645   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
646     NewType = M->getPointeeType();
647     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
648   }
649 
650   if (!NewType->isFunctionProtoType())
651     return;
652 
653   // There's lots of special cases for functions. For function pointers, system
654   // libraries are hopefully not as broken so that we don't need these
655   // workarounds.
656   if (CheckEquivalentExceptionSpec(
657         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
658         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
659     New->setInvalidDecl();
660   }
661 }
662 
663 /// CheckCXXDefaultArguments - Verify that the default arguments for a
664 /// function declaration are well-formed according to C++
665 /// [dcl.fct.default].
666 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
667   unsigned NumParams = FD->getNumParams();
668   unsigned p;
669 
670   // Find first parameter with a default argument
671   for (p = 0; p < NumParams; ++p) {
672     ParmVarDecl *Param = FD->getParamDecl(p);
673     if (Param->hasDefaultArg())
674       break;
675   }
676 
677   // C++ [dcl.fct.default]p4:
678   //   In a given function declaration, all parameters
679   //   subsequent to a parameter with a default argument shall
680   //   have default arguments supplied in this or previous
681   //   declarations. A default argument shall not be redefined
682   //   by a later declaration (not even to the same value).
683   unsigned LastMissingDefaultArg = 0;
684   for (; p < NumParams; ++p) {
685     ParmVarDecl *Param = FD->getParamDecl(p);
686     if (!Param->hasDefaultArg()) {
687       if (Param->isInvalidDecl())
688         /* We already complained about this parameter. */;
689       else if (Param->getIdentifier())
690         Diag(Param->getLocation(),
691              diag::err_param_default_argument_missing_name)
692           << Param->getIdentifier();
693       else
694         Diag(Param->getLocation(),
695              diag::err_param_default_argument_missing);
696 
697       LastMissingDefaultArg = p;
698     }
699   }
700 
701   if (LastMissingDefaultArg > 0) {
702     // Some default arguments were missing. Clear out all of the
703     // default arguments up to (and including) the last missing
704     // default argument, so that we leave the function parameters
705     // in a semantically valid state.
706     for (p = 0; p <= LastMissingDefaultArg; ++p) {
707       ParmVarDecl *Param = FD->getParamDecl(p);
708       if (Param->hasDefaultArg()) {
709         Param->setDefaultArg(nullptr);
710       }
711     }
712   }
713 }
714 
715 // CheckConstexprParameterTypes - Check whether a function's parameter types
716 // are all literal types. If so, return true. If not, produce a suitable
717 // diagnostic and return false.
718 static bool CheckConstexprParameterTypes(Sema &SemaRef,
719                                          const FunctionDecl *FD) {
720   unsigned ArgIndex = 0;
721   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
722   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
723                                               e = FT->param_type_end();
724        i != e; ++i, ++ArgIndex) {
725     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
726     SourceLocation ParamLoc = PD->getLocation();
727     if (!(*i)->isDependentType() &&
728         SemaRef.RequireLiteralType(ParamLoc, *i,
729                                    diag::err_constexpr_non_literal_param,
730                                    ArgIndex+1, PD->getSourceRange(),
731                                    isa<CXXConstructorDecl>(FD)))
732       return false;
733   }
734   return true;
735 }
736 
737 /// \brief Get diagnostic %select index for tag kind for
738 /// record diagnostic message.
739 /// WARNING: Indexes apply to particular diagnostics only!
740 ///
741 /// \returns diagnostic %select index.
742 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
743   switch (Tag) {
744   case TTK_Struct: return 0;
745   case TTK_Interface: return 1;
746   case TTK_Class:  return 2;
747   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
748   }
749 }
750 
751 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
752 // the requirements of a constexpr function definition or a constexpr
753 // constructor definition. If so, return true. If not, produce appropriate
754 // diagnostics and return false.
755 //
756 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
757 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
758   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
759   if (MD && MD->isInstance()) {
760     // C++11 [dcl.constexpr]p4:
761     //  The definition of a constexpr constructor shall satisfy the following
762     //  constraints:
763     //  - the class shall not have any virtual base classes;
764     const CXXRecordDecl *RD = MD->getParent();
765     if (RD->getNumVBases()) {
766       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
767         << isa<CXXConstructorDecl>(NewFD)
768         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
769       for (const auto &I : RD->vbases())
770         Diag(I.getLocStart(),
771              diag::note_constexpr_virtual_base_here) << I.getSourceRange();
772       return false;
773     }
774   }
775 
776   if (!isa<CXXConstructorDecl>(NewFD)) {
777     // C++11 [dcl.constexpr]p3:
778     //  The definition of a constexpr function shall satisfy the following
779     //  constraints:
780     // - it shall not be virtual;
781     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
782     if (Method && Method->isVirtual()) {
783       Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
784 
785       // If it's not obvious why this function is virtual, find an overridden
786       // function which uses the 'virtual' keyword.
787       const CXXMethodDecl *WrittenVirtual = Method;
788       while (!WrittenVirtual->isVirtualAsWritten())
789         WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
790       if (WrittenVirtual != Method)
791         Diag(WrittenVirtual->getLocation(),
792              diag::note_overridden_virtual_function);
793       return false;
794     }
795 
796     // - its return type shall be a literal type;
797     QualType RT = NewFD->getReturnType();
798     if (!RT->isDependentType() &&
799         RequireLiteralType(NewFD->getLocation(), RT,
800                            diag::err_constexpr_non_literal_return))
801       return false;
802   }
803 
804   // - each of its parameter types shall be a literal type;
805   if (!CheckConstexprParameterTypes(*this, NewFD))
806     return false;
807 
808   return true;
809 }
810 
811 /// Check the given declaration statement is legal within a constexpr function
812 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
813 ///
814 /// \return true if the body is OK (maybe only as an extension), false if we
815 ///         have diagnosed a problem.
816 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
817                                    DeclStmt *DS, SourceLocation &Cxx1yLoc) {
818   // C++11 [dcl.constexpr]p3 and p4:
819   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
820   //  contain only
821   for (const auto *DclIt : DS->decls()) {
822     switch (DclIt->getKind()) {
823     case Decl::StaticAssert:
824     case Decl::Using:
825     case Decl::UsingShadow:
826     case Decl::UsingDirective:
827     case Decl::UnresolvedUsingTypename:
828     case Decl::UnresolvedUsingValue:
829       //   - static_assert-declarations
830       //   - using-declarations,
831       //   - using-directives,
832       continue;
833 
834     case Decl::Typedef:
835     case Decl::TypeAlias: {
836       //   - typedef declarations and alias-declarations that do not define
837       //     classes or enumerations,
838       const auto *TN = cast<TypedefNameDecl>(DclIt);
839       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
840         // Don't allow variably-modified types in constexpr functions.
841         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
842         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
843           << TL.getSourceRange() << TL.getType()
844           << isa<CXXConstructorDecl>(Dcl);
845         return false;
846       }
847       continue;
848     }
849 
850     case Decl::Enum:
851     case Decl::CXXRecord:
852       // C++1y allows types to be defined, not just declared.
853       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
854         SemaRef.Diag(DS->getLocStart(),
855                      SemaRef.getLangOpts().CPlusPlus1y
856                        ? diag::warn_cxx11_compat_constexpr_type_definition
857                        : diag::ext_constexpr_type_definition)
858           << isa<CXXConstructorDecl>(Dcl);
859       continue;
860 
861     case Decl::EnumConstant:
862     case Decl::IndirectField:
863     case Decl::ParmVar:
864       // These can only appear with other declarations which are banned in
865       // C++11 and permitted in C++1y, so ignore them.
866       continue;
867 
868     case Decl::Var: {
869       // C++1y [dcl.constexpr]p3 allows anything except:
870       //   a definition of a variable of non-literal type or of static or
871       //   thread storage duration or for which no initialization is performed.
872       const auto *VD = cast<VarDecl>(DclIt);
873       if (VD->isThisDeclarationADefinition()) {
874         if (VD->isStaticLocal()) {
875           SemaRef.Diag(VD->getLocation(),
876                        diag::err_constexpr_local_var_static)
877             << isa<CXXConstructorDecl>(Dcl)
878             << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
879           return false;
880         }
881         if (!VD->getType()->isDependentType() &&
882             SemaRef.RequireLiteralType(
883               VD->getLocation(), VD->getType(),
884               diag::err_constexpr_local_var_non_literal_type,
885               isa<CXXConstructorDecl>(Dcl)))
886           return false;
887         if (!VD->getType()->isDependentType() &&
888             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
889           SemaRef.Diag(VD->getLocation(),
890                        diag::err_constexpr_local_var_no_init)
891             << isa<CXXConstructorDecl>(Dcl);
892           return false;
893         }
894       }
895       SemaRef.Diag(VD->getLocation(),
896                    SemaRef.getLangOpts().CPlusPlus1y
897                     ? diag::warn_cxx11_compat_constexpr_local_var
898                     : diag::ext_constexpr_local_var)
899         << isa<CXXConstructorDecl>(Dcl);
900       continue;
901     }
902 
903     case Decl::NamespaceAlias:
904     case Decl::Function:
905       // These are disallowed in C++11 and permitted in C++1y. Allow them
906       // everywhere as an extension.
907       if (!Cxx1yLoc.isValid())
908         Cxx1yLoc = DS->getLocStart();
909       continue;
910 
911     default:
912       SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
913         << isa<CXXConstructorDecl>(Dcl);
914       return false;
915     }
916   }
917 
918   return true;
919 }
920 
921 /// Check that the given field is initialized within a constexpr constructor.
922 ///
923 /// \param Dcl The constexpr constructor being checked.
924 /// \param Field The field being checked. This may be a member of an anonymous
925 ///        struct or union nested within the class being checked.
926 /// \param Inits All declarations, including anonymous struct/union members and
927 ///        indirect members, for which any initialization was provided.
928 /// \param Diagnosed Set to true if an error is produced.
929 static void CheckConstexprCtorInitializer(Sema &SemaRef,
930                                           const FunctionDecl *Dcl,
931                                           FieldDecl *Field,
932                                           llvm::SmallSet<Decl*, 16> &Inits,
933                                           bool &Diagnosed) {
934   if (Field->isInvalidDecl())
935     return;
936 
937   if (Field->isUnnamedBitfield())
938     return;
939 
940   // Anonymous unions with no variant members and empty anonymous structs do not
941   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
942   // indirect fields don't need initializing.
943   if (Field->isAnonymousStructOrUnion() &&
944       (Field->getType()->isUnionType()
945            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
946            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
947     return;
948 
949   if (!Inits.count(Field)) {
950     if (!Diagnosed) {
951       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
952       Diagnosed = true;
953     }
954     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
955   } else if (Field->isAnonymousStructOrUnion()) {
956     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
957     for (auto *I : RD->fields())
958       // If an anonymous union contains an anonymous struct of which any member
959       // is initialized, all members must be initialized.
960       if (!RD->isUnion() || Inits.count(I))
961         CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
962   }
963 }
964 
965 /// Check the provided statement is allowed in a constexpr function
966 /// definition.
967 static bool
968 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
969                            SmallVectorImpl<SourceLocation> &ReturnStmts,
970                            SourceLocation &Cxx1yLoc) {
971   // - its function-body shall be [...] a compound-statement that contains only
972   switch (S->getStmtClass()) {
973   case Stmt::NullStmtClass:
974     //   - null statements,
975     return true;
976 
977   case Stmt::DeclStmtClass:
978     //   - static_assert-declarations
979     //   - using-declarations,
980     //   - using-directives,
981     //   - typedef declarations and alias-declarations that do not define
982     //     classes or enumerations,
983     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
984       return false;
985     return true;
986 
987   case Stmt::ReturnStmtClass:
988     //   - and exactly one return statement;
989     if (isa<CXXConstructorDecl>(Dcl)) {
990       // C++1y allows return statements in constexpr constructors.
991       if (!Cxx1yLoc.isValid())
992         Cxx1yLoc = S->getLocStart();
993       return true;
994     }
995 
996     ReturnStmts.push_back(S->getLocStart());
997     return true;
998 
999   case Stmt::CompoundStmtClass: {
1000     // C++1y allows compound-statements.
1001     if (!Cxx1yLoc.isValid())
1002       Cxx1yLoc = S->getLocStart();
1003 
1004     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1005     for (auto *BodyIt : CompStmt->body()) {
1006       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1007                                       Cxx1yLoc))
1008         return false;
1009     }
1010     return true;
1011   }
1012 
1013   case Stmt::AttributedStmtClass:
1014     if (!Cxx1yLoc.isValid())
1015       Cxx1yLoc = S->getLocStart();
1016     return true;
1017 
1018   case Stmt::IfStmtClass: {
1019     // C++1y allows if-statements.
1020     if (!Cxx1yLoc.isValid())
1021       Cxx1yLoc = S->getLocStart();
1022 
1023     IfStmt *If = cast<IfStmt>(S);
1024     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1025                                     Cxx1yLoc))
1026       return false;
1027     if (If->getElse() &&
1028         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1029                                     Cxx1yLoc))
1030       return false;
1031     return true;
1032   }
1033 
1034   case Stmt::WhileStmtClass:
1035   case Stmt::DoStmtClass:
1036   case Stmt::ForStmtClass:
1037   case Stmt::CXXForRangeStmtClass:
1038   case Stmt::ContinueStmtClass:
1039     // C++1y allows all of these. We don't allow them as extensions in C++11,
1040     // because they don't make sense without variable mutation.
1041     if (!SemaRef.getLangOpts().CPlusPlus1y)
1042       break;
1043     if (!Cxx1yLoc.isValid())
1044       Cxx1yLoc = S->getLocStart();
1045     for (Stmt::child_range Children = S->children(); Children; ++Children)
1046       if (*Children &&
1047           !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1048                                       Cxx1yLoc))
1049         return false;
1050     return true;
1051 
1052   case Stmt::SwitchStmtClass:
1053   case Stmt::CaseStmtClass:
1054   case Stmt::DefaultStmtClass:
1055   case Stmt::BreakStmtClass:
1056     // C++1y allows switch-statements, and since they don't need variable
1057     // mutation, we can reasonably allow them in C++11 as an extension.
1058     if (!Cxx1yLoc.isValid())
1059       Cxx1yLoc = S->getLocStart();
1060     for (Stmt::child_range Children = S->children(); Children; ++Children)
1061       if (*Children &&
1062           !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1063                                       Cxx1yLoc))
1064         return false;
1065     return true;
1066 
1067   default:
1068     if (!isa<Expr>(S))
1069       break;
1070 
1071     // C++1y allows expression-statements.
1072     if (!Cxx1yLoc.isValid())
1073       Cxx1yLoc = S->getLocStart();
1074     return true;
1075   }
1076 
1077   SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1078     << isa<CXXConstructorDecl>(Dcl);
1079   return false;
1080 }
1081 
1082 /// Check the body for the given constexpr function declaration only contains
1083 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1084 ///
1085 /// \return true if the body is OK, false if we have diagnosed a problem.
1086 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1087   if (isa<CXXTryStmt>(Body)) {
1088     // C++11 [dcl.constexpr]p3:
1089     //  The definition of a constexpr function shall satisfy the following
1090     //  constraints: [...]
1091     // - its function-body shall be = delete, = default, or a
1092     //   compound-statement
1093     //
1094     // C++11 [dcl.constexpr]p4:
1095     //  In the definition of a constexpr constructor, [...]
1096     // - its function-body shall not be a function-try-block;
1097     Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1098       << isa<CXXConstructorDecl>(Dcl);
1099     return false;
1100   }
1101 
1102   SmallVector<SourceLocation, 4> ReturnStmts;
1103 
1104   // - its function-body shall be [...] a compound-statement that contains only
1105   //   [... list of cases ...]
1106   CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1107   SourceLocation Cxx1yLoc;
1108   for (auto *BodyIt : CompBody->body()) {
1109     if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
1110       return false;
1111   }
1112 
1113   if (Cxx1yLoc.isValid())
1114     Diag(Cxx1yLoc,
1115          getLangOpts().CPlusPlus1y
1116            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1117            : diag::ext_constexpr_body_invalid_stmt)
1118       << isa<CXXConstructorDecl>(Dcl);
1119 
1120   if (const CXXConstructorDecl *Constructor
1121         = dyn_cast<CXXConstructorDecl>(Dcl)) {
1122     const CXXRecordDecl *RD = Constructor->getParent();
1123     // DR1359:
1124     // - every non-variant non-static data member and base class sub-object
1125     //   shall be initialized;
1126     // DR1460:
1127     // - if the class is a union having variant members, exactly one of them
1128     //   shall be initialized;
1129     if (RD->isUnion()) {
1130       if (Constructor->getNumCtorInitializers() == 0 &&
1131           RD->hasVariantMembers()) {
1132         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1133         return false;
1134       }
1135     } else if (!Constructor->isDependentContext() &&
1136                !Constructor->isDelegatingConstructor()) {
1137       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1138 
1139       // Skip detailed checking if we have enough initializers, and we would
1140       // allow at most one initializer per member.
1141       bool AnyAnonStructUnionMembers = false;
1142       unsigned Fields = 0;
1143       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1144            E = RD->field_end(); I != E; ++I, ++Fields) {
1145         if (I->isAnonymousStructOrUnion()) {
1146           AnyAnonStructUnionMembers = true;
1147           break;
1148         }
1149       }
1150       // DR1460:
1151       // - if the class is a union-like class, but is not a union, for each of
1152       //   its anonymous union members having variant members, exactly one of
1153       //   them shall be initialized;
1154       if (AnyAnonStructUnionMembers ||
1155           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1156         // Check initialization of non-static data members. Base classes are
1157         // always initialized so do not need to be checked. Dependent bases
1158         // might not have initializers in the member initializer list.
1159         llvm::SmallSet<Decl*, 16> Inits;
1160         for (const auto *I: Constructor->inits()) {
1161           if (FieldDecl *FD = I->getMember())
1162             Inits.insert(FD);
1163           else if (IndirectFieldDecl *ID = I->getIndirectMember())
1164             Inits.insert(ID->chain_begin(), ID->chain_end());
1165         }
1166 
1167         bool Diagnosed = false;
1168         for (auto *I : RD->fields())
1169           CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
1170         if (Diagnosed)
1171           return false;
1172       }
1173     }
1174   } else {
1175     if (ReturnStmts.empty()) {
1176       // C++1y doesn't require constexpr functions to contain a 'return'
1177       // statement. We still do, unless the return type might be void, because
1178       // otherwise if there's no return statement, the function cannot
1179       // be used in a core constant expression.
1180       bool OK = getLangOpts().CPlusPlus1y &&
1181                 (Dcl->getReturnType()->isVoidType() ||
1182                  Dcl->getReturnType()->isDependentType());
1183       Diag(Dcl->getLocation(),
1184            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1185               : diag::err_constexpr_body_no_return);
1186       return OK;
1187     }
1188     if (ReturnStmts.size() > 1) {
1189       Diag(ReturnStmts.back(),
1190            getLangOpts().CPlusPlus1y
1191              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1192              : diag::ext_constexpr_body_multiple_return);
1193       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1194         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
1195     }
1196   }
1197 
1198   // C++11 [dcl.constexpr]p5:
1199   //   if no function argument values exist such that the function invocation
1200   //   substitution would produce a constant expression, the program is
1201   //   ill-formed; no diagnostic required.
1202   // C++11 [dcl.constexpr]p3:
1203   //   - every constructor call and implicit conversion used in initializing the
1204   //     return value shall be one of those allowed in a constant expression.
1205   // C++11 [dcl.constexpr]p4:
1206   //   - every constructor involved in initializing non-static data members and
1207   //     base class sub-objects shall be a constexpr constructor.
1208   SmallVector<PartialDiagnosticAt, 8> Diags;
1209   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
1210     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
1211       << isa<CXXConstructorDecl>(Dcl);
1212     for (size_t I = 0, N = Diags.size(); I != N; ++I)
1213       Diag(Diags[I].first, Diags[I].second);
1214     // Don't return false here: we allow this for compatibility in
1215     // system headers.
1216   }
1217 
1218   return true;
1219 }
1220 
1221 /// isCurrentClassName - Determine whether the identifier II is the
1222 /// name of the class type currently being defined. In the case of
1223 /// nested classes, this will only return true if II is the name of
1224 /// the innermost class.
1225 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1226                               const CXXScopeSpec *SS) {
1227   assert(getLangOpts().CPlusPlus && "No class names in C!");
1228 
1229   CXXRecordDecl *CurDecl;
1230   if (SS && SS->isSet() && !SS->isInvalid()) {
1231     DeclContext *DC = computeDeclContext(*SS, true);
1232     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1233   } else
1234     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1235 
1236   if (CurDecl && CurDecl->getIdentifier())
1237     return &II == CurDecl->getIdentifier();
1238   return false;
1239 }
1240 
1241 /// \brief Determine whether the identifier II is a typo for the name of
1242 /// the class type currently being defined. If so, update it to the identifier
1243 /// that should have been used.
1244 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1245   assert(getLangOpts().CPlusPlus && "No class names in C!");
1246 
1247   if (!getLangOpts().SpellChecking)
1248     return false;
1249 
1250   CXXRecordDecl *CurDecl;
1251   if (SS && SS->isSet() && !SS->isInvalid()) {
1252     DeclContext *DC = computeDeclContext(*SS, true);
1253     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1254   } else
1255     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1256 
1257   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1258       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1259           < II->getLength()) {
1260     II = CurDecl->getIdentifier();
1261     return true;
1262   }
1263 
1264   return false;
1265 }
1266 
1267 /// \brief Determine whether the given class is a base class of the given
1268 /// class, including looking at dependent bases.
1269 static bool findCircularInheritance(const CXXRecordDecl *Class,
1270                                     const CXXRecordDecl *Current) {
1271   SmallVector<const CXXRecordDecl*, 8> Queue;
1272 
1273   Class = Class->getCanonicalDecl();
1274   while (true) {
1275     for (const auto &I : Current->bases()) {
1276       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
1277       if (!Base)
1278         continue;
1279 
1280       Base = Base->getDefinition();
1281       if (!Base)
1282         continue;
1283 
1284       if (Base->getCanonicalDecl() == Class)
1285         return true;
1286 
1287       Queue.push_back(Base);
1288     }
1289 
1290     if (Queue.empty())
1291       return false;
1292 
1293     Current = Queue.pop_back_val();
1294   }
1295 
1296   return false;
1297 }
1298 
1299 /// \brief Check the validity of a C++ base class specifier.
1300 ///
1301 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1302 /// and returns NULL otherwise.
1303 CXXBaseSpecifier *
1304 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1305                          SourceRange SpecifierRange,
1306                          bool Virtual, AccessSpecifier Access,
1307                          TypeSourceInfo *TInfo,
1308                          SourceLocation EllipsisLoc) {
1309   QualType BaseType = TInfo->getType();
1310 
1311   // C++ [class.union]p1:
1312   //   A union shall not have base classes.
1313   if (Class->isUnion()) {
1314     Diag(Class->getLocation(), diag::err_base_clause_on_union)
1315       << SpecifierRange;
1316     return nullptr;
1317   }
1318 
1319   if (EllipsisLoc.isValid() &&
1320       !TInfo->getType()->containsUnexpandedParameterPack()) {
1321     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1322       << TInfo->getTypeLoc().getSourceRange();
1323     EllipsisLoc = SourceLocation();
1324   }
1325 
1326   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1327 
1328   if (BaseType->isDependentType()) {
1329     // Make sure that we don't have circular inheritance among our dependent
1330     // bases. For non-dependent bases, the check for completeness below handles
1331     // this.
1332     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1333       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1334           ((BaseDecl = BaseDecl->getDefinition()) &&
1335            findCircularInheritance(Class, BaseDecl))) {
1336         Diag(BaseLoc, diag::err_circular_inheritance)
1337           << BaseType << Context.getTypeDeclType(Class);
1338 
1339         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1340           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1341             << BaseType;
1342 
1343         return nullptr;
1344       }
1345     }
1346 
1347     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1348                                           Class->getTagKind() == TTK_Class,
1349                                           Access, TInfo, EllipsisLoc);
1350   }
1351 
1352   // Base specifiers must be record types.
1353   if (!BaseType->isRecordType()) {
1354     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1355     return nullptr;
1356   }
1357 
1358   // C++ [class.union]p1:
1359   //   A union shall not be used as a base class.
1360   if (BaseType->isUnionType()) {
1361     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1362     return nullptr;
1363   }
1364 
1365   // C++ [class.derived]p2:
1366   //   The class-name in a base-specifier shall not be an incompletely
1367   //   defined class.
1368   if (RequireCompleteType(BaseLoc, BaseType,
1369                           diag::err_incomplete_base_class, SpecifierRange)) {
1370     Class->setInvalidDecl();
1371     return nullptr;
1372   }
1373 
1374   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1375   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1376   assert(BaseDecl && "Record type has no declaration");
1377   BaseDecl = BaseDecl->getDefinition();
1378   assert(BaseDecl && "Base type is not incomplete, but has no definition");
1379   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1380   assert(CXXBaseDecl && "Base type is not a C++ type");
1381 
1382   // A class which contains a flexible array member is not suitable for use as a
1383   // base class:
1384   //   - If the layout determines that a base comes before another base,
1385   //     the flexible array member would index into the subsequent base.
1386   //   - If the layout determines that base comes before the derived class,
1387   //     the flexible array member would index into the derived class.
1388   if (CXXBaseDecl->hasFlexibleArrayMember()) {
1389     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1390       << CXXBaseDecl->getDeclName();
1391     return nullptr;
1392   }
1393 
1394   // C++ [class]p3:
1395   //   If a class is marked final and it appears as a base-type-specifier in
1396   //   base-clause, the program is ill-formed.
1397   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
1398     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1399       << CXXBaseDecl->getDeclName()
1400       << FA->isSpelledAsSealed();
1401     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
1402         << CXXBaseDecl->getDeclName() << FA->getRange();
1403     return nullptr;
1404   }
1405 
1406   if (BaseDecl->isInvalidDecl())
1407     Class->setInvalidDecl();
1408 
1409   // Create the base specifier.
1410   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1411                                         Class->getTagKind() == TTK_Class,
1412                                         Access, TInfo, EllipsisLoc);
1413 }
1414 
1415 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1416 /// one entry in the base class list of a class specifier, for
1417 /// example:
1418 ///    class foo : public bar, virtual private baz {
1419 /// 'public bar' and 'virtual private baz' are each base-specifiers.
1420 BaseResult
1421 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1422                          ParsedAttributes &Attributes,
1423                          bool Virtual, AccessSpecifier Access,
1424                          ParsedType basetype, SourceLocation BaseLoc,
1425                          SourceLocation EllipsisLoc) {
1426   if (!classdecl)
1427     return true;
1428 
1429   AdjustDeclIfTemplate(classdecl);
1430   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1431   if (!Class)
1432     return true;
1433 
1434   // We do not support any C++11 attributes on base-specifiers yet.
1435   // Diagnose any attributes we see.
1436   if (!Attributes.empty()) {
1437     for (AttributeList *Attr = Attributes.getList(); Attr;
1438          Attr = Attr->getNext()) {
1439       if (Attr->isInvalid() ||
1440           Attr->getKind() == AttributeList::IgnoredAttribute)
1441         continue;
1442       Diag(Attr->getLoc(),
1443            Attr->getKind() == AttributeList::UnknownAttribute
1444              ? diag::warn_unknown_attribute_ignored
1445              : diag::err_base_specifier_attribute)
1446         << Attr->getName();
1447     }
1448   }
1449 
1450   TypeSourceInfo *TInfo = nullptr;
1451   GetTypeFromParser(basetype, &TInfo);
1452 
1453   if (EllipsisLoc.isInvalid() &&
1454       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1455                                       UPPC_BaseType))
1456     return true;
1457 
1458   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1459                                                       Virtual, Access, TInfo,
1460                                                       EllipsisLoc))
1461     return BaseSpec;
1462   else
1463     Class->setInvalidDecl();
1464 
1465   return true;
1466 }
1467 
1468 /// \brief Performs the actual work of attaching the given base class
1469 /// specifiers to a C++ class.
1470 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1471                                 unsigned NumBases) {
1472  if (NumBases == 0)
1473     return false;
1474 
1475   // Used to keep track of which base types we have already seen, so
1476   // that we can properly diagnose redundant direct base types. Note
1477   // that the key is always the unqualified canonical type of the base
1478   // class.
1479   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1480 
1481   // Copy non-redundant base specifiers into permanent storage.
1482   unsigned NumGoodBases = 0;
1483   bool Invalid = false;
1484   for (unsigned idx = 0; idx < NumBases; ++idx) {
1485     QualType NewBaseType
1486       = Context.getCanonicalType(Bases[idx]->getType());
1487     NewBaseType = NewBaseType.getLocalUnqualifiedType();
1488 
1489     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1490     if (KnownBase) {
1491       // C++ [class.mi]p3:
1492       //   A class shall not be specified as a direct base class of a
1493       //   derived class more than once.
1494       Diag(Bases[idx]->getLocStart(),
1495            diag::err_duplicate_base_class)
1496         << KnownBase->getType()
1497         << Bases[idx]->getSourceRange();
1498 
1499       // Delete the duplicate base class specifier; we're going to
1500       // overwrite its pointer later.
1501       Context.Deallocate(Bases[idx]);
1502 
1503       Invalid = true;
1504     } else {
1505       // Okay, add this new base class.
1506       KnownBase = Bases[idx];
1507       Bases[NumGoodBases++] = Bases[idx];
1508       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1509         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1510         if (Class->isInterface() &&
1511               (!RD->isInterface() ||
1512                KnownBase->getAccessSpecifier() != AS_public)) {
1513           // The Microsoft extension __interface does not permit bases that
1514           // are not themselves public interfaces.
1515           Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1516             << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1517             << RD->getSourceRange();
1518           Invalid = true;
1519         }
1520         if (RD->hasAttr<WeakAttr>())
1521           Class->addAttr(WeakAttr::CreateImplicit(Context));
1522       }
1523     }
1524   }
1525 
1526   // Attach the remaining base class specifiers to the derived class.
1527   Class->setBases(Bases, NumGoodBases);
1528 
1529   // Delete the remaining (good) base class specifiers, since their
1530   // data has been copied into the CXXRecordDecl.
1531   for (unsigned idx = 0; idx < NumGoodBases; ++idx)
1532     Context.Deallocate(Bases[idx]);
1533 
1534   return Invalid;
1535 }
1536 
1537 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
1538 /// class, after checking whether there are any duplicate base
1539 /// classes.
1540 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
1541                                unsigned NumBases) {
1542   if (!ClassDecl || !Bases || !NumBases)
1543     return;
1544 
1545   AdjustDeclIfTemplate(ClassDecl);
1546   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
1547 }
1548 
1549 /// \brief Determine whether the type \p Derived is a C++ class that is
1550 /// derived from the type \p Base.
1551 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1552   if (!getLangOpts().CPlusPlus)
1553     return false;
1554 
1555   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1556   if (!DerivedRD)
1557     return false;
1558 
1559   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1560   if (!BaseRD)
1561     return false;
1562 
1563   // If either the base or the derived type is invalid, don't try to
1564   // check whether one is derived from the other.
1565   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1566     return false;
1567 
1568   // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
1569   return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
1570 }
1571 
1572 /// \brief Determine whether the type \p Derived is a C++ class that is
1573 /// derived from the type \p Base.
1574 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1575   if (!getLangOpts().CPlusPlus)
1576     return false;
1577 
1578   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1579   if (!DerivedRD)
1580     return false;
1581 
1582   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1583   if (!BaseRD)
1584     return false;
1585 
1586   return DerivedRD->isDerivedFrom(BaseRD, Paths);
1587 }
1588 
1589 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1590                               CXXCastPath &BasePathArray) {
1591   assert(BasePathArray.empty() && "Base path array must be empty!");
1592   assert(Paths.isRecordingPaths() && "Must record paths!");
1593 
1594   const CXXBasePath &Path = Paths.front();
1595 
1596   // We first go backward and check if we have a virtual base.
1597   // FIXME: It would be better if CXXBasePath had the base specifier for
1598   // the nearest virtual base.
1599   unsigned Start = 0;
1600   for (unsigned I = Path.size(); I != 0; --I) {
1601     if (Path[I - 1].Base->isVirtual()) {
1602       Start = I - 1;
1603       break;
1604     }
1605   }
1606 
1607   // Now add all bases.
1608   for (unsigned I = Start, E = Path.size(); I != E; ++I)
1609     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1610 }
1611 
1612 /// \brief Determine whether the given base path includes a virtual
1613 /// base class.
1614 bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1615   for (CXXCastPath::const_iterator B = BasePath.begin(),
1616                                 BEnd = BasePath.end();
1617        B != BEnd; ++B)
1618     if ((*B)->isVirtual())
1619       return true;
1620 
1621   return false;
1622 }
1623 
1624 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1625 /// conversion (where Derived and Base are class types) is
1626 /// well-formed, meaning that the conversion is unambiguous (and
1627 /// that all of the base classes are accessible). Returns true
1628 /// and emits a diagnostic if the code is ill-formed, returns false
1629 /// otherwise. Loc is the location where this routine should point to
1630 /// if there is an error, and Range is the source range to highlight
1631 /// if there is an error.
1632 bool
1633 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1634                                    unsigned InaccessibleBaseID,
1635                                    unsigned AmbigiousBaseConvID,
1636                                    SourceLocation Loc, SourceRange Range,
1637                                    DeclarationName Name,
1638                                    CXXCastPath *BasePath) {
1639   // First, determine whether the path from Derived to Base is
1640   // ambiguous. This is slightly more expensive than checking whether
1641   // the Derived to Base conversion exists, because here we need to
1642   // explore multiple paths to determine if there is an ambiguity.
1643   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1644                      /*DetectVirtual=*/false);
1645   bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1646   assert(DerivationOkay &&
1647          "Can only be used with a derived-to-base conversion");
1648   (void)DerivationOkay;
1649 
1650   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1651     if (InaccessibleBaseID) {
1652       // Check that the base class can be accessed.
1653       switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1654                                    InaccessibleBaseID)) {
1655         case AR_inaccessible:
1656           return true;
1657         case AR_accessible:
1658         case AR_dependent:
1659         case AR_delayed:
1660           break;
1661       }
1662     }
1663 
1664     // Build a base path if necessary.
1665     if (BasePath)
1666       BuildBasePathArray(Paths, *BasePath);
1667     return false;
1668   }
1669 
1670   if (AmbigiousBaseConvID) {
1671     // We know that the derived-to-base conversion is ambiguous, and
1672     // we're going to produce a diagnostic. Perform the derived-to-base
1673     // search just one more time to compute all of the possible paths so
1674     // that we can print them out. This is more expensive than any of
1675     // the previous derived-to-base checks we've done, but at this point
1676     // performance isn't as much of an issue.
1677     Paths.clear();
1678     Paths.setRecordingPaths(true);
1679     bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1680     assert(StillOkay && "Can only be used with a derived-to-base conversion");
1681     (void)StillOkay;
1682 
1683     // Build up a textual representation of the ambiguous paths, e.g.,
1684     // D -> B -> A, that will be used to illustrate the ambiguous
1685     // conversions in the diagnostic. We only print one of the paths
1686     // to each base class subobject.
1687     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1688 
1689     Diag(Loc, AmbigiousBaseConvID)
1690     << Derived << Base << PathDisplayStr << Range << Name;
1691   }
1692   return true;
1693 }
1694 
1695 bool
1696 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1697                                    SourceLocation Loc, SourceRange Range,
1698                                    CXXCastPath *BasePath,
1699                                    bool IgnoreAccess) {
1700   return CheckDerivedToBaseConversion(Derived, Base,
1701                                       IgnoreAccess ? 0
1702                                        : diag::err_upcast_to_inaccessible_base,
1703                                       diag::err_ambiguous_derived_to_base_conv,
1704                                       Loc, Range, DeclarationName(),
1705                                       BasePath);
1706 }
1707 
1708 
1709 /// @brief Builds a string representing ambiguous paths from a
1710 /// specific derived class to different subobjects of the same base
1711 /// class.
1712 ///
1713 /// This function builds a string that can be used in error messages
1714 /// to show the different paths that one can take through the
1715 /// inheritance hierarchy to go from the derived class to different
1716 /// subobjects of a base class. The result looks something like this:
1717 /// @code
1718 /// struct D -> struct B -> struct A
1719 /// struct D -> struct C -> struct A
1720 /// @endcode
1721 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1722   std::string PathDisplayStr;
1723   std::set<unsigned> DisplayedPaths;
1724   for (CXXBasePaths::paths_iterator Path = Paths.begin();
1725        Path != Paths.end(); ++Path) {
1726     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1727       // We haven't displayed a path to this particular base
1728       // class subobject yet.
1729       PathDisplayStr += "\n    ";
1730       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1731       for (CXXBasePath::const_iterator Element = Path->begin();
1732            Element != Path->end(); ++Element)
1733         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1734     }
1735   }
1736 
1737   return PathDisplayStr;
1738 }
1739 
1740 //===----------------------------------------------------------------------===//
1741 // C++ class member Handling
1742 //===----------------------------------------------------------------------===//
1743 
1744 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1745 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1746                                 SourceLocation ASLoc,
1747                                 SourceLocation ColonLoc,
1748                                 AttributeList *Attrs) {
1749   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1750   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1751                                                   ASLoc, ColonLoc);
1752   CurContext->addHiddenDecl(ASDecl);
1753   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1754 }
1755 
1756 /// CheckOverrideControl - Check C++11 override control semantics.
1757 void Sema::CheckOverrideControl(NamedDecl *D) {
1758   if (D->isInvalidDecl())
1759     return;
1760 
1761   // We only care about "override" and "final" declarations.
1762   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1763     return;
1764 
1765   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1766 
1767   // We can't check dependent instance methods.
1768   if (MD && MD->isInstance() &&
1769       (MD->getParent()->hasAnyDependentBases() ||
1770        MD->getType()->isDependentType()))
1771     return;
1772 
1773   if (MD && !MD->isVirtual()) {
1774     // If we have a non-virtual method, check if if hides a virtual method.
1775     // (In that case, it's most likely the method has the wrong type.)
1776     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1777     FindHiddenVirtualMethods(MD, OverloadedMethods);
1778 
1779     if (!OverloadedMethods.empty()) {
1780       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1781         Diag(OA->getLocation(),
1782              diag::override_keyword_hides_virtual_member_function)
1783           << "override" << (OverloadedMethods.size() > 1);
1784       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1785         Diag(FA->getLocation(),
1786              diag::override_keyword_hides_virtual_member_function)
1787           << (FA->isSpelledAsSealed() ? "sealed" : "final")
1788           << (OverloadedMethods.size() > 1);
1789       }
1790       NoteHiddenVirtualMethods(MD, OverloadedMethods);
1791       MD->setInvalidDecl();
1792       return;
1793     }
1794     // Fall through into the general case diagnostic.
1795     // FIXME: We might want to attempt typo correction here.
1796   }
1797 
1798   if (!MD || !MD->isVirtual()) {
1799     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1800       Diag(OA->getLocation(),
1801            diag::override_keyword_only_allowed_on_virtual_member_functions)
1802         << "override" << FixItHint::CreateRemoval(OA->getLocation());
1803       D->dropAttr<OverrideAttr>();
1804     }
1805     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1806       Diag(FA->getLocation(),
1807            diag::override_keyword_only_allowed_on_virtual_member_functions)
1808         << (FA->isSpelledAsSealed() ? "sealed" : "final")
1809         << FixItHint::CreateRemoval(FA->getLocation());
1810       D->dropAttr<FinalAttr>();
1811     }
1812     return;
1813   }
1814 
1815   // C++11 [class.virtual]p5:
1816   //   If a virtual function is marked with the virt-specifier override and
1817   //   does not override a member function of a base class, the program is
1818   //   ill-formed.
1819   bool HasOverriddenMethods =
1820     MD->begin_overridden_methods() != MD->end_overridden_methods();
1821   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1822     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1823       << MD->getDeclName();
1824 }
1825 
1826 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1827 /// function overrides a virtual member function marked 'final', according to
1828 /// C++11 [class.virtual]p4.
1829 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1830                                                   const CXXMethodDecl *Old) {
1831   FinalAttr *FA = Old->getAttr<FinalAttr>();
1832   if (!FA)
1833     return false;
1834 
1835   Diag(New->getLocation(), diag::err_final_function_overridden)
1836     << New->getDeclName()
1837     << FA->isSpelledAsSealed();
1838   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1839   return true;
1840 }
1841 
1842 static bool InitializationHasSideEffects(const FieldDecl &FD) {
1843   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1844   // FIXME: Destruction of ObjC lifetime types has side-effects.
1845   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1846     return !RD->isCompleteDefinition() ||
1847            !RD->hasTrivialDefaultConstructor() ||
1848            !RD->hasTrivialDestructor();
1849   return false;
1850 }
1851 
1852 static AttributeList *getMSPropertyAttr(AttributeList *list) {
1853   for (AttributeList *it = list; it != nullptr; it = it->getNext())
1854     if (it->isDeclspecPropertyAttribute())
1855       return it;
1856   return nullptr;
1857 }
1858 
1859 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1860 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1861 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
1862 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1863 /// present (but parsing it has been deferred).
1864 NamedDecl *
1865 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1866                                MultiTemplateParamsArg TemplateParameterLists,
1867                                Expr *BW, const VirtSpecifiers &VS,
1868                                InClassInitStyle InitStyle) {
1869   const DeclSpec &DS = D.getDeclSpec();
1870   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1871   DeclarationName Name = NameInfo.getName();
1872   SourceLocation Loc = NameInfo.getLoc();
1873 
1874   // For anonymous bitfields, the location should point to the type.
1875   if (Loc.isInvalid())
1876     Loc = D.getLocStart();
1877 
1878   Expr *BitWidth = static_cast<Expr*>(BW);
1879 
1880   assert(isa<CXXRecordDecl>(CurContext));
1881   assert(!DS.isFriendSpecified());
1882 
1883   bool isFunc = D.isDeclarationOfFunction();
1884 
1885   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1886     // The Microsoft extension __interface only permits public member functions
1887     // and prohibits constructors, destructors, operators, non-public member
1888     // functions, static methods and data members.
1889     unsigned InvalidDecl;
1890     bool ShowDeclName = true;
1891     if (!isFunc)
1892       InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1893     else if (AS != AS_public)
1894       InvalidDecl = 2;
1895     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1896       InvalidDecl = 3;
1897     else switch (Name.getNameKind()) {
1898       case DeclarationName::CXXConstructorName:
1899         InvalidDecl = 4;
1900         ShowDeclName = false;
1901         break;
1902 
1903       case DeclarationName::CXXDestructorName:
1904         InvalidDecl = 5;
1905         ShowDeclName = false;
1906         break;
1907 
1908       case DeclarationName::CXXOperatorName:
1909       case DeclarationName::CXXConversionFunctionName:
1910         InvalidDecl = 6;
1911         break;
1912 
1913       default:
1914         InvalidDecl = 0;
1915         break;
1916     }
1917 
1918     if (InvalidDecl) {
1919       if (ShowDeclName)
1920         Diag(Loc, diag::err_invalid_member_in_interface)
1921           << (InvalidDecl-1) << Name;
1922       else
1923         Diag(Loc, diag::err_invalid_member_in_interface)
1924           << (InvalidDecl-1) << "";
1925       return nullptr;
1926     }
1927   }
1928 
1929   // C++ 9.2p6: A member shall not be declared to have automatic storage
1930   // duration (auto, register) or with the extern storage-class-specifier.
1931   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1932   // data members and cannot be applied to names declared const or static,
1933   // and cannot be applied to reference members.
1934   switch (DS.getStorageClassSpec()) {
1935   case DeclSpec::SCS_unspecified:
1936   case DeclSpec::SCS_typedef:
1937   case DeclSpec::SCS_static:
1938     break;
1939   case DeclSpec::SCS_mutable:
1940     if (isFunc) {
1941       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
1942 
1943       // FIXME: It would be nicer if the keyword was ignored only for this
1944       // declarator. Otherwise we could get follow-up errors.
1945       D.getMutableDeclSpec().ClearStorageClassSpecs();
1946     }
1947     break;
1948   default:
1949     Diag(DS.getStorageClassSpecLoc(),
1950          diag::err_storageclass_invalid_for_member);
1951     D.getMutableDeclSpec().ClearStorageClassSpecs();
1952     break;
1953   }
1954 
1955   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1956                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
1957                       !isFunc);
1958 
1959   if (DS.isConstexprSpecified() && isInstField) {
1960     SemaDiagnosticBuilder B =
1961         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1962     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1963     if (InitStyle == ICIS_NoInit) {
1964       B << 0 << 0;
1965       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
1966         B << FixItHint::CreateRemoval(ConstexprLoc);
1967       else {
1968         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
1969         D.getMutableDeclSpec().ClearConstexprSpec();
1970         const char *PrevSpec;
1971         unsigned DiagID;
1972         bool Failed = D.getMutableDeclSpec().SetTypeQual(
1973             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
1974         (void)Failed;
1975         assert(!Failed && "Making a constexpr member const shouldn't fail");
1976       }
1977     } else {
1978       B << 1;
1979       const char *PrevSpec;
1980       unsigned DiagID;
1981       if (D.getMutableDeclSpec().SetStorageClassSpec(
1982           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
1983           Context.getPrintingPolicy())) {
1984         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
1985                "This is the only DeclSpec that should fail to be applied");
1986         B << 1;
1987       } else {
1988         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1989         isInstField = false;
1990       }
1991     }
1992   }
1993 
1994   NamedDecl *Member;
1995   if (isInstField) {
1996     CXXScopeSpec &SS = D.getCXXScopeSpec();
1997 
1998     // Data members must have identifiers for names.
1999     if (!Name.isIdentifier()) {
2000       Diag(Loc, diag::err_bad_variable_name)
2001         << Name;
2002       return nullptr;
2003     }
2004 
2005     IdentifierInfo *II = Name.getAsIdentifierInfo();
2006 
2007     // Member field could not be with "template" keyword.
2008     // So TemplateParameterLists should be empty in this case.
2009     if (TemplateParameterLists.size()) {
2010       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
2011       if (TemplateParams->size()) {
2012         // There is no such thing as a member field template.
2013         Diag(D.getIdentifierLoc(), diag::err_template_member)
2014             << II
2015             << SourceRange(TemplateParams->getTemplateLoc(),
2016                 TemplateParams->getRAngleLoc());
2017       } else {
2018         // There is an extraneous 'template<>' for this member.
2019         Diag(TemplateParams->getTemplateLoc(),
2020             diag::err_template_member_noparams)
2021             << II
2022             << SourceRange(TemplateParams->getTemplateLoc(),
2023                 TemplateParams->getRAngleLoc());
2024       }
2025       return nullptr;
2026     }
2027 
2028     if (SS.isSet() && !SS.isInvalid()) {
2029       // The user provided a superfluous scope specifier inside a class
2030       // definition:
2031       //
2032       // class X {
2033       //   int X::member;
2034       // };
2035       if (DeclContext *DC = computeDeclContext(SS, false))
2036         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
2037       else
2038         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2039           << Name << SS.getRange();
2040 
2041       SS.clear();
2042     }
2043 
2044     AttributeList *MSPropertyAttr =
2045       getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
2046     if (MSPropertyAttr) {
2047       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2048                                 BitWidth, InitStyle, AS, MSPropertyAttr);
2049       if (!Member)
2050         return nullptr;
2051       isInstField = false;
2052     } else {
2053       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2054                                 BitWidth, InitStyle, AS);
2055       assert(Member && "HandleField never returns null");
2056     }
2057   } else {
2058     assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2059 
2060     Member = HandleDeclarator(S, D, TemplateParameterLists);
2061     if (!Member)
2062       return nullptr;
2063 
2064     // Non-instance-fields can't have a bitfield.
2065     if (BitWidth) {
2066       if (Member->isInvalidDecl()) {
2067         // don't emit another diagnostic.
2068       } else if (isa<VarDecl>(Member)) {
2069         // C++ 9.6p3: A bit-field shall not be a static member.
2070         // "static member 'A' cannot be a bit-field"
2071         Diag(Loc, diag::err_static_not_bitfield)
2072           << Name << BitWidth->getSourceRange();
2073       } else if (isa<TypedefDecl>(Member)) {
2074         // "typedef member 'x' cannot be a bit-field"
2075         Diag(Loc, diag::err_typedef_not_bitfield)
2076           << Name << BitWidth->getSourceRange();
2077       } else {
2078         // A function typedef ("typedef int f(); f a;").
2079         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2080         Diag(Loc, diag::err_not_integral_type_bitfield)
2081           << Name << cast<ValueDecl>(Member)->getType()
2082           << BitWidth->getSourceRange();
2083       }
2084 
2085       BitWidth = nullptr;
2086       Member->setInvalidDecl();
2087     }
2088 
2089     Member->setAccess(AS);
2090 
2091     // If we have declared a member function template or static data member
2092     // template, set the access of the templated declaration as well.
2093     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2094       FunTmpl->getTemplatedDecl()->setAccess(AS);
2095     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2096       VarTmpl->getTemplatedDecl()->setAccess(AS);
2097   }
2098 
2099   if (VS.isOverrideSpecified())
2100     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
2101   if (VS.isFinalSpecified())
2102     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2103                                             VS.isFinalSpelledSealed()));
2104 
2105   if (VS.getLastLocation().isValid()) {
2106     // Update the end location of a method that has a virt-specifiers.
2107     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2108       MD->setRangeEnd(VS.getLastLocation());
2109   }
2110 
2111   CheckOverrideControl(Member);
2112 
2113   assert((Name || isInstField) && "No identifier for non-field ?");
2114 
2115   if (isInstField) {
2116     FieldDecl *FD = cast<FieldDecl>(Member);
2117     FieldCollector->Add(FD);
2118 
2119     if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2120                                  FD->getLocation())
2121           != DiagnosticsEngine::Ignored) {
2122       // Remember all explicit private FieldDecls that have a name, no side
2123       // effects and are not part of a dependent type declaration.
2124       if (!FD->isImplicit() && FD->getDeclName() &&
2125           FD->getAccess() == AS_private &&
2126           !FD->hasAttr<UnusedAttr>() &&
2127           !FD->getParent()->isDependentContext() &&
2128           !InitializationHasSideEffects(*FD))
2129         UnusedPrivateFields.insert(FD);
2130     }
2131   }
2132 
2133   return Member;
2134 }
2135 
2136 namespace {
2137   class UninitializedFieldVisitor
2138       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2139     Sema &S;
2140     // List of Decls to generate a warning on.  Also remove Decls that become
2141     // initialized.
2142     llvm::SmallPtrSet<ValueDecl*, 4> &Decls;
2143     // If non-null, add a note to the warning pointing back to the constructor.
2144     const CXXConstructorDecl *Constructor;
2145   public:
2146     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2147     UninitializedFieldVisitor(Sema &S,
2148                               llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
2149                               const CXXConstructorDecl *Constructor)
2150       : Inherited(S.Context), S(S), Decls(Decls),
2151         Constructor(Constructor) { }
2152 
2153     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) {
2154       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2155         return;
2156 
2157       // FieldME is the inner-most MemberExpr that is not an anonymous struct
2158       // or union.
2159       MemberExpr *FieldME = ME;
2160 
2161       Expr *Base = ME;
2162       while (isa<MemberExpr>(Base)) {
2163         ME = cast<MemberExpr>(Base);
2164 
2165         if (isa<VarDecl>(ME->getMemberDecl()))
2166           return;
2167 
2168         if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2169           if (!FD->isAnonymousStructOrUnion())
2170             FieldME = ME;
2171 
2172         Base = ME->getBase();
2173       }
2174 
2175       if (!isa<CXXThisExpr>(Base))
2176         return;
2177 
2178       ValueDecl* FoundVD = FieldME->getMemberDecl();
2179 
2180       if (!Decls.count(FoundVD))
2181         return;
2182 
2183       const bool IsReference = FoundVD->getType()->isReferenceType();
2184 
2185       // Prevent double warnings on use of unbounded references.
2186       if (IsReference != CheckReferenceOnly)
2187         return;
2188 
2189       unsigned diag = IsReference
2190           ? diag::warn_reference_field_is_uninit
2191           : diag::warn_field_is_uninit;
2192       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2193       if (Constructor)
2194         S.Diag(Constructor->getLocation(),
2195                diag::note_uninit_in_this_constructor)
2196           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2197 
2198     }
2199 
2200     void HandleValue(Expr *E) {
2201       E = E->IgnoreParens();
2202 
2203       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2204         HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
2205         return;
2206       }
2207 
2208       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2209         HandleValue(CO->getTrueExpr());
2210         HandleValue(CO->getFalseExpr());
2211         return;
2212       }
2213 
2214       if (BinaryConditionalOperator *BCO =
2215               dyn_cast<BinaryConditionalOperator>(E)) {
2216         HandleValue(BCO->getCommon());
2217         HandleValue(BCO->getFalseExpr());
2218         return;
2219       }
2220 
2221       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2222         switch (BO->getOpcode()) {
2223         default:
2224           return;
2225         case(BO_PtrMemD):
2226         case(BO_PtrMemI):
2227           HandleValue(BO->getLHS());
2228           return;
2229         case(BO_Comma):
2230           HandleValue(BO->getRHS());
2231           return;
2232         }
2233       }
2234     }
2235 
2236     void VisitMemberExpr(MemberExpr *ME) {
2237       // All uses of unbounded reference fields will warn.
2238       HandleMemberExpr(ME, true /*CheckReferenceOnly*/);
2239 
2240       Inherited::VisitMemberExpr(ME);
2241     }
2242 
2243     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2244       if (E->getCastKind() == CK_LValueToRValue)
2245         HandleValue(E->getSubExpr());
2246 
2247       Inherited::VisitImplicitCastExpr(E);
2248     }
2249 
2250     void VisitCXXConstructExpr(CXXConstructExpr *E) {
2251       if (E->getConstructor()->isCopyConstructor())
2252         if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0)))
2253           if (ICE->getCastKind() == CK_NoOp)
2254             if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr()))
2255               HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
2256 
2257       Inherited::VisitCXXConstructExpr(E);
2258     }
2259 
2260     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2261       Expr *Callee = E->getCallee();
2262       if (isa<MemberExpr>(Callee))
2263         HandleValue(Callee);
2264 
2265       Inherited::VisitCXXMemberCallExpr(E);
2266     }
2267 
2268     void VisitBinaryOperator(BinaryOperator *E) {
2269       // If a field assignment is detected, remove the field from the
2270       // uninitiailized field set.
2271       if (E->getOpcode() == BO_Assign)
2272         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2273           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2274             if (!FD->getType()->isReferenceType())
2275               Decls.erase(FD);
2276 
2277       Inherited::VisitBinaryOperator(E);
2278     }
2279   };
2280   static void CheckInitExprContainsUninitializedFields(
2281       Sema &S, Expr *E, llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
2282       const CXXConstructorDecl *Constructor) {
2283     if (Decls.size() == 0)
2284       return;
2285 
2286     if (!E)
2287       return;
2288 
2289     if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(E)) {
2290       E = Default->getExpr();
2291       if (!E)
2292         return;
2293       // In class initializers will point to the constructor.
2294       UninitializedFieldVisitor(S, Decls, Constructor).Visit(E);
2295     } else {
2296       UninitializedFieldVisitor(S, Decls, nullptr).Visit(E);
2297     }
2298   }
2299 
2300   // Diagnose value-uses of fields to initialize themselves, e.g.
2301   //   foo(foo)
2302   // where foo is not also a parameter to the constructor.
2303   // Also diagnose across field uninitialized use such as
2304   //   x(y), y(x)
2305   // TODO: implement -Wuninitialized and fold this into that framework.
2306   static void DiagnoseUninitializedFields(
2307       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2308 
2309     if (SemaRef.getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit,
2310                                                     Constructor->getLocation())
2311         == DiagnosticsEngine::Ignored) {
2312       return;
2313     }
2314 
2315     if (Constructor->isInvalidDecl())
2316       return;
2317 
2318     const CXXRecordDecl *RD = Constructor->getParent();
2319 
2320     // Holds fields that are uninitialized.
2321     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2322 
2323     // At the beginning, all fields are uninitialized.
2324     for (auto *I : RD->decls()) {
2325       if (auto *FD = dyn_cast<FieldDecl>(I)) {
2326         UninitializedFields.insert(FD);
2327       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
2328         UninitializedFields.insert(IFD->getAnonField());
2329       }
2330     }
2331 
2332     for (const auto *FieldInit : Constructor->inits()) {
2333       Expr *InitExpr = FieldInit->getInit();
2334 
2335       CheckInitExprContainsUninitializedFields(
2336           SemaRef, InitExpr, UninitializedFields, Constructor);
2337 
2338       if (FieldDecl *Field = FieldInit->getAnyMember())
2339         UninitializedFields.erase(Field);
2340     }
2341   }
2342 } // namespace
2343 
2344 /// \brief Enter a new C++ default initializer scope. After calling this, the
2345 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2346 /// parsing or instantiating the initializer failed.
2347 void Sema::ActOnStartCXXInClassMemberInitializer() {
2348   // Create a synthetic function scope to represent the call to the constructor
2349   // that notionally surrounds a use of this initializer.
2350   PushFunctionScope();
2351 }
2352 
2353 /// \brief This is invoked after parsing an in-class initializer for a
2354 /// non-static C++ class member, and after instantiating an in-class initializer
2355 /// in a class template. Such actions are deferred until the class is complete.
2356 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2357                                                   SourceLocation InitLoc,
2358                                                   Expr *InitExpr) {
2359   // Pop the notional constructor scope we created earlier.
2360   PopFunctionScopeInfo(nullptr, D);
2361 
2362   FieldDecl *FD = cast<FieldDecl>(D);
2363   assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2364          "must set init style when field is created");
2365 
2366   if (!InitExpr) {
2367     FD->setInvalidDecl();
2368     FD->removeInClassInitializer();
2369     return;
2370   }
2371 
2372   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2373     FD->setInvalidDecl();
2374     FD->removeInClassInitializer();
2375     return;
2376   }
2377 
2378   ExprResult Init = InitExpr;
2379   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
2380     InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
2381     InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
2382         ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
2383         : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
2384     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2385     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
2386     if (Init.isInvalid()) {
2387       FD->setInvalidDecl();
2388       return;
2389     }
2390   }
2391 
2392   // C++11 [class.base.init]p7:
2393   //   The initialization of each base and member constitutes a
2394   //   full-expression.
2395   Init = ActOnFinishFullExpr(Init.get(), InitLoc);
2396   if (Init.isInvalid()) {
2397     FD->setInvalidDecl();
2398     return;
2399   }
2400 
2401   InitExpr = Init.get();
2402 
2403   FD->setInClassInitializer(InitExpr);
2404 }
2405 
2406 /// \brief Find the direct and/or virtual base specifiers that
2407 /// correspond to the given base type, for use in base initialization
2408 /// within a constructor.
2409 static bool FindBaseInitializer(Sema &SemaRef,
2410                                 CXXRecordDecl *ClassDecl,
2411                                 QualType BaseType,
2412                                 const CXXBaseSpecifier *&DirectBaseSpec,
2413                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
2414   // First, check for a direct base class.
2415   DirectBaseSpec = nullptr;
2416   for (const auto &Base : ClassDecl->bases()) {
2417     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
2418       // We found a direct base of this type. That's what we're
2419       // initializing.
2420       DirectBaseSpec = &Base;
2421       break;
2422     }
2423   }
2424 
2425   // Check for a virtual base class.
2426   // FIXME: We might be able to short-circuit this if we know in advance that
2427   // there are no virtual bases.
2428   VirtualBaseSpec = nullptr;
2429   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2430     // We haven't found a base yet; search the class hierarchy for a
2431     // virtual base class.
2432     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2433                        /*DetectVirtual=*/false);
2434     if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2435                               BaseType, Paths)) {
2436       for (CXXBasePaths::paths_iterator Path = Paths.begin();
2437            Path != Paths.end(); ++Path) {
2438         if (Path->back().Base->isVirtual()) {
2439           VirtualBaseSpec = Path->back().Base;
2440           break;
2441         }
2442       }
2443     }
2444   }
2445 
2446   return DirectBaseSpec || VirtualBaseSpec;
2447 }
2448 
2449 /// \brief Handle a C++ member initializer using braced-init-list syntax.
2450 MemInitResult
2451 Sema::ActOnMemInitializer(Decl *ConstructorD,
2452                           Scope *S,
2453                           CXXScopeSpec &SS,
2454                           IdentifierInfo *MemberOrBase,
2455                           ParsedType TemplateTypeTy,
2456                           const DeclSpec &DS,
2457                           SourceLocation IdLoc,
2458                           Expr *InitList,
2459                           SourceLocation EllipsisLoc) {
2460   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2461                              DS, IdLoc, InitList,
2462                              EllipsisLoc);
2463 }
2464 
2465 /// \brief Handle a C++ member initializer using parentheses syntax.
2466 MemInitResult
2467 Sema::ActOnMemInitializer(Decl *ConstructorD,
2468                           Scope *S,
2469                           CXXScopeSpec &SS,
2470                           IdentifierInfo *MemberOrBase,
2471                           ParsedType TemplateTypeTy,
2472                           const DeclSpec &DS,
2473                           SourceLocation IdLoc,
2474                           SourceLocation LParenLoc,
2475                           ArrayRef<Expr *> Args,
2476                           SourceLocation RParenLoc,
2477                           SourceLocation EllipsisLoc) {
2478   Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2479                                            Args, RParenLoc);
2480   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2481                              DS, IdLoc, List, EllipsisLoc);
2482 }
2483 
2484 namespace {
2485 
2486 // Callback to only accept typo corrections that can be a valid C++ member
2487 // intializer: either a non-static field member or a base class.
2488 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2489 public:
2490   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2491       : ClassDecl(ClassDecl) {}
2492 
2493   bool ValidateCandidate(const TypoCorrection &candidate) override {
2494     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2495       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2496         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2497       return isa<TypeDecl>(ND);
2498     }
2499     return false;
2500   }
2501 
2502 private:
2503   CXXRecordDecl *ClassDecl;
2504 };
2505 
2506 }
2507 
2508 /// \brief Handle a C++ member initializer.
2509 MemInitResult
2510 Sema::BuildMemInitializer(Decl *ConstructorD,
2511                           Scope *S,
2512                           CXXScopeSpec &SS,
2513                           IdentifierInfo *MemberOrBase,
2514                           ParsedType TemplateTypeTy,
2515                           const DeclSpec &DS,
2516                           SourceLocation IdLoc,
2517                           Expr *Init,
2518                           SourceLocation EllipsisLoc) {
2519   if (!ConstructorD)
2520     return true;
2521 
2522   AdjustDeclIfTemplate(ConstructorD);
2523 
2524   CXXConstructorDecl *Constructor
2525     = dyn_cast<CXXConstructorDecl>(ConstructorD);
2526   if (!Constructor) {
2527     // The user wrote a constructor initializer on a function that is
2528     // not a C++ constructor. Ignore the error for now, because we may
2529     // have more member initializers coming; we'll diagnose it just
2530     // once in ActOnMemInitializers.
2531     return true;
2532   }
2533 
2534   CXXRecordDecl *ClassDecl = Constructor->getParent();
2535 
2536   // C++ [class.base.init]p2:
2537   //   Names in a mem-initializer-id are looked up in the scope of the
2538   //   constructor's class and, if not found in that scope, are looked
2539   //   up in the scope containing the constructor's definition.
2540   //   [Note: if the constructor's class contains a member with the
2541   //   same name as a direct or virtual base class of the class, a
2542   //   mem-initializer-id naming the member or base class and composed
2543   //   of a single identifier refers to the class member. A
2544   //   mem-initializer-id for the hidden base class may be specified
2545   //   using a qualified name. ]
2546   if (!SS.getScopeRep() && !TemplateTypeTy) {
2547     // Look for a member, first.
2548     DeclContext::lookup_result Result
2549       = ClassDecl->lookup(MemberOrBase);
2550     if (!Result.empty()) {
2551       ValueDecl *Member;
2552       if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2553           (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
2554         if (EllipsisLoc.isValid())
2555           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
2556             << MemberOrBase
2557             << SourceRange(IdLoc, Init->getSourceRange().getEnd());
2558 
2559         return BuildMemberInitializer(Member, Init, IdLoc);
2560       }
2561     }
2562   }
2563   // It didn't name a member, so see if it names a class.
2564   QualType BaseType;
2565   TypeSourceInfo *TInfo = nullptr;
2566 
2567   if (TemplateTypeTy) {
2568     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
2569   } else if (DS.getTypeSpecType() == TST_decltype) {
2570     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
2571   } else {
2572     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2573     LookupParsedName(R, S, &SS);
2574 
2575     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2576     if (!TyD) {
2577       if (R.isAmbiguous()) return true;
2578 
2579       // We don't want access-control diagnostics here.
2580       R.suppressDiagnostics();
2581 
2582       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2583         bool NotUnknownSpecialization = false;
2584         DeclContext *DC = computeDeclContext(SS, false);
2585         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2586           NotUnknownSpecialization = !Record->hasAnyDependentBases();
2587 
2588         if (!NotUnknownSpecialization) {
2589           // When the scope specifier can refer to a member of an unknown
2590           // specialization, we take it as a type name.
2591           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2592                                        SS.getWithLocInContext(Context),
2593                                        *MemberOrBase, IdLoc);
2594           if (BaseType.isNull())
2595             return true;
2596 
2597           R.clear();
2598           R.setLookupName(MemberOrBase);
2599         }
2600       }
2601 
2602       // If no results were found, try to correct typos.
2603       TypoCorrection Corr;
2604       MemInitializerValidatorCCC Validator(ClassDecl);
2605       if (R.empty() && BaseType.isNull() &&
2606           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2607                               Validator, CTK_ErrorRecovery, ClassDecl))) {
2608         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
2609           // We have found a non-static data member with a similar
2610           // name to what was typed; complain and initialize that
2611           // member.
2612           diagnoseTypo(Corr,
2613                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
2614                          << MemberOrBase << true);
2615           return BuildMemberInitializer(Member, Init, IdLoc);
2616         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
2617           const CXXBaseSpecifier *DirectBaseSpec;
2618           const CXXBaseSpecifier *VirtualBaseSpec;
2619           if (FindBaseInitializer(*this, ClassDecl,
2620                                   Context.getTypeDeclType(Type),
2621                                   DirectBaseSpec, VirtualBaseSpec)) {
2622             // We have found a direct or virtual base class with a
2623             // similar name to what was typed; complain and initialize
2624             // that base class.
2625             diagnoseTypo(Corr,
2626                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
2627                            << MemberOrBase << false,
2628                          PDiag() /*Suppress note, we provide our own.*/);
2629 
2630             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2631                                                               : VirtualBaseSpec;
2632             Diag(BaseSpec->getLocStart(),
2633                  diag::note_base_class_specified_here)
2634               << BaseSpec->getType()
2635               << BaseSpec->getSourceRange();
2636 
2637             TyD = Type;
2638           }
2639         }
2640       }
2641 
2642       if (!TyD && BaseType.isNull()) {
2643         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
2644           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
2645         return true;
2646       }
2647     }
2648 
2649     if (BaseType.isNull()) {
2650       BaseType = Context.getTypeDeclType(TyD);
2651       if (SS.isSet())
2652         // FIXME: preserve source range information
2653         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2654                                              BaseType);
2655     }
2656   }
2657 
2658   if (!TInfo)
2659     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
2660 
2661   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
2662 }
2663 
2664 /// Checks a member initializer expression for cases where reference (or
2665 /// pointer) members are bound to by-value parameters (or their addresses).
2666 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2667                                                Expr *Init,
2668                                                SourceLocation IdLoc) {
2669   QualType MemberTy = Member->getType();
2670 
2671   // We only handle pointers and references currently.
2672   // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2673   if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2674     return;
2675 
2676   const bool IsPointer = MemberTy->isPointerType();
2677   if (IsPointer) {
2678     if (const UnaryOperator *Op
2679           = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2680       // The only case we're worried about with pointers requires taking the
2681       // address.
2682       if (Op->getOpcode() != UO_AddrOf)
2683         return;
2684 
2685       Init = Op->getSubExpr();
2686     } else {
2687       // We only handle address-of expression initializers for pointers.
2688       return;
2689     }
2690   }
2691 
2692   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2693     // We only warn when referring to a non-reference parameter declaration.
2694     const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2695     if (!Parameter || Parameter->getType()->isReferenceType())
2696       return;
2697 
2698     S.Diag(Init->getExprLoc(),
2699            IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2700                      : diag::warn_bind_ref_member_to_parameter)
2701       << Member << Parameter << Init->getSourceRange();
2702   } else {
2703     // Other initializers are fine.
2704     return;
2705   }
2706 
2707   S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2708     << (unsigned)IsPointer;
2709 }
2710 
2711 MemInitResult
2712 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
2713                              SourceLocation IdLoc) {
2714   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2715   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2716   assert((DirectMember || IndirectMember) &&
2717          "Member must be a FieldDecl or IndirectFieldDecl");
2718 
2719   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2720     return true;
2721 
2722   if (Member->isInvalidDecl())
2723     return true;
2724 
2725   MultiExprArg Args;
2726   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2727     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2728   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2729     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
2730   } else {
2731     // Template instantiation doesn't reconstruct ParenListExprs for us.
2732     Args = Init;
2733   }
2734 
2735   SourceRange InitRange = Init->getSourceRange();
2736 
2737   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
2738     // Can't check initialization for a member of dependent type or when
2739     // any of the arguments are type-dependent expressions.
2740     DiscardCleanupsInEvaluationContext();
2741   } else {
2742     bool InitList = false;
2743     if (isa<InitListExpr>(Init)) {
2744       InitList = true;
2745       Args = Init;
2746     }
2747 
2748     // Initialize the member.
2749     InitializedEntity MemberEntity =
2750       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
2751                    : InitializedEntity::InitializeMember(IndirectMember,
2752                                                          nullptr);
2753     InitializationKind Kind =
2754       InitList ? InitializationKind::CreateDirectList(IdLoc)
2755                : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2756                                                   InitRange.getEnd());
2757 
2758     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2759     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
2760                                             nullptr);
2761     if (MemberInit.isInvalid())
2762       return true;
2763 
2764     CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2765 
2766     // C++11 [class.base.init]p7:
2767     //   The initialization of each base and member constitutes a
2768     //   full-expression.
2769     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
2770     if (MemberInit.isInvalid())
2771       return true;
2772 
2773     Init = MemberInit.get();
2774   }
2775 
2776   if (DirectMember) {
2777     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2778                                             InitRange.getBegin(), Init,
2779                                             InitRange.getEnd());
2780   } else {
2781     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2782                                             InitRange.getBegin(), Init,
2783                                             InitRange.getEnd());
2784   }
2785 }
2786 
2787 MemInitResult
2788 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
2789                                  CXXRecordDecl *ClassDecl) {
2790   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
2791   if (!LangOpts.CPlusPlus11)
2792     return Diag(NameLoc, diag::err_delegating_ctor)
2793       << TInfo->getTypeLoc().getLocalSourceRange();
2794   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
2795 
2796   bool InitList = true;
2797   MultiExprArg Args = Init;
2798   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2799     InitList = false;
2800     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2801   }
2802 
2803   SourceRange InitRange = Init->getSourceRange();
2804   // Initialize the object.
2805   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2806                                      QualType(ClassDecl->getTypeForDecl(), 0));
2807   InitializationKind Kind =
2808     InitList ? InitializationKind::CreateDirectList(NameLoc)
2809              : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2810                                                 InitRange.getEnd());
2811   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
2812   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2813                                               Args, nullptr);
2814   if (DelegationInit.isInvalid())
2815     return true;
2816 
2817   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2818          "Delegating constructor with no target?");
2819 
2820   // C++11 [class.base.init]p7:
2821   //   The initialization of each base and member constitutes a
2822   //   full-expression.
2823   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2824                                        InitRange.getBegin());
2825   if (DelegationInit.isInvalid())
2826     return true;
2827 
2828   // If we are in a dependent context, template instantiation will
2829   // perform this type-checking again. Just save the arguments that we
2830   // received in a ParenListExpr.
2831   // FIXME: This isn't quite ideal, since our ASTs don't capture all
2832   // of the information that we have about the base
2833   // initializer. However, deconstructing the ASTs is a dicey process,
2834   // and this approach is far more likely to get the corner cases right.
2835   if (CurContext->isDependentContext())
2836     DelegationInit = Init;
2837 
2838   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
2839                                           DelegationInit.getAs<Expr>(),
2840                                           InitRange.getEnd());
2841 }
2842 
2843 MemInitResult
2844 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
2845                            Expr *Init, CXXRecordDecl *ClassDecl,
2846                            SourceLocation EllipsisLoc) {
2847   SourceLocation BaseLoc
2848     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
2849 
2850   if (!BaseType->isDependentType() && !BaseType->isRecordType())
2851     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2852              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2853 
2854   // C++ [class.base.init]p2:
2855   //   [...] Unless the mem-initializer-id names a nonstatic data
2856   //   member of the constructor's class or a direct or virtual base
2857   //   of that class, the mem-initializer is ill-formed. A
2858   //   mem-initializer-list can initialize a base class using any
2859   //   name that denotes that base class type.
2860   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
2861 
2862   SourceRange InitRange = Init->getSourceRange();
2863   if (EllipsisLoc.isValid()) {
2864     // This is a pack expansion.
2865     if (!BaseType->containsUnexpandedParameterPack())  {
2866       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2867         << SourceRange(BaseLoc, InitRange.getEnd());
2868 
2869       EllipsisLoc = SourceLocation();
2870     }
2871   } else {
2872     // Check for any unexpanded parameter packs.
2873     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2874       return true;
2875 
2876     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2877       return true;
2878   }
2879 
2880   // Check for direct and virtual base classes.
2881   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
2882   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
2883   if (!Dependent) {
2884     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2885                                        BaseType))
2886       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
2887 
2888     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2889                         VirtualBaseSpec);
2890 
2891     // C++ [base.class.init]p2:
2892     // Unless the mem-initializer-id names a nonstatic data member of the
2893     // constructor's class or a direct or virtual base of that class, the
2894     // mem-initializer is ill-formed.
2895     if (!DirectBaseSpec && !VirtualBaseSpec) {
2896       // If the class has any dependent bases, then it's possible that
2897       // one of those types will resolve to the same type as
2898       // BaseType. Therefore, just treat this as a dependent base
2899       // class initialization.  FIXME: Should we try to check the
2900       // initialization anyway? It seems odd.
2901       if (ClassDecl->hasAnyDependentBases())
2902         Dependent = true;
2903       else
2904         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2905           << BaseType << Context.getTypeDeclType(ClassDecl)
2906           << BaseTInfo->getTypeLoc().getLocalSourceRange();
2907     }
2908   }
2909 
2910   if (Dependent) {
2911     DiscardCleanupsInEvaluationContext();
2912 
2913     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2914                                             /*IsVirtual=*/false,
2915                                             InitRange.getBegin(), Init,
2916                                             InitRange.getEnd(), EllipsisLoc);
2917   }
2918 
2919   // C++ [base.class.init]p2:
2920   //   If a mem-initializer-id is ambiguous because it designates both
2921   //   a direct non-virtual base class and an inherited virtual base
2922   //   class, the mem-initializer is ill-formed.
2923   if (DirectBaseSpec && VirtualBaseSpec)
2924     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
2925       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2926 
2927   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
2928   if (!BaseSpec)
2929     BaseSpec = VirtualBaseSpec;
2930 
2931   // Initialize the base.
2932   bool InitList = true;
2933   MultiExprArg Args = Init;
2934   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2935     InitList = false;
2936     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2937   }
2938 
2939   InitializedEntity BaseEntity =
2940     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2941   InitializationKind Kind =
2942     InitList ? InitializationKind::CreateDirectList(BaseLoc)
2943              : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2944                                                 InitRange.getEnd());
2945   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2946   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
2947   if (BaseInit.isInvalid())
2948     return true;
2949 
2950   // C++11 [class.base.init]p7:
2951   //   The initialization of each base and member constitutes a
2952   //   full-expression.
2953   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
2954   if (BaseInit.isInvalid())
2955     return true;
2956 
2957   // If we are in a dependent context, template instantiation will
2958   // perform this type-checking again. Just save the arguments that we
2959   // received in a ParenListExpr.
2960   // FIXME: This isn't quite ideal, since our ASTs don't capture all
2961   // of the information that we have about the base
2962   // initializer. However, deconstructing the ASTs is a dicey process,
2963   // and this approach is far more likely to get the corner cases right.
2964   if (CurContext->isDependentContext())
2965     BaseInit = Init;
2966 
2967   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2968                                           BaseSpec->isVirtual(),
2969                                           InitRange.getBegin(),
2970                                           BaseInit.getAs<Expr>(),
2971                                           InitRange.getEnd(), EllipsisLoc);
2972 }
2973 
2974 // Create a static_cast\<T&&>(expr).
2975 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2976   if (T.isNull()) T = E->getType();
2977   QualType TargetType = SemaRef.BuildReferenceType(
2978       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
2979   SourceLocation ExprLoc = E->getLocStart();
2980   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2981       TargetType, ExprLoc);
2982 
2983   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2984                                    SourceRange(ExprLoc, ExprLoc),
2985                                    E->getSourceRange()).get();
2986 }
2987 
2988 /// ImplicitInitializerKind - How an implicit base or member initializer should
2989 /// initialize its base or member.
2990 enum ImplicitInitializerKind {
2991   IIK_Default,
2992   IIK_Copy,
2993   IIK_Move,
2994   IIK_Inherit
2995 };
2996 
2997 static bool
2998 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2999                              ImplicitInitializerKind ImplicitInitKind,
3000                              CXXBaseSpecifier *BaseSpec,
3001                              bool IsInheritedVirtualBase,
3002                              CXXCtorInitializer *&CXXBaseInit) {
3003   InitializedEntity InitEntity
3004     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3005                                         IsInheritedVirtualBase);
3006 
3007   ExprResult BaseInit;
3008 
3009   switch (ImplicitInitKind) {
3010   case IIK_Inherit: {
3011     const CXXRecordDecl *Inherited =
3012         Constructor->getInheritedConstructor()->getParent();
3013     const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3014     if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3015       // C++11 [class.inhctor]p8:
3016       //   Each expression in the expression-list is of the form
3017       //   static_cast<T&&>(p), where p is the name of the corresponding
3018       //   constructor parameter and T is the declared type of p.
3019       SmallVector<Expr*, 16> Args;
3020       for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3021         ParmVarDecl *PD = Constructor->getParamDecl(I);
3022         ExprResult ArgExpr =
3023             SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3024                                      VK_LValue, SourceLocation());
3025         if (ArgExpr.isInvalid())
3026           return true;
3027         Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
3028       }
3029 
3030       InitializationKind InitKind = InitializationKind::CreateDirect(
3031           Constructor->getLocation(), SourceLocation(), SourceLocation());
3032       InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
3033       BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3034       break;
3035     }
3036   }
3037   // Fall through.
3038   case IIK_Default: {
3039     InitializationKind InitKind
3040       = InitializationKind::CreateDefault(Constructor->getLocation());
3041     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3042     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3043     break;
3044   }
3045 
3046   case IIK_Move:
3047   case IIK_Copy: {
3048     bool Moving = ImplicitInitKind == IIK_Move;
3049     ParmVarDecl *Param = Constructor->getParamDecl(0);
3050     QualType ParamType = Param->getType().getNonReferenceType();
3051 
3052     Expr *CopyCtorArg =
3053       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3054                           SourceLocation(), Param, false,
3055                           Constructor->getLocation(), ParamType,
3056                           VK_LValue, nullptr);
3057 
3058     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3059 
3060     // Cast to the base class to avoid ambiguities.
3061     QualType ArgTy =
3062       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3063                                        ParamType.getQualifiers());
3064 
3065     if (Moving) {
3066       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3067     }
3068 
3069     CXXCastPath BasePath;
3070     BasePath.push_back(BaseSpec);
3071     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3072                                             CK_UncheckedDerivedToBase,
3073                                             Moving ? VK_XValue : VK_LValue,
3074                                             &BasePath).get();
3075 
3076     InitializationKind InitKind
3077       = InitializationKind::CreateDirect(Constructor->getLocation(),
3078                                          SourceLocation(), SourceLocation());
3079     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3080     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
3081     break;
3082   }
3083   }
3084 
3085   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
3086   if (BaseInit.isInvalid())
3087     return true;
3088 
3089   CXXBaseInit =
3090     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3091                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3092                                                         SourceLocation()),
3093                                              BaseSpec->isVirtual(),
3094                                              SourceLocation(),
3095                                              BaseInit.getAs<Expr>(),
3096                                              SourceLocation(),
3097                                              SourceLocation());
3098 
3099   return false;
3100 }
3101 
3102 static bool RefersToRValueRef(Expr *MemRef) {
3103   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3104   return Referenced->getType()->isRValueReferenceType();
3105 }
3106 
3107 static bool
3108 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3109                                ImplicitInitializerKind ImplicitInitKind,
3110                                FieldDecl *Field, IndirectFieldDecl *Indirect,
3111                                CXXCtorInitializer *&CXXMemberInit) {
3112   if (Field->isInvalidDecl())
3113     return true;
3114 
3115   SourceLocation Loc = Constructor->getLocation();
3116 
3117   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3118     bool Moving = ImplicitInitKind == IIK_Move;
3119     ParmVarDecl *Param = Constructor->getParamDecl(0);
3120     QualType ParamType = Param->getType().getNonReferenceType();
3121 
3122     // Suppress copying zero-width bitfields.
3123     if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3124       return false;
3125 
3126     Expr *MemberExprBase =
3127       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3128                           SourceLocation(), Param, false,
3129                           Loc, ParamType, VK_LValue, nullptr);
3130 
3131     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3132 
3133     if (Moving) {
3134       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3135     }
3136 
3137     // Build a reference to this field within the parameter.
3138     CXXScopeSpec SS;
3139     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3140                               Sema::LookupMemberName);
3141     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3142                                   : cast<ValueDecl>(Field), AS_public);
3143     MemberLookup.resolveKind();
3144     ExprResult CtorArg
3145       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
3146                                          ParamType, Loc,
3147                                          /*IsArrow=*/false,
3148                                          SS,
3149                                          /*TemplateKWLoc=*/SourceLocation(),
3150                                          /*FirstQualifierInScope=*/nullptr,
3151                                          MemberLookup,
3152                                          /*TemplateArgs=*/nullptr);
3153     if (CtorArg.isInvalid())
3154       return true;
3155 
3156     // C++11 [class.copy]p15:
3157     //   - if a member m has rvalue reference type T&&, it is direct-initialized
3158     //     with static_cast<T&&>(x.m);
3159     if (RefersToRValueRef(CtorArg.get())) {
3160       CtorArg = CastForMoving(SemaRef, CtorArg.get());
3161     }
3162 
3163     // When the field we are copying is an array, create index variables for
3164     // each dimension of the array. We use these index variables to subscript
3165     // the source array, and other clients (e.g., CodeGen) will perform the
3166     // necessary iteration with these index variables.
3167     SmallVector<VarDecl *, 4> IndexVariables;
3168     QualType BaseType = Field->getType();
3169     QualType SizeType = SemaRef.Context.getSizeType();
3170     bool InitializingArray = false;
3171     while (const ConstantArrayType *Array
3172                           = SemaRef.Context.getAsConstantArrayType(BaseType)) {
3173       InitializingArray = true;
3174       // Create the iteration variable for this array index.
3175       IdentifierInfo *IterationVarName = nullptr;
3176       {
3177         SmallString<8> Str;
3178         llvm::raw_svector_ostream OS(Str);
3179         OS << "__i" << IndexVariables.size();
3180         IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3181       }
3182       VarDecl *IterationVar
3183         = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
3184                           IterationVarName, SizeType,
3185                         SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
3186                           SC_None);
3187       IndexVariables.push_back(IterationVar);
3188 
3189       // Create a reference to the iteration variable.
3190       ExprResult IterationVarRef
3191         = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
3192       assert(!IterationVarRef.isInvalid() &&
3193              "Reference to invented variable cannot fail!");
3194       IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
3195       assert(!IterationVarRef.isInvalid() &&
3196              "Conversion of invented variable cannot fail!");
3197 
3198       // Subscript the array with this iteration variable.
3199       CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3200                                                         IterationVarRef.get(),
3201                                                         Loc);
3202       if (CtorArg.isInvalid())
3203         return true;
3204 
3205       BaseType = Array->getElementType();
3206     }
3207 
3208     // The array subscript expression is an lvalue, which is wrong for moving.
3209     if (Moving && InitializingArray)
3210       CtorArg = CastForMoving(SemaRef, CtorArg.get());
3211 
3212     // Construct the entity that we will be initializing. For an array, this
3213     // will be first element in the array, which may require several levels
3214     // of array-subscript entities.
3215     SmallVector<InitializedEntity, 4> Entities;
3216     Entities.reserve(1 + IndexVariables.size());
3217     if (Indirect)
3218       Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3219     else
3220       Entities.push_back(InitializedEntity::InitializeMember(Field));
3221     for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3222       Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3223                                                               0,
3224                                                               Entities.back()));
3225 
3226     // Direct-initialize to use the copy constructor.
3227     InitializationKind InitKind =
3228       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3229 
3230     Expr *CtorArgE = CtorArg.getAs<Expr>();
3231     InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
3232 
3233     ExprResult MemberInit
3234       = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
3235                         MultiExprArg(&CtorArgE, 1));
3236     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3237     if (MemberInit.isInvalid())
3238       return true;
3239 
3240     if (Indirect) {
3241       assert(IndexVariables.size() == 0 &&
3242              "Indirect field improperly initialized");
3243       CXXMemberInit
3244         = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3245                                                    Loc, Loc,
3246                                                    MemberInit.getAs<Expr>(),
3247                                                    Loc);
3248     } else
3249       CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3250                                                  Loc, MemberInit.getAs<Expr>(),
3251                                                  Loc,
3252                                                  IndexVariables.data(),
3253                                                  IndexVariables.size());
3254     return false;
3255   }
3256 
3257   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3258          "Unhandled implicit init kind!");
3259 
3260   QualType FieldBaseElementType =
3261     SemaRef.Context.getBaseElementType(Field->getType());
3262 
3263   if (FieldBaseElementType->isRecordType()) {
3264     InitializedEntity InitEntity
3265       = Indirect? InitializedEntity::InitializeMember(Indirect)
3266                 : InitializedEntity::InitializeMember(Field);
3267     InitializationKind InitKind =
3268       InitializationKind::CreateDefault(Loc);
3269 
3270     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3271     ExprResult MemberInit =
3272       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3273 
3274     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3275     if (MemberInit.isInvalid())
3276       return true;
3277 
3278     if (Indirect)
3279       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3280                                                                Indirect, Loc,
3281                                                                Loc,
3282                                                                MemberInit.get(),
3283                                                                Loc);
3284     else
3285       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3286                                                                Field, Loc, Loc,
3287                                                                MemberInit.get(),
3288                                                                Loc);
3289     return false;
3290   }
3291 
3292   if (!Field->getParent()->isUnion()) {
3293     if (FieldBaseElementType->isReferenceType()) {
3294       SemaRef.Diag(Constructor->getLocation(),
3295                    diag::err_uninitialized_member_in_ctor)
3296       << (int)Constructor->isImplicit()
3297       << SemaRef.Context.getTagDeclType(Constructor->getParent())
3298       << 0 << Field->getDeclName();
3299       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3300       return true;
3301     }
3302 
3303     if (FieldBaseElementType.isConstQualified()) {
3304       SemaRef.Diag(Constructor->getLocation(),
3305                    diag::err_uninitialized_member_in_ctor)
3306       << (int)Constructor->isImplicit()
3307       << SemaRef.Context.getTagDeclType(Constructor->getParent())
3308       << 1 << Field->getDeclName();
3309       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3310       return true;
3311     }
3312   }
3313 
3314   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
3315       FieldBaseElementType->isObjCRetainableType() &&
3316       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3317       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
3318     // ARC:
3319     //   Default-initialize Objective-C pointers to NULL.
3320     CXXMemberInit
3321       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3322                                                  Loc, Loc,
3323                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3324                                                  Loc);
3325     return false;
3326   }
3327 
3328   // Nothing to initialize.
3329   CXXMemberInit = nullptr;
3330   return false;
3331 }
3332 
3333 namespace {
3334 struct BaseAndFieldInfo {
3335   Sema &S;
3336   CXXConstructorDecl *Ctor;
3337   bool AnyErrorsInInits;
3338   ImplicitInitializerKind IIK;
3339   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
3340   SmallVector<CXXCtorInitializer*, 8> AllToInit;
3341   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
3342 
3343   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3344     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
3345     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3346     if (Generated && Ctor->isCopyConstructor())
3347       IIK = IIK_Copy;
3348     else if (Generated && Ctor->isMoveConstructor())
3349       IIK = IIK_Move;
3350     else if (Ctor->getInheritedConstructor())
3351       IIK = IIK_Inherit;
3352     else
3353       IIK = IIK_Default;
3354   }
3355 
3356   bool isImplicitCopyOrMove() const {
3357     switch (IIK) {
3358     case IIK_Copy:
3359     case IIK_Move:
3360       return true;
3361 
3362     case IIK_Default:
3363     case IIK_Inherit:
3364       return false;
3365     }
3366 
3367     llvm_unreachable("Invalid ImplicitInitializerKind!");
3368   }
3369 
3370   bool addFieldInitializer(CXXCtorInitializer *Init) {
3371     AllToInit.push_back(Init);
3372 
3373     // Check whether this initializer makes the field "used".
3374     if (Init->getInit()->HasSideEffects(S.Context))
3375       S.UnusedPrivateFields.remove(Init->getAnyMember());
3376 
3377     return false;
3378   }
3379 
3380   bool isInactiveUnionMember(FieldDecl *Field) {
3381     RecordDecl *Record = Field->getParent();
3382     if (!Record->isUnion())
3383       return false;
3384 
3385     if (FieldDecl *Active =
3386             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
3387       return Active != Field->getCanonicalDecl();
3388 
3389     // In an implicit copy or move constructor, ignore any in-class initializer.
3390     if (isImplicitCopyOrMove())
3391       return true;
3392 
3393     // If there's no explicit initialization, the field is active only if it
3394     // has an in-class initializer...
3395     if (Field->hasInClassInitializer())
3396       return false;
3397     // ... or it's an anonymous struct or union whose class has an in-class
3398     // initializer.
3399     if (!Field->isAnonymousStructOrUnion())
3400       return true;
3401     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3402     return !FieldRD->hasInClassInitializer();
3403   }
3404 
3405   /// \brief Determine whether the given field is, or is within, a union member
3406   /// that is inactive (because there was an initializer given for a different
3407   /// member of the union, or because the union was not initialized at all).
3408   bool isWithinInactiveUnionMember(FieldDecl *Field,
3409                                    IndirectFieldDecl *Indirect) {
3410     if (!Indirect)
3411       return isInactiveUnionMember(Field);
3412 
3413     for (auto *C : Indirect->chain()) {
3414       FieldDecl *Field = dyn_cast<FieldDecl>(C);
3415       if (Field && isInactiveUnionMember(Field))
3416         return true;
3417     }
3418     return false;
3419   }
3420 };
3421 }
3422 
3423 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
3424 /// array type.
3425 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3426   if (T->isIncompleteArrayType())
3427     return true;
3428 
3429   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3430     if (!ArrayT->getSize())
3431       return true;
3432 
3433     T = ArrayT->getElementType();
3434   }
3435 
3436   return false;
3437 }
3438 
3439 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
3440                                     FieldDecl *Field,
3441                                     IndirectFieldDecl *Indirect = nullptr) {
3442   if (Field->isInvalidDecl())
3443     return false;
3444 
3445   // Overwhelmingly common case: we have a direct initializer for this field.
3446   if (CXXCtorInitializer *Init =
3447           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
3448     return Info.addFieldInitializer(Init);
3449 
3450   // C++11 [class.base.init]p8:
3451   //   if the entity is a non-static data member that has a
3452   //   brace-or-equal-initializer and either
3453   //   -- the constructor's class is a union and no other variant member of that
3454   //      union is designated by a mem-initializer-id or
3455   //   -- the constructor's class is not a union, and, if the entity is a member
3456   //      of an anonymous union, no other member of that union is designated by
3457   //      a mem-initializer-id,
3458   //   the entity is initialized as specified in [dcl.init].
3459   //
3460   // We also apply the same rules to handle anonymous structs within anonymous
3461   // unions.
3462   if (Info.isWithinInactiveUnionMember(Field, Indirect))
3463     return false;
3464 
3465   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
3466     Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3467                                            Info.Ctor->getLocation(), Field);
3468     CXXCtorInitializer *Init;
3469     if (Indirect)
3470       Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3471                                                       SourceLocation(),
3472                                                       SourceLocation(), DIE,
3473                                                       SourceLocation());
3474     else
3475       Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3476                                                       SourceLocation(),
3477                                                       SourceLocation(), DIE,
3478                                                       SourceLocation());
3479     return Info.addFieldInitializer(Init);
3480   }
3481 
3482   // Don't initialize incomplete or zero-length arrays.
3483   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3484     return false;
3485 
3486   // Don't try to build an implicit initializer if there were semantic
3487   // errors in any of the initializers (and therefore we might be
3488   // missing some that the user actually wrote).
3489   if (Info.AnyErrorsInInits)
3490     return false;
3491 
3492   CXXCtorInitializer *Init = nullptr;
3493   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3494                                      Indirect, Init))
3495     return true;
3496 
3497   if (!Init)
3498     return false;
3499 
3500   return Info.addFieldInitializer(Init);
3501 }
3502 
3503 bool
3504 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3505                                CXXCtorInitializer *Initializer) {
3506   assert(Initializer->isDelegatingInitializer());
3507   Constructor->setNumCtorInitializers(1);
3508   CXXCtorInitializer **initializer =
3509     new (Context) CXXCtorInitializer*[1];
3510   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3511   Constructor->setCtorInitializers(initializer);
3512 
3513   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
3514     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
3515     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3516   }
3517 
3518   DelegatingCtorDecls.push_back(Constructor);
3519 
3520   return false;
3521 }
3522 
3523 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3524                                ArrayRef<CXXCtorInitializer *> Initializers) {
3525   if (Constructor->isDependentContext()) {
3526     // Just store the initializers as written, they will be checked during
3527     // instantiation.
3528     if (!Initializers.empty()) {
3529       Constructor->setNumCtorInitializers(Initializers.size());
3530       CXXCtorInitializer **baseOrMemberInitializers =
3531         new (Context) CXXCtorInitializer*[Initializers.size()];
3532       memcpy(baseOrMemberInitializers, Initializers.data(),
3533              Initializers.size() * sizeof(CXXCtorInitializer*));
3534       Constructor->setCtorInitializers(baseOrMemberInitializers);
3535     }
3536 
3537     // Let template instantiation know whether we had errors.
3538     if (AnyErrors)
3539       Constructor->setInvalidDecl();
3540 
3541     return false;
3542   }
3543 
3544   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
3545 
3546   // We need to build the initializer AST according to order of construction
3547   // and not what user specified in the Initializers list.
3548   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
3549   if (!ClassDecl)
3550     return true;
3551 
3552   bool HadError = false;
3553 
3554   for (unsigned i = 0; i < Initializers.size(); i++) {
3555     CXXCtorInitializer *Member = Initializers[i];
3556 
3557     if (Member->isBaseInitializer())
3558       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
3559     else {
3560       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
3561 
3562       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
3563         for (auto *C : F->chain()) {
3564           FieldDecl *FD = dyn_cast<FieldDecl>(C);
3565           if (FD && FD->getParent()->isUnion())
3566             Info.ActiveUnionMember.insert(std::make_pair(
3567                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3568         }
3569       } else if (FieldDecl *FD = Member->getMember()) {
3570         if (FD->getParent()->isUnion())
3571           Info.ActiveUnionMember.insert(std::make_pair(
3572               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3573       }
3574     }
3575   }
3576 
3577   // Keep track of the direct virtual bases.
3578   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3579   for (auto &I : ClassDecl->bases()) {
3580     if (I.isVirtual())
3581       DirectVBases.insert(&I);
3582   }
3583 
3584   // Push virtual bases before others.
3585   for (auto &VBase : ClassDecl->vbases()) {
3586     if (CXXCtorInitializer *Value
3587         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
3588       // [class.base.init]p7, per DR257:
3589       //   A mem-initializer where the mem-initializer-id names a virtual base
3590       //   class is ignored during execution of a constructor of any class that
3591       //   is not the most derived class.
3592       if (ClassDecl->isAbstract()) {
3593         // FIXME: Provide a fixit to remove the base specifier. This requires
3594         // tracking the location of the associated comma for a base specifier.
3595         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3596           << VBase.getType() << ClassDecl;
3597         DiagnoseAbstractType(ClassDecl);
3598       }
3599 
3600       Info.AllToInit.push_back(Value);
3601     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3602       // [class.base.init]p8, per DR257:
3603       //   If a given [...] base class is not named by a mem-initializer-id
3604       //   [...] and the entity is not a virtual base class of an abstract
3605       //   class, then [...] the entity is default-initialized.
3606       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
3607       CXXCtorInitializer *CXXBaseInit;
3608       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3609                                        &VBase, IsInheritedVirtualBase,
3610                                        CXXBaseInit)) {
3611         HadError = true;
3612         continue;
3613       }
3614 
3615       Info.AllToInit.push_back(CXXBaseInit);
3616     }
3617   }
3618 
3619   // Non-virtual bases.
3620   for (auto &Base : ClassDecl->bases()) {
3621     // Virtuals are in the virtual base list and already constructed.
3622     if (Base.isVirtual())
3623       continue;
3624 
3625     if (CXXCtorInitializer *Value
3626           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
3627       Info.AllToInit.push_back(Value);
3628     } else if (!AnyErrors) {
3629       CXXCtorInitializer *CXXBaseInit;
3630       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3631                                        &Base, /*IsInheritedVirtualBase=*/false,
3632                                        CXXBaseInit)) {
3633         HadError = true;
3634         continue;
3635       }
3636 
3637       Info.AllToInit.push_back(CXXBaseInit);
3638     }
3639   }
3640 
3641   // Fields.
3642   for (auto *Mem : ClassDecl->decls()) {
3643     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
3644       // C++ [class.bit]p2:
3645       //   A declaration for a bit-field that omits the identifier declares an
3646       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
3647       //   initialized.
3648       if (F->isUnnamedBitfield())
3649         continue;
3650 
3651       // If we're not generating the implicit copy/move constructor, then we'll
3652       // handle anonymous struct/union fields based on their individual
3653       // indirect fields.
3654       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
3655         continue;
3656 
3657       if (CollectFieldInitializer(*this, Info, F))
3658         HadError = true;
3659       continue;
3660     }
3661 
3662     // Beyond this point, we only consider default initialization.
3663     if (Info.isImplicitCopyOrMove())
3664       continue;
3665 
3666     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
3667       if (F->getType()->isIncompleteArrayType()) {
3668         assert(ClassDecl->hasFlexibleArrayMember() &&
3669                "Incomplete array type is not valid");
3670         continue;
3671       }
3672 
3673       // Initialize each field of an anonymous struct individually.
3674       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3675         HadError = true;
3676 
3677       continue;
3678     }
3679   }
3680 
3681   unsigned NumInitializers = Info.AllToInit.size();
3682   if (NumInitializers > 0) {
3683     Constructor->setNumCtorInitializers(NumInitializers);
3684     CXXCtorInitializer **baseOrMemberInitializers =
3685       new (Context) CXXCtorInitializer*[NumInitializers];
3686     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
3687            NumInitializers * sizeof(CXXCtorInitializer*));
3688     Constructor->setCtorInitializers(baseOrMemberInitializers);
3689 
3690     // Constructors implicitly reference the base and member
3691     // destructors.
3692     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3693                                            Constructor->getParent());
3694   }
3695 
3696   return HadError;
3697 }
3698 
3699 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
3700   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
3701     const RecordDecl *RD = RT->getDecl();
3702     if (RD->isAnonymousStructOrUnion()) {
3703       for (auto *Field : RD->fields())
3704         PopulateKeysForFields(Field, IdealInits);
3705       return;
3706     }
3707   }
3708   IdealInits.push_back(Field->getCanonicalDecl());
3709 }
3710 
3711 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3712   return Context.getCanonicalType(BaseType).getTypePtr();
3713 }
3714 
3715 static const void *GetKeyForMember(ASTContext &Context,
3716                                    CXXCtorInitializer *Member) {
3717   if (!Member->isAnyMemberInitializer())
3718     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
3719 
3720   return Member->getAnyMember()->getCanonicalDecl();
3721 }
3722 
3723 static void DiagnoseBaseOrMemInitializerOrder(
3724     Sema &SemaRef, const CXXConstructorDecl *Constructor,
3725     ArrayRef<CXXCtorInitializer *> Inits) {
3726   if (Constructor->getDeclContext()->isDependentContext())
3727     return;
3728 
3729   // Don't check initializers order unless the warning is enabled at the
3730   // location of at least one initializer.
3731   bool ShouldCheckOrder = false;
3732   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3733     CXXCtorInitializer *Init = Inits[InitIndex];
3734     if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3735                                          Init->getSourceLocation())
3736           != DiagnosticsEngine::Ignored) {
3737       ShouldCheckOrder = true;
3738       break;
3739     }
3740   }
3741   if (!ShouldCheckOrder)
3742     return;
3743 
3744   // Build the list of bases and members in the order that they'll
3745   // actually be initialized.  The explicit initializers should be in
3746   // this same order but may be missing things.
3747   SmallVector<const void*, 32> IdealInitKeys;
3748 
3749   const CXXRecordDecl *ClassDecl = Constructor->getParent();
3750 
3751   // 1. Virtual bases.
3752   for (const auto &VBase : ClassDecl->vbases())
3753     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
3754 
3755   // 2. Non-virtual bases.
3756   for (const auto &Base : ClassDecl->bases()) {
3757     if (Base.isVirtual())
3758       continue;
3759     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
3760   }
3761 
3762   // 3. Direct fields.
3763   for (auto *Field : ClassDecl->fields()) {
3764     if (Field->isUnnamedBitfield())
3765       continue;
3766 
3767     PopulateKeysForFields(Field, IdealInitKeys);
3768   }
3769 
3770   unsigned NumIdealInits = IdealInitKeys.size();
3771   unsigned IdealIndex = 0;
3772 
3773   CXXCtorInitializer *PrevInit = nullptr;
3774   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3775     CXXCtorInitializer *Init = Inits[InitIndex];
3776     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
3777 
3778     // Scan forward to try to find this initializer in the idealized
3779     // initializers list.
3780     for (; IdealIndex != NumIdealInits; ++IdealIndex)
3781       if (InitKey == IdealInitKeys[IdealIndex])
3782         break;
3783 
3784     // If we didn't find this initializer, it must be because we
3785     // scanned past it on a previous iteration.  That can only
3786     // happen if we're out of order;  emit a warning.
3787     if (IdealIndex == NumIdealInits && PrevInit) {
3788       Sema::SemaDiagnosticBuilder D =
3789         SemaRef.Diag(PrevInit->getSourceLocation(),
3790                      diag::warn_initializer_out_of_order);
3791 
3792       if (PrevInit->isAnyMemberInitializer())
3793         D << 0 << PrevInit->getAnyMember()->getDeclName();
3794       else
3795         D << 1 << PrevInit->getTypeSourceInfo()->getType();
3796 
3797       if (Init->isAnyMemberInitializer())
3798         D << 0 << Init->getAnyMember()->getDeclName();
3799       else
3800         D << 1 << Init->getTypeSourceInfo()->getType();
3801 
3802       // Move back to the initializer's location in the ideal list.
3803       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3804         if (InitKey == IdealInitKeys[IdealIndex])
3805           break;
3806 
3807       assert(IdealIndex != NumIdealInits &&
3808              "initializer not found in initializer list");
3809     }
3810 
3811     PrevInit = Init;
3812   }
3813 }
3814 
3815 namespace {
3816 bool CheckRedundantInit(Sema &S,
3817                         CXXCtorInitializer *Init,
3818                         CXXCtorInitializer *&PrevInit) {
3819   if (!PrevInit) {
3820     PrevInit = Init;
3821     return false;
3822   }
3823 
3824   if (FieldDecl *Field = Init->getAnyMember())
3825     S.Diag(Init->getSourceLocation(),
3826            diag::err_multiple_mem_initialization)
3827       << Field->getDeclName()
3828       << Init->getSourceRange();
3829   else {
3830     const Type *BaseClass = Init->getBaseClass();
3831     assert(BaseClass && "neither field nor base");
3832     S.Diag(Init->getSourceLocation(),
3833            diag::err_multiple_base_initialization)
3834       << QualType(BaseClass, 0)
3835       << Init->getSourceRange();
3836   }
3837   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3838     << 0 << PrevInit->getSourceRange();
3839 
3840   return true;
3841 }
3842 
3843 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
3844 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3845 
3846 bool CheckRedundantUnionInit(Sema &S,
3847                              CXXCtorInitializer *Init,
3848                              RedundantUnionMap &Unions) {
3849   FieldDecl *Field = Init->getAnyMember();
3850   RecordDecl *Parent = Field->getParent();
3851   NamedDecl *Child = Field;
3852 
3853   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
3854     if (Parent->isUnion()) {
3855       UnionEntry &En = Unions[Parent];
3856       if (En.first && En.first != Child) {
3857         S.Diag(Init->getSourceLocation(),
3858                diag::err_multiple_mem_union_initialization)
3859           << Field->getDeclName()
3860           << Init->getSourceRange();
3861         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3862           << 0 << En.second->getSourceRange();
3863         return true;
3864       }
3865       if (!En.first) {
3866         En.first = Child;
3867         En.second = Init;
3868       }
3869       if (!Parent->isAnonymousStructOrUnion())
3870         return false;
3871     }
3872 
3873     Child = Parent;
3874     Parent = cast<RecordDecl>(Parent->getDeclContext());
3875   }
3876 
3877   return false;
3878 }
3879 }
3880 
3881 /// ActOnMemInitializers - Handle the member initializers for a constructor.
3882 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
3883                                 SourceLocation ColonLoc,
3884                                 ArrayRef<CXXCtorInitializer*> MemInits,
3885                                 bool AnyErrors) {
3886   if (!ConstructorDecl)
3887     return;
3888 
3889   AdjustDeclIfTemplate(ConstructorDecl);
3890 
3891   CXXConstructorDecl *Constructor
3892     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
3893 
3894   if (!Constructor) {
3895     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3896     return;
3897   }
3898 
3899   // Mapping for the duplicate initializers check.
3900   // For member initializers, this is keyed with a FieldDecl*.
3901   // For base initializers, this is keyed with a Type*.
3902   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
3903 
3904   // Mapping for the inconsistent anonymous-union initializers check.
3905   RedundantUnionMap MemberUnions;
3906 
3907   bool HadError = false;
3908   for (unsigned i = 0; i < MemInits.size(); i++) {
3909     CXXCtorInitializer *Init = MemInits[i];
3910 
3911     // Set the source order index.
3912     Init->setSourceOrder(i);
3913 
3914     if (Init->isAnyMemberInitializer()) {
3915       const void *Key = GetKeyForMember(Context, Init);
3916       if (CheckRedundantInit(*this, Init, Members[Key]) ||
3917           CheckRedundantUnionInit(*this, Init, MemberUnions))
3918         HadError = true;
3919     } else if (Init->isBaseInitializer()) {
3920       const void *Key = GetKeyForMember(Context, Init);
3921       if (CheckRedundantInit(*this, Init, Members[Key]))
3922         HadError = true;
3923     } else {
3924       assert(Init->isDelegatingInitializer());
3925       // This must be the only initializer
3926       if (MemInits.size() != 1) {
3927         Diag(Init->getSourceLocation(),
3928              diag::err_delegating_initializer_alone)
3929           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
3930         // We will treat this as being the only initializer.
3931       }
3932       SetDelegatingInitializer(Constructor, MemInits[i]);
3933       // Return immediately as the initializer is set.
3934       return;
3935     }
3936   }
3937 
3938   if (HadError)
3939     return;
3940 
3941   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
3942 
3943   SetCtorInitializers(Constructor, AnyErrors, MemInits);
3944 
3945   DiagnoseUninitializedFields(*this, Constructor);
3946 }
3947 
3948 void
3949 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3950                                              CXXRecordDecl *ClassDecl) {
3951   // Ignore dependent contexts. Also ignore unions, since their members never
3952   // have destructors implicitly called.
3953   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
3954     return;
3955 
3956   // FIXME: all the access-control diagnostics are positioned on the
3957   // field/base declaration.  That's probably good; that said, the
3958   // user might reasonably want to know why the destructor is being
3959   // emitted, and we currently don't say.
3960 
3961   // Non-static data members.
3962   for (auto *Field : ClassDecl->fields()) {
3963     if (Field->isInvalidDecl())
3964       continue;
3965 
3966     // Don't destroy incomplete or zero-length arrays.
3967     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3968       continue;
3969 
3970     QualType FieldType = Context.getBaseElementType(Field->getType());
3971 
3972     const RecordType* RT = FieldType->getAs<RecordType>();
3973     if (!RT)
3974       continue;
3975 
3976     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3977     if (FieldClassDecl->isInvalidDecl())
3978       continue;
3979     if (FieldClassDecl->hasIrrelevantDestructor())
3980       continue;
3981     // The destructor for an implicit anonymous union member is never invoked.
3982     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3983       continue;
3984 
3985     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
3986     assert(Dtor && "No dtor found for FieldClassDecl!");
3987     CheckDestructorAccess(Field->getLocation(), Dtor,
3988                           PDiag(diag::err_access_dtor_field)
3989                             << Field->getDeclName()
3990                             << FieldType);
3991 
3992     MarkFunctionReferenced(Location, Dtor);
3993     DiagnoseUseOfDecl(Dtor, Location);
3994   }
3995 
3996   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3997 
3998   // Bases.
3999   for (const auto &Base : ClassDecl->bases()) {
4000     // Bases are always records in a well-formed non-dependent class.
4001     const RecordType *RT = Base.getType()->getAs<RecordType>();
4002 
4003     // Remember direct virtual bases.
4004     if (Base.isVirtual())
4005       DirectVirtualBases.insert(RT);
4006 
4007     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4008     // If our base class is invalid, we probably can't get its dtor anyway.
4009     if (BaseClassDecl->isInvalidDecl())
4010       continue;
4011     if (BaseClassDecl->hasIrrelevantDestructor())
4012       continue;
4013 
4014     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4015     assert(Dtor && "No dtor found for BaseClassDecl!");
4016 
4017     // FIXME: caret should be on the start of the class name
4018     CheckDestructorAccess(Base.getLocStart(), Dtor,
4019                           PDiag(diag::err_access_dtor_base)
4020                             << Base.getType()
4021                             << Base.getSourceRange(),
4022                           Context.getTypeDeclType(ClassDecl));
4023 
4024     MarkFunctionReferenced(Location, Dtor);
4025     DiagnoseUseOfDecl(Dtor, Location);
4026   }
4027 
4028   // Virtual bases.
4029   for (const auto &VBase : ClassDecl->vbases()) {
4030     // Bases are always records in a well-formed non-dependent class.
4031     const RecordType *RT = VBase.getType()->castAs<RecordType>();
4032 
4033     // Ignore direct virtual bases.
4034     if (DirectVirtualBases.count(RT))
4035       continue;
4036 
4037     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4038     // If our base class is invalid, we probably can't get its dtor anyway.
4039     if (BaseClassDecl->isInvalidDecl())
4040       continue;
4041     if (BaseClassDecl->hasIrrelevantDestructor())
4042       continue;
4043 
4044     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4045     assert(Dtor && "No dtor found for BaseClassDecl!");
4046     if (CheckDestructorAccess(
4047             ClassDecl->getLocation(), Dtor,
4048             PDiag(diag::err_access_dtor_vbase)
4049                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
4050             Context.getTypeDeclType(ClassDecl)) ==
4051         AR_accessible) {
4052       CheckDerivedToBaseConversion(
4053           Context.getTypeDeclType(ClassDecl), VBase.getType(),
4054           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4055           SourceRange(), DeclarationName(), nullptr);
4056     }
4057 
4058     MarkFunctionReferenced(Location, Dtor);
4059     DiagnoseUseOfDecl(Dtor, Location);
4060   }
4061 }
4062 
4063 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
4064   if (!CDtorDecl)
4065     return;
4066 
4067   if (CXXConstructorDecl *Constructor
4068       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
4069     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
4070     DiagnoseUninitializedFields(*this, Constructor);
4071   }
4072 }
4073 
4074 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4075                                   unsigned DiagID, AbstractDiagSelID SelID) {
4076   class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4077     unsigned DiagID;
4078     AbstractDiagSelID SelID;
4079 
4080   public:
4081     NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4082       : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
4083 
4084     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
4085       if (Suppressed) return;
4086       if (SelID == -1)
4087         S.Diag(Loc, DiagID) << T;
4088       else
4089         S.Diag(Loc, DiagID) << SelID << T;
4090     }
4091   } Diagnoser(DiagID, SelID);
4092 
4093   return RequireNonAbstractType(Loc, T, Diagnoser);
4094 }
4095 
4096 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4097                                   TypeDiagnoser &Diagnoser) {
4098   if (!getLangOpts().CPlusPlus)
4099     return false;
4100 
4101   if (const ArrayType *AT = Context.getAsArrayType(T))
4102     return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4103 
4104   if (const PointerType *PT = T->getAs<PointerType>()) {
4105     // Find the innermost pointer type.
4106     while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
4107       PT = T;
4108 
4109     if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
4110       return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4111   }
4112 
4113   const RecordType *RT = T->getAs<RecordType>();
4114   if (!RT)
4115     return false;
4116 
4117   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4118 
4119   // We can't answer whether something is abstract until it has a
4120   // definition.  If it's currently being defined, we'll walk back
4121   // over all the declarations when we have a full definition.
4122   const CXXRecordDecl *Def = RD->getDefinition();
4123   if (!Def || Def->isBeingDefined())
4124     return false;
4125 
4126   if (!RD->isAbstract())
4127     return false;
4128 
4129   Diagnoser.diagnose(*this, Loc, T);
4130   DiagnoseAbstractType(RD);
4131 
4132   return true;
4133 }
4134 
4135 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4136   // Check if we've already emitted the list of pure virtual functions
4137   // for this class.
4138   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
4139     return;
4140 
4141   // If the diagnostic is suppressed, don't emit the notes. We're only
4142   // going to emit them once, so try to attach them to a diagnostic we're
4143   // actually going to show.
4144   if (Diags.isLastDiagnosticIgnored())
4145     return;
4146 
4147   CXXFinalOverriderMap FinalOverriders;
4148   RD->getFinalOverriders(FinalOverriders);
4149 
4150   // Keep a set of seen pure methods so we won't diagnose the same method
4151   // more than once.
4152   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4153 
4154   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4155                                    MEnd = FinalOverriders.end();
4156        M != MEnd;
4157        ++M) {
4158     for (OverridingMethods::iterator SO = M->second.begin(),
4159                                   SOEnd = M->second.end();
4160          SO != SOEnd; ++SO) {
4161       // C++ [class.abstract]p4:
4162       //   A class is abstract if it contains or inherits at least one
4163       //   pure virtual function for which the final overrider is pure
4164       //   virtual.
4165 
4166       //
4167       if (SO->second.size() != 1)
4168         continue;
4169 
4170       if (!SO->second.front().Method->isPure())
4171         continue;
4172 
4173       if (!SeenPureMethods.insert(SO->second.front().Method))
4174         continue;
4175 
4176       Diag(SO->second.front().Method->getLocation(),
4177            diag::note_pure_virtual_function)
4178         << SO->second.front().Method->getDeclName() << RD->getDeclName();
4179     }
4180   }
4181 
4182   if (!PureVirtualClassDiagSet)
4183     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4184   PureVirtualClassDiagSet->insert(RD);
4185 }
4186 
4187 namespace {
4188 struct AbstractUsageInfo {
4189   Sema &S;
4190   CXXRecordDecl *Record;
4191   CanQualType AbstractType;
4192   bool Invalid;
4193 
4194   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4195     : S(S), Record(Record),
4196       AbstractType(S.Context.getCanonicalType(
4197                    S.Context.getTypeDeclType(Record))),
4198       Invalid(false) {}
4199 
4200   void DiagnoseAbstractType() {
4201     if (Invalid) return;
4202     S.DiagnoseAbstractType(Record);
4203     Invalid = true;
4204   }
4205 
4206   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4207 };
4208 
4209 struct CheckAbstractUsage {
4210   AbstractUsageInfo &Info;
4211   const NamedDecl *Ctx;
4212 
4213   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4214     : Info(Info), Ctx(Ctx) {}
4215 
4216   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4217     switch (TL.getTypeLocClass()) {
4218 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4219 #define TYPELOC(CLASS, PARENT) \
4220     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
4221 #include "clang/AST/TypeLocNodes.def"
4222     }
4223   }
4224 
4225   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4226     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
4227     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4228       if (!TL.getParam(I))
4229         continue;
4230 
4231       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
4232       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
4233     }
4234   }
4235 
4236   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4237     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4238   }
4239 
4240   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4241     // Visit the type parameters from a permissive context.
4242     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4243       TemplateArgumentLoc TAL = TL.getArgLoc(I);
4244       if (TAL.getArgument().getKind() == TemplateArgument::Type)
4245         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4246           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4247       // TODO: other template argument types?
4248     }
4249   }
4250 
4251   // Visit pointee types from a permissive context.
4252 #define CheckPolymorphic(Type) \
4253   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4254     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4255   }
4256   CheckPolymorphic(PointerTypeLoc)
4257   CheckPolymorphic(ReferenceTypeLoc)
4258   CheckPolymorphic(MemberPointerTypeLoc)
4259   CheckPolymorphic(BlockPointerTypeLoc)
4260   CheckPolymorphic(AtomicTypeLoc)
4261 
4262   /// Handle all the types we haven't given a more specific
4263   /// implementation for above.
4264   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4265     // Every other kind of type that we haven't called out already
4266     // that has an inner type is either (1) sugar or (2) contains that
4267     // inner type in some way as a subobject.
4268     if (TypeLoc Next = TL.getNextTypeLoc())
4269       return Visit(Next, Sel);
4270 
4271     // If there's no inner type and we're in a permissive context,
4272     // don't diagnose.
4273     if (Sel == Sema::AbstractNone) return;
4274 
4275     // Check whether the type matches the abstract type.
4276     QualType T = TL.getType();
4277     if (T->isArrayType()) {
4278       Sel = Sema::AbstractArrayType;
4279       T = Info.S.Context.getBaseElementType(T);
4280     }
4281     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4282     if (CT != Info.AbstractType) return;
4283 
4284     // It matched; do some magic.
4285     if (Sel == Sema::AbstractArrayType) {
4286       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4287         << T << TL.getSourceRange();
4288     } else {
4289       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4290         << Sel << T << TL.getSourceRange();
4291     }
4292     Info.DiagnoseAbstractType();
4293   }
4294 };
4295 
4296 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4297                                   Sema::AbstractDiagSelID Sel) {
4298   CheckAbstractUsage(*this, D).Visit(TL, Sel);
4299 }
4300 
4301 }
4302 
4303 /// Check for invalid uses of an abstract type in a method declaration.
4304 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4305                                     CXXMethodDecl *MD) {
4306   // No need to do the check on definitions, which require that
4307   // the return/param types be complete.
4308   if (MD->doesThisDeclarationHaveABody())
4309     return;
4310 
4311   // For safety's sake, just ignore it if we don't have type source
4312   // information.  This should never happen for non-implicit methods,
4313   // but...
4314   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4315     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4316 }
4317 
4318 /// Check for invalid uses of an abstract type within a class definition.
4319 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4320                                     CXXRecordDecl *RD) {
4321   for (auto *D : RD->decls()) {
4322     if (D->isImplicit()) continue;
4323 
4324     // Methods and method templates.
4325     if (isa<CXXMethodDecl>(D)) {
4326       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4327     } else if (isa<FunctionTemplateDecl>(D)) {
4328       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4329       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4330 
4331     // Fields and static variables.
4332     } else if (isa<FieldDecl>(D)) {
4333       FieldDecl *FD = cast<FieldDecl>(D);
4334       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4335         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4336     } else if (isa<VarDecl>(D)) {
4337       VarDecl *VD = cast<VarDecl>(D);
4338       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4339         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4340 
4341     // Nested classes and class templates.
4342     } else if (isa<CXXRecordDecl>(D)) {
4343       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4344     } else if (isa<ClassTemplateDecl>(D)) {
4345       CheckAbstractClassUsage(Info,
4346                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4347     }
4348   }
4349 }
4350 
4351 /// \brief Return a DLL attribute from the declaration.
4352 static InheritableAttr *getDLLAttr(Decl *D) {
4353   assert(!(D->hasAttr<DLLImportAttr>() && D->hasAttr<DLLExportAttr>()) &&
4354          "A declaration cannot be both dllimport and dllexport.");
4355   if (auto *Import = D->getAttr<DLLImportAttr>())
4356     return Import;
4357   if (auto *Export = D->getAttr<DLLExportAttr>())
4358     return Export;
4359   return nullptr;
4360 }
4361 
4362 /// \brief Check class-level dllimport/dllexport attribute.
4363 static void checkDLLAttribute(Sema &S, CXXRecordDecl *Class) {
4364   Attr *ClassAttr = getDLLAttr(Class);
4365   if (!ClassAttr)
4366     return;
4367 
4368   bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4369 
4370   // Force declaration of implicit members so they can inherit the attribute.
4371   S.ForceDeclarationOfImplicitMembers(Class);
4372 
4373   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4374   // seem to be true in practice?
4375 
4376   // FIXME: We also need to propagate the attribute upwards to class template
4377   // specialization bases.
4378 
4379   for (Decl *Member : Class->decls()) {
4380     if (!isa<CXXMethodDecl>(Member) && !isa<VarDecl>(Member))
4381       continue;
4382 
4383     if (InheritableAttr *MemberAttr = getDLLAttr(Member)) {
4384       if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4385           !MemberAttr->isInherited()) {
4386         S.Diag(MemberAttr->getLocation(),
4387                diag::err_attribute_dll_member_of_dll_class)
4388             << MemberAttr << ClassAttr;
4389         S.Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
4390         Member->setInvalidDecl();
4391         continue;
4392       }
4393     } else {
4394       auto *NewAttr =
4395           cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
4396       NewAttr->setInherited(true);
4397       Member->addAttr(NewAttr);
4398     }
4399 
4400     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) {
4401       if (ClassExported) {
4402         if (MD->isDeleted())
4403           continue;
4404 
4405         if (MD->isUserProvided()) {
4406           // Instantiate non-default methods.
4407           S.MarkFunctionReferenced(Class->getLocation(), MD);
4408         } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4409                    MD->isCopyAssignmentOperator() ||
4410                    MD->isMoveAssignmentOperator()) {
4411           // Instantiate non-trivial or explicitly defaulted methods, and the
4412           // copy assignment / move assignment operators.
4413           S.MarkFunctionReferenced(Class->getLocation(), MD);
4414           // Resolve its exception specification; CodeGen needs it.
4415           auto *FPT = MD->getType()->getAs<FunctionProtoType>();
4416           S.ResolveExceptionSpec(Class->getLocation(), FPT);
4417           S.ActOnFinishInlineMethodDef(MD);
4418         }
4419       }
4420     }
4421   }
4422 }
4423 
4424 /// \brief Perform semantic checks on a class definition that has been
4425 /// completing, introducing implicitly-declared members, checking for
4426 /// abstract types, etc.
4427 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
4428   if (!Record)
4429     return;
4430 
4431   if (Record->isAbstract() && !Record->isInvalidDecl()) {
4432     AbstractUsageInfo Info(*this, Record);
4433     CheckAbstractClassUsage(Info, Record);
4434   }
4435 
4436   // If this is not an aggregate type and has no user-declared constructor,
4437   // complain about any non-static data members of reference or const scalar
4438   // type, since they will never get initializers.
4439   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
4440       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4441       !Record->isLambda()) {
4442     bool Complained = false;
4443     for (const auto *F : Record->fields()) {
4444       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
4445         continue;
4446 
4447       if (F->getType()->isReferenceType() ||
4448           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
4449         if (!Complained) {
4450           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4451             << Record->getTagKind() << Record;
4452           Complained = true;
4453         }
4454 
4455         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4456           << F->getType()->isReferenceType()
4457           << F->getDeclName();
4458       }
4459     }
4460   }
4461 
4462   if (Record->isDynamicClass() && !Record->isDependentType())
4463     DynamicClasses.push_back(Record);
4464 
4465   if (Record->getIdentifier()) {
4466     // C++ [class.mem]p13:
4467     //   If T is the name of a class, then each of the following shall have a
4468     //   name different from T:
4469     //     - every member of every anonymous union that is a member of class T.
4470     //
4471     // C++ [class.mem]p14:
4472     //   In addition, if class T has a user-declared constructor (12.1), every
4473     //   non-static data member of class T shall have a name different from T.
4474     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4475     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4476          ++I) {
4477       NamedDecl *D = *I;
4478       if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4479           isa<IndirectFieldDecl>(D)) {
4480         Diag(D->getLocation(), diag::err_member_name_of_class)
4481           << D->getDeclName();
4482         break;
4483       }
4484     }
4485   }
4486 
4487   // Warn if the class has virtual methods but non-virtual public destructor.
4488   if (Record->isPolymorphic() && !Record->isDependentType()) {
4489     CXXDestructorDecl *dtor = Record->getDestructor();
4490     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4491         !Record->hasAttr<FinalAttr>())
4492       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4493            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4494   }
4495 
4496   if (Record->isAbstract()) {
4497     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4498       Diag(Record->getLocation(), diag::warn_abstract_final_class)
4499         << FA->isSpelledAsSealed();
4500       DiagnoseAbstractType(Record);
4501     }
4502   }
4503 
4504   if (!Record->isDependentType()) {
4505     for (auto *M : Record->methods()) {
4506       // See if a method overloads virtual methods in a base
4507       // class without overriding any.
4508       if (!M->isStatic())
4509         DiagnoseHiddenVirtualMethods(M);
4510 
4511       // Check whether the explicitly-defaulted special members are valid.
4512       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4513         CheckExplicitlyDefaultedSpecialMember(M);
4514 
4515       // For an explicitly defaulted or deleted special member, we defer
4516       // determining triviality until the class is complete. That time is now!
4517       if (!M->isImplicit() && !M->isUserProvided()) {
4518         CXXSpecialMember CSM = getSpecialMember(M);
4519         if (CSM != CXXInvalid) {
4520           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
4521 
4522           // Inform the class that we've finished declaring this member.
4523           Record->finishedDefaultedOrDeletedMember(M);
4524         }
4525       }
4526     }
4527   }
4528 
4529   // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4530   // function that is not a constructor declares that member function to be
4531   // const. [...] The class of which that function is a member shall be
4532   // a literal type.
4533   //
4534   // If the class has virtual bases, any constexpr members will already have
4535   // been diagnosed by the checks performed on the member declaration, so
4536   // suppress this (less useful) diagnostic.
4537   //
4538   // We delay this until we know whether an explicitly-defaulted (or deleted)
4539   // destructor for the class is trivial.
4540   if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
4541       !Record->isLiteral() && !Record->getNumVBases()) {
4542     for (const auto *M : Record->methods()) {
4543       if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) {
4544         switch (Record->getTemplateSpecializationKind()) {
4545         case TSK_ImplicitInstantiation:
4546         case TSK_ExplicitInstantiationDeclaration:
4547         case TSK_ExplicitInstantiationDefinition:
4548           // If a template instantiates to a non-literal type, but its members
4549           // instantiate to constexpr functions, the template is technically
4550           // ill-formed, but we allow it for sanity.
4551           continue;
4552 
4553         case TSK_Undeclared:
4554         case TSK_ExplicitSpecialization:
4555           RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4556                              diag::err_constexpr_method_non_literal);
4557           break;
4558         }
4559 
4560         // Only produce one error per class.
4561         break;
4562       }
4563     }
4564   }
4565 
4566   // ms_struct is a request to use the same ABI rules as MSVC.  Check
4567   // whether this class uses any C++ features that are implemented
4568   // completely differently in MSVC, and if so, emit a diagnostic.
4569   // That diagnostic defaults to an error, but we allow projects to
4570   // map it down to a warning (or ignore it).  It's a fairly common
4571   // practice among users of the ms_struct pragma to mass-annotate
4572   // headers, sweeping up a bunch of types that the project doesn't
4573   // really rely on MSVC-compatible layout for.  We must therefore
4574   // support "ms_struct except for C++ stuff" as a secondary ABI.
4575   if (Record->isMsStruct(Context) &&
4576       (Record->isPolymorphic() || Record->getNumBases())) {
4577     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
4578   }
4579 
4580   // Declare inheriting constructors. We do this eagerly here because:
4581   // - The standard requires an eager diagnostic for conflicting inheriting
4582   //   constructors from different classes.
4583   // - The lazy declaration of the other implicit constructors is so as to not
4584   //   waste space and performance on classes that are not meant to be
4585   //   instantiated (e.g. meta-functions). This doesn't apply to classes that
4586   //   have inheriting constructors.
4587   DeclareInheritingConstructors(Record);
4588 
4589   checkDLLAttribute(*this, Record);
4590 }
4591 
4592 /// Look up the special member function that would be called by a special
4593 /// member function for a subobject of class type.
4594 ///
4595 /// \param Class The class type of the subobject.
4596 /// \param CSM The kind of special member function.
4597 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4598 /// \param ConstRHS True if this is a copy operation with a const object
4599 ///        on its RHS, that is, if the argument to the outer special member
4600 ///        function is 'const' and this is not a field marked 'mutable'.
4601 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
4602     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
4603     unsigned FieldQuals, bool ConstRHS) {
4604   unsigned LHSQuals = 0;
4605   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
4606     LHSQuals = FieldQuals;
4607 
4608   unsigned RHSQuals = FieldQuals;
4609   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4610     RHSQuals = 0;
4611   else if (ConstRHS)
4612     RHSQuals |= Qualifiers::Const;
4613 
4614   return S.LookupSpecialMember(Class, CSM,
4615                                RHSQuals & Qualifiers::Const,
4616                                RHSQuals & Qualifiers::Volatile,
4617                                false,
4618                                LHSQuals & Qualifiers::Const,
4619                                LHSQuals & Qualifiers::Volatile);
4620 }
4621 
4622 /// Is the special member function which would be selected to perform the
4623 /// specified operation on the specified class type a constexpr constructor?
4624 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4625                                      Sema::CXXSpecialMember CSM,
4626                                      unsigned Quals, bool ConstRHS) {
4627   Sema::SpecialMemberOverloadResult *SMOR =
4628       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
4629   if (!SMOR || !SMOR->getMethod())
4630     // A constructor we wouldn't select can't be "involved in initializing"
4631     // anything.
4632     return true;
4633   return SMOR->getMethod()->isConstexpr();
4634 }
4635 
4636 /// Determine whether the specified special member function would be constexpr
4637 /// if it were implicitly defined.
4638 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4639                                               Sema::CXXSpecialMember CSM,
4640                                               bool ConstArg) {
4641   if (!S.getLangOpts().CPlusPlus11)
4642     return false;
4643 
4644   // C++11 [dcl.constexpr]p4:
4645   // In the definition of a constexpr constructor [...]
4646   bool Ctor = true;
4647   switch (CSM) {
4648   case Sema::CXXDefaultConstructor:
4649     // Since default constructor lookup is essentially trivial (and cannot
4650     // involve, for instance, template instantiation), we compute whether a
4651     // defaulted default constructor is constexpr directly within CXXRecordDecl.
4652     //
4653     // This is important for performance; we need to know whether the default
4654     // constructor is constexpr to determine whether the type is a literal type.
4655     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4656 
4657   case Sema::CXXCopyConstructor:
4658   case Sema::CXXMoveConstructor:
4659     // For copy or move constructors, we need to perform overload resolution.
4660     break;
4661 
4662   case Sema::CXXCopyAssignment:
4663   case Sema::CXXMoveAssignment:
4664     if (!S.getLangOpts().CPlusPlus1y)
4665       return false;
4666     // In C++1y, we need to perform overload resolution.
4667     Ctor = false;
4668     break;
4669 
4670   case Sema::CXXDestructor:
4671   case Sema::CXXInvalid:
4672     return false;
4673   }
4674 
4675   //   -- if the class is a non-empty union, or for each non-empty anonymous
4676   //      union member of a non-union class, exactly one non-static data member
4677   //      shall be initialized; [DR1359]
4678   //
4679   // If we squint, this is guaranteed, since exactly one non-static data member
4680   // will be initialized (if the constructor isn't deleted), we just don't know
4681   // which one.
4682   if (Ctor && ClassDecl->isUnion())
4683     return true;
4684 
4685   //   -- the class shall not have any virtual base classes;
4686   if (Ctor && ClassDecl->getNumVBases())
4687     return false;
4688 
4689   // C++1y [class.copy]p26:
4690   //   -- [the class] is a literal type, and
4691   if (!Ctor && !ClassDecl->isLiteral())
4692     return false;
4693 
4694   //   -- every constructor involved in initializing [...] base class
4695   //      sub-objects shall be a constexpr constructor;
4696   //   -- the assignment operator selected to copy/move each direct base
4697   //      class is a constexpr function, and
4698   for (const auto &B : ClassDecl->bases()) {
4699     const RecordType *BaseType = B.getType()->getAs<RecordType>();
4700     if (!BaseType) continue;
4701 
4702     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4703     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
4704       return false;
4705   }
4706 
4707   //   -- every constructor involved in initializing non-static data members
4708   //      [...] shall be a constexpr constructor;
4709   //   -- every non-static data member and base class sub-object shall be
4710   //      initialized
4711   //   -- for each non-static data member of X that is of class type (or array
4712   //      thereof), the assignment operator selected to copy/move that member is
4713   //      a constexpr function
4714   for (const auto *F : ClassDecl->fields()) {
4715     if (F->isInvalidDecl())
4716       continue;
4717     QualType BaseType = S.Context.getBaseElementType(F->getType());
4718     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
4719       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4720       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
4721                                     BaseType.getCVRQualifiers(),
4722                                     ConstArg && !F->isMutable()))
4723         return false;
4724     }
4725   }
4726 
4727   // All OK, it's constexpr!
4728   return true;
4729 }
4730 
4731 static Sema::ImplicitExceptionSpecification
4732 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4733   switch (S.getSpecialMember(MD)) {
4734   case Sema::CXXDefaultConstructor:
4735     return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4736   case Sema::CXXCopyConstructor:
4737     return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4738   case Sema::CXXCopyAssignment:
4739     return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4740   case Sema::CXXMoveConstructor:
4741     return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4742   case Sema::CXXMoveAssignment:
4743     return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4744   case Sema::CXXDestructor:
4745     return S.ComputeDefaultedDtorExceptionSpec(MD);
4746   case Sema::CXXInvalid:
4747     break;
4748   }
4749   assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4750          "only special members have implicit exception specs");
4751   return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
4752 }
4753 
4754 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4755                                                             CXXMethodDecl *MD) {
4756   FunctionProtoType::ExtProtoInfo EPI;
4757 
4758   // Build an exception specification pointing back at this member.
4759   EPI.ExceptionSpecType = EST_Unevaluated;
4760   EPI.ExceptionSpecDecl = MD;
4761 
4762   // Set the calling convention to the default for C++ instance methods.
4763   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4764       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4765                                             /*IsCXXMethod=*/true));
4766   return EPI;
4767 }
4768 
4769 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4770   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4771   if (FPT->getExceptionSpecType() != EST_Unevaluated)
4772     return;
4773 
4774   // Evaluate the exception specification.
4775   ImplicitExceptionSpecification ExceptSpec =
4776       computeImplicitExceptionSpec(*this, Loc, MD);
4777 
4778   FunctionProtoType::ExtProtoInfo EPI;
4779   ExceptSpec.getEPI(EPI);
4780 
4781   // Update the type of the special member to use it.
4782   UpdateExceptionSpec(MD, EPI);
4783 
4784   // A user-provided destructor can be defined outside the class. When that
4785   // happens, be sure to update the exception specification on both
4786   // declarations.
4787   const FunctionProtoType *CanonicalFPT =
4788     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4789   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4790     UpdateExceptionSpec(MD->getCanonicalDecl(), EPI);
4791 }
4792 
4793 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4794   CXXRecordDecl *RD = MD->getParent();
4795   CXXSpecialMember CSM = getSpecialMember(MD);
4796 
4797   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4798          "not an explicitly-defaulted special member");
4799 
4800   // Whether this was the first-declared instance of the constructor.
4801   // This affects whether we implicitly add an exception spec and constexpr.
4802   bool First = MD == MD->getCanonicalDecl();
4803 
4804   bool HadError = false;
4805 
4806   // C++11 [dcl.fct.def.default]p1:
4807   //   A function that is explicitly defaulted shall
4808   //     -- be a special member function (checked elsewhere),
4809   //     -- have the same type (except for ref-qualifiers, and except that a
4810   //        copy operation can take a non-const reference) as an implicit
4811   //        declaration, and
4812   //     -- not have default arguments.
4813   unsigned ExpectedParams = 1;
4814   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4815     ExpectedParams = 0;
4816   if (MD->getNumParams() != ExpectedParams) {
4817     // This also checks for default arguments: a copy or move constructor with a
4818     // default argument is classified as a default constructor, and assignment
4819     // operations and destructors can't have default arguments.
4820     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4821       << CSM << MD->getSourceRange();
4822     HadError = true;
4823   } else if (MD->isVariadic()) {
4824     Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4825       << CSM << MD->getSourceRange();
4826     HadError = true;
4827   }
4828 
4829   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
4830 
4831   bool CanHaveConstParam = false;
4832   if (CSM == CXXCopyConstructor)
4833     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
4834   else if (CSM == CXXCopyAssignment)
4835     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
4836 
4837   QualType ReturnType = Context.VoidTy;
4838   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4839     // Check for return type matching.
4840     ReturnType = Type->getReturnType();
4841     QualType ExpectedReturnType =
4842         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4843     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4844       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4845         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4846       HadError = true;
4847     }
4848 
4849     // A defaulted special member cannot have cv-qualifiers.
4850     if (Type->getTypeQuals()) {
4851       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4852         << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
4853       HadError = true;
4854     }
4855   }
4856 
4857   // Check for parameter type matching.
4858   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
4859   bool HasConstParam = false;
4860   if (ExpectedParams && ArgType->isReferenceType()) {
4861     // Argument must be reference to possibly-const T.
4862     QualType ReferentType = ArgType->getPointeeType();
4863     HasConstParam = ReferentType.isConstQualified();
4864 
4865     if (ReferentType.isVolatileQualified()) {
4866       Diag(MD->getLocation(),
4867            diag::err_defaulted_special_member_volatile_param) << CSM;
4868       HadError = true;
4869     }
4870 
4871     if (HasConstParam && !CanHaveConstParam) {
4872       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4873         Diag(MD->getLocation(),
4874              diag::err_defaulted_special_member_copy_const_param)
4875           << (CSM == CXXCopyAssignment);
4876         // FIXME: Explain why this special member can't be const.
4877       } else {
4878         Diag(MD->getLocation(),
4879              diag::err_defaulted_special_member_move_const_param)
4880           << (CSM == CXXMoveAssignment);
4881       }
4882       HadError = true;
4883     }
4884   } else if (ExpectedParams) {
4885     // A copy assignment operator can take its argument by value, but a
4886     // defaulted one cannot.
4887     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
4888     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
4889     HadError = true;
4890   }
4891 
4892   // C++11 [dcl.fct.def.default]p2:
4893   //   An explicitly-defaulted function may be declared constexpr only if it
4894   //   would have been implicitly declared as constexpr,
4895   // Do not apply this rule to members of class templates, since core issue 1358
4896   // makes such functions always instantiate to constexpr functions. For
4897   // functions which cannot be constexpr (for non-constructors in C++11 and for
4898   // destructors in C++1y), this is checked elsewhere.
4899   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4900                                                      HasConstParam);
4901   if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4902                                  : isa<CXXConstructorDecl>(MD)) &&
4903       MD->isConstexpr() && !Constexpr &&
4904       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4905     Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
4906     // FIXME: Explain why the special member can't be constexpr.
4907     HadError = true;
4908   }
4909 
4910   //   and may have an explicit exception-specification only if it is compatible
4911   //   with the exception-specification on the implicit declaration.
4912   if (Type->hasExceptionSpec()) {
4913     // Delay the check if this is the first declaration of the special member,
4914     // since we may not have parsed some necessary in-class initializers yet.
4915     if (First) {
4916       // If the exception specification needs to be instantiated, do so now,
4917       // before we clobber it with an EST_Unevaluated specification below.
4918       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4919         InstantiateExceptionSpec(MD->getLocStart(), MD);
4920         Type = MD->getType()->getAs<FunctionProtoType>();
4921       }
4922       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
4923     } else
4924       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4925   }
4926 
4927   //   If a function is explicitly defaulted on its first declaration,
4928   if (First) {
4929     //  -- it is implicitly considered to be constexpr if the implicit
4930     //     definition would be,
4931     MD->setConstexpr(Constexpr);
4932 
4933     //  -- it is implicitly considered to have the same exception-specification
4934     //     as if it had been implicitly declared,
4935     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4936     EPI.ExceptionSpecType = EST_Unevaluated;
4937     EPI.ExceptionSpecDecl = MD;
4938     MD->setType(Context.getFunctionType(ReturnType,
4939                                         ArrayRef<QualType>(&ArgType,
4940                                                            ExpectedParams),
4941                                         EPI));
4942   }
4943 
4944   if (ShouldDeleteSpecialMember(MD, CSM)) {
4945     if (First) {
4946       SetDeclDeleted(MD, MD->getLocation());
4947     } else {
4948       // C++11 [dcl.fct.def.default]p4:
4949       //   [For a] user-provided explicitly-defaulted function [...] if such a
4950       //   function is implicitly defined as deleted, the program is ill-formed.
4951       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4952       ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
4953       HadError = true;
4954     }
4955   }
4956 
4957   if (HadError)
4958     MD->setInvalidDecl();
4959 }
4960 
4961 /// Check whether the exception specification provided for an
4962 /// explicitly-defaulted special member matches the exception specification
4963 /// that would have been generated for an implicit special member, per
4964 /// C++11 [dcl.fct.def.default]p2.
4965 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4966     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4967   // Compute the implicit exception specification.
4968   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4969                                                        /*IsCXXMethod=*/true);
4970   FunctionProtoType::ExtProtoInfo EPI(CC);
4971   computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4972   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
4973     Context.getFunctionType(Context.VoidTy, None, EPI));
4974 
4975   // Ensure that it matches.
4976   CheckEquivalentExceptionSpec(
4977     PDiag(diag::err_incorrect_defaulted_exception_spec)
4978       << getSpecialMember(MD), PDiag(),
4979     ImplicitType, SourceLocation(),
4980     SpecifiedType, MD->getLocation());
4981 }
4982 
4983 void Sema::CheckDelayedMemberExceptionSpecs() {
4984   SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
4985               2> Checks;
4986   SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
4987 
4988   std::swap(Checks, DelayedDestructorExceptionSpecChecks);
4989   std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
4990 
4991   // Perform any deferred checking of exception specifications for virtual
4992   // destructors.
4993   for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
4994     const CXXDestructorDecl *Dtor = Checks[i].first;
4995     assert(!Dtor->getParent()->isDependentType() &&
4996            "Should not ever add destructors of templates into the list.");
4997     CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
4998   }
4999 
5000   // Check that any explicitly-defaulted methods have exception specifications
5001   // compatible with their implicit exception specifications.
5002   for (unsigned I = 0, N = Specs.size(); I != N; ++I)
5003     CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
5004                                                 Specs[I].second);
5005 }
5006 
5007 namespace {
5008 struct SpecialMemberDeletionInfo {
5009   Sema &S;
5010   CXXMethodDecl *MD;
5011   Sema::CXXSpecialMember CSM;
5012   bool Diagnose;
5013 
5014   // Properties of the special member, computed for convenience.
5015   bool IsConstructor, IsAssignment, IsMove, ConstArg;
5016   SourceLocation Loc;
5017 
5018   bool AllFieldsAreConst;
5019 
5020   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
5021                             Sema::CXXSpecialMember CSM, bool Diagnose)
5022     : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
5023       IsConstructor(false), IsAssignment(false), IsMove(false),
5024       ConstArg(false), Loc(MD->getLocation()),
5025       AllFieldsAreConst(true) {
5026     switch (CSM) {
5027       case Sema::CXXDefaultConstructor:
5028       case Sema::CXXCopyConstructor:
5029         IsConstructor = true;
5030         break;
5031       case Sema::CXXMoveConstructor:
5032         IsConstructor = true;
5033         IsMove = true;
5034         break;
5035       case Sema::CXXCopyAssignment:
5036         IsAssignment = true;
5037         break;
5038       case Sema::CXXMoveAssignment:
5039         IsAssignment = true;
5040         IsMove = true;
5041         break;
5042       case Sema::CXXDestructor:
5043         break;
5044       case Sema::CXXInvalid:
5045         llvm_unreachable("invalid special member kind");
5046     }
5047 
5048     if (MD->getNumParams()) {
5049       if (const ReferenceType *RT =
5050               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5051         ConstArg = RT->getPointeeType().isConstQualified();
5052     }
5053   }
5054 
5055   bool inUnion() const { return MD->getParent()->isUnion(); }
5056 
5057   /// Look up the corresponding special member in the given class.
5058   Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
5059                                               unsigned Quals, bool IsMutable) {
5060     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5061                                        ConstArg && !IsMutable);
5062   }
5063 
5064   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
5065 
5066   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
5067   bool shouldDeleteForField(FieldDecl *FD);
5068   bool shouldDeleteForAllConstMembers();
5069 
5070   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5071                                      unsigned Quals);
5072   bool shouldDeleteForSubobjectCall(Subobject Subobj,
5073                                     Sema::SpecialMemberOverloadResult *SMOR,
5074                                     bool IsDtorCallInCtor);
5075 
5076   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
5077 };
5078 }
5079 
5080 /// Is the given special member inaccessible when used on the given
5081 /// sub-object.
5082 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5083                                              CXXMethodDecl *target) {
5084   /// If we're operating on a base class, the object type is the
5085   /// type of this special member.
5086   QualType objectTy;
5087   AccessSpecifier access = target->getAccess();
5088   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5089     objectTy = S.Context.getTypeDeclType(MD->getParent());
5090     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5091 
5092   // If we're operating on a field, the object type is the type of the field.
5093   } else {
5094     objectTy = S.Context.getTypeDeclType(target->getParent());
5095   }
5096 
5097   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5098 }
5099 
5100 /// Check whether we should delete a special member due to the implicit
5101 /// definition containing a call to a special member of a subobject.
5102 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5103     Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5104     bool IsDtorCallInCtor) {
5105   CXXMethodDecl *Decl = SMOR->getMethod();
5106   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5107 
5108   int DiagKind = -1;
5109 
5110   if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5111     DiagKind = !Decl ? 0 : 1;
5112   else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5113     DiagKind = 2;
5114   else if (!isAccessible(Subobj, Decl))
5115     DiagKind = 3;
5116   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5117            !Decl->isTrivial()) {
5118     // A member of a union must have a trivial corresponding special member.
5119     // As a weird special case, a destructor call from a union's constructor
5120     // must be accessible and non-deleted, but need not be trivial. Such a
5121     // destructor is never actually called, but is semantically checked as
5122     // if it were.
5123     DiagKind = 4;
5124   }
5125 
5126   if (DiagKind == -1)
5127     return false;
5128 
5129   if (Diagnose) {
5130     if (Field) {
5131       S.Diag(Field->getLocation(),
5132              diag::note_deleted_special_member_class_subobject)
5133         << CSM << MD->getParent() << /*IsField*/true
5134         << Field << DiagKind << IsDtorCallInCtor;
5135     } else {
5136       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5137       S.Diag(Base->getLocStart(),
5138              diag::note_deleted_special_member_class_subobject)
5139         << CSM << MD->getParent() << /*IsField*/false
5140         << Base->getType() << DiagKind << IsDtorCallInCtor;
5141     }
5142 
5143     if (DiagKind == 1)
5144       S.NoteDeletedFunction(Decl);
5145     // FIXME: Explain inaccessibility if DiagKind == 3.
5146   }
5147 
5148   return true;
5149 }
5150 
5151 /// Check whether we should delete a special member function due to having a
5152 /// direct or virtual base class or non-static data member of class type M.
5153 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
5154     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
5155   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5156   bool IsMutable = Field && Field->isMutable();
5157 
5158   // C++11 [class.ctor]p5:
5159   // -- any direct or virtual base class, or non-static data member with no
5160   //    brace-or-equal-initializer, has class type M (or array thereof) and
5161   //    either M has no default constructor or overload resolution as applied
5162   //    to M's default constructor results in an ambiguity or in a function
5163   //    that is deleted or inaccessible
5164   // C++11 [class.copy]p11, C++11 [class.copy]p23:
5165   // -- a direct or virtual base class B that cannot be copied/moved because
5166   //    overload resolution, as applied to B's corresponding special member,
5167   //    results in an ambiguity or a function that is deleted or inaccessible
5168   //    from the defaulted special member
5169   // C++11 [class.dtor]p5:
5170   // -- any direct or virtual base class [...] has a type with a destructor
5171   //    that is deleted or inaccessible
5172   if (!(CSM == Sema::CXXDefaultConstructor &&
5173         Field && Field->hasInClassInitializer()) &&
5174       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5175                                    false))
5176     return true;
5177 
5178   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5179   // -- any direct or virtual base class or non-static data member has a
5180   //    type with a destructor that is deleted or inaccessible
5181   if (IsConstructor) {
5182     Sema::SpecialMemberOverloadResult *SMOR =
5183         S.LookupSpecialMember(Class, Sema::CXXDestructor,
5184                               false, false, false, false, false);
5185     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5186       return true;
5187   }
5188 
5189   return false;
5190 }
5191 
5192 /// Check whether we should delete a special member function due to the class
5193 /// having a particular direct or virtual base class.
5194 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
5195   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
5196   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
5197 }
5198 
5199 /// Check whether we should delete a special member function due to the class
5200 /// having a particular non-static data member.
5201 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5202   QualType FieldType = S.Context.getBaseElementType(FD->getType());
5203   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5204 
5205   if (CSM == Sema::CXXDefaultConstructor) {
5206     // For a default constructor, all references must be initialized in-class
5207     // and, if a union, it must have a non-const member.
5208     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5209       if (Diagnose)
5210         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5211           << MD->getParent() << FD << FieldType << /*Reference*/0;
5212       return true;
5213     }
5214     // C++11 [class.ctor]p5: any non-variant non-static data member of
5215     // const-qualified type (or array thereof) with no
5216     // brace-or-equal-initializer does not have a user-provided default
5217     // constructor.
5218     if (!inUnion() && FieldType.isConstQualified() &&
5219         !FD->hasInClassInitializer() &&
5220         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5221       if (Diagnose)
5222         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5223           << MD->getParent() << FD << FD->getType() << /*Const*/1;
5224       return true;
5225     }
5226 
5227     if (inUnion() && !FieldType.isConstQualified())
5228       AllFieldsAreConst = false;
5229   } else if (CSM == Sema::CXXCopyConstructor) {
5230     // For a copy constructor, data members must not be of rvalue reference
5231     // type.
5232     if (FieldType->isRValueReferenceType()) {
5233       if (Diagnose)
5234         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5235           << MD->getParent() << FD << FieldType;
5236       return true;
5237     }
5238   } else if (IsAssignment) {
5239     // For an assignment operator, data members must not be of reference type.
5240     if (FieldType->isReferenceType()) {
5241       if (Diagnose)
5242         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5243           << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
5244       return true;
5245     }
5246     if (!FieldRecord && FieldType.isConstQualified()) {
5247       // C++11 [class.copy]p23:
5248       // -- a non-static data member of const non-class type (or array thereof)
5249       if (Diagnose)
5250         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5251           << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
5252       return true;
5253     }
5254   }
5255 
5256   if (FieldRecord) {
5257     // Some additional restrictions exist on the variant members.
5258     if (!inUnion() && FieldRecord->isUnion() &&
5259         FieldRecord->isAnonymousStructOrUnion()) {
5260       bool AllVariantFieldsAreConst = true;
5261 
5262       // FIXME: Handle anonymous unions declared within anonymous unions.
5263       for (auto *UI : FieldRecord->fields()) {
5264         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
5265 
5266         if (!UnionFieldType.isConstQualified())
5267           AllVariantFieldsAreConst = false;
5268 
5269         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5270         if (UnionFieldRecord &&
5271             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
5272                                           UnionFieldType.getCVRQualifiers()))
5273           return true;
5274       }
5275 
5276       // At least one member in each anonymous union must be non-const
5277       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
5278           !FieldRecord->field_empty()) {
5279         if (Diagnose)
5280           S.Diag(FieldRecord->getLocation(),
5281                  diag::note_deleted_default_ctor_all_const)
5282             << MD->getParent() << /*anonymous union*/1;
5283         return true;
5284       }
5285 
5286       // Don't check the implicit member of the anonymous union type.
5287       // This is technically non-conformant, but sanity demands it.
5288       return false;
5289     }
5290 
5291     if (shouldDeleteForClassSubobject(FieldRecord, FD,
5292                                       FieldType.getCVRQualifiers()))
5293       return true;
5294   }
5295 
5296   return false;
5297 }
5298 
5299 /// C++11 [class.ctor] p5:
5300 ///   A defaulted default constructor for a class X is defined as deleted if
5301 /// X is a union and all of its variant members are of const-qualified type.
5302 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
5303   // This is a silly definition, because it gives an empty union a deleted
5304   // default constructor. Don't do that.
5305   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5306       !MD->getParent()->field_empty()) {
5307     if (Diagnose)
5308       S.Diag(MD->getParent()->getLocation(),
5309              diag::note_deleted_default_ctor_all_const)
5310         << MD->getParent() << /*not anonymous union*/0;
5311     return true;
5312   }
5313   return false;
5314 }
5315 
5316 /// Determine whether a defaulted special member function should be defined as
5317 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5318 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
5319 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5320                                      bool Diagnose) {
5321   if (MD->isInvalidDecl())
5322     return false;
5323   CXXRecordDecl *RD = MD->getParent();
5324   assert(!RD->isDependentType() && "do deletion after instantiation");
5325   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
5326     return false;
5327 
5328   // C++11 [expr.lambda.prim]p19:
5329   //   The closure type associated with a lambda-expression has a
5330   //   deleted (8.4.3) default constructor and a deleted copy
5331   //   assignment operator.
5332   if (RD->isLambda() &&
5333       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5334     if (Diagnose)
5335       Diag(RD->getLocation(), diag::note_lambda_decl);
5336     return true;
5337   }
5338 
5339   // For an anonymous struct or union, the copy and assignment special members
5340   // will never be used, so skip the check. For an anonymous union declared at
5341   // namespace scope, the constructor and destructor are used.
5342   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5343       RD->isAnonymousStructOrUnion())
5344     return false;
5345 
5346   // C++11 [class.copy]p7, p18:
5347   //   If the class definition declares a move constructor or move assignment
5348   //   operator, an implicitly declared copy constructor or copy assignment
5349   //   operator is defined as deleted.
5350   if (MD->isImplicit() &&
5351       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5352     CXXMethodDecl *UserDeclaredMove = nullptr;
5353 
5354     // In Microsoft mode, a user-declared move only causes the deletion of the
5355     // corresponding copy operation, not both copy operations.
5356     if (RD->hasUserDeclaredMoveConstructor() &&
5357         (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
5358       if (!Diagnose) return true;
5359 
5360       // Find any user-declared move constructor.
5361       for (auto *I : RD->ctors()) {
5362         if (I->isMoveConstructor()) {
5363           UserDeclaredMove = I;
5364           break;
5365         }
5366       }
5367       assert(UserDeclaredMove);
5368     } else if (RD->hasUserDeclaredMoveAssignment() &&
5369                (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
5370       if (!Diagnose) return true;
5371 
5372       // Find any user-declared move assignment operator.
5373       for (auto *I : RD->methods()) {
5374         if (I->isMoveAssignmentOperator()) {
5375           UserDeclaredMove = I;
5376           break;
5377         }
5378       }
5379       assert(UserDeclaredMove);
5380     }
5381 
5382     if (UserDeclaredMove) {
5383       Diag(UserDeclaredMove->getLocation(),
5384            diag::note_deleted_copy_user_declared_move)
5385         << (CSM == CXXCopyAssignment) << RD
5386         << UserDeclaredMove->isMoveAssignmentOperator();
5387       return true;
5388     }
5389   }
5390 
5391   // Do access control from the special member function
5392   ContextRAII MethodContext(*this, MD);
5393 
5394   // C++11 [class.dtor]p5:
5395   // -- for a virtual destructor, lookup of the non-array deallocation function
5396   //    results in an ambiguity or in a function that is deleted or inaccessible
5397   if (CSM == CXXDestructor && MD->isVirtual()) {
5398     FunctionDecl *OperatorDelete = nullptr;
5399     DeclarationName Name =
5400       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5401     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
5402                                  OperatorDelete, false)) {
5403       if (Diagnose)
5404         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
5405       return true;
5406     }
5407   }
5408 
5409   SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
5410 
5411   for (auto &BI : RD->bases())
5412     if (!BI.isVirtual() &&
5413         SMI.shouldDeleteForBase(&BI))
5414       return true;
5415 
5416   // Per DR1611, do not consider virtual bases of constructors of abstract
5417   // classes, since we are not going to construct them.
5418   if (!RD->isAbstract() || !SMI.IsConstructor) {
5419     for (auto &BI : RD->vbases())
5420       if (SMI.shouldDeleteForBase(&BI))
5421         return true;
5422   }
5423 
5424   for (auto *FI : RD->fields())
5425     if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
5426         SMI.shouldDeleteForField(FI))
5427       return true;
5428 
5429   if (SMI.shouldDeleteForAllConstMembers())
5430     return true;
5431 
5432   return false;
5433 }
5434 
5435 /// Perform lookup for a special member of the specified kind, and determine
5436 /// whether it is trivial. If the triviality can be determined without the
5437 /// lookup, skip it. This is intended for use when determining whether a
5438 /// special member of a containing object is trivial, and thus does not ever
5439 /// perform overload resolution for default constructors.
5440 ///
5441 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5442 /// member that was most likely to be intended to be trivial, if any.
5443 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5444                                      Sema::CXXSpecialMember CSM, unsigned Quals,
5445                                      bool ConstRHS, CXXMethodDecl **Selected) {
5446   if (Selected)
5447     *Selected = nullptr;
5448 
5449   switch (CSM) {
5450   case Sema::CXXInvalid:
5451     llvm_unreachable("not a special member");
5452 
5453   case Sema::CXXDefaultConstructor:
5454     // C++11 [class.ctor]p5:
5455     //   A default constructor is trivial if:
5456     //    - all the [direct subobjects] have trivial default constructors
5457     //
5458     // Note, no overload resolution is performed in this case.
5459     if (RD->hasTrivialDefaultConstructor())
5460       return true;
5461 
5462     if (Selected) {
5463       // If there's a default constructor which could have been trivial, dig it
5464       // out. Otherwise, if there's any user-provided default constructor, point
5465       // to that as an example of why there's not a trivial one.
5466       CXXConstructorDecl *DefCtor = nullptr;
5467       if (RD->needsImplicitDefaultConstructor())
5468         S.DeclareImplicitDefaultConstructor(RD);
5469       for (auto *CI : RD->ctors()) {
5470         if (!CI->isDefaultConstructor())
5471           continue;
5472         DefCtor = CI;
5473         if (!DefCtor->isUserProvided())
5474           break;
5475       }
5476 
5477       *Selected = DefCtor;
5478     }
5479 
5480     return false;
5481 
5482   case Sema::CXXDestructor:
5483     // C++11 [class.dtor]p5:
5484     //   A destructor is trivial if:
5485     //    - all the direct [subobjects] have trivial destructors
5486     if (RD->hasTrivialDestructor())
5487       return true;
5488 
5489     if (Selected) {
5490       if (RD->needsImplicitDestructor())
5491         S.DeclareImplicitDestructor(RD);
5492       *Selected = RD->getDestructor();
5493     }
5494 
5495     return false;
5496 
5497   case Sema::CXXCopyConstructor:
5498     // C++11 [class.copy]p12:
5499     //   A copy constructor is trivial if:
5500     //    - the constructor selected to copy each direct [subobject] is trivial
5501     if (RD->hasTrivialCopyConstructor()) {
5502       if (Quals == Qualifiers::Const)
5503         // We must either select the trivial copy constructor or reach an
5504         // ambiguity; no need to actually perform overload resolution.
5505         return true;
5506     } else if (!Selected) {
5507       return false;
5508     }
5509     // In C++98, we are not supposed to perform overload resolution here, but we
5510     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5511     // cases like B as having a non-trivial copy constructor:
5512     //   struct A { template<typename T> A(T&); };
5513     //   struct B { mutable A a; };
5514     goto NeedOverloadResolution;
5515 
5516   case Sema::CXXCopyAssignment:
5517     // C++11 [class.copy]p25:
5518     //   A copy assignment operator is trivial if:
5519     //    - the assignment operator selected to copy each direct [subobject] is
5520     //      trivial
5521     if (RD->hasTrivialCopyAssignment()) {
5522       if (Quals == Qualifiers::Const)
5523         return true;
5524     } else if (!Selected) {
5525       return false;
5526     }
5527     // In C++98, we are not supposed to perform overload resolution here, but we
5528     // treat that as a language defect.
5529     goto NeedOverloadResolution;
5530 
5531   case Sema::CXXMoveConstructor:
5532   case Sema::CXXMoveAssignment:
5533   NeedOverloadResolution:
5534     Sema::SpecialMemberOverloadResult *SMOR =
5535         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
5536 
5537     // The standard doesn't describe how to behave if the lookup is ambiguous.
5538     // We treat it as not making the member non-trivial, just like the standard
5539     // mandates for the default constructor. This should rarely matter, because
5540     // the member will also be deleted.
5541     if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5542       return true;
5543 
5544     if (!SMOR->getMethod()) {
5545       assert(SMOR->getKind() ==
5546              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5547       return false;
5548     }
5549 
5550     // We deliberately don't check if we found a deleted special member. We're
5551     // not supposed to!
5552     if (Selected)
5553       *Selected = SMOR->getMethod();
5554     return SMOR->getMethod()->isTrivial();
5555   }
5556 
5557   llvm_unreachable("unknown special method kind");
5558 }
5559 
5560 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
5561   for (auto *CI : RD->ctors())
5562     if (!CI->isImplicit())
5563       return CI;
5564 
5565   // Look for constructor templates.
5566   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5567   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5568     if (CXXConstructorDecl *CD =
5569           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5570       return CD;
5571   }
5572 
5573   return nullptr;
5574 }
5575 
5576 /// The kind of subobject we are checking for triviality. The values of this
5577 /// enumeration are used in diagnostics.
5578 enum TrivialSubobjectKind {
5579   /// The subobject is a base class.
5580   TSK_BaseClass,
5581   /// The subobject is a non-static data member.
5582   TSK_Field,
5583   /// The object is actually the complete object.
5584   TSK_CompleteObject
5585 };
5586 
5587 /// Check whether the special member selected for a given type would be trivial.
5588 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5589                                       QualType SubType, bool ConstRHS,
5590                                       Sema::CXXSpecialMember CSM,
5591                                       TrivialSubobjectKind Kind,
5592                                       bool Diagnose) {
5593   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5594   if (!SubRD)
5595     return true;
5596 
5597   CXXMethodDecl *Selected;
5598   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5599                                ConstRHS, Diagnose ? &Selected : nullptr))
5600     return true;
5601 
5602   if (Diagnose) {
5603     if (ConstRHS)
5604       SubType.addConst();
5605 
5606     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5607       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5608         << Kind << SubType.getUnqualifiedType();
5609       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5610         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5611     } else if (!Selected)
5612       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5613         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5614     else if (Selected->isUserProvided()) {
5615       if (Kind == TSK_CompleteObject)
5616         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5617           << Kind << SubType.getUnqualifiedType() << CSM;
5618       else {
5619         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5620           << Kind << SubType.getUnqualifiedType() << CSM;
5621         S.Diag(Selected->getLocation(), diag::note_declared_at);
5622       }
5623     } else {
5624       if (Kind != TSK_CompleteObject)
5625         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5626           << Kind << SubType.getUnqualifiedType() << CSM;
5627 
5628       // Explain why the defaulted or deleted special member isn't trivial.
5629       S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5630     }
5631   }
5632 
5633   return false;
5634 }
5635 
5636 /// Check whether the members of a class type allow a special member to be
5637 /// trivial.
5638 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5639                                      Sema::CXXSpecialMember CSM,
5640                                      bool ConstArg, bool Diagnose) {
5641   for (const auto *FI : RD->fields()) {
5642     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5643       continue;
5644 
5645     QualType FieldType = S.Context.getBaseElementType(FI->getType());
5646 
5647     // Pretend anonymous struct or union members are members of this class.
5648     if (FI->isAnonymousStructOrUnion()) {
5649       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5650                                     CSM, ConstArg, Diagnose))
5651         return false;
5652       continue;
5653     }
5654 
5655     // C++11 [class.ctor]p5:
5656     //   A default constructor is trivial if [...]
5657     //    -- no non-static data member of its class has a
5658     //       brace-or-equal-initializer
5659     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5660       if (Diagnose)
5661         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
5662       return false;
5663     }
5664 
5665     // Objective C ARC 4.3.5:
5666     //   [...] nontrivally ownership-qualified types are [...] not trivially
5667     //   default constructible, copy constructible, move constructible, copy
5668     //   assignable, move assignable, or destructible [...]
5669     if (S.getLangOpts().ObjCAutoRefCount &&
5670         FieldType.hasNonTrivialObjCLifetime()) {
5671       if (Diagnose)
5672         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5673           << RD << FieldType.getObjCLifetime();
5674       return false;
5675     }
5676 
5677     bool ConstRHS = ConstArg && !FI->isMutable();
5678     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
5679                                    CSM, TSK_Field, Diagnose))
5680       return false;
5681   }
5682 
5683   return true;
5684 }
5685 
5686 /// Diagnose why the specified class does not have a trivial special member of
5687 /// the given kind.
5688 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5689   QualType Ty = Context.getRecordType(RD);
5690 
5691   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
5692   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
5693                             TSK_CompleteObject, /*Diagnose*/true);
5694 }
5695 
5696 /// Determine whether a defaulted or deleted special member function is trivial,
5697 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5698 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5699 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5700                                   bool Diagnose) {
5701   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5702 
5703   CXXRecordDecl *RD = MD->getParent();
5704 
5705   bool ConstArg = false;
5706 
5707   // C++11 [class.copy]p12, p25: [DR1593]
5708   //   A [special member] is trivial if [...] its parameter-type-list is
5709   //   equivalent to the parameter-type-list of an implicit declaration [...]
5710   switch (CSM) {
5711   case CXXDefaultConstructor:
5712   case CXXDestructor:
5713     // Trivial default constructors and destructors cannot have parameters.
5714     break;
5715 
5716   case CXXCopyConstructor:
5717   case CXXCopyAssignment: {
5718     // Trivial copy operations always have const, non-volatile parameter types.
5719     ConstArg = true;
5720     const ParmVarDecl *Param0 = MD->getParamDecl(0);
5721     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5722     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5723       if (Diagnose)
5724         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5725           << Param0->getSourceRange() << Param0->getType()
5726           << Context.getLValueReferenceType(
5727                Context.getRecordType(RD).withConst());
5728       return false;
5729     }
5730     break;
5731   }
5732 
5733   case CXXMoveConstructor:
5734   case CXXMoveAssignment: {
5735     // Trivial move operations always have non-cv-qualified parameters.
5736     const ParmVarDecl *Param0 = MD->getParamDecl(0);
5737     const RValueReferenceType *RT =
5738       Param0->getType()->getAs<RValueReferenceType>();
5739     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5740       if (Diagnose)
5741         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5742           << Param0->getSourceRange() << Param0->getType()
5743           << Context.getRValueReferenceType(Context.getRecordType(RD));
5744       return false;
5745     }
5746     break;
5747   }
5748 
5749   case CXXInvalid:
5750     llvm_unreachable("not a special member");
5751   }
5752 
5753   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5754     if (Diagnose)
5755       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5756            diag::note_nontrivial_default_arg)
5757         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5758     return false;
5759   }
5760   if (MD->isVariadic()) {
5761     if (Diagnose)
5762       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5763     return false;
5764   }
5765 
5766   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5767   //   A copy/move [constructor or assignment operator] is trivial if
5768   //    -- the [member] selected to copy/move each direct base class subobject
5769   //       is trivial
5770   //
5771   // C++11 [class.copy]p12, C++11 [class.copy]p25:
5772   //   A [default constructor or destructor] is trivial if
5773   //    -- all the direct base classes have trivial [default constructors or
5774   //       destructors]
5775   for (const auto &BI : RD->bases())
5776     if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
5777                                    ConstArg, CSM, TSK_BaseClass, Diagnose))
5778       return false;
5779 
5780   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5781   //   A copy/move [constructor or assignment operator] for a class X is
5782   //   trivial if
5783   //    -- for each non-static data member of X that is of class type (or array
5784   //       thereof), the constructor selected to copy/move that member is
5785   //       trivial
5786   //
5787   // C++11 [class.copy]p12, C++11 [class.copy]p25:
5788   //   A [default constructor or destructor] is trivial if
5789   //    -- for all of the non-static data members of its class that are of class
5790   //       type (or array thereof), each such class has a trivial [default
5791   //       constructor or destructor]
5792   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5793     return false;
5794 
5795   // C++11 [class.dtor]p5:
5796   //   A destructor is trivial if [...]
5797   //    -- the destructor is not virtual
5798   if (CSM == CXXDestructor && MD->isVirtual()) {
5799     if (Diagnose)
5800       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5801     return false;
5802   }
5803 
5804   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5805   //   A [special member] for class X is trivial if [...]
5806   //    -- class X has no virtual functions and no virtual base classes
5807   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5808     if (!Diagnose)
5809       return false;
5810 
5811     if (RD->getNumVBases()) {
5812       // Check for virtual bases. We already know that the corresponding
5813       // member in all bases is trivial, so vbases must all be direct.
5814       CXXBaseSpecifier &BS = *RD->vbases_begin();
5815       assert(BS.isVirtual());
5816       Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5817       return false;
5818     }
5819 
5820     // Must have a virtual method.
5821     for (const auto *MI : RD->methods()) {
5822       if (MI->isVirtual()) {
5823         SourceLocation MLoc = MI->getLocStart();
5824         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5825         return false;
5826       }
5827     }
5828 
5829     llvm_unreachable("dynamic class with no vbases and no virtual functions");
5830   }
5831 
5832   // Looks like it's trivial!
5833   return true;
5834 }
5835 
5836 /// \brief Data used with FindHiddenVirtualMethod
5837 namespace {
5838   struct FindHiddenVirtualMethodData {
5839     Sema *S;
5840     CXXMethodDecl *Method;
5841     llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
5842     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5843   };
5844 }
5845 
5846 /// \brief Check whether any most overriden method from MD in Methods
5847 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5848                    const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5849   if (MD->size_overridden_methods() == 0)
5850     return Methods.count(MD->getCanonicalDecl());
5851   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5852                                       E = MD->end_overridden_methods();
5853        I != E; ++I)
5854     if (CheckMostOverridenMethods(*I, Methods))
5855       return true;
5856   return false;
5857 }
5858 
5859 /// \brief Member lookup function that determines whether a given C++
5860 /// method overloads virtual methods in a base class without overriding any,
5861 /// to be used with CXXRecordDecl::lookupInBases().
5862 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5863                                     CXXBasePath &Path,
5864                                     void *UserData) {
5865   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5866 
5867   FindHiddenVirtualMethodData &Data
5868     = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5869 
5870   DeclarationName Name = Data.Method->getDeclName();
5871   assert(Name.getNameKind() == DeclarationName::Identifier);
5872 
5873   bool foundSameNameMethod = false;
5874   SmallVector<CXXMethodDecl *, 8> overloadedMethods;
5875   for (Path.Decls = BaseRecord->lookup(Name);
5876        !Path.Decls.empty();
5877        Path.Decls = Path.Decls.slice(1)) {
5878     NamedDecl *D = Path.Decls.front();
5879     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5880       MD = MD->getCanonicalDecl();
5881       foundSameNameMethod = true;
5882       // Interested only in hidden virtual methods.
5883       if (!MD->isVirtual())
5884         continue;
5885       // If the method we are checking overrides a method from its base
5886       // don't warn about the other overloaded methods.
5887       if (!Data.S->IsOverload(Data.Method, MD, false))
5888         return true;
5889       // Collect the overload only if its hidden.
5890       if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
5891         overloadedMethods.push_back(MD);
5892     }
5893   }
5894 
5895   if (foundSameNameMethod)
5896     Data.OverloadedMethods.append(overloadedMethods.begin(),
5897                                    overloadedMethods.end());
5898   return foundSameNameMethod;
5899 }
5900 
5901 /// \brief Add the most overriden methods from MD to Methods
5902 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5903                          llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5904   if (MD->size_overridden_methods() == 0)
5905     Methods.insert(MD->getCanonicalDecl());
5906   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5907                                       E = MD->end_overridden_methods();
5908        I != E; ++I)
5909     AddMostOverridenMethods(*I, Methods);
5910 }
5911 
5912 /// \brief Check if a method overloads virtual methods in a base class without
5913 /// overriding any.
5914 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
5915                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
5916   if (!MD->getDeclName().isIdentifier())
5917     return;
5918 
5919   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5920                      /*bool RecordPaths=*/false,
5921                      /*bool DetectVirtual=*/false);
5922   FindHiddenVirtualMethodData Data;
5923   Data.Method = MD;
5924   Data.S = this;
5925 
5926   // Keep the base methods that were overriden or introduced in the subclass
5927   // by 'using' in a set. A base method not in this set is hidden.
5928   CXXRecordDecl *DC = MD->getParent();
5929   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5930   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5931     NamedDecl *ND = *I;
5932     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
5933       ND = shad->getTargetDecl();
5934     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5935       AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
5936   }
5937 
5938   if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
5939     OverloadedMethods = Data.OverloadedMethods;
5940 }
5941 
5942 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
5943                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
5944   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
5945     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
5946     PartialDiagnostic PD = PDiag(
5947          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5948     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5949     Diag(overloadedMD->getLocation(), PD);
5950   }
5951 }
5952 
5953 /// \brief Diagnose methods which overload virtual methods in a base class
5954 /// without overriding any.
5955 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
5956   if (MD->isInvalidDecl())
5957     return;
5958 
5959   if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
5960                                MD->getLocation()) == DiagnosticsEngine::Ignored)
5961     return;
5962 
5963   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5964   FindHiddenVirtualMethods(MD, OverloadedMethods);
5965   if (!OverloadedMethods.empty()) {
5966     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5967       << MD << (OverloadedMethods.size() > 1);
5968 
5969     NoteHiddenVirtualMethods(MD, OverloadedMethods);
5970   }
5971 }
5972 
5973 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5974                                              Decl *TagDecl,
5975                                              SourceLocation LBrac,
5976                                              SourceLocation RBrac,
5977                                              AttributeList *AttrList) {
5978   if (!TagDecl)
5979     return;
5980 
5981   AdjustDeclIfTemplate(TagDecl);
5982 
5983   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5984     if (l->getKind() != AttributeList::AT_Visibility)
5985       continue;
5986     l->setInvalid();
5987     Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5988       l->getName();
5989   }
5990 
5991   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
5992               // strict aliasing violation!
5993               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
5994               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
5995 
5996   CheckCompletedCXXClass(
5997                         dyn_cast_or_null<CXXRecordDecl>(TagDecl));
5998 }
5999 
6000 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6001 /// special functions, such as the default constructor, copy
6002 /// constructor, or destructor, to the given C++ class (C++
6003 /// [special]p1).  This routine can only be executed just before the
6004 /// definition of the class is complete.
6005 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
6006   if (!ClassDecl->hasUserDeclaredConstructor())
6007     ++ASTContext::NumImplicitDefaultConstructors;
6008 
6009   if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
6010     ++ASTContext::NumImplicitCopyConstructors;
6011 
6012     // If the properties or semantics of the copy constructor couldn't be
6013     // determined while the class was being declared, force a declaration
6014     // of it now.
6015     if (ClassDecl->needsOverloadResolutionForCopyConstructor())
6016       DeclareImplicitCopyConstructor(ClassDecl);
6017   }
6018 
6019   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
6020     ++ASTContext::NumImplicitMoveConstructors;
6021 
6022     if (ClassDecl->needsOverloadResolutionForMoveConstructor())
6023       DeclareImplicitMoveConstructor(ClassDecl);
6024   }
6025 
6026   if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6027     ++ASTContext::NumImplicitCopyAssignmentOperators;
6028 
6029     // If we have a dynamic class, then the copy assignment operator may be
6030     // virtual, so we have to declare it immediately. This ensures that, e.g.,
6031     // it shows up in the right place in the vtable and that we diagnose
6032     // problems with the implicit exception specification.
6033     if (ClassDecl->isDynamicClass() ||
6034         ClassDecl->needsOverloadResolutionForCopyAssignment())
6035       DeclareImplicitCopyAssignment(ClassDecl);
6036   }
6037 
6038   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
6039     ++ASTContext::NumImplicitMoveAssignmentOperators;
6040 
6041     // Likewise for the move assignment operator.
6042     if (ClassDecl->isDynamicClass() ||
6043         ClassDecl->needsOverloadResolutionForMoveAssignment())
6044       DeclareImplicitMoveAssignment(ClassDecl);
6045   }
6046 
6047   if (!ClassDecl->hasUserDeclaredDestructor()) {
6048     ++ASTContext::NumImplicitDestructors;
6049 
6050     // If we have a dynamic class, then the destructor may be virtual, so we
6051     // have to declare the destructor immediately. This ensures that, e.g., it
6052     // shows up in the right place in the vtable and that we diagnose problems
6053     // with the implicit exception specification.
6054     if (ClassDecl->isDynamicClass() ||
6055         ClassDecl->needsOverloadResolutionForDestructor())
6056       DeclareImplicitDestructor(ClassDecl);
6057   }
6058 }
6059 
6060 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
6061   if (!D)
6062     return 0;
6063 
6064   // The order of template parameters is not important here. All names
6065   // get added to the same scope.
6066   SmallVector<TemplateParameterList *, 4> ParameterLists;
6067 
6068   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6069     D = TD->getTemplatedDecl();
6070 
6071   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6072     ParameterLists.push_back(PSD->getTemplateParameters());
6073 
6074   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6075     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6076       ParameterLists.push_back(DD->getTemplateParameterList(i));
6077 
6078     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6079       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6080         ParameterLists.push_back(FTD->getTemplateParameters());
6081     }
6082   }
6083 
6084   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6085     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6086       ParameterLists.push_back(TD->getTemplateParameterList(i));
6087 
6088     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6089       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6090         ParameterLists.push_back(CTD->getTemplateParameters());
6091     }
6092   }
6093 
6094   unsigned Count = 0;
6095   for (TemplateParameterList *Params : ParameterLists) {
6096     if (Params->size() > 0)
6097       // Ignore explicit specializations; they don't contribute to the template
6098       // depth.
6099       ++Count;
6100     for (NamedDecl *Param : *Params) {
6101       if (Param->getDeclName()) {
6102         S->AddDecl(Param);
6103         IdResolver.AddDecl(Param);
6104       }
6105     }
6106   }
6107 
6108   return Count;
6109 }
6110 
6111 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6112   if (!RecordD) return;
6113   AdjustDeclIfTemplate(RecordD);
6114   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
6115   PushDeclContext(S, Record);
6116 }
6117 
6118 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6119   if (!RecordD) return;
6120   PopDeclContext();
6121 }
6122 
6123 /// This is used to implement the constant expression evaluation part of the
6124 /// attribute enable_if extension. There is nothing in standard C++ which would
6125 /// require reentering parameters.
6126 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6127   if (!Param)
6128     return;
6129 
6130   S->AddDecl(Param);
6131   if (Param->getDeclName())
6132     IdResolver.AddDecl(Param);
6133 }
6134 
6135 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
6136 /// parsing a top-level (non-nested) C++ class, and we are now
6137 /// parsing those parts of the given Method declaration that could
6138 /// not be parsed earlier (C++ [class.mem]p2), such as default
6139 /// arguments. This action should enter the scope of the given
6140 /// Method declaration as if we had just parsed the qualified method
6141 /// name. However, it should not bring the parameters into scope;
6142 /// that will be performed by ActOnDelayedCXXMethodParameter.
6143 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6144 }
6145 
6146 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
6147 /// C++ method declaration. We're (re-)introducing the given
6148 /// function parameter into scope for use in parsing later parts of
6149 /// the method declaration. For example, we could see an
6150 /// ActOnParamDefaultArgument event for this parameter.
6151 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
6152   if (!ParamD)
6153     return;
6154 
6155   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
6156 
6157   // If this parameter has an unparsed default argument, clear it out
6158   // to make way for the parsed default argument.
6159   if (Param->hasUnparsedDefaultArg())
6160     Param->setDefaultArg(nullptr);
6161 
6162   S->AddDecl(Param);
6163   if (Param->getDeclName())
6164     IdResolver.AddDecl(Param);
6165 }
6166 
6167 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6168 /// processing the delayed method declaration for Method. The method
6169 /// declaration is now considered finished. There may be a separate
6170 /// ActOnStartOfFunctionDef action later (not necessarily
6171 /// immediately!) for this method, if it was also defined inside the
6172 /// class body.
6173 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6174   if (!MethodD)
6175     return;
6176 
6177   AdjustDeclIfTemplate(MethodD);
6178 
6179   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
6180 
6181   // Now that we have our default arguments, check the constructor
6182   // again. It could produce additional diagnostics or affect whether
6183   // the class has implicitly-declared destructors, among other
6184   // things.
6185   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6186     CheckConstructor(Constructor);
6187 
6188   // Check the default arguments, which we may have added.
6189   if (!Method->isInvalidDecl())
6190     CheckCXXDefaultArguments(Method);
6191 }
6192 
6193 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
6194 /// the well-formedness of the constructor declarator @p D with type @p
6195 /// R. If there are any errors in the declarator, this routine will
6196 /// emit diagnostics and set the invalid bit to true.  In any case, the type
6197 /// will be updated to reflect a well-formed type for the constructor and
6198 /// returned.
6199 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
6200                                           StorageClass &SC) {
6201   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6202 
6203   // C++ [class.ctor]p3:
6204   //   A constructor shall not be virtual (10.3) or static (9.4). A
6205   //   constructor can be invoked for a const, volatile or const
6206   //   volatile object. A constructor shall not be declared const,
6207   //   volatile, or const volatile (9.3.2).
6208   if (isVirtual) {
6209     if (!D.isInvalidType())
6210       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6211         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6212         << SourceRange(D.getIdentifierLoc());
6213     D.setInvalidType();
6214   }
6215   if (SC == SC_Static) {
6216     if (!D.isInvalidType())
6217       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6218         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6219         << SourceRange(D.getIdentifierLoc());
6220     D.setInvalidType();
6221     SC = SC_None;
6222   }
6223 
6224   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6225   if (FTI.TypeQuals != 0) {
6226     if (FTI.TypeQuals & Qualifiers::Const)
6227       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6228         << "const" << SourceRange(D.getIdentifierLoc());
6229     if (FTI.TypeQuals & Qualifiers::Volatile)
6230       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6231         << "volatile" << SourceRange(D.getIdentifierLoc());
6232     if (FTI.TypeQuals & Qualifiers::Restrict)
6233       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6234         << "restrict" << SourceRange(D.getIdentifierLoc());
6235     D.setInvalidType();
6236   }
6237 
6238   // C++0x [class.ctor]p4:
6239   //   A constructor shall not be declared with a ref-qualifier.
6240   if (FTI.hasRefQualifier()) {
6241     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6242       << FTI.RefQualifierIsLValueRef
6243       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6244     D.setInvalidType();
6245   }
6246 
6247   // Rebuild the function type "R" without any type qualifiers (in
6248   // case any of the errors above fired) and with "void" as the
6249   // return type, since constructors don't have return types.
6250   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6251   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
6252     return R;
6253 
6254   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6255   EPI.TypeQuals = 0;
6256   EPI.RefQualifier = RQ_None;
6257 
6258   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
6259 }
6260 
6261 /// CheckConstructor - Checks a fully-formed constructor for
6262 /// well-formedness, issuing any diagnostics required. Returns true if
6263 /// the constructor declarator is invalid.
6264 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
6265   CXXRecordDecl *ClassDecl
6266     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6267   if (!ClassDecl)
6268     return Constructor->setInvalidDecl();
6269 
6270   // C++ [class.copy]p3:
6271   //   A declaration of a constructor for a class X is ill-formed if
6272   //   its first parameter is of type (optionally cv-qualified) X and
6273   //   either there are no other parameters or else all other
6274   //   parameters have default arguments.
6275   if (!Constructor->isInvalidDecl() &&
6276       ((Constructor->getNumParams() == 1) ||
6277        (Constructor->getNumParams() > 1 &&
6278         Constructor->getParamDecl(1)->hasDefaultArg())) &&
6279       Constructor->getTemplateSpecializationKind()
6280                                               != TSK_ImplicitInstantiation) {
6281     QualType ParamType = Constructor->getParamDecl(0)->getType();
6282     QualType ClassTy = Context.getTagDeclType(ClassDecl);
6283     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
6284       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
6285       const char *ConstRef
6286         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6287                                                         : " const &";
6288       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
6289         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
6290 
6291       // FIXME: Rather that making the constructor invalid, we should endeavor
6292       // to fix the type.
6293       Constructor->setInvalidDecl();
6294     }
6295   }
6296 }
6297 
6298 /// CheckDestructor - Checks a fully-formed destructor definition for
6299 /// well-formedness, issuing any diagnostics required.  Returns true
6300 /// on error.
6301 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
6302   CXXRecordDecl *RD = Destructor->getParent();
6303 
6304   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
6305     SourceLocation Loc;
6306 
6307     if (!Destructor->isImplicit())
6308       Loc = Destructor->getLocation();
6309     else
6310       Loc = RD->getLocation();
6311 
6312     // If we have a virtual destructor, look up the deallocation function
6313     FunctionDecl *OperatorDelete = nullptr;
6314     DeclarationName Name =
6315     Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6316     if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
6317       return true;
6318     // If there's no class-specific operator delete, look up the global
6319     // non-array delete.
6320     if (!OperatorDelete)
6321       OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
6322 
6323     MarkFunctionReferenced(Loc, OperatorDelete);
6324 
6325     Destructor->setOperatorDelete(OperatorDelete);
6326   }
6327 
6328   return false;
6329 }
6330 
6331 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6332 /// the well-formednes of the destructor declarator @p D with type @p
6333 /// R. If there are any errors in the declarator, this routine will
6334 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
6335 /// will be updated to reflect a well-formed type for the destructor and
6336 /// returned.
6337 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
6338                                          StorageClass& SC) {
6339   // C++ [class.dtor]p1:
6340   //   [...] A typedef-name that names a class is a class-name
6341   //   (7.1.3); however, a typedef-name that names a class shall not
6342   //   be used as the identifier in the declarator for a destructor
6343   //   declaration.
6344   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
6345   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
6346     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6347       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
6348   else if (const TemplateSpecializationType *TST =
6349              DeclaratorType->getAs<TemplateSpecializationType>())
6350     if (TST->isTypeAlias())
6351       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6352         << DeclaratorType << 1;
6353 
6354   // C++ [class.dtor]p2:
6355   //   A destructor is used to destroy objects of its class type. A
6356   //   destructor takes no parameters, and no return type can be
6357   //   specified for it (not even void). The address of a destructor
6358   //   shall not be taken. A destructor shall not be static. A
6359   //   destructor can be invoked for a const, volatile or const
6360   //   volatile object. A destructor shall not be declared const,
6361   //   volatile or const volatile (9.3.2).
6362   if (SC == SC_Static) {
6363     if (!D.isInvalidType())
6364       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6365         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6366         << SourceRange(D.getIdentifierLoc())
6367         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6368 
6369     SC = SC_None;
6370   }
6371   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
6372     // Destructors don't have return types, but the parser will
6373     // happily parse something like:
6374     //
6375     //   class X {
6376     //     float ~X();
6377     //   };
6378     //
6379     // The return type will be eliminated later.
6380     Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6381       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6382       << SourceRange(D.getIdentifierLoc());
6383   }
6384 
6385   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6386   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
6387     if (FTI.TypeQuals & Qualifiers::Const)
6388       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6389         << "const" << SourceRange(D.getIdentifierLoc());
6390     if (FTI.TypeQuals & Qualifiers::Volatile)
6391       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6392         << "volatile" << SourceRange(D.getIdentifierLoc());
6393     if (FTI.TypeQuals & Qualifiers::Restrict)
6394       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6395         << "restrict" << SourceRange(D.getIdentifierLoc());
6396     D.setInvalidType();
6397   }
6398 
6399   // C++0x [class.dtor]p2:
6400   //   A destructor shall not be declared with a ref-qualifier.
6401   if (FTI.hasRefQualifier()) {
6402     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6403       << FTI.RefQualifierIsLValueRef
6404       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6405     D.setInvalidType();
6406   }
6407 
6408   // Make sure we don't have any parameters.
6409   if (FTIHasNonVoidParameters(FTI)) {
6410     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6411 
6412     // Delete the parameters.
6413     FTI.freeParams();
6414     D.setInvalidType();
6415   }
6416 
6417   // Make sure the destructor isn't variadic.
6418   if (FTI.isVariadic) {
6419     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
6420     D.setInvalidType();
6421   }
6422 
6423   // Rebuild the function type "R" without any type qualifiers or
6424   // parameters (in case any of the errors above fired) and with
6425   // "void" as the return type, since destructors don't have return
6426   // types.
6427   if (!D.isInvalidType())
6428     return R;
6429 
6430   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6431   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6432   EPI.Variadic = false;
6433   EPI.TypeQuals = 0;
6434   EPI.RefQualifier = RQ_None;
6435   return Context.getFunctionType(Context.VoidTy, None, EPI);
6436 }
6437 
6438 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6439 /// well-formednes of the conversion function declarator @p D with
6440 /// type @p R. If there are any errors in the declarator, this routine
6441 /// will emit diagnostics and return true. Otherwise, it will return
6442 /// false. Either way, the type @p R will be updated to reflect a
6443 /// well-formed type for the conversion operator.
6444 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
6445                                      StorageClass& SC) {
6446   // C++ [class.conv.fct]p1:
6447   //   Neither parameter types nor return type can be specified. The
6448   //   type of a conversion function (8.3.5) is "function taking no
6449   //   parameter returning conversion-type-id."
6450   if (SC == SC_Static) {
6451     if (!D.isInvalidType())
6452       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
6453         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6454         << D.getName().getSourceRange();
6455     D.setInvalidType();
6456     SC = SC_None;
6457   }
6458 
6459   QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6460 
6461   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
6462     // Conversion functions don't have return types, but the parser will
6463     // happily parse something like:
6464     //
6465     //   class X {
6466     //     float operator bool();
6467     //   };
6468     //
6469     // The return type will be changed later anyway.
6470     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6471       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6472       << SourceRange(D.getIdentifierLoc());
6473     D.setInvalidType();
6474   }
6475 
6476   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6477 
6478   // Make sure we don't have any parameters.
6479   if (Proto->getNumParams() > 0) {
6480     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6481 
6482     // Delete the parameters.
6483     D.getFunctionTypeInfo().freeParams();
6484     D.setInvalidType();
6485   } else if (Proto->isVariadic()) {
6486     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
6487     D.setInvalidType();
6488   }
6489 
6490   // Diagnose "&operator bool()" and other such nonsense.  This
6491   // is actually a gcc extension which we don't support.
6492   if (Proto->getReturnType() != ConvType) {
6493     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6494         << Proto->getReturnType();
6495     D.setInvalidType();
6496     ConvType = Proto->getReturnType();
6497   }
6498 
6499   // C++ [class.conv.fct]p4:
6500   //   The conversion-type-id shall not represent a function type nor
6501   //   an array type.
6502   if (ConvType->isArrayType()) {
6503     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6504     ConvType = Context.getPointerType(ConvType);
6505     D.setInvalidType();
6506   } else if (ConvType->isFunctionType()) {
6507     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6508     ConvType = Context.getPointerType(ConvType);
6509     D.setInvalidType();
6510   }
6511 
6512   // Rebuild the function type "R" without any parameters (in case any
6513   // of the errors above fired) and with the conversion type as the
6514   // return type.
6515   if (D.isInvalidType())
6516     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
6517 
6518   // C++0x explicit conversion operators.
6519   if (D.getDeclSpec().isExplicitSpecified())
6520     Diag(D.getDeclSpec().getExplicitSpecLoc(),
6521          getLangOpts().CPlusPlus11 ?
6522            diag::warn_cxx98_compat_explicit_conversion_functions :
6523            diag::ext_explicit_conversion_functions)
6524       << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
6525 }
6526 
6527 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6528 /// the declaration of the given C++ conversion function. This routine
6529 /// is responsible for recording the conversion function in the C++
6530 /// class, if possible.
6531 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
6532   assert(Conversion && "Expected to receive a conversion function declaration");
6533 
6534   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
6535 
6536   // Make sure we aren't redeclaring the conversion function.
6537   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
6538 
6539   // C++ [class.conv.fct]p1:
6540   //   [...] A conversion function is never used to convert a
6541   //   (possibly cv-qualified) object to the (possibly cv-qualified)
6542   //   same object type (or a reference to it), to a (possibly
6543   //   cv-qualified) base class of that type (or a reference to it),
6544   //   or to (possibly cv-qualified) void.
6545   // FIXME: Suppress this warning if the conversion function ends up being a
6546   // virtual function that overrides a virtual function in a base class.
6547   QualType ClassType
6548     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6549   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
6550     ConvType = ConvTypeRef->getPointeeType();
6551   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6552       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
6553     /* Suppress diagnostics for instantiations. */;
6554   else if (ConvType->isRecordType()) {
6555     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6556     if (ConvType == ClassType)
6557       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
6558         << ClassType;
6559     else if (IsDerivedFrom(ClassType, ConvType))
6560       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
6561         <<  ClassType << ConvType;
6562   } else if (ConvType->isVoidType()) {
6563     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
6564       << ClassType << ConvType;
6565   }
6566 
6567   if (FunctionTemplateDecl *ConversionTemplate
6568                                 = Conversion->getDescribedFunctionTemplate())
6569     return ConversionTemplate;
6570 
6571   return Conversion;
6572 }
6573 
6574 //===----------------------------------------------------------------------===//
6575 // Namespace Handling
6576 //===----------------------------------------------------------------------===//
6577 
6578 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6579 /// reopened.
6580 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6581                                             SourceLocation Loc,
6582                                             IdentifierInfo *II, bool *IsInline,
6583                                             NamespaceDecl *PrevNS) {
6584   assert(*IsInline != PrevNS->isInline());
6585 
6586   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6587   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6588   // inline namespaces, with the intention of bringing names into namespace std.
6589   //
6590   // We support this just well enough to get that case working; this is not
6591   // sufficient to support reopening namespaces as inline in general.
6592   if (*IsInline && II && II->getName().startswith("__atomic") &&
6593       S.getSourceManager().isInSystemHeader(Loc)) {
6594     // Mark all prior declarations of the namespace as inline.
6595     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6596          NS = NS->getPreviousDecl())
6597       NS->setInline(*IsInline);
6598     // Patch up the lookup table for the containing namespace. This isn't really
6599     // correct, but it's good enough for this particular case.
6600     for (auto *I : PrevNS->decls())
6601       if (auto *ND = dyn_cast<NamedDecl>(I))
6602         PrevNS->getParent()->makeDeclVisibleInContext(ND);
6603     return;
6604   }
6605 
6606   if (PrevNS->isInline())
6607     // The user probably just forgot the 'inline', so suggest that it
6608     // be added back.
6609     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6610       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6611   else
6612     S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
6613 
6614   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6615   *IsInline = PrevNS->isInline();
6616 }
6617 
6618 /// ActOnStartNamespaceDef - This is called at the start of a namespace
6619 /// definition.
6620 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
6621                                    SourceLocation InlineLoc,
6622                                    SourceLocation NamespaceLoc,
6623                                    SourceLocation IdentLoc,
6624                                    IdentifierInfo *II,
6625                                    SourceLocation LBrace,
6626                                    AttributeList *AttrList) {
6627   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6628   // For anonymous namespace, take the location of the left brace.
6629   SourceLocation Loc = II ? IdentLoc : LBrace;
6630   bool IsInline = InlineLoc.isValid();
6631   bool IsInvalid = false;
6632   bool IsStd = false;
6633   bool AddToKnown = false;
6634   Scope *DeclRegionScope = NamespcScope->getParent();
6635 
6636   NamespaceDecl *PrevNS = nullptr;
6637   if (II) {
6638     // C++ [namespace.def]p2:
6639     //   The identifier in an original-namespace-definition shall not
6640     //   have been previously defined in the declarative region in
6641     //   which the original-namespace-definition appears. The
6642     //   identifier in an original-namespace-definition is the name of
6643     //   the namespace. Subsequently in that declarative region, it is
6644     //   treated as an original-namespace-name.
6645     //
6646     // Since namespace names are unique in their scope, and we don't
6647     // look through using directives, just look for any ordinary names.
6648 
6649     const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
6650     Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6651     Decl::IDNS_Namespace;
6652     NamedDecl *PrevDecl = nullptr;
6653     DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6654     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6655          ++I) {
6656       if ((*I)->getIdentifierNamespace() & IDNS) {
6657         PrevDecl = *I;
6658         break;
6659       }
6660     }
6661 
6662     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6663 
6664     if (PrevNS) {
6665       // This is an extended namespace definition.
6666       if (IsInline != PrevNS->isInline())
6667         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6668                                         &IsInline, PrevNS);
6669     } else if (PrevDecl) {
6670       // This is an invalid name redefinition.
6671       Diag(Loc, diag::err_redefinition_different_kind)
6672         << II;
6673       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6674       IsInvalid = true;
6675       // Continue on to push Namespc as current DeclContext and return it.
6676     } else if (II->isStr("std") &&
6677                CurContext->getRedeclContext()->isTranslationUnit()) {
6678       // This is the first "real" definition of the namespace "std", so update
6679       // our cache of the "std" namespace to point at this definition.
6680       PrevNS = getStdNamespace();
6681       IsStd = true;
6682       AddToKnown = !IsInline;
6683     } else {
6684       // We've seen this namespace for the first time.
6685       AddToKnown = !IsInline;
6686     }
6687   } else {
6688     // Anonymous namespaces.
6689 
6690     // Determine whether the parent already has an anonymous namespace.
6691     DeclContext *Parent = CurContext->getRedeclContext();
6692     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6693       PrevNS = TU->getAnonymousNamespace();
6694     } else {
6695       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
6696       PrevNS = ND->getAnonymousNamespace();
6697     }
6698 
6699     if (PrevNS && IsInline != PrevNS->isInline())
6700       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6701                                       &IsInline, PrevNS);
6702   }
6703 
6704   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6705                                                  StartLoc, Loc, II, PrevNS);
6706   if (IsInvalid)
6707     Namespc->setInvalidDecl();
6708 
6709   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
6710 
6711   // FIXME: Should we be merging attributes?
6712   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
6713     PushNamespaceVisibilityAttr(Attr, Loc);
6714 
6715   if (IsStd)
6716     StdNamespace = Namespc;
6717   if (AddToKnown)
6718     KnownNamespaces[Namespc] = false;
6719 
6720   if (II) {
6721     PushOnScopeChains(Namespc, DeclRegionScope);
6722   } else {
6723     // Link the anonymous namespace into its parent.
6724     DeclContext *Parent = CurContext->getRedeclContext();
6725     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6726       TU->setAnonymousNamespace(Namespc);
6727     } else {
6728       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
6729     }
6730 
6731     CurContext->addDecl(Namespc);
6732 
6733     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
6734     //   behaves as if it were replaced by
6735     //     namespace unique { /* empty body */ }
6736     //     using namespace unique;
6737     //     namespace unique { namespace-body }
6738     //   where all occurrences of 'unique' in a translation unit are
6739     //   replaced by the same identifier and this identifier differs
6740     //   from all other identifiers in the entire program.
6741 
6742     // We just create the namespace with an empty name and then add an
6743     // implicit using declaration, just like the standard suggests.
6744     //
6745     // CodeGen enforces the "universally unique" aspect by giving all
6746     // declarations semantically contained within an anonymous
6747     // namespace internal linkage.
6748 
6749     if (!PrevNS) {
6750       UsingDirectiveDecl* UD
6751         = UsingDirectiveDecl::Create(Context, Parent,
6752                                      /* 'using' */ LBrace,
6753                                      /* 'namespace' */ SourceLocation(),
6754                                      /* qualifier */ NestedNameSpecifierLoc(),
6755                                      /* identifier */ SourceLocation(),
6756                                      Namespc,
6757                                      /* Ancestor */ Parent);
6758       UD->setImplicit();
6759       Parent->addDecl(UD);
6760     }
6761   }
6762 
6763   ActOnDocumentableDecl(Namespc);
6764 
6765   // Although we could have an invalid decl (i.e. the namespace name is a
6766   // redefinition), push it as current DeclContext and try to continue parsing.
6767   // FIXME: We should be able to push Namespc here, so that the each DeclContext
6768   // for the namespace has the declarations that showed up in that particular
6769   // namespace definition.
6770   PushDeclContext(NamespcScope, Namespc);
6771   return Namespc;
6772 }
6773 
6774 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6775 /// is a namespace alias, returns the namespace it points to.
6776 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6777   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6778     return AD->getNamespace();
6779   return dyn_cast_or_null<NamespaceDecl>(D);
6780 }
6781 
6782 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
6783 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
6784 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
6785   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6786   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
6787   Namespc->setRBraceLoc(RBrace);
6788   PopDeclContext();
6789   if (Namespc->hasAttr<VisibilityAttr>())
6790     PopPragmaVisibility(true, RBrace);
6791 }
6792 
6793 CXXRecordDecl *Sema::getStdBadAlloc() const {
6794   return cast_or_null<CXXRecordDecl>(
6795                                   StdBadAlloc.get(Context.getExternalSource()));
6796 }
6797 
6798 NamespaceDecl *Sema::getStdNamespace() const {
6799   return cast_or_null<NamespaceDecl>(
6800                                  StdNamespace.get(Context.getExternalSource()));
6801 }
6802 
6803 /// \brief Retrieve the special "std" namespace, which may require us to
6804 /// implicitly define the namespace.
6805 NamespaceDecl *Sema::getOrCreateStdNamespace() {
6806   if (!StdNamespace) {
6807     // The "std" namespace has not yet been defined, so build one implicitly.
6808     StdNamespace = NamespaceDecl::Create(Context,
6809                                          Context.getTranslationUnitDecl(),
6810                                          /*Inline=*/false,
6811                                          SourceLocation(), SourceLocation(),
6812                                          &PP.getIdentifierTable().get("std"),
6813                                          /*PrevDecl=*/nullptr);
6814     getStdNamespace()->setImplicit(true);
6815   }
6816 
6817   return getStdNamespace();
6818 }
6819 
6820 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
6821   assert(getLangOpts().CPlusPlus &&
6822          "Looking for std::initializer_list outside of C++.");
6823 
6824   // We're looking for implicit instantiations of
6825   // template <typename E> class std::initializer_list.
6826 
6827   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6828     return false;
6829 
6830   ClassTemplateDecl *Template = nullptr;
6831   const TemplateArgument *Arguments = nullptr;
6832 
6833   if (const RecordType *RT = Ty->getAs<RecordType>()) {
6834 
6835     ClassTemplateSpecializationDecl *Specialization =
6836         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6837     if (!Specialization)
6838       return false;
6839 
6840     Template = Specialization->getSpecializedTemplate();
6841     Arguments = Specialization->getTemplateArgs().data();
6842   } else if (const TemplateSpecializationType *TST =
6843                  Ty->getAs<TemplateSpecializationType>()) {
6844     Template = dyn_cast_or_null<ClassTemplateDecl>(
6845         TST->getTemplateName().getAsTemplateDecl());
6846     Arguments = TST->getArgs();
6847   }
6848   if (!Template)
6849     return false;
6850 
6851   if (!StdInitializerList) {
6852     // Haven't recognized std::initializer_list yet, maybe this is it.
6853     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6854     if (TemplateClass->getIdentifier() !=
6855             &PP.getIdentifierTable().get("initializer_list") ||
6856         !getStdNamespace()->InEnclosingNamespaceSetOf(
6857             TemplateClass->getDeclContext()))
6858       return false;
6859     // This is a template called std::initializer_list, but is it the right
6860     // template?
6861     TemplateParameterList *Params = Template->getTemplateParameters();
6862     if (Params->getMinRequiredArguments() != 1)
6863       return false;
6864     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6865       return false;
6866 
6867     // It's the right template.
6868     StdInitializerList = Template;
6869   }
6870 
6871   if (Template != StdInitializerList)
6872     return false;
6873 
6874   // This is an instance of std::initializer_list. Find the argument type.
6875   if (Element)
6876     *Element = Arguments[0].getAsType();
6877   return true;
6878 }
6879 
6880 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6881   NamespaceDecl *Std = S.getStdNamespace();
6882   if (!Std) {
6883     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6884     return nullptr;
6885   }
6886 
6887   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6888                       Loc, Sema::LookupOrdinaryName);
6889   if (!S.LookupQualifiedName(Result, Std)) {
6890     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6891     return nullptr;
6892   }
6893   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6894   if (!Template) {
6895     Result.suppressDiagnostics();
6896     // We found something weird. Complain about the first thing we found.
6897     NamedDecl *Found = *Result.begin();
6898     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6899     return nullptr;
6900   }
6901 
6902   // We found some template called std::initializer_list. Now verify that it's
6903   // correct.
6904   TemplateParameterList *Params = Template->getTemplateParameters();
6905   if (Params->getMinRequiredArguments() != 1 ||
6906       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6907     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6908     return nullptr;
6909   }
6910 
6911   return Template;
6912 }
6913 
6914 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6915   if (!StdInitializerList) {
6916     StdInitializerList = LookupStdInitializerList(*this, Loc);
6917     if (!StdInitializerList)
6918       return QualType();
6919   }
6920 
6921   TemplateArgumentListInfo Args(Loc, Loc);
6922   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6923                                        Context.getTrivialTypeSourceInfo(Element,
6924                                                                         Loc)));
6925   return Context.getCanonicalType(
6926       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6927 }
6928 
6929 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6930   // C++ [dcl.init.list]p2:
6931   //   A constructor is an initializer-list constructor if its first parameter
6932   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
6933   //   std::initializer_list<E> for some type E, and either there are no other
6934   //   parameters or else all other parameters have default arguments.
6935   if (Ctor->getNumParams() < 1 ||
6936       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6937     return false;
6938 
6939   QualType ArgType = Ctor->getParamDecl(0)->getType();
6940   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6941     ArgType = RT->getPointeeType().getUnqualifiedType();
6942 
6943   return isStdInitializerList(ArgType, nullptr);
6944 }
6945 
6946 /// \brief Determine whether a using statement is in a context where it will be
6947 /// apply in all contexts.
6948 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6949   switch (CurContext->getDeclKind()) {
6950     case Decl::TranslationUnit:
6951       return true;
6952     case Decl::LinkageSpec:
6953       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6954     default:
6955       return false;
6956   }
6957 }
6958 
6959 namespace {
6960 
6961 // Callback to only accept typo corrections that are namespaces.
6962 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6963 public:
6964   bool ValidateCandidate(const TypoCorrection &candidate) override {
6965     if (NamedDecl *ND = candidate.getCorrectionDecl())
6966       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6967     return false;
6968   }
6969 };
6970 
6971 }
6972 
6973 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6974                                        CXXScopeSpec &SS,
6975                                        SourceLocation IdentLoc,
6976                                        IdentifierInfo *Ident) {
6977   NamespaceValidatorCCC Validator;
6978   R.clear();
6979   if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
6980                                                R.getLookupKind(), Sc, &SS,
6981                                                Validator,
6982                                                Sema::CTK_ErrorRecovery)) {
6983     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
6984       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6985       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
6986                               Ident->getName().equals(CorrectedStr);
6987       S.diagnoseTypo(Corrected,
6988                      S.PDiag(diag::err_using_directive_member_suggest)
6989                        << Ident << DC << DroppedSpecifier << SS.getRange(),
6990                      S.PDiag(diag::note_namespace_defined_here));
6991     } else {
6992       S.diagnoseTypo(Corrected,
6993                      S.PDiag(diag::err_using_directive_suggest) << Ident,
6994                      S.PDiag(diag::note_namespace_defined_here));
6995     }
6996     R.addDecl(Corrected.getCorrectionDecl());
6997     return true;
6998   }
6999   return false;
7000 }
7001 
7002 Decl *Sema::ActOnUsingDirective(Scope *S,
7003                                           SourceLocation UsingLoc,
7004                                           SourceLocation NamespcLoc,
7005                                           CXXScopeSpec &SS,
7006                                           SourceLocation IdentLoc,
7007                                           IdentifierInfo *NamespcName,
7008                                           AttributeList *AttrList) {
7009   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7010   assert(NamespcName && "Invalid NamespcName.");
7011   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
7012 
7013   // This can only happen along a recovery path.
7014   while (S->getFlags() & Scope::TemplateParamScope)
7015     S = S->getParent();
7016   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7017 
7018   UsingDirectiveDecl *UDir = nullptr;
7019   NestedNameSpecifier *Qualifier = nullptr;
7020   if (SS.isSet())
7021     Qualifier = SS.getScopeRep();
7022 
7023   // Lookup namespace name.
7024   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7025   LookupParsedName(R, S, &SS);
7026   if (R.isAmbiguous())
7027     return nullptr;
7028 
7029   if (R.empty()) {
7030     R.clear();
7031     // Allow "using namespace std;" or "using namespace ::std;" even if
7032     // "std" hasn't been defined yet, for GCC compatibility.
7033     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7034         NamespcName->isStr("std")) {
7035       Diag(IdentLoc, diag::ext_using_undefined_std);
7036       R.addDecl(getOrCreateStdNamespace());
7037       R.resolveKind();
7038     }
7039     // Otherwise, attempt typo correction.
7040     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
7041   }
7042 
7043   if (!R.empty()) {
7044     NamedDecl *Named = R.getFoundDecl();
7045     assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
7046         && "expected namespace decl");
7047     // C++ [namespace.udir]p1:
7048     //   A using-directive specifies that the names in the nominated
7049     //   namespace can be used in the scope in which the
7050     //   using-directive appears after the using-directive. During
7051     //   unqualified name lookup (3.4.1), the names appear as if they
7052     //   were declared in the nearest enclosing namespace which
7053     //   contains both the using-directive and the nominated
7054     //   namespace. [Note: in this context, "contains" means "contains
7055     //   directly or indirectly". ]
7056 
7057     // Find enclosing context containing both using-directive and
7058     // nominated namespace.
7059     NamespaceDecl *NS = getNamespaceDecl(Named);
7060     DeclContext *CommonAncestor = cast<DeclContext>(NS);
7061     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7062       CommonAncestor = CommonAncestor->getParent();
7063 
7064     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
7065                                       SS.getWithLocInContext(Context),
7066                                       IdentLoc, Named, CommonAncestor);
7067 
7068     if (IsUsingDirectiveInToplevelContext(CurContext) &&
7069         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
7070       Diag(IdentLoc, diag::warn_using_directive_in_header);
7071     }
7072 
7073     PushUsingDirective(S, UDir);
7074   } else {
7075     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
7076   }
7077 
7078   if (UDir)
7079     ProcessDeclAttributeList(S, UDir, AttrList);
7080 
7081   return UDir;
7082 }
7083 
7084 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
7085   // If the scope has an associated entity and the using directive is at
7086   // namespace or translation unit scope, add the UsingDirectiveDecl into
7087   // its lookup structure so qualified name lookup can find it.
7088   DeclContext *Ctx = S->getEntity();
7089   if (Ctx && !Ctx->isFunctionOrMethod())
7090     Ctx->addDecl(UDir);
7091   else
7092     // Otherwise, it is at block scope. The using-directives will affect lookup
7093     // only to the end of the scope.
7094     S->PushUsingDirective(UDir);
7095 }
7096 
7097 
7098 Decl *Sema::ActOnUsingDeclaration(Scope *S,
7099                                   AccessSpecifier AS,
7100                                   bool HasUsingKeyword,
7101                                   SourceLocation UsingLoc,
7102                                   CXXScopeSpec &SS,
7103                                   UnqualifiedId &Name,
7104                                   AttributeList *AttrList,
7105                                   bool HasTypenameKeyword,
7106                                   SourceLocation TypenameLoc) {
7107   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7108 
7109   switch (Name.getKind()) {
7110   case UnqualifiedId::IK_ImplicitSelfParam:
7111   case UnqualifiedId::IK_Identifier:
7112   case UnqualifiedId::IK_OperatorFunctionId:
7113   case UnqualifiedId::IK_LiteralOperatorId:
7114   case UnqualifiedId::IK_ConversionFunctionId:
7115     break;
7116 
7117   case UnqualifiedId::IK_ConstructorName:
7118   case UnqualifiedId::IK_ConstructorTemplateId:
7119     // C++11 inheriting constructors.
7120     Diag(Name.getLocStart(),
7121          getLangOpts().CPlusPlus11 ?
7122            diag::warn_cxx98_compat_using_decl_constructor :
7123            diag::err_using_decl_constructor)
7124       << SS.getRange();
7125 
7126     if (getLangOpts().CPlusPlus11) break;
7127 
7128     return nullptr;
7129 
7130   case UnqualifiedId::IK_DestructorName:
7131     Diag(Name.getLocStart(), diag::err_using_decl_destructor)
7132       << SS.getRange();
7133     return nullptr;
7134 
7135   case UnqualifiedId::IK_TemplateId:
7136     Diag(Name.getLocStart(), diag::err_using_decl_template_id)
7137       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
7138     return nullptr;
7139   }
7140 
7141   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7142   DeclarationName TargetName = TargetNameInfo.getName();
7143   if (!TargetName)
7144     return nullptr;
7145 
7146   // Warn about access declarations.
7147   if (!HasUsingKeyword) {
7148     Diag(Name.getLocStart(),
7149          getLangOpts().CPlusPlus11 ? diag::err_access_decl
7150                                    : diag::warn_access_decl_deprecated)
7151       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
7152   }
7153 
7154   if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7155       DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7156     return nullptr;
7157 
7158   NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
7159                                         TargetNameInfo, AttrList,
7160                                         /* IsInstantiation */ false,
7161                                         HasTypenameKeyword, TypenameLoc);
7162   if (UD)
7163     PushOnScopeChains(UD, S, /*AddToContext*/ false);
7164 
7165   return UD;
7166 }
7167 
7168 /// \brief Determine whether a using declaration considers the given
7169 /// declarations as "equivalent", e.g., if they are redeclarations of
7170 /// the same entity or are both typedefs of the same type.
7171 static bool
7172 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7173   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
7174     return true;
7175 
7176   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
7177     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
7178       return Context.hasSameType(TD1->getUnderlyingType(),
7179                                  TD2->getUnderlyingType());
7180 
7181   return false;
7182 }
7183 
7184 
7185 /// Determines whether to create a using shadow decl for a particular
7186 /// decl, given the set of decls existing prior to this using lookup.
7187 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
7188                                 const LookupResult &Previous,
7189                                 UsingShadowDecl *&PrevShadow) {
7190   // Diagnose finding a decl which is not from a base class of the
7191   // current class.  We do this now because there are cases where this
7192   // function will silently decide not to build a shadow decl, which
7193   // will pre-empt further diagnostics.
7194   //
7195   // We don't need to do this in C++0x because we do the check once on
7196   // the qualifier.
7197   //
7198   // FIXME: diagnose the following if we care enough:
7199   //   struct A { int foo; };
7200   //   struct B : A { using A::foo; };
7201   //   template <class T> struct C : A {};
7202   //   template <class T> struct D : C<T> { using B::foo; } // <---
7203   // This is invalid (during instantiation) in C++03 because B::foo
7204   // resolves to the using decl in B, which is not a base class of D<T>.
7205   // We can't diagnose it immediately because C<T> is an unknown
7206   // specialization.  The UsingShadowDecl in D<T> then points directly
7207   // to A::foo, which will look well-formed when we instantiate.
7208   // The right solution is to not collapse the shadow-decl chain.
7209   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
7210     DeclContext *OrigDC = Orig->getDeclContext();
7211 
7212     // Handle enums and anonymous structs.
7213     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7214     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7215     while (OrigRec->isAnonymousStructOrUnion())
7216       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7217 
7218     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7219       if (OrigDC == CurContext) {
7220         Diag(Using->getLocation(),
7221              diag::err_using_decl_nested_name_specifier_is_current_class)
7222           << Using->getQualifierLoc().getSourceRange();
7223         Diag(Orig->getLocation(), diag::note_using_decl_target);
7224         return true;
7225       }
7226 
7227       Diag(Using->getQualifierLoc().getBeginLoc(),
7228            diag::err_using_decl_nested_name_specifier_is_not_base_class)
7229         << Using->getQualifier()
7230         << cast<CXXRecordDecl>(CurContext)
7231         << Using->getQualifierLoc().getSourceRange();
7232       Diag(Orig->getLocation(), diag::note_using_decl_target);
7233       return true;
7234     }
7235   }
7236 
7237   if (Previous.empty()) return false;
7238 
7239   NamedDecl *Target = Orig;
7240   if (isa<UsingShadowDecl>(Target))
7241     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7242 
7243   // If the target happens to be one of the previous declarations, we
7244   // don't have a conflict.
7245   //
7246   // FIXME: but we might be increasing its access, in which case we
7247   // should redeclare it.
7248   NamedDecl *NonTag = nullptr, *Tag = nullptr;
7249   bool FoundEquivalentDecl = false;
7250   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7251          I != E; ++I) {
7252     NamedDecl *D = (*I)->getUnderlyingDecl();
7253     if (IsEquivalentForUsingDecl(Context, D, Target)) {
7254       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7255         PrevShadow = Shadow;
7256       FoundEquivalentDecl = true;
7257     }
7258 
7259     (isa<TagDecl>(D) ? Tag : NonTag) = D;
7260   }
7261 
7262   if (FoundEquivalentDecl)
7263     return false;
7264 
7265   if (FunctionDecl *FD = Target->getAsFunction()) {
7266     NamedDecl *OldDecl = nullptr;
7267     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7268                           /*IsForUsingDecl*/ true)) {
7269     case Ovl_Overload:
7270       return false;
7271 
7272     case Ovl_NonFunction:
7273       Diag(Using->getLocation(), diag::err_using_decl_conflict);
7274       break;
7275 
7276     // We found a decl with the exact signature.
7277     case Ovl_Match:
7278       // If we're in a record, we want to hide the target, so we
7279       // return true (without a diagnostic) to tell the caller not to
7280       // build a shadow decl.
7281       if (CurContext->isRecord())
7282         return true;
7283 
7284       // If we're not in a record, this is an error.
7285       Diag(Using->getLocation(), diag::err_using_decl_conflict);
7286       break;
7287     }
7288 
7289     Diag(Target->getLocation(), diag::note_using_decl_target);
7290     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7291     return true;
7292   }
7293 
7294   // Target is not a function.
7295 
7296   if (isa<TagDecl>(Target)) {
7297     // No conflict between a tag and a non-tag.
7298     if (!Tag) return false;
7299 
7300     Diag(Using->getLocation(), diag::err_using_decl_conflict);
7301     Diag(Target->getLocation(), diag::note_using_decl_target);
7302     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7303     return true;
7304   }
7305 
7306   // No conflict between a tag and a non-tag.
7307   if (!NonTag) return false;
7308 
7309   Diag(Using->getLocation(), diag::err_using_decl_conflict);
7310   Diag(Target->getLocation(), diag::note_using_decl_target);
7311   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7312   return true;
7313 }
7314 
7315 /// Builds a shadow declaration corresponding to a 'using' declaration.
7316 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
7317                                             UsingDecl *UD,
7318                                             NamedDecl *Orig,
7319                                             UsingShadowDecl *PrevDecl) {
7320 
7321   // If we resolved to another shadow declaration, just coalesce them.
7322   NamedDecl *Target = Orig;
7323   if (isa<UsingShadowDecl>(Target)) {
7324     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7325     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
7326   }
7327 
7328   UsingShadowDecl *Shadow
7329     = UsingShadowDecl::Create(Context, CurContext,
7330                               UD->getLocation(), UD, Target);
7331   UD->addShadowDecl(Shadow);
7332 
7333   Shadow->setAccess(UD->getAccess());
7334   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7335     Shadow->setInvalidDecl();
7336 
7337   Shadow->setPreviousDecl(PrevDecl);
7338 
7339   if (S)
7340     PushOnScopeChains(Shadow, S);
7341   else
7342     CurContext->addDecl(Shadow);
7343 
7344 
7345   return Shadow;
7346 }
7347 
7348 /// Hides a using shadow declaration.  This is required by the current
7349 /// using-decl implementation when a resolvable using declaration in a
7350 /// class is followed by a declaration which would hide or override
7351 /// one or more of the using decl's targets; for example:
7352 ///
7353 ///   struct Base { void foo(int); };
7354 ///   struct Derived : Base {
7355 ///     using Base::foo;
7356 ///     void foo(int);
7357 ///   };
7358 ///
7359 /// The governing language is C++03 [namespace.udecl]p12:
7360 ///
7361 ///   When a using-declaration brings names from a base class into a
7362 ///   derived class scope, member functions in the derived class
7363 ///   override and/or hide member functions with the same name and
7364 ///   parameter types in a base class (rather than conflicting).
7365 ///
7366 /// There are two ways to implement this:
7367 ///   (1) optimistically create shadow decls when they're not hidden
7368 ///       by existing declarations, or
7369 ///   (2) don't create any shadow decls (or at least don't make them
7370 ///       visible) until we've fully parsed/instantiated the class.
7371 /// The problem with (1) is that we might have to retroactively remove
7372 /// a shadow decl, which requires several O(n) operations because the
7373 /// decl structures are (very reasonably) not designed for removal.
7374 /// (2) avoids this but is very fiddly and phase-dependent.
7375 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
7376   if (Shadow->getDeclName().getNameKind() ==
7377         DeclarationName::CXXConversionFunctionName)
7378     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7379 
7380   // Remove it from the DeclContext...
7381   Shadow->getDeclContext()->removeDecl(Shadow);
7382 
7383   // ...and the scope, if applicable...
7384   if (S) {
7385     S->RemoveDecl(Shadow);
7386     IdResolver.RemoveDecl(Shadow);
7387   }
7388 
7389   // ...and the using decl.
7390   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7391 
7392   // TODO: complain somehow if Shadow was used.  It shouldn't
7393   // be possible for this to happen, because...?
7394 }
7395 
7396 /// Find the base specifier for a base class with the given type.
7397 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7398                                                 QualType DesiredBase,
7399                                                 bool &AnyDependentBases) {
7400   // Check whether the named type is a direct base class.
7401   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7402   for (auto &Base : Derived->bases()) {
7403     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7404     if (CanonicalDesiredBase == BaseType)
7405       return &Base;
7406     if (BaseType->isDependentType())
7407       AnyDependentBases = true;
7408   }
7409   return nullptr;
7410 }
7411 
7412 namespace {
7413 class UsingValidatorCCC : public CorrectionCandidateCallback {
7414 public:
7415   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
7416                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
7417       : HasTypenameKeyword(HasTypenameKeyword),
7418         IsInstantiation(IsInstantiation), OldNNS(NNS),
7419         RequireMemberOf(RequireMemberOf) {}
7420 
7421   bool ValidateCandidate(const TypoCorrection &Candidate) override {
7422     NamedDecl *ND = Candidate.getCorrectionDecl();
7423 
7424     // Keywords are not valid here.
7425     if (!ND || isa<NamespaceDecl>(ND))
7426       return false;
7427 
7428     // Completely unqualified names are invalid for a 'using' declaration.
7429     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7430       return false;
7431 
7432     if (RequireMemberOf) {
7433       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
7434       if (FoundRecord && FoundRecord->isInjectedClassName()) {
7435         // No-one ever wants a using-declaration to name an injected-class-name
7436         // of a base class, unless they're declaring an inheriting constructor.
7437         ASTContext &Ctx = ND->getASTContext();
7438         if (!Ctx.getLangOpts().CPlusPlus11)
7439           return false;
7440         QualType FoundType = Ctx.getRecordType(FoundRecord);
7441 
7442         // Check that the injected-class-name is named as a member of its own
7443         // type; we don't want to suggest 'using Derived::Base;', since that
7444         // means something else.
7445         NestedNameSpecifier *Specifier =
7446             Candidate.WillReplaceSpecifier()
7447                 ? Candidate.getCorrectionSpecifier()
7448                 : OldNNS;
7449         if (!Specifier->getAsType() ||
7450             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
7451           return false;
7452 
7453         // Check that this inheriting constructor declaration actually names a
7454         // direct base class of the current class.
7455         bool AnyDependentBases = false;
7456         if (!findDirectBaseWithType(RequireMemberOf,
7457                                     Ctx.getRecordType(FoundRecord),
7458                                     AnyDependentBases) &&
7459             !AnyDependentBases)
7460           return false;
7461       } else {
7462         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
7463         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
7464           return false;
7465 
7466         // FIXME: Check that the base class member is accessible?
7467       }
7468     }
7469 
7470     if (isa<TypeDecl>(ND))
7471       return HasTypenameKeyword || !IsInstantiation;
7472 
7473     return !HasTypenameKeyword;
7474   }
7475 
7476 private:
7477   bool HasTypenameKeyword;
7478   bool IsInstantiation;
7479   NestedNameSpecifier *OldNNS;
7480   CXXRecordDecl *RequireMemberOf;
7481 };
7482 } // end anonymous namespace
7483 
7484 /// Builds a using declaration.
7485 ///
7486 /// \param IsInstantiation - Whether this call arises from an
7487 ///   instantiation of an unresolved using declaration.  We treat
7488 ///   the lookup differently for these declarations.
7489 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7490                                        SourceLocation UsingLoc,
7491                                        CXXScopeSpec &SS,
7492                                        DeclarationNameInfo NameInfo,
7493                                        AttributeList *AttrList,
7494                                        bool IsInstantiation,
7495                                        bool HasTypenameKeyword,
7496                                        SourceLocation TypenameLoc) {
7497   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7498   SourceLocation IdentLoc = NameInfo.getLoc();
7499   assert(IdentLoc.isValid() && "Invalid TargetName location.");
7500 
7501   // FIXME: We ignore attributes for now.
7502 
7503   if (SS.isEmpty()) {
7504     Diag(IdentLoc, diag::err_using_requires_qualname);
7505     return nullptr;
7506   }
7507 
7508   // Do the redeclaration lookup in the current scope.
7509   LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
7510                         ForRedeclaration);
7511   Previous.setHideTags(false);
7512   if (S) {
7513     LookupName(Previous, S);
7514 
7515     // It is really dumb that we have to do this.
7516     LookupResult::Filter F = Previous.makeFilter();
7517     while (F.hasNext()) {
7518       NamedDecl *D = F.next();
7519       if (!isDeclInScope(D, CurContext, S))
7520         F.erase();
7521       // If we found a local extern declaration that's not ordinarily visible,
7522       // and this declaration is being added to a non-block scope, ignore it.
7523       // We're only checking for scope conflicts here, not also for violations
7524       // of the linkage rules.
7525       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
7526                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
7527         F.erase();
7528     }
7529     F.done();
7530   } else {
7531     assert(IsInstantiation && "no scope in non-instantiation");
7532     assert(CurContext->isRecord() && "scope not record in instantiation");
7533     LookupQualifiedName(Previous, CurContext);
7534   }
7535 
7536   // Check for invalid redeclarations.
7537   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7538                                   SS, IdentLoc, Previous))
7539     return nullptr;
7540 
7541   // Check for bad qualifiers.
7542   if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
7543     return nullptr;
7544 
7545   DeclContext *LookupContext = computeDeclContext(SS);
7546   NamedDecl *D;
7547   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
7548   if (!LookupContext) {
7549     if (HasTypenameKeyword) {
7550       // FIXME: not all declaration name kinds are legal here
7551       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7552                                               UsingLoc, TypenameLoc,
7553                                               QualifierLoc,
7554                                               IdentLoc, NameInfo.getName());
7555     } else {
7556       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7557                                            QualifierLoc, NameInfo);
7558     }
7559     D->setAccess(AS);
7560     CurContext->addDecl(D);
7561     return D;
7562   }
7563 
7564   auto Build = [&](bool Invalid) {
7565     UsingDecl *UD =
7566         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
7567                           HasTypenameKeyword);
7568     UD->setAccess(AS);
7569     CurContext->addDecl(UD);
7570     UD->setInvalidDecl(Invalid);
7571     return UD;
7572   };
7573   auto BuildInvalid = [&]{ return Build(true); };
7574   auto BuildValid = [&]{ return Build(false); };
7575 
7576   if (RequireCompleteDeclContext(SS, LookupContext))
7577     return BuildInvalid();
7578 
7579   // The normal rules do not apply to inheriting constructor declarations.
7580   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
7581     UsingDecl *UD = BuildValid();
7582     CheckInheritingConstructorUsingDecl(UD);
7583     return UD;
7584   }
7585 
7586   // Otherwise, look up the target name.
7587 
7588   LookupResult R(*this, NameInfo, LookupOrdinaryName);
7589 
7590   // Unlike most lookups, we don't always want to hide tag
7591   // declarations: tag names are visible through the using declaration
7592   // even if hidden by ordinary names, *except* in a dependent context
7593   // where it's important for the sanity of two-phase lookup.
7594   if (!IsInstantiation)
7595     R.setHideTags(false);
7596 
7597   // For the purposes of this lookup, we have a base object type
7598   // equal to that of the current context.
7599   if (CurContext->isRecord()) {
7600     R.setBaseObjectType(
7601                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7602   }
7603 
7604   LookupQualifiedName(R, LookupContext);
7605 
7606   // Try to correct typos if possible.
7607   if (R.empty()) {
7608     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
7609                           dyn_cast<CXXRecordDecl>(CurContext));
7610     if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
7611                                                R.getLookupKind(), S, &SS, CCC,
7612                                                CTK_ErrorRecovery)){
7613       // We reject any correction for which ND would be NULL.
7614       NamedDecl *ND = Corrected.getCorrectionDecl();
7615 
7616       // We reject candidates where DroppedSpecifier == true, hence the
7617       // literal '0' below.
7618       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7619                                 << NameInfo.getName() << LookupContext << 0
7620                                 << SS.getRange());
7621 
7622       // If we corrected to an inheriting constructor, handle it as one.
7623       auto *RD = dyn_cast<CXXRecordDecl>(ND);
7624       if (RD && RD->isInjectedClassName()) {
7625         // Fix up the information we'll use to build the using declaration.
7626         if (Corrected.WillReplaceSpecifier()) {
7627           NestedNameSpecifierLocBuilder Builder;
7628           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
7629                               QualifierLoc.getSourceRange());
7630           QualifierLoc = Builder.getWithLocInContext(Context);
7631         }
7632 
7633         NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
7634             Context.getCanonicalType(Context.getRecordType(RD))));
7635         NameInfo.setNamedTypeInfo(nullptr);
7636 
7637         // Build it and process it as an inheriting constructor.
7638         UsingDecl *UD = BuildValid();
7639         CheckInheritingConstructorUsingDecl(UD);
7640         return UD;
7641       }
7642 
7643       // FIXME: Pick up all the declarations if we found an overloaded function.
7644       R.setLookupName(Corrected.getCorrection());
7645       R.addDecl(ND);
7646     } else {
7647       Diag(IdentLoc, diag::err_no_member)
7648         << NameInfo.getName() << LookupContext << SS.getRange();
7649       return BuildInvalid();
7650     }
7651   }
7652 
7653   if (R.isAmbiguous())
7654     return BuildInvalid();
7655 
7656   if (HasTypenameKeyword) {
7657     // If we asked for a typename and got a non-type decl, error out.
7658     if (!R.getAsSingle<TypeDecl>()) {
7659       Diag(IdentLoc, diag::err_using_typename_non_type);
7660       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7661         Diag((*I)->getUnderlyingDecl()->getLocation(),
7662              diag::note_using_decl_target);
7663       return BuildInvalid();
7664     }
7665   } else {
7666     // If we asked for a non-typename and we got a type, error out,
7667     // but only if this is an instantiation of an unresolved using
7668     // decl.  Otherwise just silently find the type name.
7669     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
7670       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7671       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
7672       return BuildInvalid();
7673     }
7674   }
7675 
7676   // C++0x N2914 [namespace.udecl]p6:
7677   // A using-declaration shall not name a namespace.
7678   if (R.getAsSingle<NamespaceDecl>()) {
7679     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7680       << SS.getRange();
7681     return BuildInvalid();
7682   }
7683 
7684   UsingDecl *UD = BuildValid();
7685   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7686     UsingShadowDecl *PrevDecl = nullptr;
7687     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
7688       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
7689   }
7690 
7691   return UD;
7692 }
7693 
7694 /// Additional checks for a using declaration referring to a constructor name.
7695 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
7696   assert(!UD->hasTypename() && "expecting a constructor name");
7697 
7698   const Type *SourceType = UD->getQualifier()->getAsType();
7699   assert(SourceType &&
7700          "Using decl naming constructor doesn't have type in scope spec.");
7701   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7702 
7703   // Check whether the named type is a direct base class.
7704   bool AnyDependentBases = false;
7705   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
7706                                       AnyDependentBases);
7707   if (!Base && !AnyDependentBases) {
7708     Diag(UD->getUsingLoc(),
7709          diag::err_using_decl_constructor_not_in_direct_base)
7710       << UD->getNameInfo().getSourceRange()
7711       << QualType(SourceType, 0) << TargetClass;
7712     UD->setInvalidDecl();
7713     return true;
7714   }
7715 
7716   if (Base)
7717     Base->setInheritConstructors();
7718 
7719   return false;
7720 }
7721 
7722 /// Checks that the given using declaration is not an invalid
7723 /// redeclaration.  Note that this is checking only for the using decl
7724 /// itself, not for any ill-formedness among the UsingShadowDecls.
7725 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7726                                        bool HasTypenameKeyword,
7727                                        const CXXScopeSpec &SS,
7728                                        SourceLocation NameLoc,
7729                                        const LookupResult &Prev) {
7730   // C++03 [namespace.udecl]p8:
7731   // C++0x [namespace.udecl]p10:
7732   //   A using-declaration is a declaration and can therefore be used
7733   //   repeatedly where (and only where) multiple declarations are
7734   //   allowed.
7735   //
7736   // That's in non-member contexts.
7737   if (!CurContext->getRedeclContext()->isRecord())
7738     return false;
7739 
7740   NestedNameSpecifier *Qual = SS.getScopeRep();
7741 
7742   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7743     NamedDecl *D = *I;
7744 
7745     bool DTypename;
7746     NestedNameSpecifier *DQual;
7747     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7748       DTypename = UD->hasTypename();
7749       DQual = UD->getQualifier();
7750     } else if (UnresolvedUsingValueDecl *UD
7751                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7752       DTypename = false;
7753       DQual = UD->getQualifier();
7754     } else if (UnresolvedUsingTypenameDecl *UD
7755                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7756       DTypename = true;
7757       DQual = UD->getQualifier();
7758     } else continue;
7759 
7760     // using decls differ if one says 'typename' and the other doesn't.
7761     // FIXME: non-dependent using decls?
7762     if (HasTypenameKeyword != DTypename) continue;
7763 
7764     // using decls differ if they name different scopes (but note that
7765     // template instantiation can cause this check to trigger when it
7766     // didn't before instantiation).
7767     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7768         Context.getCanonicalNestedNameSpecifier(DQual))
7769       continue;
7770 
7771     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
7772     Diag(D->getLocation(), diag::note_using_decl) << 1;
7773     return true;
7774   }
7775 
7776   return false;
7777 }
7778 
7779 
7780 /// Checks that the given nested-name qualifier used in a using decl
7781 /// in the current context is appropriately related to the current
7782 /// scope.  If an error is found, diagnoses it and returns true.
7783 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7784                                    const CXXScopeSpec &SS,
7785                                    const DeclarationNameInfo &NameInfo,
7786                                    SourceLocation NameLoc) {
7787   DeclContext *NamedContext = computeDeclContext(SS);
7788 
7789   if (!CurContext->isRecord()) {
7790     // C++03 [namespace.udecl]p3:
7791     // C++0x [namespace.udecl]p8:
7792     //   A using-declaration for a class member shall be a member-declaration.
7793 
7794     // If we weren't able to compute a valid scope, it must be a
7795     // dependent class scope.
7796     if (!NamedContext || NamedContext->isRecord()) {
7797       auto *RD = dyn_cast<CXXRecordDecl>(NamedContext);
7798       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
7799         RD = nullptr;
7800 
7801       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7802         << SS.getRange();
7803 
7804       // If we have a complete, non-dependent source type, try to suggest a
7805       // way to get the same effect.
7806       if (!RD)
7807         return true;
7808 
7809       // Find what this using-declaration was referring to.
7810       LookupResult R(*this, NameInfo, LookupOrdinaryName);
7811       R.setHideTags(false);
7812       R.suppressDiagnostics();
7813       LookupQualifiedName(R, RD);
7814 
7815       if (R.getAsSingle<TypeDecl>()) {
7816         if (getLangOpts().CPlusPlus11) {
7817           // Convert 'using X::Y;' to 'using Y = X::Y;'.
7818           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
7819             << 0 // alias declaration
7820             << FixItHint::CreateInsertion(SS.getBeginLoc(),
7821                                           NameInfo.getName().getAsString() +
7822                                               " = ");
7823         } else {
7824           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
7825           SourceLocation InsertLoc =
7826               PP.getLocForEndOfToken(NameInfo.getLocEnd());
7827           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
7828             << 1 // typedef declaration
7829             << FixItHint::CreateReplacement(UsingLoc, "typedef")
7830             << FixItHint::CreateInsertion(
7831                    InsertLoc, " " + NameInfo.getName().getAsString());
7832         }
7833       } else if (R.getAsSingle<VarDecl>()) {
7834         // Don't provide a fixit outside C++11 mode; we don't want to suggest
7835         // repeating the type of the static data member here.
7836         FixItHint FixIt;
7837         if (getLangOpts().CPlusPlus11) {
7838           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
7839           FixIt = FixItHint::CreateReplacement(
7840               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
7841         }
7842 
7843         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
7844           << 2 // reference declaration
7845           << FixIt;
7846       }
7847       return true;
7848     }
7849 
7850     // Otherwise, everything is known to be fine.
7851     return false;
7852   }
7853 
7854   // The current scope is a record.
7855 
7856   // If the named context is dependent, we can't decide much.
7857   if (!NamedContext) {
7858     // FIXME: in C++0x, we can diagnose if we can prove that the
7859     // nested-name-specifier does not refer to a base class, which is
7860     // still possible in some cases.
7861 
7862     // Otherwise we have to conservatively report that things might be
7863     // okay.
7864     return false;
7865   }
7866 
7867   if (!NamedContext->isRecord()) {
7868     // Ideally this would point at the last name in the specifier,
7869     // but we don't have that level of source info.
7870     Diag(SS.getRange().getBegin(),
7871          diag::err_using_decl_nested_name_specifier_is_not_class)
7872       << SS.getScopeRep() << SS.getRange();
7873     return true;
7874   }
7875 
7876   if (!NamedContext->isDependentContext() &&
7877       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7878     return true;
7879 
7880   if (getLangOpts().CPlusPlus11) {
7881     // C++0x [namespace.udecl]p3:
7882     //   In a using-declaration used as a member-declaration, the
7883     //   nested-name-specifier shall name a base class of the class
7884     //   being defined.
7885 
7886     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7887                                  cast<CXXRecordDecl>(NamedContext))) {
7888       if (CurContext == NamedContext) {
7889         Diag(NameLoc,
7890              diag::err_using_decl_nested_name_specifier_is_current_class)
7891           << SS.getRange();
7892         return true;
7893       }
7894 
7895       Diag(SS.getRange().getBegin(),
7896            diag::err_using_decl_nested_name_specifier_is_not_base_class)
7897         << SS.getScopeRep()
7898         << cast<CXXRecordDecl>(CurContext)
7899         << SS.getRange();
7900       return true;
7901     }
7902 
7903     return false;
7904   }
7905 
7906   // C++03 [namespace.udecl]p4:
7907   //   A using-declaration used as a member-declaration shall refer
7908   //   to a member of a base class of the class being defined [etc.].
7909 
7910   // Salient point: SS doesn't have to name a base class as long as
7911   // lookup only finds members from base classes.  Therefore we can
7912   // diagnose here only if we can prove that that can't happen,
7913   // i.e. if the class hierarchies provably don't intersect.
7914 
7915   // TODO: it would be nice if "definitely valid" results were cached
7916   // in the UsingDecl and UsingShadowDecl so that these checks didn't
7917   // need to be repeated.
7918 
7919   struct UserData {
7920     llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
7921 
7922     static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7923       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7924       Data->Bases.insert(Base);
7925       return true;
7926     }
7927 
7928     bool hasDependentBases(const CXXRecordDecl *Class) {
7929       return !Class->forallBases(collect, this);
7930     }
7931 
7932     /// Returns true if the base is dependent or is one of the
7933     /// accumulated base classes.
7934     static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7935       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7936       return !Data->Bases.count(Base);
7937     }
7938 
7939     bool mightShareBases(const CXXRecordDecl *Class) {
7940       return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7941     }
7942   };
7943 
7944   UserData Data;
7945 
7946   // Returns false if we find a dependent base.
7947   if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7948     return false;
7949 
7950   // Returns false if the class has a dependent base or if it or one
7951   // of its bases is present in the base set of the current context.
7952   if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7953     return false;
7954 
7955   Diag(SS.getRange().getBegin(),
7956        diag::err_using_decl_nested_name_specifier_is_not_base_class)
7957     << SS.getScopeRep()
7958     << cast<CXXRecordDecl>(CurContext)
7959     << SS.getRange();
7960 
7961   return true;
7962 }
7963 
7964 Decl *Sema::ActOnAliasDeclaration(Scope *S,
7965                                   AccessSpecifier AS,
7966                                   MultiTemplateParamsArg TemplateParamLists,
7967                                   SourceLocation UsingLoc,
7968                                   UnqualifiedId &Name,
7969                                   AttributeList *AttrList,
7970                                   TypeResult Type) {
7971   // Skip up to the relevant declaration scope.
7972   while (S->getFlags() & Scope::TemplateParamScope)
7973     S = S->getParent();
7974   assert((S->getFlags() & Scope::DeclScope) &&
7975          "got alias-declaration outside of declaration scope");
7976 
7977   if (Type.isInvalid())
7978     return nullptr;
7979 
7980   bool Invalid = false;
7981   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7982   TypeSourceInfo *TInfo = nullptr;
7983   GetTypeFromParser(Type.get(), &TInfo);
7984 
7985   if (DiagnoseClassNameShadow(CurContext, NameInfo))
7986     return nullptr;
7987 
7988   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
7989                                       UPPC_DeclarationType)) {
7990     Invalid = true;
7991     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7992                                              TInfo->getTypeLoc().getBeginLoc());
7993   }
7994 
7995   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7996   LookupName(Previous, S);
7997 
7998   // Warn about shadowing the name of a template parameter.
7999   if (Previous.isSingleResult() &&
8000       Previous.getFoundDecl()->isTemplateParameter()) {
8001     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
8002     Previous.clear();
8003   }
8004 
8005   assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8006          "name in alias declaration must be an identifier");
8007   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
8008                                                Name.StartLocation,
8009                                                Name.Identifier, TInfo);
8010 
8011   NewTD->setAccess(AS);
8012 
8013   if (Invalid)
8014     NewTD->setInvalidDecl();
8015 
8016   ProcessDeclAttributeList(S, NewTD, AttrList);
8017 
8018   CheckTypedefForVariablyModifiedType(S, NewTD);
8019   Invalid |= NewTD->isInvalidDecl();
8020 
8021   bool Redeclaration = false;
8022 
8023   NamedDecl *NewND;
8024   if (TemplateParamLists.size()) {
8025     TypeAliasTemplateDecl *OldDecl = nullptr;
8026     TemplateParameterList *OldTemplateParams = nullptr;
8027 
8028     if (TemplateParamLists.size() != 1) {
8029       Diag(UsingLoc, diag::err_alias_template_extra_headers)
8030         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8031          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
8032     }
8033     TemplateParameterList *TemplateParams = TemplateParamLists[0];
8034 
8035     // Only consider previous declarations in the same scope.
8036     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8037                          /*ExplicitInstantiationOrSpecialization*/false);
8038     if (!Previous.empty()) {
8039       Redeclaration = true;
8040 
8041       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8042       if (!OldDecl && !Invalid) {
8043         Diag(UsingLoc, diag::err_redefinition_different_kind)
8044           << Name.Identifier;
8045 
8046         NamedDecl *OldD = Previous.getRepresentativeDecl();
8047         if (OldD->getLocation().isValid())
8048           Diag(OldD->getLocation(), diag::note_previous_definition);
8049 
8050         Invalid = true;
8051       }
8052 
8053       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8054         if (TemplateParameterListsAreEqual(TemplateParams,
8055                                            OldDecl->getTemplateParameters(),
8056                                            /*Complain=*/true,
8057                                            TPL_TemplateMatch))
8058           OldTemplateParams = OldDecl->getTemplateParameters();
8059         else
8060           Invalid = true;
8061 
8062         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8063         if (!Invalid &&
8064             !Context.hasSameType(OldTD->getUnderlyingType(),
8065                                  NewTD->getUnderlyingType())) {
8066           // FIXME: The C++0x standard does not clearly say this is ill-formed,
8067           // but we can't reasonably accept it.
8068           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8069             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8070           if (OldTD->getLocation().isValid())
8071             Diag(OldTD->getLocation(), diag::note_previous_definition);
8072           Invalid = true;
8073         }
8074       }
8075     }
8076 
8077     // Merge any previous default template arguments into our parameters,
8078     // and check the parameter list.
8079     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8080                                    TPC_TypeAliasTemplate))
8081       return nullptr;
8082 
8083     TypeAliasTemplateDecl *NewDecl =
8084       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8085                                     Name.Identifier, TemplateParams,
8086                                     NewTD);
8087 
8088     NewDecl->setAccess(AS);
8089 
8090     if (Invalid)
8091       NewDecl->setInvalidDecl();
8092     else if (OldDecl)
8093       NewDecl->setPreviousDecl(OldDecl);
8094 
8095     NewND = NewDecl;
8096   } else {
8097     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8098     NewND = NewTD;
8099   }
8100 
8101   if (!Redeclaration)
8102     PushOnScopeChains(NewND, S);
8103 
8104   ActOnDocumentableDecl(NewND);
8105   return NewND;
8106 }
8107 
8108 Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
8109                                              SourceLocation NamespaceLoc,
8110                                              SourceLocation AliasLoc,
8111                                              IdentifierInfo *Alias,
8112                                              CXXScopeSpec &SS,
8113                                              SourceLocation IdentLoc,
8114                                              IdentifierInfo *Ident) {
8115 
8116   // Lookup the namespace name.
8117   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8118   LookupParsedName(R, S, &SS);
8119 
8120   // Check if we have a previous declaration with the same name.
8121   NamedDecl *PrevDecl
8122     = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
8123                        ForRedeclaration);
8124   if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
8125     PrevDecl = nullptr;
8126 
8127   if (PrevDecl) {
8128     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
8129       // We already have an alias with the same name that points to the same
8130       // namespace, so don't create a new one.
8131       // FIXME: At some point, we'll want to create the (redundant)
8132       // declaration to maintain better source information.
8133       if (!R.isAmbiguous() && !R.empty() &&
8134           AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
8135         return nullptr;
8136     }
8137 
8138     unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
8139       diag::err_redefinition_different_kind;
8140     Diag(AliasLoc, DiagID) << Alias;
8141     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8142     return nullptr;
8143   }
8144 
8145   if (R.isAmbiguous())
8146     return nullptr;
8147 
8148   if (R.empty()) {
8149     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
8150       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
8151       return nullptr;
8152     }
8153   }
8154 
8155   NamespaceAliasDecl *AliasDecl =
8156     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
8157                                Alias, SS.getWithLocInContext(Context),
8158                                IdentLoc, R.getFoundDecl());
8159 
8160   PushOnScopeChains(AliasDecl, S);
8161   return AliasDecl;
8162 }
8163 
8164 Sema::ImplicitExceptionSpecification
8165 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8166                                                CXXMethodDecl *MD) {
8167   CXXRecordDecl *ClassDecl = MD->getParent();
8168 
8169   // C++ [except.spec]p14:
8170   //   An implicitly declared special member function (Clause 12) shall have an
8171   //   exception-specification. [...]
8172   ImplicitExceptionSpecification ExceptSpec(*this);
8173   if (ClassDecl->isInvalidDecl())
8174     return ExceptSpec;
8175 
8176   // Direct base-class constructors.
8177   for (const auto &B : ClassDecl->bases()) {
8178     if (B.isVirtual()) // Handled below.
8179       continue;
8180 
8181     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8182       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8183       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8184       // If this is a deleted function, add it anyway. This might be conformant
8185       // with the standard. This might not. I'm not sure. It might not matter.
8186       if (Constructor)
8187         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8188     }
8189   }
8190 
8191   // Virtual base-class constructors.
8192   for (const auto &B : ClassDecl->vbases()) {
8193     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8194       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8195       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8196       // If this is a deleted function, add it anyway. This might be conformant
8197       // with the standard. This might not. I'm not sure. It might not matter.
8198       if (Constructor)
8199         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8200     }
8201   }
8202 
8203   // Field constructors.
8204   for (const auto *F : ClassDecl->fields()) {
8205     if (F->hasInClassInitializer()) {
8206       if (Expr *E = F->getInClassInitializer())
8207         ExceptSpec.CalledExpr(E);
8208       else if (!F->isInvalidDecl())
8209         // DR1351:
8210         //   If the brace-or-equal-initializer of a non-static data member
8211         //   invokes a defaulted default constructor of its class or of an
8212         //   enclosing class in a potentially evaluated subexpression, the
8213         //   program is ill-formed.
8214         //
8215         // This resolution is unworkable: the exception specification of the
8216         // default constructor can be needed in an unevaluated context, in
8217         // particular, in the operand of a noexcept-expression, and we can be
8218         // unable to compute an exception specification for an enclosed class.
8219         //
8220         // We do not allow an in-class initializer to require the evaluation
8221         // of the exception specification for any in-class initializer whose
8222         // definition is not lexically complete.
8223         Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
8224     } else if (const RecordType *RecordTy
8225               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8226       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8227       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8228       // If this is a deleted function, add it anyway. This might be conformant
8229       // with the standard. This might not. I'm not sure. It might not matter.
8230       // In particular, the problem is that this function never gets called. It
8231       // might just be ill-formed because this function attempts to refer to
8232       // a deleted function here.
8233       if (Constructor)
8234         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8235     }
8236   }
8237 
8238   return ExceptSpec;
8239 }
8240 
8241 Sema::ImplicitExceptionSpecification
8242 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8243   CXXRecordDecl *ClassDecl = CD->getParent();
8244 
8245   // C++ [except.spec]p14:
8246   //   An inheriting constructor [...] shall have an exception-specification. [...]
8247   ImplicitExceptionSpecification ExceptSpec(*this);
8248   if (ClassDecl->isInvalidDecl())
8249     return ExceptSpec;
8250 
8251   // Inherited constructor.
8252   const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8253   const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8254   // FIXME: Copying or moving the parameters could add extra exceptions to the
8255   // set, as could the default arguments for the inherited constructor. This
8256   // will be addressed when we implement the resolution of core issue 1351.
8257   ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8258 
8259   // Direct base-class constructors.
8260   for (const auto &B : ClassDecl->bases()) {
8261     if (B.isVirtual()) // Handled below.
8262       continue;
8263 
8264     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8265       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8266       if (BaseClassDecl == InheritedDecl)
8267         continue;
8268       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8269       if (Constructor)
8270         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8271     }
8272   }
8273 
8274   // Virtual base-class constructors.
8275   for (const auto &B : ClassDecl->vbases()) {
8276     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8277       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8278       if (BaseClassDecl == InheritedDecl)
8279         continue;
8280       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8281       if (Constructor)
8282         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8283     }
8284   }
8285 
8286   // Field constructors.
8287   for (const auto *F : ClassDecl->fields()) {
8288     if (F->hasInClassInitializer()) {
8289       if (Expr *E = F->getInClassInitializer())
8290         ExceptSpec.CalledExpr(E);
8291       else if (!F->isInvalidDecl())
8292         Diag(CD->getLocation(),
8293              diag::err_in_class_initializer_references_def_ctor) << CD;
8294     } else if (const RecordType *RecordTy
8295               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8296       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8297       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8298       if (Constructor)
8299         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8300     }
8301   }
8302 
8303   return ExceptSpec;
8304 }
8305 
8306 namespace {
8307 /// RAII object to register a special member as being currently declared.
8308 struct DeclaringSpecialMember {
8309   Sema &S;
8310   Sema::SpecialMemberDecl D;
8311   bool WasAlreadyBeingDeclared;
8312 
8313   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8314     : S(S), D(RD, CSM) {
8315     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8316     if (WasAlreadyBeingDeclared)
8317       // This almost never happens, but if it does, ensure that our cache
8318       // doesn't contain a stale result.
8319       S.SpecialMemberCache.clear();
8320 
8321     // FIXME: Register a note to be produced if we encounter an error while
8322     // declaring the special member.
8323   }
8324   ~DeclaringSpecialMember() {
8325     if (!WasAlreadyBeingDeclared)
8326       S.SpecialMembersBeingDeclared.erase(D);
8327   }
8328 
8329   /// \brief Are we already trying to declare this special member?
8330   bool isAlreadyBeingDeclared() const {
8331     return WasAlreadyBeingDeclared;
8332   }
8333 };
8334 }
8335 
8336 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8337                                                      CXXRecordDecl *ClassDecl) {
8338   // C++ [class.ctor]p5:
8339   //   A default constructor for a class X is a constructor of class X
8340   //   that can be called without an argument. If there is no
8341   //   user-declared constructor for class X, a default constructor is
8342   //   implicitly declared. An implicitly-declared default constructor
8343   //   is an inline public member of its class.
8344   assert(ClassDecl->needsImplicitDefaultConstructor() &&
8345          "Should not build implicit default constructor!");
8346 
8347   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8348   if (DSM.isAlreadyBeingDeclared())
8349     return nullptr;
8350 
8351   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8352                                                      CXXDefaultConstructor,
8353                                                      false);
8354 
8355   // Create the actual constructor declaration.
8356   CanQualType ClassType
8357     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8358   SourceLocation ClassLoc = ClassDecl->getLocation();
8359   DeclarationName Name
8360     = Context.DeclarationNames.getCXXConstructorName(ClassType);
8361   DeclarationNameInfo NameInfo(Name, ClassLoc);
8362   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
8363       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8364       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8365       /*isImplicitlyDeclared=*/true, Constexpr);
8366   DefaultCon->setAccess(AS_public);
8367   DefaultCon->setDefaulted();
8368   DefaultCon->setImplicit();
8369 
8370   // Build an exception specification pointing back at this constructor.
8371   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
8372   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8373 
8374   // We don't need to use SpecialMemberIsTrivial here; triviality for default
8375   // constructors is easy to compute.
8376   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8377 
8378   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
8379     SetDeclDeleted(DefaultCon, ClassLoc);
8380 
8381   // Note that we have declared this constructor.
8382   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
8383 
8384   if (Scope *S = getScopeForContext(ClassDecl))
8385     PushOnScopeChains(DefaultCon, S, false);
8386   ClassDecl->addDecl(DefaultCon);
8387 
8388   return DefaultCon;
8389 }
8390 
8391 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8392                                             CXXConstructorDecl *Constructor) {
8393   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
8394           !Constructor->doesThisDeclarationHaveABody() &&
8395           !Constructor->isDeleted()) &&
8396     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
8397 
8398   CXXRecordDecl *ClassDecl = Constructor->getParent();
8399   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
8400 
8401   SynthesizedFunctionScope Scope(*this, Constructor);
8402   DiagnosticErrorTrap Trap(Diags);
8403   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8404       Trap.hasErrorOccurred()) {
8405     Diag(CurrentLocation, diag::note_member_synthesized_at)
8406       << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
8407     Constructor->setInvalidDecl();
8408     return;
8409   }
8410 
8411   SourceLocation Loc = Constructor->getLocation();
8412   Constructor->setBody(new (Context) CompoundStmt(Loc));
8413 
8414   Constructor->markUsed(Context);
8415   MarkVTableUsed(CurrentLocation, ClassDecl);
8416 
8417   if (ASTMutationListener *L = getASTMutationListener()) {
8418     L->CompletedImplicitDefinition(Constructor);
8419   }
8420 
8421   DiagnoseUninitializedFields(*this, Constructor);
8422 }
8423 
8424 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
8425   // Perform any delayed checks on exception specifications.
8426   CheckDelayedMemberExceptionSpecs();
8427 }
8428 
8429 namespace {
8430 /// Information on inheriting constructors to declare.
8431 class InheritingConstructorInfo {
8432 public:
8433   InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8434       : SemaRef(SemaRef), Derived(Derived) {
8435     // Mark the constructors that we already have in the derived class.
8436     //
8437     // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8438     //   unless there is a user-declared constructor with the same signature in
8439     //   the class where the using-declaration appears.
8440     visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8441   }
8442 
8443   void inheritAll(CXXRecordDecl *RD) {
8444     visitAll(RD, &InheritingConstructorInfo::inherit);
8445   }
8446 
8447 private:
8448   /// Information about an inheriting constructor.
8449   struct InheritingConstructor {
8450     InheritingConstructor()
8451       : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
8452 
8453     /// If \c true, a constructor with this signature is already declared
8454     /// in the derived class.
8455     bool DeclaredInDerived;
8456 
8457     /// The constructor which is inherited.
8458     const CXXConstructorDecl *BaseCtor;
8459 
8460     /// The derived constructor we declared.
8461     CXXConstructorDecl *DerivedCtor;
8462   };
8463 
8464   /// Inheriting constructors with a given canonical type. There can be at
8465   /// most one such non-template constructor, and any number of templated
8466   /// constructors.
8467   struct InheritingConstructorsForType {
8468     InheritingConstructor NonTemplate;
8469     SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8470         Templates;
8471 
8472     InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8473       if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8474         TemplateParameterList *ParamList = FTD->getTemplateParameters();
8475         for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8476           if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8477                                                false, S.TPL_TemplateMatch))
8478             return Templates[I].second;
8479         Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8480         return Templates.back().second;
8481       }
8482 
8483       return NonTemplate;
8484     }
8485   };
8486 
8487   /// Get or create the inheriting constructor record for a constructor.
8488   InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8489                                   QualType CtorType) {
8490     return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8491         .getEntry(SemaRef, Ctor);
8492   }
8493 
8494   typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8495 
8496   /// Process all constructors for a class.
8497   void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
8498     for (const auto *Ctor : RD->ctors())
8499       (this->*Callback)(Ctor);
8500     for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8501              I(RD->decls_begin()), E(RD->decls_end());
8502          I != E; ++I) {
8503       const FunctionDecl *FD = (*I)->getTemplatedDecl();
8504       if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8505         (this->*Callback)(CD);
8506     }
8507   }
8508 
8509   /// Note that a constructor (or constructor template) was declared in Derived.
8510   void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8511     getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8512   }
8513 
8514   /// Inherit a single constructor.
8515   void inherit(const CXXConstructorDecl *Ctor) {
8516     const FunctionProtoType *CtorType =
8517         Ctor->getType()->castAs<FunctionProtoType>();
8518     ArrayRef<QualType> ArgTypes(CtorType->getParamTypes());
8519     FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8520 
8521     SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8522 
8523     // Core issue (no number yet): the ellipsis is always discarded.
8524     if (EPI.Variadic) {
8525       SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8526       SemaRef.Diag(Ctor->getLocation(),
8527                    diag::note_using_decl_constructor_ellipsis);
8528       EPI.Variadic = false;
8529     }
8530 
8531     // Declare a constructor for each number of parameters.
8532     //
8533     // C++11 [class.inhctor]p1:
8534     //   The candidate set of inherited constructors from the class X named in
8535     //   the using-declaration consists of [... modulo defects ...] for each
8536     //   constructor or constructor template of X, the set of constructors or
8537     //   constructor templates that results from omitting any ellipsis parameter
8538     //   specification and successively omitting parameters with a default
8539     //   argument from the end of the parameter-type-list
8540     unsigned MinParams = minParamsToInherit(Ctor);
8541     unsigned Params = Ctor->getNumParams();
8542     if (Params >= MinParams) {
8543       do
8544         declareCtor(UsingLoc, Ctor,
8545                     SemaRef.Context.getFunctionType(
8546                         Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
8547       while (Params > MinParams &&
8548              Ctor->getParamDecl(--Params)->hasDefaultArg());
8549     }
8550   }
8551 
8552   /// Find the using-declaration which specified that we should inherit the
8553   /// constructors of \p Base.
8554   SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8555     // No fancy lookup required; just look for the base constructor name
8556     // directly within the derived class.
8557     ASTContext &Context = SemaRef.Context;
8558     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8559         Context.getCanonicalType(Context.getRecordType(Base)));
8560     DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8561     return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8562   }
8563 
8564   unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8565     // C++11 [class.inhctor]p3:
8566     //   [F]or each constructor template in the candidate set of inherited
8567     //   constructors, a constructor template is implicitly declared
8568     if (Ctor->getDescribedFunctionTemplate())
8569       return 0;
8570 
8571     //   For each non-template constructor in the candidate set of inherited
8572     //   constructors other than a constructor having no parameters or a
8573     //   copy/move constructor having a single parameter, a constructor is
8574     //   implicitly declared [...]
8575     if (Ctor->getNumParams() == 0)
8576       return 1;
8577     if (Ctor->isCopyOrMoveConstructor())
8578       return 2;
8579 
8580     // Per discussion on core reflector, never inherit a constructor which
8581     // would become a default, copy, or move constructor of Derived either.
8582     const ParmVarDecl *PD = Ctor->getParamDecl(0);
8583     const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8584     return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8585   }
8586 
8587   /// Declare a single inheriting constructor, inheriting the specified
8588   /// constructor, with the given type.
8589   void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8590                    QualType DerivedType) {
8591     InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8592 
8593     // C++11 [class.inhctor]p3:
8594     //   ... a constructor is implicitly declared with the same constructor
8595     //   characteristics unless there is a user-declared constructor with
8596     //   the same signature in the class where the using-declaration appears
8597     if (Entry.DeclaredInDerived)
8598       return;
8599 
8600     // C++11 [class.inhctor]p7:
8601     //   If two using-declarations declare inheriting constructors with the
8602     //   same signature, the program is ill-formed
8603     if (Entry.DerivedCtor) {
8604       if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8605         // Only diagnose this once per constructor.
8606         if (Entry.DerivedCtor->isInvalidDecl())
8607           return;
8608         Entry.DerivedCtor->setInvalidDecl();
8609 
8610         SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8611         SemaRef.Diag(BaseCtor->getLocation(),
8612                      diag::note_using_decl_constructor_conflict_current_ctor);
8613         SemaRef.Diag(Entry.BaseCtor->getLocation(),
8614                      diag::note_using_decl_constructor_conflict_previous_ctor);
8615         SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8616                      diag::note_using_decl_constructor_conflict_previous_using);
8617       } else {
8618         // Core issue (no number): if the same inheriting constructor is
8619         // produced by multiple base class constructors from the same base
8620         // class, the inheriting constructor is defined as deleted.
8621         SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8622       }
8623 
8624       return;
8625     }
8626 
8627     ASTContext &Context = SemaRef.Context;
8628     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8629         Context.getCanonicalType(Context.getRecordType(Derived)));
8630     DeclarationNameInfo NameInfo(Name, UsingLoc);
8631 
8632     TemplateParameterList *TemplateParams = nullptr;
8633     if (const FunctionTemplateDecl *FTD =
8634             BaseCtor->getDescribedFunctionTemplate()) {
8635       TemplateParams = FTD->getTemplateParameters();
8636       // We're reusing template parameters from a different DeclContext. This
8637       // is questionable at best, but works out because the template depth in
8638       // both places is guaranteed to be 0.
8639       // FIXME: Rebuild the template parameters in the new context, and
8640       // transform the function type to refer to them.
8641     }
8642 
8643     // Build type source info pointing at the using-declaration. This is
8644     // required by template instantiation.
8645     TypeSourceInfo *TInfo =
8646         Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8647     FunctionProtoTypeLoc ProtoLoc =
8648         TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8649 
8650     CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8651         Context, Derived, UsingLoc, NameInfo, DerivedType,
8652         TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8653         /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8654 
8655     // Build an unevaluated exception specification for this constructor.
8656     const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8657     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8658     EPI.ExceptionSpecType = EST_Unevaluated;
8659     EPI.ExceptionSpecDecl = DerivedCtor;
8660     DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
8661                                                  FPT->getParamTypes(), EPI));
8662 
8663     // Build the parameter declarations.
8664     SmallVector<ParmVarDecl *, 16> ParamDecls;
8665     for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
8666       TypeSourceInfo *TInfo =
8667           Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
8668       ParmVarDecl *PD = ParmVarDecl::Create(
8669           Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
8670           FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
8671       PD->setScopeInfo(0, I);
8672       PD->setImplicit();
8673       ParamDecls.push_back(PD);
8674       ProtoLoc.setParam(I, PD);
8675     }
8676 
8677     // Set up the new constructor.
8678     DerivedCtor->setAccess(BaseCtor->getAccess());
8679     DerivedCtor->setParams(ParamDecls);
8680     DerivedCtor->setInheritedConstructor(BaseCtor);
8681     if (BaseCtor->isDeleted())
8682       SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8683 
8684     // If this is a constructor template, build the template declaration.
8685     if (TemplateParams) {
8686       FunctionTemplateDecl *DerivedTemplate =
8687           FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8688                                        TemplateParams, DerivedCtor);
8689       DerivedTemplate->setAccess(BaseCtor->getAccess());
8690       DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8691       Derived->addDecl(DerivedTemplate);
8692     } else {
8693       Derived->addDecl(DerivedCtor);
8694     }
8695 
8696     Entry.BaseCtor = BaseCtor;
8697     Entry.DerivedCtor = DerivedCtor;
8698   }
8699 
8700   Sema &SemaRef;
8701   CXXRecordDecl *Derived;
8702   typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8703   MapType Map;
8704 };
8705 }
8706 
8707 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8708   // Defer declaring the inheriting constructors until the class is
8709   // instantiated.
8710   if (ClassDecl->isDependentContext())
8711     return;
8712 
8713   // Find base classes from which we might inherit constructors.
8714   SmallVector<CXXRecordDecl*, 4> InheritedBases;
8715   for (const auto &BaseIt : ClassDecl->bases())
8716     if (BaseIt.getInheritConstructors())
8717       InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
8718 
8719   // Go no further if we're not inheriting any constructors.
8720   if (InheritedBases.empty())
8721     return;
8722 
8723   // Declare the inherited constructors.
8724   InheritingConstructorInfo ICI(*this, ClassDecl);
8725   for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8726     ICI.inheritAll(InheritedBases[I]);
8727 }
8728 
8729 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8730                                        CXXConstructorDecl *Constructor) {
8731   CXXRecordDecl *ClassDecl = Constructor->getParent();
8732   assert(Constructor->getInheritedConstructor() &&
8733          !Constructor->doesThisDeclarationHaveABody() &&
8734          !Constructor->isDeleted());
8735 
8736   SynthesizedFunctionScope Scope(*this, Constructor);
8737   DiagnosticErrorTrap Trap(Diags);
8738   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8739       Trap.hasErrorOccurred()) {
8740     Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8741       << Context.getTagDeclType(ClassDecl);
8742     Constructor->setInvalidDecl();
8743     return;
8744   }
8745 
8746   SourceLocation Loc = Constructor->getLocation();
8747   Constructor->setBody(new (Context) CompoundStmt(Loc));
8748 
8749   Constructor->markUsed(Context);
8750   MarkVTableUsed(CurrentLocation, ClassDecl);
8751 
8752   if (ASTMutationListener *L = getASTMutationListener()) {
8753     L->CompletedImplicitDefinition(Constructor);
8754   }
8755 }
8756 
8757 
8758 Sema::ImplicitExceptionSpecification
8759 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8760   CXXRecordDecl *ClassDecl = MD->getParent();
8761 
8762   // C++ [except.spec]p14:
8763   //   An implicitly declared special member function (Clause 12) shall have
8764   //   an exception-specification.
8765   ImplicitExceptionSpecification ExceptSpec(*this);
8766   if (ClassDecl->isInvalidDecl())
8767     return ExceptSpec;
8768 
8769   // Direct base-class destructors.
8770   for (const auto &B : ClassDecl->bases()) {
8771     if (B.isVirtual()) // Handled below.
8772       continue;
8773 
8774     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8775       ExceptSpec.CalledDecl(B.getLocStart(),
8776                    LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
8777   }
8778 
8779   // Virtual base-class destructors.
8780   for (const auto &B : ClassDecl->vbases()) {
8781     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8782       ExceptSpec.CalledDecl(B.getLocStart(),
8783                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
8784   }
8785 
8786   // Field destructors.
8787   for (const auto *F : ClassDecl->fields()) {
8788     if (const RecordType *RecordTy
8789         = Context.getBaseElementType(F->getType())->getAs<RecordType>())
8790       ExceptSpec.CalledDecl(F->getLocation(),
8791                   LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
8792   }
8793 
8794   return ExceptSpec;
8795 }
8796 
8797 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8798   // C++ [class.dtor]p2:
8799   //   If a class has no user-declared destructor, a destructor is
8800   //   declared implicitly. An implicitly-declared destructor is an
8801   //   inline public member of its class.
8802   assert(ClassDecl->needsImplicitDestructor());
8803 
8804   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8805   if (DSM.isAlreadyBeingDeclared())
8806     return nullptr;
8807 
8808   // Create the actual destructor declaration.
8809   CanQualType ClassType
8810     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8811   SourceLocation ClassLoc = ClassDecl->getLocation();
8812   DeclarationName Name
8813     = Context.DeclarationNames.getCXXDestructorName(ClassType);
8814   DeclarationNameInfo NameInfo(Name, ClassLoc);
8815   CXXDestructorDecl *Destructor
8816       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8817                                   QualType(), nullptr, /*isInline=*/true,
8818                                   /*isImplicitlyDeclared=*/true);
8819   Destructor->setAccess(AS_public);
8820   Destructor->setDefaulted();
8821   Destructor->setImplicit();
8822 
8823   // Build an exception specification pointing back at this destructor.
8824   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
8825   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8826 
8827   AddOverriddenMethods(ClassDecl, Destructor);
8828 
8829   // We don't need to use SpecialMemberIsTrivial here; triviality for
8830   // destructors is easy to compute.
8831   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8832 
8833   if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
8834     SetDeclDeleted(Destructor, ClassLoc);
8835 
8836   // Note that we have declared this destructor.
8837   ++ASTContext::NumImplicitDestructorsDeclared;
8838 
8839   // Introduce this destructor into its scope.
8840   if (Scope *S = getScopeForContext(ClassDecl))
8841     PushOnScopeChains(Destructor, S, false);
8842   ClassDecl->addDecl(Destructor);
8843 
8844   return Destructor;
8845 }
8846 
8847 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
8848                                     CXXDestructorDecl *Destructor) {
8849   assert((Destructor->isDefaulted() &&
8850           !Destructor->doesThisDeclarationHaveABody() &&
8851           !Destructor->isDeleted()) &&
8852          "DefineImplicitDestructor - call it for implicit default dtor");
8853   CXXRecordDecl *ClassDecl = Destructor->getParent();
8854   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
8855 
8856   if (Destructor->isInvalidDecl())
8857     return;
8858 
8859   SynthesizedFunctionScope Scope(*this, Destructor);
8860 
8861   DiagnosticErrorTrap Trap(Diags);
8862   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8863                                          Destructor->getParent());
8864 
8865   if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
8866     Diag(CurrentLocation, diag::note_member_synthesized_at)
8867       << CXXDestructor << Context.getTagDeclType(ClassDecl);
8868 
8869     Destructor->setInvalidDecl();
8870     return;
8871   }
8872 
8873   SourceLocation Loc = Destructor->getLocation();
8874   Destructor->setBody(new (Context) CompoundStmt(Loc));
8875   Destructor->markUsed(Context);
8876   MarkVTableUsed(CurrentLocation, ClassDecl);
8877 
8878   if (ASTMutationListener *L = getASTMutationListener()) {
8879     L->CompletedImplicitDefinition(Destructor);
8880   }
8881 }
8882 
8883 /// \brief Perform any semantic analysis which needs to be delayed until all
8884 /// pending class member declarations have been parsed.
8885 void Sema::ActOnFinishCXXMemberDecls() {
8886   // If the context is an invalid C++ class, just suppress these checks.
8887   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8888     if (Record->isInvalidDecl()) {
8889       DelayedDefaultedMemberExceptionSpecs.clear();
8890       DelayedDestructorExceptionSpecChecks.clear();
8891       return;
8892     }
8893   }
8894 }
8895 
8896 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8897                                          CXXDestructorDecl *Destructor) {
8898   assert(getLangOpts().CPlusPlus11 &&
8899          "adjusting dtor exception specs was introduced in c++11");
8900 
8901   // C++11 [class.dtor]p3:
8902   //   A declaration of a destructor that does not have an exception-
8903   //   specification is implicitly considered to have the same exception-
8904   //   specification as an implicit declaration.
8905   const FunctionProtoType *DtorType = Destructor->getType()->
8906                                         getAs<FunctionProtoType>();
8907   if (DtorType->hasExceptionSpec())
8908     return;
8909 
8910   // Replace the destructor's type, building off the existing one. Fortunately,
8911   // the only thing of interest in the destructor type is its extended info.
8912   // The return and arguments are fixed.
8913   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8914   EPI.ExceptionSpecType = EST_Unevaluated;
8915   EPI.ExceptionSpecDecl = Destructor;
8916   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8917 
8918   // FIXME: If the destructor has a body that could throw, and the newly created
8919   // spec doesn't allow exceptions, we should emit a warning, because this
8920   // change in behavior can break conforming C++03 programs at runtime.
8921   // However, we don't have a body or an exception specification yet, so it
8922   // needs to be done somewhere else.
8923 }
8924 
8925 namespace {
8926 /// \brief An abstract base class for all helper classes used in building the
8927 //  copy/move operators. These classes serve as factory functions and help us
8928 //  avoid using the same Expr* in the AST twice.
8929 class ExprBuilder {
8930   ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8931   ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8932 
8933 protected:
8934   static Expr *assertNotNull(Expr *E) {
8935     assert(E && "Expression construction must not fail.");
8936     return E;
8937   }
8938 
8939 public:
8940   ExprBuilder() {}
8941   virtual ~ExprBuilder() {}
8942 
8943   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
8944 };
8945 
8946 class RefBuilder: public ExprBuilder {
8947   VarDecl *Var;
8948   QualType VarType;
8949 
8950 public:
8951   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
8952     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
8953   }
8954 
8955   RefBuilder(VarDecl *Var, QualType VarType)
8956       : Var(Var), VarType(VarType) {}
8957 };
8958 
8959 class ThisBuilder: public ExprBuilder {
8960 public:
8961   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
8962     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
8963   }
8964 };
8965 
8966 class CastBuilder: public ExprBuilder {
8967   const ExprBuilder &Builder;
8968   QualType Type;
8969   ExprValueKind Kind;
8970   const CXXCastPath &Path;
8971 
8972 public:
8973   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
8974     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
8975                                              CK_UncheckedDerivedToBase, Kind,
8976                                              &Path).get());
8977   }
8978 
8979   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
8980               const CXXCastPath &Path)
8981       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
8982 };
8983 
8984 class DerefBuilder: public ExprBuilder {
8985   const ExprBuilder &Builder;
8986 
8987 public:
8988   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
8989     return assertNotNull(
8990         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
8991   }
8992 
8993   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8994 };
8995 
8996 class MemberBuilder: public ExprBuilder {
8997   const ExprBuilder &Builder;
8998   QualType Type;
8999   CXXScopeSpec SS;
9000   bool IsArrow;
9001   LookupResult &MemberLookup;
9002 
9003 public:
9004   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9005     return assertNotNull(S.BuildMemberReferenceExpr(
9006         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
9007         nullptr, MemberLookup, nullptr).get());
9008   }
9009 
9010   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9011                 LookupResult &MemberLookup)
9012       : Builder(Builder), Type(Type), IsArrow(IsArrow),
9013         MemberLookup(MemberLookup) {}
9014 };
9015 
9016 class MoveCastBuilder: public ExprBuilder {
9017   const ExprBuilder &Builder;
9018 
9019 public:
9020   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9021     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9022   }
9023 
9024   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9025 };
9026 
9027 class LvalueConvBuilder: public ExprBuilder {
9028   const ExprBuilder &Builder;
9029 
9030 public:
9031   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9032     return assertNotNull(
9033         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
9034   }
9035 
9036   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9037 };
9038 
9039 class SubscriptBuilder: public ExprBuilder {
9040   const ExprBuilder &Base;
9041   const ExprBuilder &Index;
9042 
9043 public:
9044   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9045     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
9046         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
9047   }
9048 
9049   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9050       : Base(Base), Index(Index) {}
9051 };
9052 
9053 } // end anonymous namespace
9054 
9055 /// When generating a defaulted copy or move assignment operator, if a field
9056 /// should be copied with __builtin_memcpy rather than via explicit assignments,
9057 /// do so. This optimization only applies for arrays of scalars, and for arrays
9058 /// of class type where the selected copy/move-assignment operator is trivial.
9059 static StmtResult
9060 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
9061                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
9062   // Compute the size of the memory buffer to be copied.
9063   QualType SizeType = S.Context.getSizeType();
9064   llvm::APInt Size(S.Context.getTypeSize(SizeType),
9065                    S.Context.getTypeSizeInChars(T).getQuantity());
9066 
9067   // Take the address of the field references for "from" and "to". We
9068   // directly construct UnaryOperators here because semantic analysis
9069   // does not permit us to take the address of an xvalue.
9070   Expr *From = FromB.build(S, Loc);
9071   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9072                          S.Context.getPointerType(From->getType()),
9073                          VK_RValue, OK_Ordinary, Loc);
9074   Expr *To = ToB.build(S, Loc);
9075   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9076                        S.Context.getPointerType(To->getType()),
9077                        VK_RValue, OK_Ordinary, Loc);
9078 
9079   const Type *E = T->getBaseElementTypeUnsafe();
9080   bool NeedsCollectableMemCpy =
9081     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9082 
9083   // Create a reference to the __builtin_objc_memmove_collectable function
9084   StringRef MemCpyName = NeedsCollectableMemCpy ?
9085     "__builtin_objc_memmove_collectable" :
9086     "__builtin_memcpy";
9087   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9088                  Sema::LookupOrdinaryName);
9089   S.LookupName(R, S.TUScope, true);
9090 
9091   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9092   if (!MemCpy)
9093     // Something went horribly wrong earlier, and we will have complained
9094     // about it.
9095     return StmtError();
9096 
9097   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
9098                                             VK_RValue, Loc, nullptr);
9099   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9100 
9101   Expr *CallArgs[] = {
9102     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9103   };
9104   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
9105                                     Loc, CallArgs, Loc);
9106 
9107   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
9108   return Call.getAs<Stmt>();
9109 }
9110 
9111 /// \brief Builds a statement that copies/moves the given entity from \p From to
9112 /// \c To.
9113 ///
9114 /// This routine is used to copy/move the members of a class with an
9115 /// implicitly-declared copy/move assignment operator. When the entities being
9116 /// copied are arrays, this routine builds for loops to copy them.
9117 ///
9118 /// \param S The Sema object used for type-checking.
9119 ///
9120 /// \param Loc The location where the implicit copy/move is being generated.
9121 ///
9122 /// \param T The type of the expressions being copied/moved. Both expressions
9123 /// must have this type.
9124 ///
9125 /// \param To The expression we are copying/moving to.
9126 ///
9127 /// \param From The expression we are copying/moving from.
9128 ///
9129 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
9130 /// Otherwise, it's a non-static member subobject.
9131 ///
9132 /// \param Copying Whether we're copying or moving.
9133 ///
9134 /// \param Depth Internal parameter recording the depth of the recursion.
9135 ///
9136 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9137 /// if a memcpy should be used instead.
9138 static StmtResult
9139 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
9140                                  const ExprBuilder &To, const ExprBuilder &From,
9141                                  bool CopyingBaseSubobject, bool Copying,
9142                                  unsigned Depth = 0) {
9143   // C++11 [class.copy]p28:
9144   //   Each subobject is assigned in the manner appropriate to its type:
9145   //
9146   //     - if the subobject is of class type, as if by a call to operator= with
9147   //       the subobject as the object expression and the corresponding
9148   //       subobject of x as a single function argument (as if by explicit
9149   //       qualification; that is, ignoring any possible virtual overriding
9150   //       functions in more derived classes);
9151   //
9152   // C++03 [class.copy]p13:
9153   //     - if the subobject is of class type, the copy assignment operator for
9154   //       the class is used (as if by explicit qualification; that is,
9155   //       ignoring any possible virtual overriding functions in more derived
9156   //       classes);
9157   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9158     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9159 
9160     // Look for operator=.
9161     DeclarationName Name
9162       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9163     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9164     S.LookupQualifiedName(OpLookup, ClassDecl, false);
9165 
9166     // Prior to C++11, filter out any result that isn't a copy/move-assignment
9167     // operator.
9168     if (!S.getLangOpts().CPlusPlus11) {
9169       LookupResult::Filter F = OpLookup.makeFilter();
9170       while (F.hasNext()) {
9171         NamedDecl *D = F.next();
9172         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9173           if (Method->isCopyAssignmentOperator() ||
9174               (!Copying && Method->isMoveAssignmentOperator()))
9175             continue;
9176 
9177         F.erase();
9178       }
9179       F.done();
9180     }
9181 
9182     // Suppress the protected check (C++ [class.protected]) for each of the
9183     // assignment operators we found. This strange dance is required when
9184     // we're assigning via a base classes's copy-assignment operator. To
9185     // ensure that we're getting the right base class subobject (without
9186     // ambiguities), we need to cast "this" to that subobject type; to
9187     // ensure that we don't go through the virtual call mechanism, we need
9188     // to qualify the operator= name with the base class (see below). However,
9189     // this means that if the base class has a protected copy assignment
9190     // operator, the protected member access check will fail. So, we
9191     // rewrite "protected" access to "public" access in this case, since we
9192     // know by construction that we're calling from a derived class.
9193     if (CopyingBaseSubobject) {
9194       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9195            L != LEnd; ++L) {
9196         if (L.getAccess() == AS_protected)
9197           L.setAccess(AS_public);
9198       }
9199     }
9200 
9201     // Create the nested-name-specifier that will be used to qualify the
9202     // reference to operator=; this is required to suppress the virtual
9203     // call mechanism.
9204     CXXScopeSpec SS;
9205     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
9206     SS.MakeTrivial(S.Context,
9207                    NestedNameSpecifier::Create(S.Context, nullptr, false,
9208                                                CanonicalT),
9209                    Loc);
9210 
9211     // Create the reference to operator=.
9212     ExprResult OpEqualRef
9213       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9214                                    SS, /*TemplateKWLoc=*/SourceLocation(),
9215                                    /*FirstQualifierInScope=*/nullptr,
9216                                    OpLookup,
9217                                    /*TemplateArgs=*/nullptr,
9218                                    /*SuppressQualifierCheck=*/true);
9219     if (OpEqualRef.isInvalid())
9220       return StmtError();
9221 
9222     // Build the call to the assignment operator.
9223 
9224     Expr *FromInst = From.build(S, Loc);
9225     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
9226                                                   OpEqualRef.getAs<Expr>(),
9227                                                   Loc, FromInst, Loc);
9228     if (Call.isInvalid())
9229       return StmtError();
9230 
9231     // If we built a call to a trivial 'operator=' while copying an array,
9232     // bail out. We'll replace the whole shebang with a memcpy.
9233     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9234     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9235       return StmtResult((Stmt*)nullptr);
9236 
9237     // Convert to an expression-statement, and clean up any produced
9238     // temporaries.
9239     return S.ActOnExprStmt(Call);
9240   }
9241 
9242   //     - if the subobject is of scalar type, the built-in assignment
9243   //       operator is used.
9244   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
9245   if (!ArrayTy) {
9246     ExprResult Assignment = S.CreateBuiltinBinOp(
9247         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
9248     if (Assignment.isInvalid())
9249       return StmtError();
9250     return S.ActOnExprStmt(Assignment);
9251   }
9252 
9253   //     - if the subobject is an array, each element is assigned, in the
9254   //       manner appropriate to the element type;
9255 
9256   // Construct a loop over the array bounds, e.g.,
9257   //
9258   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9259   //
9260   // that will copy each of the array elements.
9261   QualType SizeType = S.Context.getSizeType();
9262 
9263   // Create the iteration variable.
9264   IdentifierInfo *IterationVarName = nullptr;
9265   {
9266     SmallString<8> Str;
9267     llvm::raw_svector_ostream OS(Str);
9268     OS << "__i" << Depth;
9269     IterationVarName = &S.Context.Idents.get(OS.str());
9270   }
9271   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
9272                                           IterationVarName, SizeType,
9273                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
9274                                           SC_None);
9275 
9276   // Initialize the iteration variable to zero.
9277   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
9278   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
9279 
9280   // Creates a reference to the iteration variable.
9281   RefBuilder IterationVarRef(IterationVar, SizeType);
9282   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
9283 
9284   // Create the DeclStmt that holds the iteration variable.
9285   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
9286 
9287   // Subscript the "from" and "to" expressions with the iteration variable.
9288   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9289   MoveCastBuilder FromIndexMove(FromIndexCopy);
9290   const ExprBuilder *FromIndex;
9291   if (Copying)
9292     FromIndex = &FromIndexCopy;
9293   else
9294     FromIndex = &FromIndexMove;
9295 
9296   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
9297 
9298   // Build the copy/move for an individual element of the array.
9299   StmtResult Copy =
9300     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
9301                                      ToIndex, *FromIndex, CopyingBaseSubobject,
9302                                      Copying, Depth + 1);
9303   // Bail out if copying fails or if we determined that we should use memcpy.
9304   if (Copy.isInvalid() || !Copy.get())
9305     return Copy;
9306 
9307   // Create the comparison against the array bound.
9308   llvm::APInt Upper
9309     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9310   Expr *Comparison
9311     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
9312                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9313                                      BO_NE, S.Context.BoolTy,
9314                                      VK_RValue, OK_Ordinary, Loc, false);
9315 
9316   // Create the pre-increment of the iteration variable.
9317   Expr *Increment
9318     = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9319                                     SizeType, VK_LValue, OK_Ordinary, Loc);
9320 
9321   // Construct the loop that copies all elements of this array.
9322   return S.ActOnForStmt(Loc, Loc, InitStmt,
9323                         S.MakeFullExpr(Comparison),
9324                         nullptr, S.MakeFullDiscardedValueExpr(Increment),
9325                         Loc, Copy.get());
9326 }
9327 
9328 static StmtResult
9329 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
9330                       const ExprBuilder &To, const ExprBuilder &From,
9331                       bool CopyingBaseSubobject, bool Copying) {
9332   // Maybe we should use a memcpy?
9333   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9334       T.isTriviallyCopyableType(S.Context))
9335     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9336 
9337   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9338                                                      CopyingBaseSubobject,
9339                                                      Copying, 0));
9340 
9341   // If we ended up picking a trivial assignment operator for an array of a
9342   // non-trivially-copyable class type, just emit a memcpy.
9343   if (!Result.isInvalid() && !Result.get())
9344     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9345 
9346   return Result;
9347 }
9348 
9349 Sema::ImplicitExceptionSpecification
9350 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9351   CXXRecordDecl *ClassDecl = MD->getParent();
9352 
9353   ImplicitExceptionSpecification ExceptSpec(*this);
9354   if (ClassDecl->isInvalidDecl())
9355     return ExceptSpec;
9356 
9357   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9358   assert(T->getNumParams() == 1 && "not a copy assignment op");
9359   unsigned ArgQuals =
9360       T->getParamType(0).getNonReferenceType().getCVRQualifiers();
9361 
9362   // C++ [except.spec]p14:
9363   //   An implicitly declared special member function (Clause 12) shall have an
9364   //   exception-specification. [...]
9365 
9366   // It is unspecified whether or not an implicit copy assignment operator
9367   // attempts to deduplicate calls to assignment operators of virtual bases are
9368   // made. As such, this exception specification is effectively unspecified.
9369   // Based on a similar decision made for constness in C++0x, we're erring on
9370   // the side of assuming such calls to be made regardless of whether they
9371   // actually happen.
9372   for (const auto &Base : ClassDecl->bases()) {
9373     if (Base.isVirtual())
9374       continue;
9375 
9376     CXXRecordDecl *BaseClassDecl
9377       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9378     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9379                                                             ArgQuals, false, 0))
9380       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
9381   }
9382 
9383   for (const auto &Base : ClassDecl->vbases()) {
9384     CXXRecordDecl *BaseClassDecl
9385       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9386     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9387                                                             ArgQuals, false, 0))
9388       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
9389   }
9390 
9391   for (const auto *Field : ClassDecl->fields()) {
9392     QualType FieldType = Context.getBaseElementType(Field->getType());
9393     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9394       if (CXXMethodDecl *CopyAssign =
9395           LookupCopyingAssignment(FieldClassDecl,
9396                                   ArgQuals | FieldType.getCVRQualifiers(),
9397                                   false, 0))
9398         ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
9399     }
9400   }
9401 
9402   return ExceptSpec;
9403 }
9404 
9405 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9406   // Note: The following rules are largely analoguous to the copy
9407   // constructor rules. Note that virtual bases are not taken into account
9408   // for determining the argument type of the operator. Note also that
9409   // operators taking an object instead of a reference are allowed.
9410   assert(ClassDecl->needsImplicitCopyAssignment());
9411 
9412   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9413   if (DSM.isAlreadyBeingDeclared())
9414     return nullptr;
9415 
9416   QualType ArgType = Context.getTypeDeclType(ClassDecl);
9417   QualType RetType = Context.getLValueReferenceType(ArgType);
9418   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9419   if (Const)
9420     ArgType = ArgType.withConst();
9421   ArgType = Context.getLValueReferenceType(ArgType);
9422 
9423   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9424                                                      CXXCopyAssignment,
9425                                                      Const);
9426 
9427   //   An implicitly-declared copy assignment operator is an inline public
9428   //   member of its class.
9429   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9430   SourceLocation ClassLoc = ClassDecl->getLocation();
9431   DeclarationNameInfo NameInfo(Name, ClassLoc);
9432   CXXMethodDecl *CopyAssignment =
9433       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9434                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
9435                             /*isInline=*/true, Constexpr, SourceLocation());
9436   CopyAssignment->setAccess(AS_public);
9437   CopyAssignment->setDefaulted();
9438   CopyAssignment->setImplicit();
9439 
9440   // Build an exception specification pointing back at this member.
9441   FunctionProtoType::ExtProtoInfo EPI =
9442       getImplicitMethodEPI(*this, CopyAssignment);
9443   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
9444 
9445   // Add the parameter to the operator.
9446   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
9447                                                ClassLoc, ClassLoc,
9448                                                /*Id=*/nullptr, ArgType,
9449                                                /*TInfo=*/nullptr, SC_None,
9450                                                nullptr);
9451   CopyAssignment->setParams(FromParam);
9452 
9453   AddOverriddenMethods(ClassDecl, CopyAssignment);
9454 
9455   CopyAssignment->setTrivial(
9456     ClassDecl->needsOverloadResolutionForCopyAssignment()
9457       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9458       : ClassDecl->hasTrivialCopyAssignment());
9459 
9460   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
9461     SetDeclDeleted(CopyAssignment, ClassLoc);
9462 
9463   // Note that we have added this copy-assignment operator.
9464   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9465 
9466   if (Scope *S = getScopeForContext(ClassDecl))
9467     PushOnScopeChains(CopyAssignment, S, false);
9468   ClassDecl->addDecl(CopyAssignment);
9469 
9470   return CopyAssignment;
9471 }
9472 
9473 /// Diagnose an implicit copy operation for a class which is odr-used, but
9474 /// which is deprecated because the class has a user-declared copy constructor,
9475 /// copy assignment operator, or destructor.
9476 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9477                                             SourceLocation UseLoc) {
9478   assert(CopyOp->isImplicit());
9479 
9480   CXXRecordDecl *RD = CopyOp->getParent();
9481   CXXMethodDecl *UserDeclaredOperation = nullptr;
9482 
9483   // In Microsoft mode, assignment operations don't affect constructors and
9484   // vice versa.
9485   if (RD->hasUserDeclaredDestructor()) {
9486     UserDeclaredOperation = RD->getDestructor();
9487   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9488              RD->hasUserDeclaredCopyConstructor() &&
9489              !S.getLangOpts().MSVCCompat) {
9490     // Find any user-declared copy constructor.
9491     for (auto *I : RD->ctors()) {
9492       if (I->isCopyConstructor()) {
9493         UserDeclaredOperation = I;
9494         break;
9495       }
9496     }
9497     assert(UserDeclaredOperation);
9498   } else if (isa<CXXConstructorDecl>(CopyOp) &&
9499              RD->hasUserDeclaredCopyAssignment() &&
9500              !S.getLangOpts().MSVCCompat) {
9501     // Find any user-declared move assignment operator.
9502     for (auto *I : RD->methods()) {
9503       if (I->isCopyAssignmentOperator()) {
9504         UserDeclaredOperation = I;
9505         break;
9506       }
9507     }
9508     assert(UserDeclaredOperation);
9509   }
9510 
9511   if (UserDeclaredOperation) {
9512     S.Diag(UserDeclaredOperation->getLocation(),
9513          diag::warn_deprecated_copy_operation)
9514       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9515       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9516     S.Diag(UseLoc, diag::note_member_synthesized_at)
9517       << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9518                                           : Sema::CXXCopyAssignment)
9519       << RD;
9520   }
9521 }
9522 
9523 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9524                                         CXXMethodDecl *CopyAssignOperator) {
9525   assert((CopyAssignOperator->isDefaulted() &&
9526           CopyAssignOperator->isOverloadedOperator() &&
9527           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
9528           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9529           !CopyAssignOperator->isDeleted()) &&
9530          "DefineImplicitCopyAssignment called for wrong function");
9531 
9532   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9533 
9534   if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9535     CopyAssignOperator->setInvalidDecl();
9536     return;
9537   }
9538 
9539   // C++11 [class.copy]p18:
9540   //   The [definition of an implicitly declared copy assignment operator] is
9541   //   deprecated if the class has a user-declared copy constructor or a
9542   //   user-declared destructor.
9543   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9544     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9545 
9546   CopyAssignOperator->markUsed(Context);
9547 
9548   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
9549   DiagnosticErrorTrap Trap(Diags);
9550 
9551   // C++0x [class.copy]p30:
9552   //   The implicitly-defined or explicitly-defaulted copy assignment operator
9553   //   for a non-union class X performs memberwise copy assignment of its
9554   //   subobjects. The direct base classes of X are assigned first, in the
9555   //   order of their declaration in the base-specifier-list, and then the
9556   //   immediate non-static data members of X are assigned, in the order in
9557   //   which they were declared in the class definition.
9558 
9559   // The statements that form the synthesized function body.
9560   SmallVector<Stmt*, 8> Statements;
9561 
9562   // The parameter for the "other" object, which we are copying from.
9563   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9564   Qualifiers OtherQuals = Other->getType().getQualifiers();
9565   QualType OtherRefType = Other->getType();
9566   if (const LValueReferenceType *OtherRef
9567                                 = OtherRefType->getAs<LValueReferenceType>()) {
9568     OtherRefType = OtherRef->getPointeeType();
9569     OtherQuals = OtherRefType.getQualifiers();
9570   }
9571 
9572   // Our location for everything implicitly-generated.
9573   SourceLocation Loc = CopyAssignOperator->getLocation();
9574 
9575   // Builds a DeclRefExpr for the "other" object.
9576   RefBuilder OtherRef(Other, OtherRefType);
9577 
9578   // Builds the "this" pointer.
9579   ThisBuilder This;
9580 
9581   // Assign base classes.
9582   bool Invalid = false;
9583   for (auto &Base : ClassDecl->bases()) {
9584     // Form the assignment:
9585     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
9586     QualType BaseType = Base.getType().getUnqualifiedType();
9587     if (!BaseType->isRecordType()) {
9588       Invalid = true;
9589       continue;
9590     }
9591 
9592     CXXCastPath BasePath;
9593     BasePath.push_back(&Base);
9594 
9595     // Construct the "from" expression, which is an implicit cast to the
9596     // appropriately-qualified base type.
9597     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9598                      VK_LValue, BasePath);
9599 
9600     // Dereference "this".
9601     DerefBuilder DerefThis(This);
9602     CastBuilder To(DerefThis,
9603                    Context.getCVRQualifiedType(
9604                        BaseType, CopyAssignOperator->getTypeQualifiers()),
9605                    VK_LValue, BasePath);
9606 
9607     // Build the copy.
9608     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
9609                                             To, From,
9610                                             /*CopyingBaseSubobject=*/true,
9611                                             /*Copying=*/true);
9612     if (Copy.isInvalid()) {
9613       Diag(CurrentLocation, diag::note_member_synthesized_at)
9614         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9615       CopyAssignOperator->setInvalidDecl();
9616       return;
9617     }
9618 
9619     // Success! Record the copy.
9620     Statements.push_back(Copy.getAs<Expr>());
9621   }
9622 
9623   // Assign non-static members.
9624   for (auto *Field : ClassDecl->fields()) {
9625     if (Field->isUnnamedBitfield())
9626       continue;
9627 
9628     if (Field->isInvalidDecl()) {
9629       Invalid = true;
9630       continue;
9631     }
9632 
9633     // Check for members of reference type; we can't copy those.
9634     if (Field->getType()->isReferenceType()) {
9635       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9636         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9637       Diag(Field->getLocation(), diag::note_declared_at);
9638       Diag(CurrentLocation, diag::note_member_synthesized_at)
9639         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9640       Invalid = true;
9641       continue;
9642     }
9643 
9644     // Check for members of const-qualified, non-class type.
9645     QualType BaseType = Context.getBaseElementType(Field->getType());
9646     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9647       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9648         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9649       Diag(Field->getLocation(), diag::note_declared_at);
9650       Diag(CurrentLocation, diag::note_member_synthesized_at)
9651         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9652       Invalid = true;
9653       continue;
9654     }
9655 
9656     // Suppress assigning zero-width bitfields.
9657     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9658       continue;
9659 
9660     QualType FieldType = Field->getType().getNonReferenceType();
9661     if (FieldType->isIncompleteArrayType()) {
9662       assert(ClassDecl->hasFlexibleArrayMember() &&
9663              "Incomplete array type is not valid");
9664       continue;
9665     }
9666 
9667     // Build references to the field in the object we're copying from and to.
9668     CXXScopeSpec SS; // Intentionally empty
9669     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9670                               LookupMemberName);
9671     MemberLookup.addDecl(Field);
9672     MemberLookup.resolveKind();
9673 
9674     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9675 
9676     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
9677 
9678     // Build the copy of this field.
9679     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
9680                                             To, From,
9681                                             /*CopyingBaseSubobject=*/false,
9682                                             /*Copying=*/true);
9683     if (Copy.isInvalid()) {
9684       Diag(CurrentLocation, diag::note_member_synthesized_at)
9685         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9686       CopyAssignOperator->setInvalidDecl();
9687       return;
9688     }
9689 
9690     // Success! Record the copy.
9691     Statements.push_back(Copy.getAs<Stmt>());
9692   }
9693 
9694   if (!Invalid) {
9695     // Add a "return *this;"
9696     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
9697 
9698     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
9699     if (Return.isInvalid())
9700       Invalid = true;
9701     else {
9702       Statements.push_back(Return.getAs<Stmt>());
9703 
9704       if (Trap.hasErrorOccurred()) {
9705         Diag(CurrentLocation, diag::note_member_synthesized_at)
9706           << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9707         Invalid = true;
9708       }
9709     }
9710   }
9711 
9712   if (Invalid) {
9713     CopyAssignOperator->setInvalidDecl();
9714     return;
9715   }
9716 
9717   StmtResult Body;
9718   {
9719     CompoundScopeRAII CompoundScope(*this);
9720     Body = ActOnCompoundStmt(Loc, Loc, Statements,
9721                              /*isStmtExpr=*/false);
9722     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9723   }
9724   CopyAssignOperator->setBody(Body.getAs<Stmt>());
9725 
9726   if (ASTMutationListener *L = getASTMutationListener()) {
9727     L->CompletedImplicitDefinition(CopyAssignOperator);
9728   }
9729 }
9730 
9731 Sema::ImplicitExceptionSpecification
9732 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9733   CXXRecordDecl *ClassDecl = MD->getParent();
9734 
9735   ImplicitExceptionSpecification ExceptSpec(*this);
9736   if (ClassDecl->isInvalidDecl())
9737     return ExceptSpec;
9738 
9739   // C++0x [except.spec]p14:
9740   //   An implicitly declared special member function (Clause 12) shall have an
9741   //   exception-specification. [...]
9742 
9743   // It is unspecified whether or not an implicit move assignment operator
9744   // attempts to deduplicate calls to assignment operators of virtual bases are
9745   // made. As such, this exception specification is effectively unspecified.
9746   // Based on a similar decision made for constness in C++0x, we're erring on
9747   // the side of assuming such calls to be made regardless of whether they
9748   // actually happen.
9749   // Note that a move constructor is not implicitly declared when there are
9750   // virtual bases, but it can still be user-declared and explicitly defaulted.
9751   for (const auto &Base : ClassDecl->bases()) {
9752     if (Base.isVirtual())
9753       continue;
9754 
9755     CXXRecordDecl *BaseClassDecl
9756       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9757     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
9758                                                            0, false, 0))
9759       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
9760   }
9761 
9762   for (const auto &Base : ClassDecl->vbases()) {
9763     CXXRecordDecl *BaseClassDecl
9764       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9765     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
9766                                                            0, false, 0))
9767       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
9768   }
9769 
9770   for (const auto *Field : ClassDecl->fields()) {
9771     QualType FieldType = Context.getBaseElementType(Field->getType());
9772     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9773       if (CXXMethodDecl *MoveAssign =
9774               LookupMovingAssignment(FieldClassDecl,
9775                                      FieldType.getCVRQualifiers(),
9776                                      false, 0))
9777         ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
9778     }
9779   }
9780 
9781   return ExceptSpec;
9782 }
9783 
9784 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
9785   assert(ClassDecl->needsImplicitMoveAssignment());
9786 
9787   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9788   if (DSM.isAlreadyBeingDeclared())
9789     return nullptr;
9790 
9791   // Note: The following rules are largely analoguous to the move
9792   // constructor rules.
9793 
9794   QualType ArgType = Context.getTypeDeclType(ClassDecl);
9795   QualType RetType = Context.getLValueReferenceType(ArgType);
9796   ArgType = Context.getRValueReferenceType(ArgType);
9797 
9798   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9799                                                      CXXMoveAssignment,
9800                                                      false);
9801 
9802   //   An implicitly-declared move assignment operator is an inline public
9803   //   member of its class.
9804   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9805   SourceLocation ClassLoc = ClassDecl->getLocation();
9806   DeclarationNameInfo NameInfo(Name, ClassLoc);
9807   CXXMethodDecl *MoveAssignment =
9808       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9809                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
9810                             /*isInline=*/true, Constexpr, SourceLocation());
9811   MoveAssignment->setAccess(AS_public);
9812   MoveAssignment->setDefaulted();
9813   MoveAssignment->setImplicit();
9814 
9815   // Build an exception specification pointing back at this member.
9816   FunctionProtoType::ExtProtoInfo EPI =
9817       getImplicitMethodEPI(*this, MoveAssignment);
9818   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
9819 
9820   // Add the parameter to the operator.
9821   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9822                                                ClassLoc, ClassLoc,
9823                                                /*Id=*/nullptr, ArgType,
9824                                                /*TInfo=*/nullptr, SC_None,
9825                                                nullptr);
9826   MoveAssignment->setParams(FromParam);
9827 
9828   AddOverriddenMethods(ClassDecl, MoveAssignment);
9829 
9830   MoveAssignment->setTrivial(
9831     ClassDecl->needsOverloadResolutionForMoveAssignment()
9832       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9833       : ClassDecl->hasTrivialMoveAssignment());
9834 
9835   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
9836     ClassDecl->setImplicitMoveAssignmentIsDeleted();
9837     SetDeclDeleted(MoveAssignment, ClassLoc);
9838   }
9839 
9840   // Note that we have added this copy-assignment operator.
9841   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9842 
9843   if (Scope *S = getScopeForContext(ClassDecl))
9844     PushOnScopeChains(MoveAssignment, S, false);
9845   ClassDecl->addDecl(MoveAssignment);
9846 
9847   return MoveAssignment;
9848 }
9849 
9850 /// Check if we're implicitly defining a move assignment operator for a class
9851 /// with virtual bases. Such a move assignment might move-assign the virtual
9852 /// base multiple times.
9853 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
9854                                                SourceLocation CurrentLocation) {
9855   assert(!Class->isDependentContext() && "should not define dependent move");
9856 
9857   // Only a virtual base could get implicitly move-assigned multiple times.
9858   // Only a non-trivial move assignment can observe this. We only want to
9859   // diagnose if we implicitly define an assignment operator that assigns
9860   // two base classes, both of which move-assign the same virtual base.
9861   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
9862       Class->getNumBases() < 2)
9863     return;
9864 
9865   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
9866   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
9867   VBaseMap VBases;
9868 
9869   for (auto &BI : Class->bases()) {
9870     Worklist.push_back(&BI);
9871     while (!Worklist.empty()) {
9872       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
9873       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
9874 
9875       // If the base has no non-trivial move assignment operators,
9876       // we don't care about moves from it.
9877       if (!Base->hasNonTrivialMoveAssignment())
9878         continue;
9879 
9880       // If there's nothing virtual here, skip it.
9881       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
9882         continue;
9883 
9884       // If we're not actually going to call a move assignment for this base,
9885       // or the selected move assignment is trivial, skip it.
9886       Sema::SpecialMemberOverloadResult *SMOR =
9887         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
9888                               /*ConstArg*/false, /*VolatileArg*/false,
9889                               /*RValueThis*/true, /*ConstThis*/false,
9890                               /*VolatileThis*/false);
9891       if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
9892           !SMOR->getMethod()->isMoveAssignmentOperator())
9893         continue;
9894 
9895       if (BaseSpec->isVirtual()) {
9896         // We're going to move-assign this virtual base, and its move
9897         // assignment operator is not trivial. If this can happen for
9898         // multiple distinct direct bases of Class, diagnose it. (If it
9899         // only happens in one base, we'll diagnose it when synthesizing
9900         // that base class's move assignment operator.)
9901         CXXBaseSpecifier *&Existing =
9902             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
9903                 .first->second;
9904         if (Existing && Existing != &BI) {
9905           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
9906             << Class << Base;
9907           S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
9908             << (Base->getCanonicalDecl() ==
9909                 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9910             << Base << Existing->getType() << Existing->getSourceRange();
9911           S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
9912             << (Base->getCanonicalDecl() ==
9913                 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9914             << Base << BI.getType() << BaseSpec->getSourceRange();
9915 
9916           // Only diagnose each vbase once.
9917           Existing = nullptr;
9918         }
9919       } else {
9920         // Only walk over bases that have defaulted move assignment operators.
9921         // We assume that any user-provided move assignment operator handles
9922         // the multiple-moves-of-vbase case itself somehow.
9923         if (!SMOR->getMethod()->isDefaulted())
9924           continue;
9925 
9926         // We're going to move the base classes of Base. Add them to the list.
9927         for (auto &BI : Base->bases())
9928           Worklist.push_back(&BI);
9929       }
9930     }
9931   }
9932 }
9933 
9934 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9935                                         CXXMethodDecl *MoveAssignOperator) {
9936   assert((MoveAssignOperator->isDefaulted() &&
9937           MoveAssignOperator->isOverloadedOperator() &&
9938           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
9939           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9940           !MoveAssignOperator->isDeleted()) &&
9941          "DefineImplicitMoveAssignment called for wrong function");
9942 
9943   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9944 
9945   if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9946     MoveAssignOperator->setInvalidDecl();
9947     return;
9948   }
9949 
9950   MoveAssignOperator->markUsed(Context);
9951 
9952   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
9953   DiagnosticErrorTrap Trap(Diags);
9954 
9955   // C++0x [class.copy]p28:
9956   //   The implicitly-defined or move assignment operator for a non-union class
9957   //   X performs memberwise move assignment of its subobjects. The direct base
9958   //   classes of X are assigned first, in the order of their declaration in the
9959   //   base-specifier-list, and then the immediate non-static data members of X
9960   //   are assigned, in the order in which they were declared in the class
9961   //   definition.
9962 
9963   // Issue a warning if our implicit move assignment operator will move
9964   // from a virtual base more than once.
9965   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
9966 
9967   // The statements that form the synthesized function body.
9968   SmallVector<Stmt*, 8> Statements;
9969 
9970   // The parameter for the "other" object, which we are move from.
9971   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9972   QualType OtherRefType = Other->getType()->
9973       getAs<RValueReferenceType>()->getPointeeType();
9974   assert(!OtherRefType.getQualifiers() &&
9975          "Bad argument type of defaulted move assignment");
9976 
9977   // Our location for everything implicitly-generated.
9978   SourceLocation Loc = MoveAssignOperator->getLocation();
9979 
9980   // Builds a reference to the "other" object.
9981   RefBuilder OtherRef(Other, OtherRefType);
9982   // Cast to rvalue.
9983   MoveCastBuilder MoveOther(OtherRef);
9984 
9985   // Builds the "this" pointer.
9986   ThisBuilder This;
9987 
9988   // Assign base classes.
9989   bool Invalid = false;
9990   for (auto &Base : ClassDecl->bases()) {
9991     // C++11 [class.copy]p28:
9992     //   It is unspecified whether subobjects representing virtual base classes
9993     //   are assigned more than once by the implicitly-defined copy assignment
9994     //   operator.
9995     // FIXME: Do not assign to a vbase that will be assigned by some other base
9996     // class. For a move-assignment, this can result in the vbase being moved
9997     // multiple times.
9998 
9999     // Form the assignment:
10000     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
10001     QualType BaseType = Base.getType().getUnqualifiedType();
10002     if (!BaseType->isRecordType()) {
10003       Invalid = true;
10004       continue;
10005     }
10006 
10007     CXXCastPath BasePath;
10008     BasePath.push_back(&Base);
10009 
10010     // Construct the "from" expression, which is an implicit cast to the
10011     // appropriately-qualified base type.
10012     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
10013 
10014     // Dereference "this".
10015     DerefBuilder DerefThis(This);
10016 
10017     // Implicitly cast "this" to the appropriately-qualified base type.
10018     CastBuilder To(DerefThis,
10019                    Context.getCVRQualifiedType(
10020                        BaseType, MoveAssignOperator->getTypeQualifiers()),
10021                    VK_LValue, BasePath);
10022 
10023     // Build the move.
10024     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
10025                                             To, From,
10026                                             /*CopyingBaseSubobject=*/true,
10027                                             /*Copying=*/false);
10028     if (Move.isInvalid()) {
10029       Diag(CurrentLocation, diag::note_member_synthesized_at)
10030         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10031       MoveAssignOperator->setInvalidDecl();
10032       return;
10033     }
10034 
10035     // Success! Record the move.
10036     Statements.push_back(Move.getAs<Expr>());
10037   }
10038 
10039   // Assign non-static members.
10040   for (auto *Field : ClassDecl->fields()) {
10041     if (Field->isUnnamedBitfield())
10042       continue;
10043 
10044     if (Field->isInvalidDecl()) {
10045       Invalid = true;
10046       continue;
10047     }
10048 
10049     // Check for members of reference type; we can't move those.
10050     if (Field->getType()->isReferenceType()) {
10051       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10052         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10053       Diag(Field->getLocation(), diag::note_declared_at);
10054       Diag(CurrentLocation, diag::note_member_synthesized_at)
10055         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10056       Invalid = true;
10057       continue;
10058     }
10059 
10060     // Check for members of const-qualified, non-class type.
10061     QualType BaseType = Context.getBaseElementType(Field->getType());
10062     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10063       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10064         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10065       Diag(Field->getLocation(), diag::note_declared_at);
10066       Diag(CurrentLocation, diag::note_member_synthesized_at)
10067         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10068       Invalid = true;
10069       continue;
10070     }
10071 
10072     // Suppress assigning zero-width bitfields.
10073     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10074       continue;
10075 
10076     QualType FieldType = Field->getType().getNonReferenceType();
10077     if (FieldType->isIncompleteArrayType()) {
10078       assert(ClassDecl->hasFlexibleArrayMember() &&
10079              "Incomplete array type is not valid");
10080       continue;
10081     }
10082 
10083     // Build references to the field in the object we're copying from and to.
10084     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10085                               LookupMemberName);
10086     MemberLookup.addDecl(Field);
10087     MemberLookup.resolveKind();
10088     MemberBuilder From(MoveOther, OtherRefType,
10089                        /*IsArrow=*/false, MemberLookup);
10090     MemberBuilder To(This, getCurrentThisType(),
10091                      /*IsArrow=*/true, MemberLookup);
10092 
10093     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
10094         "Member reference with rvalue base must be rvalue except for reference "
10095         "members, which aren't allowed for move assignment.");
10096 
10097     // Build the move of this field.
10098     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
10099                                             To, From,
10100                                             /*CopyingBaseSubobject=*/false,
10101                                             /*Copying=*/false);
10102     if (Move.isInvalid()) {
10103       Diag(CurrentLocation, diag::note_member_synthesized_at)
10104         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10105       MoveAssignOperator->setInvalidDecl();
10106       return;
10107     }
10108 
10109     // Success! Record the copy.
10110     Statements.push_back(Move.getAs<Stmt>());
10111   }
10112 
10113   if (!Invalid) {
10114     // Add a "return *this;"
10115     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10116 
10117     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
10118     if (Return.isInvalid())
10119       Invalid = true;
10120     else {
10121       Statements.push_back(Return.getAs<Stmt>());
10122 
10123       if (Trap.hasErrorOccurred()) {
10124         Diag(CurrentLocation, diag::note_member_synthesized_at)
10125           << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10126         Invalid = true;
10127       }
10128     }
10129   }
10130 
10131   if (Invalid) {
10132     MoveAssignOperator->setInvalidDecl();
10133     return;
10134   }
10135 
10136   StmtResult Body;
10137   {
10138     CompoundScopeRAII CompoundScope(*this);
10139     Body = ActOnCompoundStmt(Loc, Loc, Statements,
10140                              /*isStmtExpr=*/false);
10141     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10142   }
10143   MoveAssignOperator->setBody(Body.getAs<Stmt>());
10144 
10145   if (ASTMutationListener *L = getASTMutationListener()) {
10146     L->CompletedImplicitDefinition(MoveAssignOperator);
10147   }
10148 }
10149 
10150 Sema::ImplicitExceptionSpecification
10151 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10152   CXXRecordDecl *ClassDecl = MD->getParent();
10153 
10154   ImplicitExceptionSpecification ExceptSpec(*this);
10155   if (ClassDecl->isInvalidDecl())
10156     return ExceptSpec;
10157 
10158   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
10159   assert(T->getNumParams() >= 1 && "not a copy ctor");
10160   unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
10161 
10162   // C++ [except.spec]p14:
10163   //   An implicitly declared special member function (Clause 12) shall have an
10164   //   exception-specification. [...]
10165   for (const auto &Base : ClassDecl->bases()) {
10166     // Virtual bases are handled below.
10167     if (Base.isVirtual())
10168       continue;
10169 
10170     CXXRecordDecl *BaseClassDecl
10171       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10172     if (CXXConstructorDecl *CopyConstructor =
10173           LookupCopyingConstructor(BaseClassDecl, Quals))
10174       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10175   }
10176   for (const auto &Base : ClassDecl->vbases()) {
10177     CXXRecordDecl *BaseClassDecl
10178       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10179     if (CXXConstructorDecl *CopyConstructor =
10180           LookupCopyingConstructor(BaseClassDecl, Quals))
10181       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10182   }
10183   for (const auto *Field : ClassDecl->fields()) {
10184     QualType FieldType = Context.getBaseElementType(Field->getType());
10185     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10186       if (CXXConstructorDecl *CopyConstructor =
10187               LookupCopyingConstructor(FieldClassDecl,
10188                                        Quals | FieldType.getCVRQualifiers()))
10189       ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
10190     }
10191   }
10192 
10193   return ExceptSpec;
10194 }
10195 
10196 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10197                                                     CXXRecordDecl *ClassDecl) {
10198   // C++ [class.copy]p4:
10199   //   If the class definition does not explicitly declare a copy
10200   //   constructor, one is declared implicitly.
10201   assert(ClassDecl->needsImplicitCopyConstructor());
10202 
10203   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10204   if (DSM.isAlreadyBeingDeclared())
10205     return nullptr;
10206 
10207   QualType ClassType = Context.getTypeDeclType(ClassDecl);
10208   QualType ArgType = ClassType;
10209   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
10210   if (Const)
10211     ArgType = ArgType.withConst();
10212   ArgType = Context.getLValueReferenceType(ArgType);
10213 
10214   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10215                                                      CXXCopyConstructor,
10216                                                      Const);
10217 
10218   DeclarationName Name
10219     = Context.DeclarationNames.getCXXConstructorName(
10220                                            Context.getCanonicalType(ClassType));
10221   SourceLocation ClassLoc = ClassDecl->getLocation();
10222   DeclarationNameInfo NameInfo(Name, ClassLoc);
10223 
10224   //   An implicitly-declared copy constructor is an inline public
10225   //   member of its class.
10226   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
10227       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
10228       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10229       Constexpr);
10230   CopyConstructor->setAccess(AS_public);
10231   CopyConstructor->setDefaulted();
10232 
10233   // Build an exception specification pointing back at this member.
10234   FunctionProtoType::ExtProtoInfo EPI =
10235       getImplicitMethodEPI(*this, CopyConstructor);
10236   CopyConstructor->setType(
10237       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10238 
10239   // Add the parameter to the constructor.
10240   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
10241                                                ClassLoc, ClassLoc,
10242                                                /*IdentifierInfo=*/nullptr,
10243                                                ArgType, /*TInfo=*/nullptr,
10244                                                SC_None, nullptr);
10245   CopyConstructor->setParams(FromParam);
10246 
10247   CopyConstructor->setTrivial(
10248     ClassDecl->needsOverloadResolutionForCopyConstructor()
10249       ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10250       : ClassDecl->hasTrivialCopyConstructor());
10251 
10252   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
10253     SetDeclDeleted(CopyConstructor, ClassLoc);
10254 
10255   // Note that we have declared this constructor.
10256   ++ASTContext::NumImplicitCopyConstructorsDeclared;
10257 
10258   if (Scope *S = getScopeForContext(ClassDecl))
10259     PushOnScopeChains(CopyConstructor, S, false);
10260   ClassDecl->addDecl(CopyConstructor);
10261 
10262   return CopyConstructor;
10263 }
10264 
10265 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
10266                                    CXXConstructorDecl *CopyConstructor) {
10267   assert((CopyConstructor->isDefaulted() &&
10268           CopyConstructor->isCopyConstructor() &&
10269           !CopyConstructor->doesThisDeclarationHaveABody() &&
10270           !CopyConstructor->isDeleted()) &&
10271          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
10272 
10273   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
10274   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
10275 
10276   // C++11 [class.copy]p7:
10277   //   The [definition of an implicitly declared copy constructor] is
10278   //   deprecated if the class has a user-declared copy assignment operator
10279   //   or a user-declared destructor.
10280   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10281     diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10282 
10283   SynthesizedFunctionScope Scope(*this, CopyConstructor);
10284   DiagnosticErrorTrap Trap(Diags);
10285 
10286   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
10287       Trap.hasErrorOccurred()) {
10288     Diag(CurrentLocation, diag::note_member_synthesized_at)
10289       << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
10290     CopyConstructor->setInvalidDecl();
10291   }  else {
10292     Sema::CompoundScopeRAII CompoundScope(*this);
10293     CopyConstructor->setBody(ActOnCompoundStmt(
10294         CopyConstructor->getLocation(), CopyConstructor->getLocation(), None,
10295         /*isStmtExpr=*/ false).getAs<Stmt>());
10296   }
10297 
10298   CopyConstructor->markUsed(Context);
10299   if (ASTMutationListener *L = getASTMutationListener()) {
10300     L->CompletedImplicitDefinition(CopyConstructor);
10301   }
10302 }
10303 
10304 Sema::ImplicitExceptionSpecification
10305 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10306   CXXRecordDecl *ClassDecl = MD->getParent();
10307 
10308   // C++ [except.spec]p14:
10309   //   An implicitly declared special member function (Clause 12) shall have an
10310   //   exception-specification. [...]
10311   ImplicitExceptionSpecification ExceptSpec(*this);
10312   if (ClassDecl->isInvalidDecl())
10313     return ExceptSpec;
10314 
10315   // Direct base-class constructors.
10316   for (const auto &B : ClassDecl->bases()) {
10317     if (B.isVirtual()) // Handled below.
10318       continue;
10319 
10320     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
10321       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10322       CXXConstructorDecl *Constructor =
10323           LookupMovingConstructor(BaseClassDecl, 0);
10324       // If this is a deleted function, add it anyway. This might be conformant
10325       // with the standard. This might not. I'm not sure. It might not matter.
10326       if (Constructor)
10327         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
10328     }
10329   }
10330 
10331   // Virtual base-class constructors.
10332   for (const auto &B : ClassDecl->vbases()) {
10333     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
10334       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10335       CXXConstructorDecl *Constructor =
10336           LookupMovingConstructor(BaseClassDecl, 0);
10337       // If this is a deleted function, add it anyway. This might be conformant
10338       // with the standard. This might not. I'm not sure. It might not matter.
10339       if (Constructor)
10340         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
10341     }
10342   }
10343 
10344   // Field constructors.
10345   for (const auto *F : ClassDecl->fields()) {
10346     QualType FieldType = Context.getBaseElementType(F->getType());
10347     if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10348       CXXConstructorDecl *Constructor =
10349           LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
10350       // If this is a deleted function, add it anyway. This might be conformant
10351       // with the standard. This might not. I'm not sure. It might not matter.
10352       // In particular, the problem is that this function never gets called. It
10353       // might just be ill-formed because this function attempts to refer to
10354       // a deleted function here.
10355       if (Constructor)
10356         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
10357     }
10358   }
10359 
10360   return ExceptSpec;
10361 }
10362 
10363 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10364                                                     CXXRecordDecl *ClassDecl) {
10365   assert(ClassDecl->needsImplicitMoveConstructor());
10366 
10367   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10368   if (DSM.isAlreadyBeingDeclared())
10369     return nullptr;
10370 
10371   QualType ClassType = Context.getTypeDeclType(ClassDecl);
10372   QualType ArgType = Context.getRValueReferenceType(ClassType);
10373 
10374   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10375                                                      CXXMoveConstructor,
10376                                                      false);
10377 
10378   DeclarationName Name
10379     = Context.DeclarationNames.getCXXConstructorName(
10380                                            Context.getCanonicalType(ClassType));
10381   SourceLocation ClassLoc = ClassDecl->getLocation();
10382   DeclarationNameInfo NameInfo(Name, ClassLoc);
10383 
10384   // C++11 [class.copy]p11:
10385   //   An implicitly-declared copy/move constructor is an inline public
10386   //   member of its class.
10387   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
10388       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
10389       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10390       Constexpr);
10391   MoveConstructor->setAccess(AS_public);
10392   MoveConstructor->setDefaulted();
10393 
10394   // Build an exception specification pointing back at this member.
10395   FunctionProtoType::ExtProtoInfo EPI =
10396       getImplicitMethodEPI(*this, MoveConstructor);
10397   MoveConstructor->setType(
10398       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10399 
10400   // Add the parameter to the constructor.
10401   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10402                                                ClassLoc, ClassLoc,
10403                                                /*IdentifierInfo=*/nullptr,
10404                                                ArgType, /*TInfo=*/nullptr,
10405                                                SC_None, nullptr);
10406   MoveConstructor->setParams(FromParam);
10407 
10408   MoveConstructor->setTrivial(
10409     ClassDecl->needsOverloadResolutionForMoveConstructor()
10410       ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10411       : ClassDecl->hasTrivialMoveConstructor());
10412 
10413   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
10414     ClassDecl->setImplicitMoveConstructorIsDeleted();
10415     SetDeclDeleted(MoveConstructor, ClassLoc);
10416   }
10417 
10418   // Note that we have declared this constructor.
10419   ++ASTContext::NumImplicitMoveConstructorsDeclared;
10420 
10421   if (Scope *S = getScopeForContext(ClassDecl))
10422     PushOnScopeChains(MoveConstructor, S, false);
10423   ClassDecl->addDecl(MoveConstructor);
10424 
10425   return MoveConstructor;
10426 }
10427 
10428 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10429                                    CXXConstructorDecl *MoveConstructor) {
10430   assert((MoveConstructor->isDefaulted() &&
10431           MoveConstructor->isMoveConstructor() &&
10432           !MoveConstructor->doesThisDeclarationHaveABody() &&
10433           !MoveConstructor->isDeleted()) &&
10434          "DefineImplicitMoveConstructor - call it for implicit move ctor");
10435 
10436   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10437   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10438 
10439   SynthesizedFunctionScope Scope(*this, MoveConstructor);
10440   DiagnosticErrorTrap Trap(Diags);
10441 
10442   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
10443       Trap.hasErrorOccurred()) {
10444     Diag(CurrentLocation, diag::note_member_synthesized_at)
10445       << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10446     MoveConstructor->setInvalidDecl();
10447   }  else {
10448     Sema::CompoundScopeRAII CompoundScope(*this);
10449     MoveConstructor->setBody(ActOnCompoundStmt(
10450         MoveConstructor->getLocation(), MoveConstructor->getLocation(), None,
10451         /*isStmtExpr=*/ false).getAs<Stmt>());
10452   }
10453 
10454   MoveConstructor->markUsed(Context);
10455 
10456   if (ASTMutationListener *L = getASTMutationListener()) {
10457     L->CompletedImplicitDefinition(MoveConstructor);
10458   }
10459 }
10460 
10461 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
10462   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
10463 }
10464 
10465 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
10466                             SourceLocation CurrentLocation,
10467                             CXXConversionDecl *Conv) {
10468   CXXRecordDecl *Lambda = Conv->getParent();
10469   CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10470   // If we are defining a specialization of a conversion to function-ptr
10471   // cache the deduced template arguments for this specialization
10472   // so that we can use them to retrieve the corresponding call-operator
10473   // and static-invoker.
10474   const TemplateArgumentList *DeducedTemplateArgs = nullptr;
10475 
10476   // Retrieve the corresponding call-operator specialization.
10477   if (Lambda->isGenericLambda()) {
10478     assert(Conv->isFunctionTemplateSpecialization());
10479     FunctionTemplateDecl *CallOpTemplate =
10480         CallOp->getDescribedFunctionTemplate();
10481     DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
10482     void *InsertPos = nullptr;
10483     FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
10484                                                 DeducedTemplateArgs->data(),
10485                                                 DeducedTemplateArgs->size(),
10486                                                 InsertPos);
10487     assert(CallOpSpec &&
10488           "Conversion operator must have a corresponding call operator");
10489     CallOp = cast<CXXMethodDecl>(CallOpSpec);
10490   }
10491   // Mark the call operator referenced (and add to pending instantiations
10492   // if necessary).
10493   // For both the conversion and static-invoker template specializations
10494   // we construct their body's in this function, so no need to add them
10495   // to the PendingInstantiations.
10496   MarkFunctionReferenced(CurrentLocation, CallOp);
10497 
10498   SynthesizedFunctionScope Scope(*this, Conv);
10499   DiagnosticErrorTrap Trap(Diags);
10500 
10501   // Retrieve the static invoker...
10502   CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10503   // ... and get the corresponding specialization for a generic lambda.
10504   if (Lambda->isGenericLambda()) {
10505     assert(DeducedTemplateArgs &&
10506       "Must have deduced template arguments from Conversion Operator");
10507     FunctionTemplateDecl *InvokeTemplate =
10508                           Invoker->getDescribedFunctionTemplate();
10509     void *InsertPos = nullptr;
10510     FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
10511                                                 DeducedTemplateArgs->data(),
10512                                                 DeducedTemplateArgs->size(),
10513                                                 InsertPos);
10514     assert(InvokeSpec &&
10515       "Must have a corresponding static invoker specialization");
10516     Invoker = cast<CXXMethodDecl>(InvokeSpec);
10517   }
10518   // Construct the body of the conversion function { return __invoke; }.
10519   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
10520                                         VK_LValue, Conv->getLocation()).get();
10521    assert(FunctionRef && "Can't refer to __invoke function?");
10522    Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
10523    Conv->setBody(new (Context) CompoundStmt(Context, Return,
10524                                             Conv->getLocation(),
10525                                             Conv->getLocation()));
10526 
10527   Conv->markUsed(Context);
10528   Conv->setReferenced();
10529 
10530   // Fill in the __invoke function with a dummy implementation. IR generation
10531   // will fill in the actual details.
10532   Invoker->markUsed(Context);
10533   Invoker->setReferenced();
10534   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10535 
10536   if (ASTMutationListener *L = getASTMutationListener()) {
10537     L->CompletedImplicitDefinition(Conv);
10538     L->CompletedImplicitDefinition(Invoker);
10539    }
10540 }
10541 
10542 
10543 
10544 void Sema::DefineImplicitLambdaToBlockPointerConversion(
10545        SourceLocation CurrentLocation,
10546        CXXConversionDecl *Conv)
10547 {
10548   assert(!Conv->getParent()->isGenericLambda());
10549 
10550   Conv->markUsed(Context);
10551 
10552   SynthesizedFunctionScope Scope(*this, Conv);
10553   DiagnosticErrorTrap Trap(Diags);
10554 
10555   // Copy-initialize the lambda object as needed to capture it.
10556   Expr *This = ActOnCXXThis(CurrentLocation).get();
10557   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
10558 
10559   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10560                                                         Conv->getLocation(),
10561                                                         Conv, DerefThis);
10562 
10563   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10564   // behavior.  Note that only the general conversion function does this
10565   // (since it's unusable otherwise); in the case where we inline the
10566   // block literal, it has block literal lifetime semantics.
10567   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
10568     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10569                                           CK_CopyAndAutoreleaseBlockObject,
10570                                           BuildBlock.get(), nullptr, VK_RValue);
10571 
10572   if (BuildBlock.isInvalid()) {
10573     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10574     Conv->setInvalidDecl();
10575     return;
10576   }
10577 
10578   // Create the return statement that returns the block from the conversion
10579   // function.
10580   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
10581   if (Return.isInvalid()) {
10582     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10583     Conv->setInvalidDecl();
10584     return;
10585   }
10586 
10587   // Set the body of the conversion function.
10588   Stmt *ReturnS = Return.get();
10589   Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
10590                                            Conv->getLocation(),
10591                                            Conv->getLocation()));
10592 
10593   // We're done; notify the mutation listener, if any.
10594   if (ASTMutationListener *L = getASTMutationListener()) {
10595     L->CompletedImplicitDefinition(Conv);
10596   }
10597 }
10598 
10599 /// \brief Determine whether the given list arguments contains exactly one
10600 /// "real" (non-default) argument.
10601 static bool hasOneRealArgument(MultiExprArg Args) {
10602   switch (Args.size()) {
10603   case 0:
10604     return false;
10605 
10606   default:
10607     if (!Args[1]->isDefaultArgument())
10608       return false;
10609 
10610     // fall through
10611   case 1:
10612     return !Args[0]->isDefaultArgument();
10613   }
10614 
10615   return false;
10616 }
10617 
10618 ExprResult
10619 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10620                             CXXConstructorDecl *Constructor,
10621                             MultiExprArg ExprArgs,
10622                             bool HadMultipleCandidates,
10623                             bool IsListInitialization,
10624                             bool RequiresZeroInit,
10625                             unsigned ConstructKind,
10626                             SourceRange ParenRange) {
10627   bool Elidable = false;
10628 
10629   // C++0x [class.copy]p34:
10630   //   When certain criteria are met, an implementation is allowed to
10631   //   omit the copy/move construction of a class object, even if the
10632   //   copy/move constructor and/or destructor for the object have
10633   //   side effects. [...]
10634   //     - when a temporary class object that has not been bound to a
10635   //       reference (12.2) would be copied/moved to a class object
10636   //       with the same cv-unqualified type, the copy/move operation
10637   //       can be omitted by constructing the temporary object
10638   //       directly into the target of the omitted copy/move
10639   if (ConstructKind == CXXConstructExpr::CK_Complete &&
10640       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
10641     Expr *SubExpr = ExprArgs[0];
10642     Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
10643   }
10644 
10645   return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
10646                                Elidable, ExprArgs, HadMultipleCandidates,
10647                                IsListInitialization, RequiresZeroInit,
10648                                ConstructKind, ParenRange);
10649 }
10650 
10651 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
10652 /// including handling of its default argument expressions.
10653 ExprResult
10654 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10655                             CXXConstructorDecl *Constructor, bool Elidable,
10656                             MultiExprArg ExprArgs,
10657                             bool HadMultipleCandidates,
10658                             bool IsListInitialization,
10659                             bool RequiresZeroInit,
10660                             unsigned ConstructKind,
10661                             SourceRange ParenRange) {
10662   MarkFunctionReferenced(ConstructLoc, Constructor);
10663   return CXXConstructExpr::Create(
10664       Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
10665       HadMultipleCandidates, IsListInitialization, RequiresZeroInit,
10666       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10667       ParenRange);
10668 }
10669 
10670 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
10671   if (VD->isInvalidDecl()) return;
10672 
10673   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
10674   if (ClassDecl->isInvalidDecl()) return;
10675   if (ClassDecl->hasIrrelevantDestructor()) return;
10676   if (ClassDecl->isDependentContext()) return;
10677 
10678   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10679   MarkFunctionReferenced(VD->getLocation(), Destructor);
10680   CheckDestructorAccess(VD->getLocation(), Destructor,
10681                         PDiag(diag::err_access_dtor_var)
10682                         << VD->getDeclName()
10683                         << VD->getType());
10684   DiagnoseUseOfDecl(Destructor, VD->getLocation());
10685 
10686   if (Destructor->isTrivial()) return;
10687   if (!VD->hasGlobalStorage()) return;
10688 
10689   // Emit warning for non-trivial dtor in global scope (a real global,
10690   // class-static, function-static).
10691   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10692 
10693   // TODO: this should be re-enabled for static locals by !CXAAtExit
10694   if (!VD->isStaticLocal())
10695     Diag(VD->getLocation(), diag::warn_global_destructor);
10696 }
10697 
10698 /// \brief Given a constructor and the set of arguments provided for the
10699 /// constructor, convert the arguments and add any required default arguments
10700 /// to form a proper call to this constructor.
10701 ///
10702 /// \returns true if an error occurred, false otherwise.
10703 bool
10704 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10705                               MultiExprArg ArgsPtr,
10706                               SourceLocation Loc,
10707                               SmallVectorImpl<Expr*> &ConvertedArgs,
10708                               bool AllowExplicit,
10709                               bool IsListInitialization) {
10710   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10711   unsigned NumArgs = ArgsPtr.size();
10712   Expr **Args = ArgsPtr.data();
10713 
10714   const FunctionProtoType *Proto
10715     = Constructor->getType()->getAs<FunctionProtoType>();
10716   assert(Proto && "Constructor without a prototype?");
10717   unsigned NumParams = Proto->getNumParams();
10718 
10719   // If too few arguments are available, we'll fill in the rest with defaults.
10720   if (NumArgs < NumParams)
10721     ConvertedArgs.reserve(NumParams);
10722   else
10723     ConvertedArgs.reserve(NumArgs);
10724 
10725   VariadicCallType CallType =
10726     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
10727   SmallVector<Expr *, 8> AllArgs;
10728   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
10729                                         Proto, 0,
10730                                         llvm::makeArrayRef(Args, NumArgs),
10731                                         AllArgs,
10732                                         CallType, AllowExplicit,
10733                                         IsListInitialization);
10734   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
10735 
10736   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
10737 
10738   CheckConstructorCall(Constructor,
10739                        llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10740                                                         AllArgs.size()),
10741                        Proto, Loc);
10742 
10743   return Invalid;
10744 }
10745 
10746 static inline bool
10747 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10748                                        const FunctionDecl *FnDecl) {
10749   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
10750   if (isa<NamespaceDecl>(DC)) {
10751     return SemaRef.Diag(FnDecl->getLocation(),
10752                         diag::err_operator_new_delete_declared_in_namespace)
10753       << FnDecl->getDeclName();
10754   }
10755 
10756   if (isa<TranslationUnitDecl>(DC) &&
10757       FnDecl->getStorageClass() == SC_Static) {
10758     return SemaRef.Diag(FnDecl->getLocation(),
10759                         diag::err_operator_new_delete_declared_static)
10760       << FnDecl->getDeclName();
10761   }
10762 
10763   return false;
10764 }
10765 
10766 static inline bool
10767 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10768                             CanQualType ExpectedResultType,
10769                             CanQualType ExpectedFirstParamType,
10770                             unsigned DependentParamTypeDiag,
10771                             unsigned InvalidParamTypeDiag) {
10772   QualType ResultType =
10773       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
10774 
10775   // Check that the result type is not dependent.
10776   if (ResultType->isDependentType())
10777     return SemaRef.Diag(FnDecl->getLocation(),
10778                         diag::err_operator_new_delete_dependent_result_type)
10779     << FnDecl->getDeclName() << ExpectedResultType;
10780 
10781   // Check that the result type is what we expect.
10782   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10783     return SemaRef.Diag(FnDecl->getLocation(),
10784                         diag::err_operator_new_delete_invalid_result_type)
10785     << FnDecl->getDeclName() << ExpectedResultType;
10786 
10787   // A function template must have at least 2 parameters.
10788   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10789     return SemaRef.Diag(FnDecl->getLocation(),
10790                       diag::err_operator_new_delete_template_too_few_parameters)
10791         << FnDecl->getDeclName();
10792 
10793   // The function decl must have at least 1 parameter.
10794   if (FnDecl->getNumParams() == 0)
10795     return SemaRef.Diag(FnDecl->getLocation(),
10796                         diag::err_operator_new_delete_too_few_parameters)
10797       << FnDecl->getDeclName();
10798 
10799   // Check the first parameter type is not dependent.
10800   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10801   if (FirstParamType->isDependentType())
10802     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10803       << FnDecl->getDeclName() << ExpectedFirstParamType;
10804 
10805   // Check that the first parameter type is what we expect.
10806   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
10807       ExpectedFirstParamType)
10808     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10809     << FnDecl->getDeclName() << ExpectedFirstParamType;
10810 
10811   return false;
10812 }
10813 
10814 static bool
10815 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
10816   // C++ [basic.stc.dynamic.allocation]p1:
10817   //   A program is ill-formed if an allocation function is declared in a
10818   //   namespace scope other than global scope or declared static in global
10819   //   scope.
10820   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10821     return true;
10822 
10823   CanQualType SizeTy =
10824     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10825 
10826   // C++ [basic.stc.dynamic.allocation]p1:
10827   //  The return type shall be void*. The first parameter shall have type
10828   //  std::size_t.
10829   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10830                                   SizeTy,
10831                                   diag::err_operator_new_dependent_param_type,
10832                                   diag::err_operator_new_param_type))
10833     return true;
10834 
10835   // C++ [basic.stc.dynamic.allocation]p1:
10836   //  The first parameter shall not have an associated default argument.
10837   if (FnDecl->getParamDecl(0)->hasDefaultArg())
10838     return SemaRef.Diag(FnDecl->getLocation(),
10839                         diag::err_operator_new_default_arg)
10840       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10841 
10842   return false;
10843 }
10844 
10845 static bool
10846 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
10847   // C++ [basic.stc.dynamic.deallocation]p1:
10848   //   A program is ill-formed if deallocation functions are declared in a
10849   //   namespace scope other than global scope or declared static in global
10850   //   scope.
10851   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10852     return true;
10853 
10854   // C++ [basic.stc.dynamic.deallocation]p2:
10855   //   Each deallocation function shall return void and its first parameter
10856   //   shall be void*.
10857   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10858                                   SemaRef.Context.VoidPtrTy,
10859                                  diag::err_operator_delete_dependent_param_type,
10860                                  diag::err_operator_delete_param_type))
10861     return true;
10862 
10863   return false;
10864 }
10865 
10866 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
10867 /// of this overloaded operator is well-formed. If so, returns false;
10868 /// otherwise, emits appropriate diagnostics and returns true.
10869 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
10870   assert(FnDecl && FnDecl->isOverloadedOperator() &&
10871          "Expected an overloaded operator declaration");
10872 
10873   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10874 
10875   // C++ [over.oper]p5:
10876   //   The allocation and deallocation functions, operator new,
10877   //   operator new[], operator delete and operator delete[], are
10878   //   described completely in 3.7.3. The attributes and restrictions
10879   //   found in the rest of this subclause do not apply to them unless
10880   //   explicitly stated in 3.7.3.
10881   if (Op == OO_Delete || Op == OO_Array_Delete)
10882     return CheckOperatorDeleteDeclaration(*this, FnDecl);
10883 
10884   if (Op == OO_New || Op == OO_Array_New)
10885     return CheckOperatorNewDeclaration(*this, FnDecl);
10886 
10887   // C++ [over.oper]p6:
10888   //   An operator function shall either be a non-static member
10889   //   function or be a non-member function and have at least one
10890   //   parameter whose type is a class, a reference to a class, an
10891   //   enumeration, or a reference to an enumeration.
10892   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10893     if (MethodDecl->isStatic())
10894       return Diag(FnDecl->getLocation(),
10895                   diag::err_operator_overload_static) << FnDecl->getDeclName();
10896   } else {
10897     bool ClassOrEnumParam = false;
10898     for (auto Param : FnDecl->params()) {
10899       QualType ParamType = Param->getType().getNonReferenceType();
10900       if (ParamType->isDependentType() || ParamType->isRecordType() ||
10901           ParamType->isEnumeralType()) {
10902         ClassOrEnumParam = true;
10903         break;
10904       }
10905     }
10906 
10907     if (!ClassOrEnumParam)
10908       return Diag(FnDecl->getLocation(),
10909                   diag::err_operator_overload_needs_class_or_enum)
10910         << FnDecl->getDeclName();
10911   }
10912 
10913   // C++ [over.oper]p8:
10914   //   An operator function cannot have default arguments (8.3.6),
10915   //   except where explicitly stated below.
10916   //
10917   // Only the function-call operator allows default arguments
10918   // (C++ [over.call]p1).
10919   if (Op != OO_Call) {
10920     for (auto Param : FnDecl->params()) {
10921       if (Param->hasDefaultArg())
10922         return Diag(Param->getLocation(),
10923                     diag::err_operator_overload_default_arg)
10924           << FnDecl->getDeclName() << Param->getDefaultArgRange();
10925     }
10926   }
10927 
10928   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10929     { false, false, false }
10930 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10931     , { Unary, Binary, MemberOnly }
10932 #include "clang/Basic/OperatorKinds.def"
10933   };
10934 
10935   bool CanBeUnaryOperator = OperatorUses[Op][0];
10936   bool CanBeBinaryOperator = OperatorUses[Op][1];
10937   bool MustBeMemberOperator = OperatorUses[Op][2];
10938 
10939   // C++ [over.oper]p8:
10940   //   [...] Operator functions cannot have more or fewer parameters
10941   //   than the number required for the corresponding operator, as
10942   //   described in the rest of this subclause.
10943   unsigned NumParams = FnDecl->getNumParams()
10944                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
10945   if (Op != OO_Call &&
10946       ((NumParams == 1 && !CanBeUnaryOperator) ||
10947        (NumParams == 2 && !CanBeBinaryOperator) ||
10948        (NumParams < 1) || (NumParams > 2))) {
10949     // We have the wrong number of parameters.
10950     unsigned ErrorKind;
10951     if (CanBeUnaryOperator && CanBeBinaryOperator) {
10952       ErrorKind = 2;  // 2 -> unary or binary.
10953     } else if (CanBeUnaryOperator) {
10954       ErrorKind = 0;  // 0 -> unary
10955     } else {
10956       assert(CanBeBinaryOperator &&
10957              "All non-call overloaded operators are unary or binary!");
10958       ErrorKind = 1;  // 1 -> binary
10959     }
10960 
10961     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
10962       << FnDecl->getDeclName() << NumParams << ErrorKind;
10963   }
10964 
10965   // Overloaded operators other than operator() cannot be variadic.
10966   if (Op != OO_Call &&
10967       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
10968     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
10969       << FnDecl->getDeclName();
10970   }
10971 
10972   // Some operators must be non-static member functions.
10973   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10974     return Diag(FnDecl->getLocation(),
10975                 diag::err_operator_overload_must_be_member)
10976       << FnDecl->getDeclName();
10977   }
10978 
10979   // C++ [over.inc]p1:
10980   //   The user-defined function called operator++ implements the
10981   //   prefix and postfix ++ operator. If this function is a member
10982   //   function with no parameters, or a non-member function with one
10983   //   parameter of class or enumeration type, it defines the prefix
10984   //   increment operator ++ for objects of that type. If the function
10985   //   is a member function with one parameter (which shall be of type
10986   //   int) or a non-member function with two parameters (the second
10987   //   of which shall be of type int), it defines the postfix
10988   //   increment operator ++ for objects of that type.
10989   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10990     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10991     QualType ParamType = LastParam->getType();
10992 
10993     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
10994         !ParamType->isDependentType())
10995       return Diag(LastParam->getLocation(),
10996                   diag::err_operator_overload_post_incdec_must_be_int)
10997         << LastParam->getType() << (Op == OO_MinusMinus);
10998   }
10999 
11000   return false;
11001 }
11002 
11003 /// CheckLiteralOperatorDeclaration - Check whether the declaration
11004 /// of this literal operator function is well-formed. If so, returns
11005 /// false; otherwise, emits appropriate diagnostics and returns true.
11006 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
11007   if (isa<CXXMethodDecl>(FnDecl)) {
11008     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11009       << FnDecl->getDeclName();
11010     return true;
11011   }
11012 
11013   if (FnDecl->isExternC()) {
11014     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11015     return true;
11016   }
11017 
11018   bool Valid = false;
11019 
11020   // This might be the definition of a literal operator template.
11021   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11022   // This might be a specialization of a literal operator template.
11023   if (!TpDecl)
11024     TpDecl = FnDecl->getPrimaryTemplate();
11025 
11026   // template <char...> type operator "" name() and
11027   // template <class T, T...> type operator "" name() are the only valid
11028   // template signatures, and the only valid signatures with no parameters.
11029   if (TpDecl) {
11030     if (FnDecl->param_size() == 0) {
11031       // Must have one or two template parameters
11032       TemplateParameterList *Params = TpDecl->getTemplateParameters();
11033       if (Params->size() == 1) {
11034         NonTypeTemplateParmDecl *PmDecl =
11035           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
11036 
11037         // The template parameter must be a char parameter pack.
11038         if (PmDecl && PmDecl->isTemplateParameterPack() &&
11039             Context.hasSameType(PmDecl->getType(), Context.CharTy))
11040           Valid = true;
11041       } else if (Params->size() == 2) {
11042         TemplateTypeParmDecl *PmType =
11043           dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
11044         NonTypeTemplateParmDecl *PmArgs =
11045           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
11046 
11047         // The second template parameter must be a parameter pack with the
11048         // first template parameter as its type.
11049         if (PmType && PmArgs &&
11050             !PmType->isTemplateParameterPack() &&
11051             PmArgs->isTemplateParameterPack()) {
11052           const TemplateTypeParmType *TArgs =
11053             PmArgs->getType()->getAs<TemplateTypeParmType>();
11054           if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11055               TArgs->getIndex() == PmType->getIndex()) {
11056             Valid = true;
11057             if (ActiveTemplateInstantiations.empty())
11058               Diag(FnDecl->getLocation(),
11059                    diag::ext_string_literal_operator_template);
11060           }
11061         }
11062       }
11063     }
11064   } else if (FnDecl->param_size()) {
11065     // Check the first parameter
11066     FunctionDecl::param_iterator Param = FnDecl->param_begin();
11067 
11068     QualType T = (*Param)->getType().getUnqualifiedType();
11069 
11070     // unsigned long long int, long double, and any character type are allowed
11071     // as the only parameters.
11072     if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
11073         Context.hasSameType(T, Context.LongDoubleTy) ||
11074         Context.hasSameType(T, Context.CharTy) ||
11075         Context.hasSameType(T, Context.WideCharTy) ||
11076         Context.hasSameType(T, Context.Char16Ty) ||
11077         Context.hasSameType(T, Context.Char32Ty)) {
11078       if (++Param == FnDecl->param_end())
11079         Valid = true;
11080       goto FinishedParams;
11081     }
11082 
11083     // Otherwise it must be a pointer to const; let's strip those qualifiers.
11084     const PointerType *PT = T->getAs<PointerType>();
11085     if (!PT)
11086       goto FinishedParams;
11087     T = PT->getPointeeType();
11088     if (!T.isConstQualified() || T.isVolatileQualified())
11089       goto FinishedParams;
11090     T = T.getUnqualifiedType();
11091 
11092     // Move on to the second parameter;
11093     ++Param;
11094 
11095     // If there is no second parameter, the first must be a const char *
11096     if (Param == FnDecl->param_end()) {
11097       if (Context.hasSameType(T, Context.CharTy))
11098         Valid = true;
11099       goto FinishedParams;
11100     }
11101 
11102     // const char *, const wchar_t*, const char16_t*, and const char32_t*
11103     // are allowed as the first parameter to a two-parameter function
11104     if (!(Context.hasSameType(T, Context.CharTy) ||
11105           Context.hasSameType(T, Context.WideCharTy) ||
11106           Context.hasSameType(T, Context.Char16Ty) ||
11107           Context.hasSameType(T, Context.Char32Ty)))
11108       goto FinishedParams;
11109 
11110     // The second and final parameter must be an std::size_t
11111     T = (*Param)->getType().getUnqualifiedType();
11112     if (Context.hasSameType(T, Context.getSizeType()) &&
11113         ++Param == FnDecl->param_end())
11114       Valid = true;
11115   }
11116 
11117   // FIXME: This diagnostic is absolutely terrible.
11118 FinishedParams:
11119   if (!Valid) {
11120     Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11121       << FnDecl->getDeclName();
11122     return true;
11123   }
11124 
11125   // A parameter-declaration-clause containing a default argument is not
11126   // equivalent to any of the permitted forms.
11127   for (auto Param : FnDecl->params()) {
11128     if (Param->hasDefaultArg()) {
11129       Diag(Param->getDefaultArgRange().getBegin(),
11130            diag::err_literal_operator_default_argument)
11131         << Param->getDefaultArgRange();
11132       break;
11133     }
11134   }
11135 
11136   StringRef LiteralName
11137     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11138   if (LiteralName[0] != '_') {
11139     // C++11 [usrlit.suffix]p1:
11140     //   Literal suffix identifiers that do not start with an underscore
11141     //   are reserved for future standardization.
11142     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11143       << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
11144   }
11145 
11146   return false;
11147 }
11148 
11149 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11150 /// linkage specification, including the language and (if present)
11151 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
11152 /// language string literal. LBraceLoc, if valid, provides the location of
11153 /// the '{' brace. Otherwise, this linkage specification does not
11154 /// have any braces.
11155 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
11156                                            Expr *LangStr,
11157                                            SourceLocation LBraceLoc) {
11158   StringLiteral *Lit = cast<StringLiteral>(LangStr);
11159   if (!Lit->isAscii()) {
11160     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11161       << LangStr->getSourceRange();
11162     return nullptr;
11163   }
11164 
11165   StringRef Lang = Lit->getString();
11166   LinkageSpecDecl::LanguageIDs Language;
11167   if (Lang == "C")
11168     Language = LinkageSpecDecl::lang_c;
11169   else if (Lang == "C++")
11170     Language = LinkageSpecDecl::lang_cxx;
11171   else {
11172     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11173       << LangStr->getSourceRange();
11174     return nullptr;
11175   }
11176 
11177   // FIXME: Add all the various semantics of linkage specifications
11178 
11179   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11180                                                LangStr->getExprLoc(), Language,
11181                                                LBraceLoc.isValid());
11182   CurContext->addDecl(D);
11183   PushDeclContext(S, D);
11184   return D;
11185 }
11186 
11187 /// ActOnFinishLinkageSpecification - Complete the definition of
11188 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
11189 /// valid, it's the position of the closing '}' brace in a linkage
11190 /// specification that uses braces.
11191 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
11192                                             Decl *LinkageSpec,
11193                                             SourceLocation RBraceLoc) {
11194   if (RBraceLoc.isValid()) {
11195     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11196     LSDecl->setRBraceLoc(RBraceLoc);
11197   }
11198   PopDeclContext();
11199   return LinkageSpec;
11200 }
11201 
11202 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11203                                   AttributeList *AttrList,
11204                                   SourceLocation SemiLoc) {
11205   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11206   // Attribute declarations appertain to empty declaration so we handle
11207   // them here.
11208   if (AttrList)
11209     ProcessDeclAttributeList(S, ED, AttrList);
11210 
11211   CurContext->addDecl(ED);
11212   return ED;
11213 }
11214 
11215 /// \brief Perform semantic analysis for the variable declaration that
11216 /// occurs within a C++ catch clause, returning the newly-created
11217 /// variable.
11218 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
11219                                          TypeSourceInfo *TInfo,
11220                                          SourceLocation StartLoc,
11221                                          SourceLocation Loc,
11222                                          IdentifierInfo *Name) {
11223   bool Invalid = false;
11224   QualType ExDeclType = TInfo->getType();
11225 
11226   // Arrays and functions decay.
11227   if (ExDeclType->isArrayType())
11228     ExDeclType = Context.getArrayDecayedType(ExDeclType);
11229   else if (ExDeclType->isFunctionType())
11230     ExDeclType = Context.getPointerType(ExDeclType);
11231 
11232   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11233   // The exception-declaration shall not denote a pointer or reference to an
11234   // incomplete type, other than [cv] void*.
11235   // N2844 forbids rvalue references.
11236   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
11237     Diag(Loc, diag::err_catch_rvalue_ref);
11238     Invalid = true;
11239   }
11240 
11241   QualType BaseType = ExDeclType;
11242   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
11243   unsigned DK = diag::err_catch_incomplete;
11244   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
11245     BaseType = Ptr->getPointeeType();
11246     Mode = 1;
11247     DK = diag::err_catch_incomplete_ptr;
11248   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
11249     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
11250     BaseType = Ref->getPointeeType();
11251     Mode = 2;
11252     DK = diag::err_catch_incomplete_ref;
11253   }
11254   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
11255       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
11256     Invalid = true;
11257 
11258   if (!Invalid && !ExDeclType->isDependentType() &&
11259       RequireNonAbstractType(Loc, ExDeclType,
11260                              diag::err_abstract_type_in_decl,
11261                              AbstractVariableType))
11262     Invalid = true;
11263 
11264   // Only the non-fragile NeXT runtime currently supports C++ catches
11265   // of ObjC types, and no runtime supports catching ObjC types by value.
11266   if (!Invalid && getLangOpts().ObjC1) {
11267     QualType T = ExDeclType;
11268     if (const ReferenceType *RT = T->getAs<ReferenceType>())
11269       T = RT->getPointeeType();
11270 
11271     if (T->isObjCObjectType()) {
11272       Diag(Loc, diag::err_objc_object_catch);
11273       Invalid = true;
11274     } else if (T->isObjCObjectPointerType()) {
11275       // FIXME: should this be a test for macosx-fragile specifically?
11276       if (getLangOpts().ObjCRuntime.isFragile())
11277         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
11278     }
11279   }
11280 
11281   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
11282                                     ExDeclType, TInfo, SC_None);
11283   ExDecl->setExceptionVariable(true);
11284 
11285   // In ARC, infer 'retaining' for variables of retainable type.
11286   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
11287     Invalid = true;
11288 
11289   if (!Invalid && !ExDeclType->isDependentType()) {
11290     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
11291       // Insulate this from anything else we might currently be parsing.
11292       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11293 
11294       // C++ [except.handle]p16:
11295       //   The object declared in an exception-declaration or, if the
11296       //   exception-declaration does not specify a name, a temporary (12.2) is
11297       //   copy-initialized (8.5) from the exception object. [...]
11298       //   The object is destroyed when the handler exits, after the destruction
11299       //   of any automatic objects initialized within the handler.
11300       //
11301       // We just pretend to initialize the object with itself, then make sure
11302       // it can be destroyed later.
11303       QualType initType = ExDeclType;
11304 
11305       InitializedEntity entity =
11306         InitializedEntity::InitializeVariable(ExDecl);
11307       InitializationKind initKind =
11308         InitializationKind::CreateCopy(Loc, SourceLocation());
11309 
11310       Expr *opaqueValue =
11311         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
11312       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11313       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
11314       if (result.isInvalid())
11315         Invalid = true;
11316       else {
11317         // If the constructor used was non-trivial, set this as the
11318         // "initializer".
11319         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
11320         if (!construct->getConstructor()->isTrivial()) {
11321           Expr *init = MaybeCreateExprWithCleanups(construct);
11322           ExDecl->setInit(init);
11323         }
11324 
11325         // And make sure it's destructable.
11326         FinalizeVarWithDestructor(ExDecl, recordType);
11327       }
11328     }
11329   }
11330 
11331   if (Invalid)
11332     ExDecl->setInvalidDecl();
11333 
11334   return ExDecl;
11335 }
11336 
11337 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11338 /// handler.
11339 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
11340   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11341   bool Invalid = D.isInvalidType();
11342 
11343   // Check for unexpanded parameter packs.
11344   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11345                                       UPPC_ExceptionType)) {
11346     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11347                                              D.getIdentifierLoc());
11348     Invalid = true;
11349   }
11350 
11351   IdentifierInfo *II = D.getIdentifier();
11352   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
11353                                              LookupOrdinaryName,
11354                                              ForRedeclaration)) {
11355     // The scope should be freshly made just for us. There is just no way
11356     // it contains any previous declaration, except for function parameters in
11357     // a function-try-block's catch statement.
11358     assert(!S->isDeclScope(PrevDecl));
11359     if (isDeclInScope(PrevDecl, CurContext, S)) {
11360       Diag(D.getIdentifierLoc(), diag::err_redefinition)
11361         << D.getIdentifier();
11362       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11363       Invalid = true;
11364     } else if (PrevDecl->isTemplateParameter())
11365       // Maybe we will complain about the shadowed template parameter.
11366       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11367   }
11368 
11369   if (D.getCXXScopeSpec().isSet() && !Invalid) {
11370     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11371       << D.getCXXScopeSpec().getRange();
11372     Invalid = true;
11373   }
11374 
11375   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
11376                                               D.getLocStart(),
11377                                               D.getIdentifierLoc(),
11378                                               D.getIdentifier());
11379   if (Invalid)
11380     ExDecl->setInvalidDecl();
11381 
11382   // Add the exception declaration into this scope.
11383   if (II)
11384     PushOnScopeChains(ExDecl, S);
11385   else
11386     CurContext->addDecl(ExDecl);
11387 
11388   ProcessDeclAttributes(S, ExDecl, D);
11389   return ExDecl;
11390 }
11391 
11392 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11393                                          Expr *AssertExpr,
11394                                          Expr *AssertMessageExpr,
11395                                          SourceLocation RParenLoc) {
11396   StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
11397 
11398   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
11399     return nullptr;
11400 
11401   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11402                                       AssertMessage, RParenLoc, false);
11403 }
11404 
11405 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11406                                          Expr *AssertExpr,
11407                                          StringLiteral *AssertMessage,
11408                                          SourceLocation RParenLoc,
11409                                          bool Failed) {
11410   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11411       !Failed) {
11412     // In a static_assert-declaration, the constant-expression shall be a
11413     // constant expression that can be contextually converted to bool.
11414     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11415     if (Converted.isInvalid())
11416       Failed = true;
11417 
11418     llvm::APSInt Cond;
11419     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
11420           diag::err_static_assert_expression_is_not_constant,
11421           /*AllowFold=*/false).isInvalid())
11422       Failed = true;
11423 
11424     if (!Failed && !Cond) {
11425       SmallString<256> MsgBuffer;
11426       llvm::raw_svector_ostream Msg(MsgBuffer);
11427       AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
11428       Diag(StaticAssertLoc, diag::err_static_assert_failed)
11429         << Msg.str() << AssertExpr->getSourceRange();
11430       Failed = true;
11431     }
11432   }
11433 
11434   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
11435                                         AssertExpr, AssertMessage, RParenLoc,
11436                                         Failed);
11437 
11438   CurContext->addDecl(Decl);
11439   return Decl;
11440 }
11441 
11442 /// \brief Perform semantic analysis of the given friend type declaration.
11443 ///
11444 /// \returns A friend declaration that.
11445 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
11446                                       SourceLocation FriendLoc,
11447                                       TypeSourceInfo *TSInfo) {
11448   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11449 
11450   QualType T = TSInfo->getType();
11451   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
11452 
11453   // C++03 [class.friend]p2:
11454   //   An elaborated-type-specifier shall be used in a friend declaration
11455   //   for a class.*
11456   //
11457   //   * The class-key of the elaborated-type-specifier is required.
11458   if (!ActiveTemplateInstantiations.empty()) {
11459     // Do not complain about the form of friend template types during
11460     // template instantiation; we will already have complained when the
11461     // template was declared.
11462   } else {
11463     if (!T->isElaboratedTypeSpecifier()) {
11464       // If we evaluated the type to a record type, suggest putting
11465       // a tag in front.
11466       if (const RecordType *RT = T->getAs<RecordType>()) {
11467         RecordDecl *RD = RT->getDecl();
11468 
11469         SmallString<16> InsertionText(" ");
11470         InsertionText += RD->getKindName();
11471 
11472         Diag(TypeRange.getBegin(),
11473              getLangOpts().CPlusPlus11 ?
11474                diag::warn_cxx98_compat_unelaborated_friend_type :
11475                diag::ext_unelaborated_friend_type)
11476           << (unsigned) RD->getTagKind()
11477           << T
11478           << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11479                                         InsertionText);
11480       } else {
11481         Diag(FriendLoc,
11482              getLangOpts().CPlusPlus11 ?
11483                diag::warn_cxx98_compat_nonclass_type_friend :
11484                diag::ext_nonclass_type_friend)
11485           << T
11486           << TypeRange;
11487       }
11488     } else if (T->getAs<EnumType>()) {
11489       Diag(FriendLoc,
11490            getLangOpts().CPlusPlus11 ?
11491              diag::warn_cxx98_compat_enum_friend :
11492              diag::ext_enum_friend)
11493         << T
11494         << TypeRange;
11495     }
11496 
11497     // C++11 [class.friend]p3:
11498     //   A friend declaration that does not declare a function shall have one
11499     //   of the following forms:
11500     //     friend elaborated-type-specifier ;
11501     //     friend simple-type-specifier ;
11502     //     friend typename-specifier ;
11503     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11504       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11505   }
11506 
11507   //   If the type specifier in a friend declaration designates a (possibly
11508   //   cv-qualified) class type, that class is declared as a friend; otherwise,
11509   //   the friend declaration is ignored.
11510   return FriendDecl::Create(Context, CurContext,
11511                             TSInfo->getTypeLoc().getLocStart(), TSInfo,
11512                             FriendLoc);
11513 }
11514 
11515 /// Handle a friend tag declaration where the scope specifier was
11516 /// templated.
11517 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11518                                     unsigned TagSpec, SourceLocation TagLoc,
11519                                     CXXScopeSpec &SS,
11520                                     IdentifierInfo *Name,
11521                                     SourceLocation NameLoc,
11522                                     AttributeList *Attr,
11523                                     MultiTemplateParamsArg TempParamLists) {
11524   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11525 
11526   bool isExplicitSpecialization = false;
11527   bool Invalid = false;
11528 
11529   if (TemplateParameterList *TemplateParams =
11530           MatchTemplateParametersToScopeSpecifier(
11531               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
11532               isExplicitSpecialization, Invalid)) {
11533     if (TemplateParams->size() > 0) {
11534       // This is a declaration of a class template.
11535       if (Invalid)
11536         return nullptr;
11537 
11538       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
11539                                 SS, Name, NameLoc, Attr,
11540                                 TemplateParams, AS_public,
11541                                 /*ModulePrivateLoc=*/SourceLocation(),
11542                                 TempParamLists.size() - 1,
11543                                 TempParamLists.data()).get();
11544     } else {
11545       // The "template<>" header is extraneous.
11546       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11547         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11548       isExplicitSpecialization = true;
11549     }
11550   }
11551 
11552   if (Invalid) return nullptr;
11553 
11554   bool isAllExplicitSpecializations = true;
11555   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
11556     if (TempParamLists[I]->size()) {
11557       isAllExplicitSpecializations = false;
11558       break;
11559     }
11560   }
11561 
11562   // FIXME: don't ignore attributes.
11563 
11564   // If it's explicit specializations all the way down, just forget
11565   // about the template header and build an appropriate non-templated
11566   // friend.  TODO: for source fidelity, remember the headers.
11567   if (isAllExplicitSpecializations) {
11568     if (SS.isEmpty()) {
11569       bool Owned = false;
11570       bool IsDependent = false;
11571       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
11572                       Attr, AS_public,
11573                       /*ModulePrivateLoc=*/SourceLocation(),
11574                       MultiTemplateParamsArg(), Owned, IsDependent,
11575                       /*ScopedEnumKWLoc=*/SourceLocation(),
11576                       /*ScopedEnumUsesClassTag=*/false,
11577                       /*UnderlyingType=*/TypeResult(),
11578                       /*IsTypeSpecifier=*/false);
11579     }
11580 
11581     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11582     ElaboratedTypeKeyword Keyword
11583       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11584     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
11585                                    *Name, NameLoc);
11586     if (T.isNull())
11587       return nullptr;
11588 
11589     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11590     if (isa<DependentNameType>(T)) {
11591       DependentNameTypeLoc TL =
11592           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
11593       TL.setElaboratedKeywordLoc(TagLoc);
11594       TL.setQualifierLoc(QualifierLoc);
11595       TL.setNameLoc(NameLoc);
11596     } else {
11597       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
11598       TL.setElaboratedKeywordLoc(TagLoc);
11599       TL.setQualifierLoc(QualifierLoc);
11600       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
11601     }
11602 
11603     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
11604                                             TSI, FriendLoc, TempParamLists);
11605     Friend->setAccess(AS_public);
11606     CurContext->addDecl(Friend);
11607     return Friend;
11608   }
11609 
11610   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11611 
11612 
11613 
11614   // Handle the case of a templated-scope friend class.  e.g.
11615   //   template <class T> class A<T>::B;
11616   // FIXME: we don't support these right now.
11617   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
11618     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
11619   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11620   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11621   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11622   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
11623   TL.setElaboratedKeywordLoc(TagLoc);
11624   TL.setQualifierLoc(SS.getWithLocInContext(Context));
11625   TL.setNameLoc(NameLoc);
11626 
11627   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
11628                                           TSI, FriendLoc, TempParamLists);
11629   Friend->setAccess(AS_public);
11630   Friend->setUnsupportedFriend(true);
11631   CurContext->addDecl(Friend);
11632   return Friend;
11633 }
11634 
11635 
11636 /// Handle a friend type declaration.  This works in tandem with
11637 /// ActOnTag.
11638 ///
11639 /// Notes on friend class templates:
11640 ///
11641 /// We generally treat friend class declarations as if they were
11642 /// declaring a class.  So, for example, the elaborated type specifier
11643 /// in a friend declaration is required to obey the restrictions of a
11644 /// class-head (i.e. no typedefs in the scope chain), template
11645 /// parameters are required to match up with simple template-ids, &c.
11646 /// However, unlike when declaring a template specialization, it's
11647 /// okay to refer to a template specialization without an empty
11648 /// template parameter declaration, e.g.
11649 ///   friend class A<T>::B<unsigned>;
11650 /// We permit this as a special case; if there are any template
11651 /// parameters present at all, require proper matching, i.e.
11652 ///   template <> template \<class T> friend class A<int>::B;
11653 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
11654                                 MultiTemplateParamsArg TempParams) {
11655   SourceLocation Loc = DS.getLocStart();
11656 
11657   assert(DS.isFriendSpecified());
11658   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11659 
11660   // Try to convert the decl specifier to a type.  This works for
11661   // friend templates because ActOnTag never produces a ClassTemplateDecl
11662   // for a TUK_Friend.
11663   Declarator TheDeclarator(DS, Declarator::MemberContext);
11664   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11665   QualType T = TSI->getType();
11666   if (TheDeclarator.isInvalidType())
11667     return nullptr;
11668 
11669   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11670     return nullptr;
11671 
11672   // This is definitely an error in C++98.  It's probably meant to
11673   // be forbidden in C++0x, too, but the specification is just
11674   // poorly written.
11675   //
11676   // The problem is with declarations like the following:
11677   //   template <T> friend A<T>::foo;
11678   // where deciding whether a class C is a friend or not now hinges
11679   // on whether there exists an instantiation of A that causes
11680   // 'foo' to equal C.  There are restrictions on class-heads
11681   // (which we declare (by fiat) elaborated friend declarations to
11682   // be) that makes this tractable.
11683   //
11684   // FIXME: handle "template <> friend class A<T>;", which
11685   // is possibly well-formed?  Who even knows?
11686   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
11687     Diag(Loc, diag::err_tagless_friend_type_template)
11688       << DS.getSourceRange();
11689     return nullptr;
11690   }
11691 
11692   // C++98 [class.friend]p1: A friend of a class is a function
11693   //   or class that is not a member of the class . . .
11694   // This is fixed in DR77, which just barely didn't make the C++03
11695   // deadline.  It's also a very silly restriction that seriously
11696   // affects inner classes and which nobody else seems to implement;
11697   // thus we never diagnose it, not even in -pedantic.
11698   //
11699   // But note that we could warn about it: it's always useless to
11700   // friend one of your own members (it's not, however, worthless to
11701   // friend a member of an arbitrary specialization of your template).
11702 
11703   Decl *D;
11704   if (unsigned NumTempParamLists = TempParams.size())
11705     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
11706                                    NumTempParamLists,
11707                                    TempParams.data(),
11708                                    TSI,
11709                                    DS.getFriendSpecLoc());
11710   else
11711     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
11712 
11713   if (!D)
11714     return nullptr;
11715 
11716   D->setAccess(AS_public);
11717   CurContext->addDecl(D);
11718 
11719   return D;
11720 }
11721 
11722 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11723                                         MultiTemplateParamsArg TemplateParams) {
11724   const DeclSpec &DS = D.getDeclSpec();
11725 
11726   assert(DS.isFriendSpecified());
11727   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11728 
11729   SourceLocation Loc = D.getIdentifierLoc();
11730   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11731 
11732   // C++ [class.friend]p1
11733   //   A friend of a class is a function or class....
11734   // Note that this sees through typedefs, which is intended.
11735   // It *doesn't* see through dependent types, which is correct
11736   // according to [temp.arg.type]p3:
11737   //   If a declaration acquires a function type through a
11738   //   type dependent on a template-parameter and this causes
11739   //   a declaration that does not use the syntactic form of a
11740   //   function declarator to have a function type, the program
11741   //   is ill-formed.
11742   if (!TInfo->getType()->isFunctionType()) {
11743     Diag(Loc, diag::err_unexpected_friend);
11744 
11745     // It might be worthwhile to try to recover by creating an
11746     // appropriate declaration.
11747     return nullptr;
11748   }
11749 
11750   // C++ [namespace.memdef]p3
11751   //  - If a friend declaration in a non-local class first declares a
11752   //    class or function, the friend class or function is a member
11753   //    of the innermost enclosing namespace.
11754   //  - The name of the friend is not found by simple name lookup
11755   //    until a matching declaration is provided in that namespace
11756   //    scope (either before or after the class declaration granting
11757   //    friendship).
11758   //  - If a friend function is called, its name may be found by the
11759   //    name lookup that considers functions from namespaces and
11760   //    classes associated with the types of the function arguments.
11761   //  - When looking for a prior declaration of a class or a function
11762   //    declared as a friend, scopes outside the innermost enclosing
11763   //    namespace scope are not considered.
11764 
11765   CXXScopeSpec &SS = D.getCXXScopeSpec();
11766   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11767   DeclarationName Name = NameInfo.getName();
11768   assert(Name);
11769 
11770   // Check for unexpanded parameter packs.
11771   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11772       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11773       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11774     return nullptr;
11775 
11776   // The context we found the declaration in, or in which we should
11777   // create the declaration.
11778   DeclContext *DC;
11779   Scope *DCScope = S;
11780   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
11781                         ForRedeclaration);
11782 
11783   // There are five cases here.
11784   //   - There's no scope specifier and we're in a local class. Only look
11785   //     for functions declared in the immediately-enclosing block scope.
11786   // We recover from invalid scope qualifiers as if they just weren't there.
11787   FunctionDecl *FunctionContainingLocalClass = nullptr;
11788   if ((SS.isInvalid() || !SS.isSet()) &&
11789       (FunctionContainingLocalClass =
11790            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11791     // C++11 [class.friend]p11:
11792     //   If a friend declaration appears in a local class and the name
11793     //   specified is an unqualified name, a prior declaration is
11794     //   looked up without considering scopes that are outside the
11795     //   innermost enclosing non-class scope. For a friend function
11796     //   declaration, if there is no prior declaration, the program is
11797     //   ill-formed.
11798 
11799     // Find the innermost enclosing non-class scope. This is the block
11800     // scope containing the local class definition (or for a nested class,
11801     // the outer local class).
11802     DCScope = S->getFnParent();
11803 
11804     // Look up the function name in the scope.
11805     Previous.clear(LookupLocalFriendName);
11806     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11807 
11808     if (!Previous.empty()) {
11809       // All possible previous declarations must have the same context:
11810       // either they were declared at block scope or they are members of
11811       // one of the enclosing local classes.
11812       DC = Previous.getRepresentativeDecl()->getDeclContext();
11813     } else {
11814       // This is ill-formed, but provide the context that we would have
11815       // declared the function in, if we were permitted to, for error recovery.
11816       DC = FunctionContainingLocalClass;
11817     }
11818     adjustContextForLocalExternDecl(DC);
11819 
11820     // C++ [class.friend]p6:
11821     //   A function can be defined in a friend declaration of a class if and
11822     //   only if the class is a non-local class (9.8), the function name is
11823     //   unqualified, and the function has namespace scope.
11824     if (D.isFunctionDefinition()) {
11825       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11826     }
11827 
11828   //   - There's no scope specifier, in which case we just go to the
11829   //     appropriate scope and look for a function or function template
11830   //     there as appropriate.
11831   } else if (SS.isInvalid() || !SS.isSet()) {
11832     // C++11 [namespace.memdef]p3:
11833     //   If the name in a friend declaration is neither qualified nor
11834     //   a template-id and the declaration is a function or an
11835     //   elaborated-type-specifier, the lookup to determine whether
11836     //   the entity has been previously declared shall not consider
11837     //   any scopes outside the innermost enclosing namespace.
11838     bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
11839 
11840     // Find the appropriate context according to the above.
11841     DC = CurContext;
11842 
11843     // Skip class contexts.  If someone can cite chapter and verse
11844     // for this behavior, that would be nice --- it's what GCC and
11845     // EDG do, and it seems like a reasonable intent, but the spec
11846     // really only says that checks for unqualified existing
11847     // declarations should stop at the nearest enclosing namespace,
11848     // not that they should only consider the nearest enclosing
11849     // namespace.
11850     while (DC->isRecord())
11851       DC = DC->getParent();
11852 
11853     DeclContext *LookupDC = DC;
11854     while (LookupDC->isTransparentContext())
11855       LookupDC = LookupDC->getParent();
11856 
11857     while (true) {
11858       LookupQualifiedName(Previous, LookupDC);
11859 
11860       if (!Previous.empty()) {
11861         DC = LookupDC;
11862         break;
11863       }
11864 
11865       if (isTemplateId) {
11866         if (isa<TranslationUnitDecl>(LookupDC)) break;
11867       } else {
11868         if (LookupDC->isFileContext()) break;
11869       }
11870       LookupDC = LookupDC->getParent();
11871     }
11872 
11873     DCScope = getScopeForDeclContext(S, DC);
11874 
11875   //   - There's a non-dependent scope specifier, in which case we
11876   //     compute it and do a previous lookup there for a function
11877   //     or function template.
11878   } else if (!SS.getScopeRep()->isDependent()) {
11879     DC = computeDeclContext(SS);
11880     if (!DC) return nullptr;
11881 
11882     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
11883 
11884     LookupQualifiedName(Previous, DC);
11885 
11886     // Ignore things found implicitly in the wrong scope.
11887     // TODO: better diagnostics for this case.  Suggesting the right
11888     // qualified scope would be nice...
11889     LookupResult::Filter F = Previous.makeFilter();
11890     while (F.hasNext()) {
11891       NamedDecl *D = F.next();
11892       if (!DC->InEnclosingNamespaceSetOf(
11893               D->getDeclContext()->getRedeclContext()))
11894         F.erase();
11895     }
11896     F.done();
11897 
11898     if (Previous.empty()) {
11899       D.setInvalidType();
11900       Diag(Loc, diag::err_qualified_friend_not_found)
11901           << Name << TInfo->getType();
11902       return nullptr;
11903     }
11904 
11905     // C++ [class.friend]p1: A friend of a class is a function or
11906     //   class that is not a member of the class . . .
11907     if (DC->Equals(CurContext))
11908       Diag(DS.getFriendSpecLoc(),
11909            getLangOpts().CPlusPlus11 ?
11910              diag::warn_cxx98_compat_friend_is_member :
11911              diag::err_friend_is_member);
11912 
11913     if (D.isFunctionDefinition()) {
11914       // C++ [class.friend]p6:
11915       //   A function can be defined in a friend declaration of a class if and
11916       //   only if the class is a non-local class (9.8), the function name is
11917       //   unqualified, and the function has namespace scope.
11918       SemaDiagnosticBuilder DB
11919         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11920 
11921       DB << SS.getScopeRep();
11922       if (DC->isFileContext())
11923         DB << FixItHint::CreateRemoval(SS.getRange());
11924       SS.clear();
11925     }
11926 
11927   //   - There's a scope specifier that does not match any template
11928   //     parameter lists, in which case we use some arbitrary context,
11929   //     create a method or method template, and wait for instantiation.
11930   //   - There's a scope specifier that does match some template
11931   //     parameter lists, which we don't handle right now.
11932   } else {
11933     if (D.isFunctionDefinition()) {
11934       // C++ [class.friend]p6:
11935       //   A function can be defined in a friend declaration of a class if and
11936       //   only if the class is a non-local class (9.8), the function name is
11937       //   unqualified, and the function has namespace scope.
11938       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11939         << SS.getScopeRep();
11940     }
11941 
11942     DC = CurContext;
11943     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
11944   }
11945 
11946   if (!DC->isRecord()) {
11947     // This implies that it has to be an operator or function.
11948     if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11949         D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11950         D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
11951       Diag(Loc, diag::err_introducing_special_friend) <<
11952         (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11953          D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
11954       return nullptr;
11955     }
11956   }
11957 
11958   // FIXME: This is an egregious hack to cope with cases where the scope stack
11959   // does not contain the declaration context, i.e., in an out-of-line
11960   // definition of a class.
11961   Scope FakeDCScope(S, Scope::DeclScope, Diags);
11962   if (!DCScope) {
11963     FakeDCScope.setEntity(DC);
11964     DCScope = &FakeDCScope;
11965   }
11966 
11967   bool AddToScope = true;
11968   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
11969                                           TemplateParams, AddToScope);
11970   if (!ND) return nullptr;
11971 
11972   assert(ND->getLexicalDeclContext() == CurContext);
11973 
11974   // If we performed typo correction, we might have added a scope specifier
11975   // and changed the decl context.
11976   DC = ND->getDeclContext();
11977 
11978   // Add the function declaration to the appropriate lookup tables,
11979   // adjusting the redeclarations list as necessary.  We don't
11980   // want to do this yet if the friending class is dependent.
11981   //
11982   // Also update the scope-based lookup if the target context's
11983   // lookup context is in lexical scope.
11984   if (!CurContext->isDependentContext()) {
11985     DC = DC->getRedeclContext();
11986     DC->makeDeclVisibleInContext(ND);
11987     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11988       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
11989   }
11990 
11991   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
11992                                        D.getIdentifierLoc(), ND,
11993                                        DS.getFriendSpecLoc());
11994   FrD->setAccess(AS_public);
11995   CurContext->addDecl(FrD);
11996 
11997   if (ND->isInvalidDecl()) {
11998     FrD->setInvalidDecl();
11999   } else {
12000     if (DC->isRecord()) CheckFriendAccess(ND);
12001 
12002     FunctionDecl *FD;
12003     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12004       FD = FTD->getTemplatedDecl();
12005     else
12006       FD = cast<FunctionDecl>(ND);
12007 
12008     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12009     // default argument expression, that declaration shall be a definition
12010     // and shall be the only declaration of the function or function
12011     // template in the translation unit.
12012     if (functionDeclHasDefaultArgument(FD)) {
12013       if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12014         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12015         Diag(OldFD->getLocation(), diag::note_previous_declaration);
12016       } else if (!D.isFunctionDefinition())
12017         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12018     }
12019 
12020     // Mark templated-scope function declarations as unsupported.
12021     if (FD->getNumTemplateParameterLists())
12022       FrD->setUnsupportedFriend(true);
12023   }
12024 
12025   return ND;
12026 }
12027 
12028 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12029   AdjustDeclIfTemplate(Dcl);
12030 
12031   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
12032   if (!Fn) {
12033     Diag(DelLoc, diag::err_deleted_non_function);
12034     return;
12035   }
12036 
12037   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
12038     // Don't consider the implicit declaration we generate for explicit
12039     // specializations. FIXME: Do not generate these implicit declarations.
12040     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12041          Prev->getPreviousDecl()) &&
12042         !Prev->isDefined()) {
12043       Diag(DelLoc, diag::err_deleted_decl_not_first);
12044       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12045            Prev->isImplicit() ? diag::note_previous_implicit_declaration
12046                               : diag::note_previous_declaration);
12047     }
12048     // If the declaration wasn't the first, we delete the function anyway for
12049     // recovery.
12050     Fn = Fn->getCanonicalDecl();
12051   }
12052 
12053   // dllimport/dllexport cannot be deleted.
12054   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12055     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12056     Fn->setInvalidDecl();
12057   }
12058 
12059   if (Fn->isDeleted())
12060     return;
12061 
12062   // See if we're deleting a function which is already known to override a
12063   // non-deleted virtual function.
12064   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
12065     bool IssuedDiagnostic = false;
12066     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
12067                                         E = MD->end_overridden_methods();
12068          I != E; ++I) {
12069       if (!(*MD->begin_overridden_methods())->isDeleted()) {
12070         if (!IssuedDiagnostic) {
12071           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
12072           IssuedDiagnostic = true;
12073         }
12074         Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
12075       }
12076     }
12077   }
12078 
12079   // C++11 [basic.start.main]p3:
12080   //   A program that defines main as deleted [...] is ill-formed.
12081   if (Fn->isMain())
12082     Diag(DelLoc, diag::err_deleted_main);
12083 
12084   Fn->setDeletedAsWritten();
12085 }
12086 
12087 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
12088   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
12089 
12090   if (MD) {
12091     if (MD->getParent()->isDependentType()) {
12092       MD->setDefaulted();
12093       MD->setExplicitlyDefaulted();
12094       return;
12095     }
12096 
12097     CXXSpecialMember Member = getSpecialMember(MD);
12098     if (Member == CXXInvalid) {
12099       if (!MD->isInvalidDecl())
12100         Diag(DefaultLoc, diag::err_default_special_members);
12101       return;
12102     }
12103 
12104     MD->setDefaulted();
12105     MD->setExplicitlyDefaulted();
12106 
12107     // If this definition appears within the record, do the checking when
12108     // the record is complete.
12109     const FunctionDecl *Primary = MD;
12110     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
12111       // Find the uninstantiated declaration that actually had the '= default'
12112       // on it.
12113       Pattern->isDefined(Primary);
12114 
12115     // If the method was defaulted on its first declaration, we will have
12116     // already performed the checking in CheckCompletedCXXClass. Such a
12117     // declaration doesn't trigger an implicit definition.
12118     if (Primary == Primary->getCanonicalDecl())
12119       return;
12120 
12121     CheckExplicitlyDefaultedSpecialMember(MD);
12122 
12123     // The exception specification is needed because we are defining the
12124     // function.
12125     ResolveExceptionSpec(DefaultLoc,
12126                          MD->getType()->castAs<FunctionProtoType>());
12127 
12128     if (MD->isInvalidDecl())
12129       return;
12130 
12131     switch (Member) {
12132     case CXXDefaultConstructor:
12133       DefineImplicitDefaultConstructor(DefaultLoc,
12134                                        cast<CXXConstructorDecl>(MD));
12135       break;
12136     case CXXCopyConstructor:
12137       DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
12138       break;
12139     case CXXCopyAssignment:
12140       DefineImplicitCopyAssignment(DefaultLoc, MD);
12141       break;
12142     case CXXDestructor:
12143       DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
12144       break;
12145     case CXXMoveConstructor:
12146       DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
12147       break;
12148     case CXXMoveAssignment:
12149       DefineImplicitMoveAssignment(DefaultLoc, MD);
12150       break;
12151     case CXXInvalid:
12152       llvm_unreachable("Invalid special member.");
12153     }
12154   } else {
12155     Diag(DefaultLoc, diag::err_default_special_members);
12156   }
12157 }
12158 
12159 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
12160   for (Stmt::child_range CI = S->children(); CI; ++CI) {
12161     Stmt *SubStmt = *CI;
12162     if (!SubStmt)
12163       continue;
12164     if (isa<ReturnStmt>(SubStmt))
12165       Self.Diag(SubStmt->getLocStart(),
12166            diag::err_return_in_constructor_handler);
12167     if (!isa<Expr>(SubStmt))
12168       SearchForReturnInStmt(Self, SubStmt);
12169   }
12170 }
12171 
12172 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12173   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12174     CXXCatchStmt *Handler = TryBlock->getHandler(I);
12175     SearchForReturnInStmt(*this, Handler);
12176   }
12177 }
12178 
12179 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
12180                                              const CXXMethodDecl *Old) {
12181   const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12182   const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12183 
12184   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12185 
12186   // If the calling conventions match, everything is fine
12187   if (NewCC == OldCC)
12188     return false;
12189 
12190   // If the calling conventions mismatch because the new function is static,
12191   // suppress the calling convention mismatch error; the error about static
12192   // function override (err_static_overrides_virtual from
12193   // Sema::CheckFunctionDeclaration) is more clear.
12194   if (New->getStorageClass() == SC_Static)
12195     return false;
12196 
12197   Diag(New->getLocation(),
12198        diag::err_conflicting_overriding_cc_attributes)
12199     << New->getDeclName() << New->getType() << Old->getType();
12200   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12201   return true;
12202 }
12203 
12204 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
12205                                              const CXXMethodDecl *Old) {
12206   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12207   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
12208 
12209   if (Context.hasSameType(NewTy, OldTy) ||
12210       NewTy->isDependentType() || OldTy->isDependentType())
12211     return false;
12212 
12213   // Check if the return types are covariant
12214   QualType NewClassTy, OldClassTy;
12215 
12216   /// Both types must be pointers or references to classes.
12217   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12218     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
12219       NewClassTy = NewPT->getPointeeType();
12220       OldClassTy = OldPT->getPointeeType();
12221     }
12222   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12223     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12224       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12225         NewClassTy = NewRT->getPointeeType();
12226         OldClassTy = OldRT->getPointeeType();
12227       }
12228     }
12229   }
12230 
12231   // The return types aren't either both pointers or references to a class type.
12232   if (NewClassTy.isNull()) {
12233     Diag(New->getLocation(),
12234          diag::err_different_return_type_for_overriding_virtual_function)
12235       << New->getDeclName() << NewTy << OldTy;
12236     Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12237 
12238     return true;
12239   }
12240 
12241   // C++ [class.virtual]p6:
12242   //   If the return type of D::f differs from the return type of B::f, the
12243   //   class type in the return type of D::f shall be complete at the point of
12244   //   declaration of D::f or shall be the class type D.
12245   if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12246     if (!RT->isBeingDefined() &&
12247         RequireCompleteType(New->getLocation(), NewClassTy,
12248                             diag::err_covariant_return_incomplete,
12249                             New->getDeclName()))
12250     return true;
12251   }
12252 
12253   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
12254     // Check if the new class derives from the old class.
12255     if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12256       Diag(New->getLocation(),
12257            diag::err_covariant_return_not_derived)
12258       << New->getDeclName() << NewTy << OldTy;
12259       Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12260       return true;
12261     }
12262 
12263     // Check if we the conversion from derived to base is valid.
12264     if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
12265                     diag::err_covariant_return_inaccessible_base,
12266                     diag::err_covariant_return_ambiguous_derived_to_base_conv,
12267                     // FIXME: Should this point to the return type?
12268                     New->getLocation(), SourceRange(), New->getDeclName(),
12269                     nullptr)) {
12270       // FIXME: this note won't trigger for delayed access control
12271       // diagnostics, and it's impossible to get an undelayed error
12272       // here from access control during the original parse because
12273       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
12274       Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12275       return true;
12276     }
12277   }
12278 
12279   // The qualifiers of the return types must be the same.
12280   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
12281     Diag(New->getLocation(),
12282          diag::err_covariant_return_type_different_qualifications)
12283     << New->getDeclName() << NewTy << OldTy;
12284     Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12285     return true;
12286   };
12287 
12288 
12289   // The new class type must have the same or less qualifiers as the old type.
12290   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12291     Diag(New->getLocation(),
12292          diag::err_covariant_return_type_class_type_more_qualified)
12293     << New->getDeclName() << NewTy << OldTy;
12294     Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12295     return true;
12296   };
12297 
12298   return false;
12299 }
12300 
12301 /// \brief Mark the given method pure.
12302 ///
12303 /// \param Method the method to be marked pure.
12304 ///
12305 /// \param InitRange the source range that covers the "0" initializer.
12306 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
12307   SourceLocation EndLoc = InitRange.getEnd();
12308   if (EndLoc.isValid())
12309     Method->setRangeEnd(EndLoc);
12310 
12311   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12312     Method->setPure();
12313     return false;
12314   }
12315 
12316   if (!Method->isInvalidDecl())
12317     Diag(Method->getLocation(), diag::err_non_virtual_pure)
12318       << Method->getDeclName() << InitRange;
12319   return true;
12320 }
12321 
12322 /// \brief Determine whether the given declaration is a static data member.
12323 static bool isStaticDataMember(const Decl *D) {
12324   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12325     return Var->isStaticDataMember();
12326 
12327   return false;
12328 }
12329 
12330 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12331 /// an initializer for the out-of-line declaration 'Dcl'.  The scope
12332 /// is a fresh scope pushed for just this purpose.
12333 ///
12334 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12335 /// static data member of class X, names should be looked up in the scope of
12336 /// class X.
12337 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
12338   // If there is no declaration, there was an error parsing it.
12339   if (!D || D->isInvalidDecl())
12340     return;
12341 
12342   // We will always have a nested name specifier here, but this declaration
12343   // might not be out of line if the specifier names the current namespace:
12344   //   extern int n;
12345   //   int ::n = 0;
12346   if (D->isOutOfLine())
12347     EnterDeclaratorContext(S, D->getDeclContext());
12348 
12349   // If we are parsing the initializer for a static data member, push a
12350   // new expression evaluation context that is associated with this static
12351   // data member.
12352   if (isStaticDataMember(D))
12353     PushExpressionEvaluationContext(PotentiallyEvaluated, D);
12354 }
12355 
12356 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
12357 /// initializer for the out-of-line declaration 'D'.
12358 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
12359   // If there is no declaration, there was an error parsing it.
12360   if (!D || D->isInvalidDecl())
12361     return;
12362 
12363   if (isStaticDataMember(D))
12364     PopExpressionEvaluationContext();
12365 
12366   if (D->isOutOfLine())
12367     ExitDeclaratorContext(S);
12368 }
12369 
12370 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12371 /// C++ if/switch/while/for statement.
12372 /// e.g: "if (int x = f()) {...}"
12373 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
12374   // C++ 6.4p2:
12375   // The declarator shall not specify a function or an array.
12376   // The type-specifier-seq shall not contain typedef and shall not declare a
12377   // new class or enumeration.
12378   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12379          "Parser allowed 'typedef' as storage class of condition decl.");
12380 
12381   Decl *Dcl = ActOnDeclarator(S, D);
12382   if (!Dcl)
12383     return true;
12384 
12385   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12386     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
12387       << D.getSourceRange();
12388     return true;
12389   }
12390 
12391   return Dcl;
12392 }
12393 
12394 void Sema::LoadExternalVTableUses() {
12395   if (!ExternalSource)
12396     return;
12397 
12398   SmallVector<ExternalVTableUse, 4> VTables;
12399   ExternalSource->ReadUsedVTables(VTables);
12400   SmallVector<VTableUse, 4> NewUses;
12401   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12402     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12403       = VTablesUsed.find(VTables[I].Record);
12404     // Even if a definition wasn't required before, it may be required now.
12405     if (Pos != VTablesUsed.end()) {
12406       if (!Pos->second && VTables[I].DefinitionRequired)
12407         Pos->second = true;
12408       continue;
12409     }
12410 
12411     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12412     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12413   }
12414 
12415   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12416 }
12417 
12418 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12419                           bool DefinitionRequired) {
12420   // Ignore any vtable uses in unevaluated operands or for classes that do
12421   // not have a vtable.
12422   if (!Class->isDynamicClass() || Class->isDependentContext() ||
12423       CurContext->isDependentContext() || isUnevaluatedContext())
12424     return;
12425 
12426   // Try to insert this class into the map.
12427   LoadExternalVTableUses();
12428   Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12429   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12430     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12431   if (!Pos.second) {
12432     // If we already had an entry, check to see if we are promoting this vtable
12433     // to required a definition. If so, we need to reappend to the VTableUses
12434     // list, since we may have already processed the first entry.
12435     if (DefinitionRequired && !Pos.first->second) {
12436       Pos.first->second = true;
12437     } else {
12438       // Otherwise, we can early exit.
12439       return;
12440     }
12441   } else {
12442     // The Microsoft ABI requires that we perform the destructor body
12443     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
12444     // the deleting destructor is emitted with the vtable, not with the
12445     // destructor definition as in the Itanium ABI.
12446     // If it has a definition, we do the check at that point instead.
12447     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12448         Class->hasUserDeclaredDestructor() &&
12449         !Class->getDestructor()->isDefined() &&
12450         !Class->getDestructor()->isDeleted()) {
12451       CheckDestructor(Class->getDestructor());
12452     }
12453   }
12454 
12455   // Local classes need to have their virtual members marked
12456   // immediately. For all other classes, we mark their virtual members
12457   // at the end of the translation unit.
12458   if (Class->isLocalClass())
12459     MarkVirtualMembersReferenced(Loc, Class);
12460   else
12461     VTableUses.push_back(std::make_pair(Class, Loc));
12462 }
12463 
12464 bool Sema::DefineUsedVTables() {
12465   LoadExternalVTableUses();
12466   if (VTableUses.empty())
12467     return false;
12468 
12469   // Note: The VTableUses vector could grow as a result of marking
12470   // the members of a class as "used", so we check the size each
12471   // time through the loop and prefer indices (which are stable) to
12472   // iterators (which are not).
12473   bool DefinedAnything = false;
12474   for (unsigned I = 0; I != VTableUses.size(); ++I) {
12475     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
12476     if (!Class)
12477       continue;
12478 
12479     SourceLocation Loc = VTableUses[I].second;
12480 
12481     bool DefineVTable = true;
12482 
12483     // If this class has a key function, but that key function is
12484     // defined in another translation unit, we don't need to emit the
12485     // vtable even though we're using it.
12486     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
12487     if (KeyFunction && !KeyFunction->hasBody()) {
12488       // The key function is in another translation unit.
12489       DefineVTable = false;
12490       TemplateSpecializationKind TSK =
12491           KeyFunction->getTemplateSpecializationKind();
12492       assert(TSK != TSK_ExplicitInstantiationDefinition &&
12493              TSK != TSK_ImplicitInstantiation &&
12494              "Instantiations don't have key functions");
12495       (void)TSK;
12496     } else if (!KeyFunction) {
12497       // If we have a class with no key function that is the subject
12498       // of an explicit instantiation declaration, suppress the
12499       // vtable; it will live with the explicit instantiation
12500       // definition.
12501       bool IsExplicitInstantiationDeclaration
12502         = Class->getTemplateSpecializationKind()
12503                                       == TSK_ExplicitInstantiationDeclaration;
12504       for (auto R : Class->redecls()) {
12505         TemplateSpecializationKind TSK
12506           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
12507         if (TSK == TSK_ExplicitInstantiationDeclaration)
12508           IsExplicitInstantiationDeclaration = true;
12509         else if (TSK == TSK_ExplicitInstantiationDefinition) {
12510           IsExplicitInstantiationDeclaration = false;
12511           break;
12512         }
12513       }
12514 
12515       if (IsExplicitInstantiationDeclaration)
12516         DefineVTable = false;
12517     }
12518 
12519     // The exception specifications for all virtual members may be needed even
12520     // if we are not providing an authoritative form of the vtable in this TU.
12521     // We may choose to emit it available_externally anyway.
12522     if (!DefineVTable) {
12523       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12524       continue;
12525     }
12526 
12527     // Mark all of the virtual members of this class as referenced, so
12528     // that we can build a vtable. Then, tell the AST consumer that a
12529     // vtable for this class is required.
12530     DefinedAnything = true;
12531     MarkVirtualMembersReferenced(Loc, Class);
12532     CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12533     Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12534 
12535     // Optionally warn if we're emitting a weak vtable.
12536     if (Class->isExternallyVisible() &&
12537         Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
12538       const FunctionDecl *KeyFunctionDef = nullptr;
12539       if (!KeyFunction ||
12540           (KeyFunction->hasBody(KeyFunctionDef) &&
12541            KeyFunctionDef->isInlined()))
12542         Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12543              TSK_ExplicitInstantiationDefinition
12544              ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12545           << Class;
12546     }
12547   }
12548   VTableUses.clear();
12549 
12550   return DefinedAnything;
12551 }
12552 
12553 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12554                                                  const CXXRecordDecl *RD) {
12555   for (const auto *I : RD->methods())
12556     if (I->isVirtual() && !I->isPure())
12557       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
12558 }
12559 
12560 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12561                                         const CXXRecordDecl *RD) {
12562   // Mark all functions which will appear in RD's vtable as used.
12563   CXXFinalOverriderMap FinalOverriders;
12564   RD->getFinalOverriders(FinalOverriders);
12565   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12566                                             E = FinalOverriders.end();
12567        I != E; ++I) {
12568     for (OverridingMethods::const_iterator OI = I->second.begin(),
12569                                            OE = I->second.end();
12570          OI != OE; ++OI) {
12571       assert(OI->second.size() > 0 && "no final overrider");
12572       CXXMethodDecl *Overrider = OI->second.front().Method;
12573 
12574       // C++ [basic.def.odr]p2:
12575       //   [...] A virtual member function is used if it is not pure. [...]
12576       if (!Overrider->isPure())
12577         MarkFunctionReferenced(Loc, Overrider);
12578     }
12579   }
12580 
12581   // Only classes that have virtual bases need a VTT.
12582   if (RD->getNumVBases() == 0)
12583     return;
12584 
12585   for (const auto &I : RD->bases()) {
12586     const CXXRecordDecl *Base =
12587         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
12588     if (Base->getNumVBases() == 0)
12589       continue;
12590     MarkVirtualMembersReferenced(Loc, Base);
12591   }
12592 }
12593 
12594 /// SetIvarInitializers - This routine builds initialization ASTs for the
12595 /// Objective-C implementation whose ivars need be initialized.
12596 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
12597   if (!getLangOpts().CPlusPlus)
12598     return;
12599   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
12600     SmallVector<ObjCIvarDecl*, 8> ivars;
12601     CollectIvarsToConstructOrDestruct(OID, ivars);
12602     if (ivars.empty())
12603       return;
12604     SmallVector<CXXCtorInitializer*, 32> AllToInit;
12605     for (unsigned i = 0; i < ivars.size(); i++) {
12606       FieldDecl *Field = ivars[i];
12607       if (Field->isInvalidDecl())
12608         continue;
12609 
12610       CXXCtorInitializer *Member;
12611       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12612       InitializationKind InitKind =
12613         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
12614 
12615       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12616       ExprResult MemberInit =
12617         InitSeq.Perform(*this, InitEntity, InitKind, None);
12618       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
12619       // Note, MemberInit could actually come back empty if no initialization
12620       // is required (e.g., because it would call a trivial default constructor)
12621       if (!MemberInit.get() || MemberInit.isInvalid())
12622         continue;
12623 
12624       Member =
12625         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12626                                          SourceLocation(),
12627                                          MemberInit.getAs<Expr>(),
12628                                          SourceLocation());
12629       AllToInit.push_back(Member);
12630 
12631       // Be sure that the destructor is accessible and is marked as referenced.
12632       if (const RecordType *RecordTy
12633                   = Context.getBaseElementType(Field->getType())
12634                                                         ->getAs<RecordType>()) {
12635                     CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
12636         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
12637           MarkFunctionReferenced(Field->getLocation(), Destructor);
12638           CheckDestructorAccess(Field->getLocation(), Destructor,
12639                             PDiag(diag::err_access_dtor_ivar)
12640                               << Context.getBaseElementType(Field->getType()));
12641         }
12642       }
12643     }
12644     ObjCImplementation->setIvarInitializers(Context,
12645                                             AllToInit.data(), AllToInit.size());
12646   }
12647 }
12648 
12649 static
12650 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12651                            llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12652                            llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12653                            llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12654                            Sema &S) {
12655   if (Ctor->isInvalidDecl())
12656     return;
12657 
12658   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12659 
12660   // Target may not be determinable yet, for instance if this is a dependent
12661   // call in an uninstantiated template.
12662   if (Target) {
12663     const FunctionDecl *FNTarget = nullptr;
12664     (void)Target->hasBody(FNTarget);
12665     Target = const_cast<CXXConstructorDecl*>(
12666       cast_or_null<CXXConstructorDecl>(FNTarget));
12667   }
12668 
12669   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12670                      // Avoid dereferencing a null pointer here.
12671                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
12672 
12673   if (!Current.insert(Canonical))
12674     return;
12675 
12676   // We know that beyond here, we aren't chaining into a cycle.
12677   if (!Target || !Target->isDelegatingConstructor() ||
12678       Target->isInvalidDecl() || Valid.count(TCanonical)) {
12679     Valid.insert(Current.begin(), Current.end());
12680     Current.clear();
12681   // We've hit a cycle.
12682   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12683              Current.count(TCanonical)) {
12684     // If we haven't diagnosed this cycle yet, do so now.
12685     if (!Invalid.count(TCanonical)) {
12686       S.Diag((*Ctor->init_begin())->getSourceLocation(),
12687              diag::warn_delegating_ctor_cycle)
12688         << Ctor;
12689 
12690       // Don't add a note for a function delegating directly to itself.
12691       if (TCanonical != Canonical)
12692         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12693 
12694       CXXConstructorDecl *C = Target;
12695       while (C->getCanonicalDecl() != Canonical) {
12696         const FunctionDecl *FNTarget = nullptr;
12697         (void)C->getTargetConstructor()->hasBody(FNTarget);
12698         assert(FNTarget && "Ctor cycle through bodiless function");
12699 
12700         C = const_cast<CXXConstructorDecl*>(
12701           cast<CXXConstructorDecl>(FNTarget));
12702         S.Diag(C->getLocation(), diag::note_which_delegates_to);
12703       }
12704     }
12705 
12706     Invalid.insert(Current.begin(), Current.end());
12707     Current.clear();
12708   } else {
12709     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12710   }
12711 }
12712 
12713 
12714 void Sema::CheckDelegatingCtorCycles() {
12715   llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12716 
12717   for (DelegatingCtorDeclsType::iterator
12718          I = DelegatingCtorDecls.begin(ExternalSource),
12719          E = DelegatingCtorDecls.end();
12720        I != E; ++I)
12721     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
12722 
12723   for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12724                                                          CE = Invalid.end();
12725        CI != CE; ++CI)
12726     (*CI)->setInvalidDecl();
12727 }
12728 
12729 namespace {
12730   /// \brief AST visitor that finds references to the 'this' expression.
12731   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12732     Sema &S;
12733 
12734   public:
12735     explicit FindCXXThisExpr(Sema &S) : S(S) { }
12736 
12737     bool VisitCXXThisExpr(CXXThisExpr *E) {
12738       S.Diag(E->getLocation(), diag::err_this_static_member_func)
12739         << E->isImplicit();
12740       return false;
12741     }
12742   };
12743 }
12744 
12745 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12746   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12747   if (!TSInfo)
12748     return false;
12749 
12750   TypeLoc TL = TSInfo->getTypeLoc();
12751   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
12752   if (!ProtoTL)
12753     return false;
12754 
12755   // C++11 [expr.prim.general]p3:
12756   //   [The expression this] shall not appear before the optional
12757   //   cv-qualifier-seq and it shall not appear within the declaration of a
12758   //   static member function (although its type and value category are defined
12759   //   within a static member function as they are within a non-static member
12760   //   function). [ Note: this is because declaration matching does not occur
12761   //  until the complete declarator is known. - end note ]
12762   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
12763   FindCXXThisExpr Finder(*this);
12764 
12765   // If the return type came after the cv-qualifier-seq, check it now.
12766   if (Proto->hasTrailingReturn() &&
12767       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
12768     return true;
12769 
12770   // Check the exception specification.
12771   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12772     return true;
12773 
12774   return checkThisInStaticMemberFunctionAttributes(Method);
12775 }
12776 
12777 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12778   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12779   if (!TSInfo)
12780     return false;
12781 
12782   TypeLoc TL = TSInfo->getTypeLoc();
12783   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
12784   if (!ProtoTL)
12785     return false;
12786 
12787   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
12788   FindCXXThisExpr Finder(*this);
12789 
12790   switch (Proto->getExceptionSpecType()) {
12791   case EST_Uninstantiated:
12792   case EST_Unevaluated:
12793   case EST_BasicNoexcept:
12794   case EST_DynamicNone:
12795   case EST_MSAny:
12796   case EST_None:
12797     break;
12798 
12799   case EST_ComputedNoexcept:
12800     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12801       return true;
12802 
12803   case EST_Dynamic:
12804     for (const auto &E : Proto->exceptions()) {
12805       if (!Finder.TraverseType(E))
12806         return true;
12807     }
12808     break;
12809   }
12810 
12811   return false;
12812 }
12813 
12814 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12815   FindCXXThisExpr Finder(*this);
12816 
12817   // Check attributes.
12818   for (const auto *A : Method->attrs()) {
12819     // FIXME: This should be emitted by tblgen.
12820     Expr *Arg = nullptr;
12821     ArrayRef<Expr *> Args;
12822     if (const auto *G = dyn_cast<GuardedByAttr>(A))
12823       Arg = G->getArg();
12824     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
12825       Arg = G->getArg();
12826     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
12827       Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12828     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
12829       Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12830     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
12831       Arg = ETLF->getSuccessValue();
12832       Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12833     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
12834       Arg = STLF->getSuccessValue();
12835       Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12836     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
12837       Arg = LR->getArg();
12838     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
12839       Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12840     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
12841       Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
12842     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
12843       Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
12844     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
12845       Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
12846     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
12847       Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
12848 
12849     if (Arg && !Finder.TraverseStmt(Arg))
12850       return true;
12851 
12852     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12853       if (!Finder.TraverseStmt(Args[I]))
12854         return true;
12855     }
12856   }
12857 
12858   return false;
12859 }
12860 
12861 void
12862 Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12863                                   ArrayRef<ParsedType> DynamicExceptions,
12864                                   ArrayRef<SourceRange> DynamicExceptionRanges,
12865                                   Expr *NoexceptExpr,
12866                                   SmallVectorImpl<QualType> &Exceptions,
12867                                   FunctionProtoType::ExtProtoInfo &EPI) {
12868   Exceptions.clear();
12869   EPI.ExceptionSpecType = EST;
12870   if (EST == EST_Dynamic) {
12871     Exceptions.reserve(DynamicExceptions.size());
12872     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12873       // FIXME: Preserve type source info.
12874       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12875 
12876       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12877       collectUnexpandedParameterPacks(ET, Unexpanded);
12878       if (!Unexpanded.empty()) {
12879         DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12880                                          UPPC_ExceptionType,
12881                                          Unexpanded);
12882         continue;
12883       }
12884 
12885       // Check that the type is valid for an exception spec, and
12886       // drop it if not.
12887       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12888         Exceptions.push_back(ET);
12889     }
12890     EPI.NumExceptions = Exceptions.size();
12891     EPI.Exceptions = Exceptions.data();
12892     return;
12893   }
12894 
12895   if (EST == EST_ComputedNoexcept) {
12896     // If an error occurred, there's no expression here.
12897     if (NoexceptExpr) {
12898       assert((NoexceptExpr->isTypeDependent() ||
12899               NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12900               Context.BoolTy) &&
12901              "Parser should have made sure that the expression is boolean");
12902       if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12903         EPI.ExceptionSpecType = EST_BasicNoexcept;
12904         return;
12905       }
12906 
12907       if (!NoexceptExpr->isValueDependent())
12908         NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
12909                          diag::err_noexcept_needs_constant_expression,
12910                          /*AllowFold*/ false).get();
12911       EPI.NoexceptExpr = NoexceptExpr;
12912     }
12913     return;
12914   }
12915 }
12916 
12917 /// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12918 Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12919   // Implicitly declared functions (e.g. copy constructors) are
12920   // __host__ __device__
12921   if (D->isImplicit())
12922     return CFT_HostDevice;
12923 
12924   if (D->hasAttr<CUDAGlobalAttr>())
12925     return CFT_Global;
12926 
12927   if (D->hasAttr<CUDADeviceAttr>()) {
12928     if (D->hasAttr<CUDAHostAttr>())
12929       return CFT_HostDevice;
12930     return CFT_Device;
12931   }
12932 
12933   return CFT_Host;
12934 }
12935 
12936 bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12937                            CUDAFunctionTarget CalleeTarget) {
12938   // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12939   // Callable from the device only."
12940   if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12941     return true;
12942 
12943   // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12944   // Callable from the host only."
12945   // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12946   // Callable from the host only."
12947   if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12948       (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12949     return true;
12950 
12951   if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12952     return true;
12953 
12954   return false;
12955 }
12956 
12957 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12958 ///
12959 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12960                                        SourceLocation DeclStart,
12961                                        Declarator &D, Expr *BitWidth,
12962                                        InClassInitStyle InitStyle,
12963                                        AccessSpecifier AS,
12964                                        AttributeList *MSPropertyAttr) {
12965   IdentifierInfo *II = D.getIdentifier();
12966   if (!II) {
12967     Diag(DeclStart, diag::err_anonymous_property);
12968     return nullptr;
12969   }
12970   SourceLocation Loc = D.getIdentifierLoc();
12971 
12972   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12973   QualType T = TInfo->getType();
12974   if (getLangOpts().CPlusPlus) {
12975     CheckExtraCXXDefaultArguments(D);
12976 
12977     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12978                                         UPPC_DataMemberType)) {
12979       D.setInvalidType();
12980       T = Context.IntTy;
12981       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12982     }
12983   }
12984 
12985   DiagnoseFunctionSpecifiers(D.getDeclSpec());
12986 
12987   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12988     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12989          diag::err_invalid_thread)
12990       << DeclSpec::getSpecifierName(TSCS);
12991 
12992   // Check to see if this name was declared as a member previously
12993   NamedDecl *PrevDecl = nullptr;
12994   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12995   LookupName(Previous, S);
12996   switch (Previous.getResultKind()) {
12997   case LookupResult::Found:
12998   case LookupResult::FoundUnresolvedValue:
12999     PrevDecl = Previous.getAsSingle<NamedDecl>();
13000     break;
13001 
13002   case LookupResult::FoundOverloaded:
13003     PrevDecl = Previous.getRepresentativeDecl();
13004     break;
13005 
13006   case LookupResult::NotFound:
13007   case LookupResult::NotFoundInCurrentInstantiation:
13008   case LookupResult::Ambiguous:
13009     break;
13010   }
13011 
13012   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13013     // Maybe we will complain about the shadowed template parameter.
13014     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13015     // Just pretend that we didn't see the previous declaration.
13016     PrevDecl = nullptr;
13017   }
13018 
13019   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13020     PrevDecl = nullptr;
13021 
13022   SourceLocation TSSL = D.getLocStart();
13023   const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
13024   MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13025       Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
13026   ProcessDeclAttributes(TUScope, NewPD, D);
13027   NewPD->setAccess(AS);
13028 
13029   if (NewPD->isInvalidDecl())
13030     Record->setInvalidDecl();
13031 
13032   if (D.getDeclSpec().isModulePrivateSpecified())
13033     NewPD->setModulePrivate();
13034 
13035   if (NewPD->isInvalidDecl() && PrevDecl) {
13036     // Don't introduce NewFD into scope; there's already something
13037     // with the same name in the same scope.
13038   } else if (II) {
13039     PushOnScopeChains(NewPD, S);
13040   } else
13041     Record->addDecl(NewPD);
13042 
13043   return NewPD;
13044 }
13045