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/DeclVisitor.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/RecordLayout.h"
25 #include "clang/AST/RecursiveASTVisitor.h"
26 #include "clang/AST/StmtVisitor.h"
27 #include "clang/AST/TypeLoc.h"
28 #include "clang/AST/TypeOrdering.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/LiteralSupport.h"
32 #include "clang/Lex/Preprocessor.h"
33 #include "clang/Sema/CXXFieldCollector.h"
34 #include "clang/Sema/DeclSpec.h"
35 #include "clang/Sema/Initialization.h"
36 #include "clang/Sema/Lookup.h"
37 #include "clang/Sema/ParsedTemplate.h"
38 #include "clang/Sema/Scope.h"
39 #include "clang/Sema/ScopeInfo.h"
40 #include "llvm/ADT/STLExtras.h"
41 #include "llvm/ADT/SmallString.h"
42 #include <map>
43 #include <set>
44 
45 using namespace clang;
46 
47 //===----------------------------------------------------------------------===//
48 // CheckDefaultArgumentVisitor
49 //===----------------------------------------------------------------------===//
50 
51 namespace {
52   /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
53   /// the default argument of a parameter to determine whether it
54   /// contains any ill-formed subexpressions. For example, this will
55   /// diagnose the use of local variables or parameters within the
56   /// default argument expression.
57   class CheckDefaultArgumentVisitor
58     : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
59     Expr *DefaultArg;
60     Sema *S;
61 
62   public:
63     CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
64       : DefaultArg(defarg), S(s) {}
65 
66     bool VisitExpr(Expr *Node);
67     bool VisitDeclRefExpr(DeclRefExpr *DRE);
68     bool VisitCXXThisExpr(CXXThisExpr *ThisE);
69     bool VisitLambdaExpr(LambdaExpr *Lambda);
70     bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
71   };
72 
73   /// VisitExpr - Visit all of the children of this expression.
74   bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
75     bool IsInvalid = false;
76     for (Stmt::child_range I = Node->children(); I; ++I)
77       IsInvalid |= Visit(*I);
78     return IsInvalid;
79   }
80 
81   /// VisitDeclRefExpr - Visit a reference to a declaration, to
82   /// determine whether this declaration can be used in the default
83   /// argument expression.
84   bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
85     NamedDecl *Decl = DRE->getDecl();
86     if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
87       // C++ [dcl.fct.default]p9
88       //   Default arguments are evaluated each time the function is
89       //   called. The order of evaluation of function arguments is
90       //   unspecified. Consequently, parameters of a function shall not
91       //   be used in default argument expressions, even if they are not
92       //   evaluated. Parameters of a function declared before a default
93       //   argument expression are in scope and can hide namespace and
94       //   class member names.
95       return S->Diag(DRE->getLocStart(),
96                      diag::err_param_default_argument_references_param)
97          << Param->getDeclName() << DefaultArg->getSourceRange();
98     } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
99       // C++ [dcl.fct.default]p7
100       //   Local variables shall not be used in default argument
101       //   expressions.
102       if (VDecl->isLocalVarDecl())
103         return S->Diag(DRE->getLocStart(),
104                        diag::err_param_default_argument_references_local)
105           << VDecl->getDeclName() << DefaultArg->getSourceRange();
106     }
107 
108     return false;
109   }
110 
111   /// VisitCXXThisExpr - Visit a C++ "this" expression.
112   bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
113     // C++ [dcl.fct.default]p8:
114     //   The keyword this shall not be used in a default argument of a
115     //   member function.
116     return S->Diag(ThisE->getLocStart(),
117                    diag::err_param_default_argument_references_this)
118                << ThisE->getSourceRange();
119   }
120 
121   bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
122     bool Invalid = false;
123     for (PseudoObjectExpr::semantics_iterator
124            i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
125       Expr *E = *i;
126 
127       // Look through bindings.
128       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
129         E = OVE->getSourceExpr();
130         assert(E && "pseudo-object binding without source expression?");
131       }
132 
133       Invalid |= Visit(E);
134     }
135     return Invalid;
136   }
137 
138   bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
139     // C++11 [expr.lambda.prim]p13:
140     //   A lambda-expression appearing in a default argument shall not
141     //   implicitly or explicitly capture any entity.
142     if (Lambda->capture_begin() == Lambda->capture_end())
143       return false;
144 
145     return S->Diag(Lambda->getLocStart(),
146                    diag::err_lambda_capture_default_arg);
147   }
148 }
149 
150 void
151 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
152                                                  const CXXMethodDecl *Method) {
153   // If we have an MSAny spec already, don't bother.
154   if (!Method || ComputedEST == EST_MSAny)
155     return;
156 
157   const FunctionProtoType *Proto
158     = Method->getType()->getAs<FunctionProtoType>();
159   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
160   if (!Proto)
161     return;
162 
163   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
164 
165   // If this function can throw any exceptions, make a note of that.
166   if (EST == EST_MSAny || EST == EST_None) {
167     ClearExceptions();
168     ComputedEST = EST;
169     return;
170   }
171 
172   // FIXME: If the call to this decl is using any of its default arguments, we
173   // need to search them for potentially-throwing calls.
174 
175   // If this function has a basic noexcept, it doesn't affect the outcome.
176   if (EST == EST_BasicNoexcept)
177     return;
178 
179   // If we have a throw-all spec at this point, ignore the function.
180   if (ComputedEST == EST_None)
181     return;
182 
183   // If we're still at noexcept(true) and there's a nothrow() callee,
184   // change to that specification.
185   if (EST == EST_DynamicNone) {
186     if (ComputedEST == EST_BasicNoexcept)
187       ComputedEST = EST_DynamicNone;
188     return;
189   }
190 
191   // Check out noexcept specs.
192   if (EST == EST_ComputedNoexcept) {
193     FunctionProtoType::NoexceptResult NR =
194         Proto->getNoexceptSpec(Self->Context);
195     assert(NR != FunctionProtoType::NR_NoNoexcept &&
196            "Must have noexcept result for EST_ComputedNoexcept.");
197     assert(NR != FunctionProtoType::NR_Dependent &&
198            "Should not generate implicit declarations for dependent cases, "
199            "and don't know how to handle them anyway.");
200 
201     // noexcept(false) -> no spec on the new function
202     if (NR == FunctionProtoType::NR_Throw) {
203       ClearExceptions();
204       ComputedEST = EST_None;
205     }
206     // noexcept(true) won't change anything either.
207     return;
208   }
209 
210   assert(EST == EST_Dynamic && "EST case not considered earlier.");
211   assert(ComputedEST != EST_None &&
212          "Shouldn't collect exceptions when throw-all is guaranteed.");
213   ComputedEST = EST_Dynamic;
214   // Record the exceptions in this function's exception specification.
215   for (const auto &E : Proto->exceptions())
216     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)))
217       Exceptions.push_back(E);
218 }
219 
220 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
221   if (!E || ComputedEST == EST_MSAny)
222     return;
223 
224   // FIXME:
225   //
226   // C++0x [except.spec]p14:
227   //   [An] implicit exception-specification specifies the type-id T if and
228   // only if T is allowed by the exception-specification of a function directly
229   // invoked by f's implicit definition; f shall allow all exceptions if any
230   // function it directly invokes allows all exceptions, and f shall allow no
231   // exceptions if every function it directly invokes allows no exceptions.
232   //
233   // Note in particular that if an implicit exception-specification is generated
234   // for a function containing a throw-expression, that specification can still
235   // be noexcept(true).
236   //
237   // Note also that 'directly invoked' is not defined in the standard, and there
238   // is no indication that we should only consider potentially-evaluated calls.
239   //
240   // Ultimately we should implement the intent of the standard: the exception
241   // specification should be the set of exceptions which can be thrown by the
242   // implicit definition. For now, we assume that any non-nothrow expression can
243   // throw any exception.
244 
245   if (Self->canThrow(E))
246     ComputedEST = EST_None;
247 }
248 
249 bool
250 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
251                               SourceLocation EqualLoc) {
252   if (RequireCompleteType(Param->getLocation(), Param->getType(),
253                           diag::err_typecheck_decl_incomplete_type)) {
254     Param->setInvalidDecl();
255     return true;
256   }
257 
258   // C++ [dcl.fct.default]p5
259   //   A default argument expression is implicitly converted (clause
260   //   4) to the parameter type. The default argument expression has
261   //   the same semantic constraints as the initializer expression in
262   //   a declaration of a variable of the parameter type, using the
263   //   copy-initialization semantics (8.5).
264   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
265                                                                     Param);
266   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
267                                                            EqualLoc);
268   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
269   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
270   if (Result.isInvalid())
271     return true;
272   Arg = Result.takeAs<Expr>();
273 
274   CheckCompletedExpr(Arg, EqualLoc);
275   Arg = MaybeCreateExprWithCleanups(Arg);
276 
277   // Okay: add the default argument to the parameter
278   Param->setDefaultArg(Arg);
279 
280   // We have already instantiated this parameter; provide each of the
281   // instantiations with the uninstantiated default argument.
282   UnparsedDefaultArgInstantiationsMap::iterator InstPos
283     = UnparsedDefaultArgInstantiations.find(Param);
284   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
285     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
286       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
287 
288     // We're done tracking this parameter's instantiations.
289     UnparsedDefaultArgInstantiations.erase(InstPos);
290   }
291 
292   return false;
293 }
294 
295 /// ActOnParamDefaultArgument - Check whether the default argument
296 /// provided for a function parameter is well-formed. If so, attach it
297 /// to the parameter declaration.
298 void
299 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
300                                 Expr *DefaultArg) {
301   if (!param || !DefaultArg)
302     return;
303 
304   ParmVarDecl *Param = cast<ParmVarDecl>(param);
305   UnparsedDefaultArgLocs.erase(Param);
306 
307   // Default arguments are only permitted in C++
308   if (!getLangOpts().CPlusPlus) {
309     Diag(EqualLoc, diag::err_param_default_argument)
310       << DefaultArg->getSourceRange();
311     Param->setInvalidDecl();
312     return;
313   }
314 
315   // Check for unexpanded parameter packs.
316   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
317     Param->setInvalidDecl();
318     return;
319   }
320 
321   // Check that the default argument is well-formed
322   CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
323   if (DefaultArgChecker.Visit(DefaultArg)) {
324     Param->setInvalidDecl();
325     return;
326   }
327 
328   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
329 }
330 
331 /// ActOnParamUnparsedDefaultArgument - We've seen a default
332 /// argument for a function parameter, but we can't parse it yet
333 /// because we're inside a class definition. Note that this default
334 /// argument will be parsed later.
335 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
336                                              SourceLocation EqualLoc,
337                                              SourceLocation ArgLoc) {
338   if (!param)
339     return;
340 
341   ParmVarDecl *Param = cast<ParmVarDecl>(param);
342   Param->setUnparsedDefaultArg();
343   UnparsedDefaultArgLocs[Param] = ArgLoc;
344 }
345 
346 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
347 /// the default argument for the parameter param failed.
348 void Sema::ActOnParamDefaultArgumentError(Decl *param) {
349   if (!param)
350     return;
351 
352   ParmVarDecl *Param = cast<ParmVarDecl>(param);
353   Param->setInvalidDecl();
354   UnparsedDefaultArgLocs.erase(Param);
355 }
356 
357 /// CheckExtraCXXDefaultArguments - Check for any extra default
358 /// arguments in the declarator, which is not a function declaration
359 /// or definition and therefore is not permitted to have default
360 /// arguments. This routine should be invoked for every declarator
361 /// that is not a function declaration or definition.
362 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
363   // C++ [dcl.fct.default]p3
364   //   A default argument expression shall be specified only in the
365   //   parameter-declaration-clause of a function declaration or in a
366   //   template-parameter (14.1). It shall not be specified for a
367   //   parameter pack. If it is specified in a
368   //   parameter-declaration-clause, it shall not occur within a
369   //   declarator or abstract-declarator of a parameter-declaration.
370   bool MightBeFunction = D.isFunctionDeclarationContext();
371   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
372     DeclaratorChunk &chunk = D.getTypeObject(i);
373     if (chunk.Kind == DeclaratorChunk::Function) {
374       if (MightBeFunction) {
375         // This is a function declaration. It can have default arguments, but
376         // keep looking in case its return type is a function type with default
377         // arguments.
378         MightBeFunction = false;
379         continue;
380       }
381       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
382            ++argIdx) {
383         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
384         if (Param->hasUnparsedDefaultArg()) {
385           CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
386           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
387             << SourceRange((*Toks)[1].getLocation(),
388                            Toks->back().getLocation());
389           delete Toks;
390           chunk.Fun.Params[argIdx].DefaultArgTokens = 0;
391         } else if (Param->getDefaultArg()) {
392           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
393             << Param->getDefaultArg()->getSourceRange();
394           Param->setDefaultArg(0);
395         }
396       }
397     } else if (chunk.Kind != DeclaratorChunk::Paren) {
398       MightBeFunction = false;
399     }
400   }
401 }
402 
403 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
404   for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
405     const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
406     if (!PVD->hasDefaultArg())
407       return false;
408     if (!PVD->hasInheritedDefaultArg())
409       return true;
410   }
411   return false;
412 }
413 
414 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
415 /// function, once we already know that they have the same
416 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
417 /// error, false otherwise.
418 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
419                                 Scope *S) {
420   bool Invalid = false;
421 
422   // C++ [dcl.fct.default]p4:
423   //   For non-template functions, default arguments can be added in
424   //   later declarations of a function in the same
425   //   scope. Declarations in different scopes have completely
426   //   distinct sets of default arguments. That is, declarations in
427   //   inner scopes do not acquire default arguments from
428   //   declarations in outer scopes, and vice versa. In a given
429   //   function declaration, all parameters subsequent to a
430   //   parameter with a default argument shall have default
431   //   arguments supplied in this or previous declarations. A
432   //   default argument shall not be redefined by a later
433   //   declaration (not even to the same value).
434   //
435   // C++ [dcl.fct.default]p6:
436   //   Except for member functions of class templates, the default arguments
437   //   in a member function definition that appears outside of the class
438   //   definition are added to the set of default arguments provided by the
439   //   member function declaration in the class definition.
440   for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
441     ParmVarDecl *OldParam = Old->getParamDecl(p);
442     ParmVarDecl *NewParam = New->getParamDecl(p);
443 
444     bool OldParamHasDfl = OldParam->hasDefaultArg();
445     bool NewParamHasDfl = NewParam->hasDefaultArg();
446 
447     NamedDecl *ND = Old;
448 
449     // The declaration context corresponding to the scope is the semantic
450     // parent, unless this is a local function declaration, in which case
451     // it is that surrounding function.
452     DeclContext *ScopeDC = New->getLexicalDeclContext();
453     if (!ScopeDC->isFunctionOrMethod())
454       ScopeDC = New->getDeclContext();
455     if (S && !isDeclInScope(ND, ScopeDC, S) &&
456         !New->getDeclContext()->isRecord())
457       // Ignore default parameters of old decl if they are not in
458       // the same scope and this is not an out-of-line definition of
459       // a member function.
460       OldParamHasDfl = false;
461 
462     if (OldParamHasDfl && NewParamHasDfl) {
463 
464       unsigned DiagDefaultParamID =
465         diag::err_param_default_argument_redefinition;
466 
467       // MSVC accepts that default parameters be redefined for member functions
468       // of template class. The new default parameter's value is ignored.
469       Invalid = true;
470       if (getLangOpts().MicrosoftExt) {
471         CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
472         if (MD && MD->getParent()->getDescribedClassTemplate()) {
473           // Merge the old default argument into the new parameter.
474           NewParam->setHasInheritedDefaultArg();
475           if (OldParam->hasUninstantiatedDefaultArg())
476             NewParam->setUninstantiatedDefaultArg(
477                                       OldParam->getUninstantiatedDefaultArg());
478           else
479             NewParam->setDefaultArg(OldParam->getInit());
480           DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
481           Invalid = false;
482         }
483       }
484 
485       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
486       // hint here. Alternatively, we could walk the type-source information
487       // for NewParam to find the last source location in the type... but it
488       // isn't worth the effort right now. This is the kind of test case that
489       // is hard to get right:
490       //   int f(int);
491       //   void g(int (*fp)(int) = f);
492       //   void g(int (*fp)(int) = &f);
493       Diag(NewParam->getLocation(), DiagDefaultParamID)
494         << NewParam->getDefaultArgRange();
495 
496       // Look for the function declaration where the default argument was
497       // actually written, which may be a declaration prior to Old.
498       for (FunctionDecl *Older = Old->getPreviousDecl();
499            Older; Older = Older->getPreviousDecl()) {
500         if (!Older->getParamDecl(p)->hasDefaultArg())
501           break;
502 
503         OldParam = Older->getParamDecl(p);
504       }
505 
506       Diag(OldParam->getLocation(), diag::note_previous_definition)
507         << OldParam->getDefaultArgRange();
508     } else if (OldParamHasDfl) {
509       // Merge the old default argument into the new parameter.
510       // It's important to use getInit() here;  getDefaultArg()
511       // strips off any top-level ExprWithCleanups.
512       NewParam->setHasInheritedDefaultArg();
513       if (OldParam->hasUninstantiatedDefaultArg())
514         NewParam->setUninstantiatedDefaultArg(
515                                       OldParam->getUninstantiatedDefaultArg());
516       else
517         NewParam->setDefaultArg(OldParam->getInit());
518     } else if (NewParamHasDfl) {
519       if (New->getDescribedFunctionTemplate()) {
520         // Paragraph 4, quoted above, only applies to non-template functions.
521         Diag(NewParam->getLocation(),
522              diag::err_param_default_argument_template_redecl)
523           << NewParam->getDefaultArgRange();
524         Diag(Old->getLocation(), diag::note_template_prev_declaration)
525           << false;
526       } else if (New->getTemplateSpecializationKind()
527                    != TSK_ImplicitInstantiation &&
528                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
529         // C++ [temp.expr.spec]p21:
530         //   Default function arguments shall not be specified in a declaration
531         //   or a definition for one of the following explicit specializations:
532         //     - the explicit specialization of a function template;
533         //     - the explicit specialization of a member function template;
534         //     - the explicit specialization of a member function of a class
535         //       template where the class template specialization to which the
536         //       member function specialization belongs is implicitly
537         //       instantiated.
538         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
539           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
540           << New->getDeclName()
541           << NewParam->getDefaultArgRange();
542       } else if (New->getDeclContext()->isDependentContext()) {
543         // C++ [dcl.fct.default]p6 (DR217):
544         //   Default arguments for a member function of a class template shall
545         //   be specified on the initial declaration of the member function
546         //   within the class template.
547         //
548         // Reading the tea leaves a bit in DR217 and its reference to DR205
549         // leads me to the conclusion that one cannot add default function
550         // arguments for an out-of-line definition of a member function of a
551         // dependent type.
552         int WhichKind = 2;
553         if (CXXRecordDecl *Record
554               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
555           if (Record->getDescribedClassTemplate())
556             WhichKind = 0;
557           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
558             WhichKind = 1;
559           else
560             WhichKind = 2;
561         }
562 
563         Diag(NewParam->getLocation(),
564              diag::err_param_default_argument_member_template_redecl)
565           << WhichKind
566           << NewParam->getDefaultArgRange();
567       }
568     }
569   }
570 
571   // DR1344: If a default argument is added outside a class definition and that
572   // default argument makes the function a special member function, the program
573   // is ill-formed. This can only happen for constructors.
574   if (isa<CXXConstructorDecl>(New) &&
575       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
576     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
577                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
578     if (NewSM != OldSM) {
579       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
580       assert(NewParam->hasDefaultArg());
581       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
582         << NewParam->getDefaultArgRange() << NewSM;
583       Diag(Old->getLocation(), diag::note_previous_declaration);
584     }
585   }
586 
587   const FunctionDecl *Def;
588   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
589   // template has a constexpr specifier then all its declarations shall
590   // contain the constexpr specifier.
591   if (New->isConstexpr() != Old->isConstexpr()) {
592     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
593       << New << New->isConstexpr();
594     Diag(Old->getLocation(), diag::note_previous_declaration);
595     Invalid = true;
596   } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) {
597     // C++11 [dcl.fcn.spec]p4:
598     //   If the definition of a function appears in a translation unit before its
599     //   first declaration as inline, the program is ill-formed.
600     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
601     Diag(Def->getLocation(), diag::note_previous_definition);
602     Invalid = true;
603   }
604 
605   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
606   // argument expression, that declaration shall be a definition and shall be
607   // the only declaration of the function or function template in the
608   // translation unit.
609   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
610       functionDeclHasDefaultArgument(Old)) {
611     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
612     Diag(Old->getLocation(), diag::note_previous_declaration);
613     Invalid = true;
614   }
615 
616   if (CheckEquivalentExceptionSpec(Old, New))
617     Invalid = true;
618 
619   return Invalid;
620 }
621 
622 /// \brief Merge the exception specifications of two variable declarations.
623 ///
624 /// This is called when there's a redeclaration of a VarDecl. The function
625 /// checks if the redeclaration might have an exception specification and
626 /// validates compatibility and merges the specs if necessary.
627 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
628   // Shortcut if exceptions are disabled.
629   if (!getLangOpts().CXXExceptions)
630     return;
631 
632   assert(Context.hasSameType(New->getType(), Old->getType()) &&
633          "Should only be called if types are otherwise the same.");
634 
635   QualType NewType = New->getType();
636   QualType OldType = Old->getType();
637 
638   // We're only interested in pointers and references to functions, as well
639   // as pointers to member functions.
640   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
641     NewType = R->getPointeeType();
642     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
643   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
644     NewType = P->getPointeeType();
645     OldType = OldType->getAs<PointerType>()->getPointeeType();
646   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
647     NewType = M->getPointeeType();
648     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
649   }
650 
651   if (!NewType->isFunctionProtoType())
652     return;
653 
654   // There's lots of special cases for functions. For function pointers, system
655   // libraries are hopefully not as broken so that we don't need these
656   // workarounds.
657   if (CheckEquivalentExceptionSpec(
658         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
659         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
660     New->setInvalidDecl();
661   }
662 }
663 
664 /// CheckCXXDefaultArguments - Verify that the default arguments for a
665 /// function declaration are well-formed according to C++
666 /// [dcl.fct.default].
667 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
668   unsigned NumParams = FD->getNumParams();
669   unsigned p;
670 
671   // Find first parameter with a default argument
672   for (p = 0; p < NumParams; ++p) {
673     ParmVarDecl *Param = FD->getParamDecl(p);
674     if (Param->hasDefaultArg())
675       break;
676   }
677 
678   // C++ [dcl.fct.default]p4:
679   //   In a given function declaration, all parameters
680   //   subsequent to a parameter with a default argument shall
681   //   have default arguments supplied in this or previous
682   //   declarations. A default argument shall not be redefined
683   //   by a later declaration (not even to the same value).
684   unsigned LastMissingDefaultArg = 0;
685   for (; p < NumParams; ++p) {
686     ParmVarDecl *Param = FD->getParamDecl(p);
687     if (!Param->hasDefaultArg()) {
688       if (Param->isInvalidDecl())
689         /* We already complained about this parameter. */;
690       else if (Param->getIdentifier())
691         Diag(Param->getLocation(),
692              diag::err_param_default_argument_missing_name)
693           << Param->getIdentifier();
694       else
695         Diag(Param->getLocation(),
696              diag::err_param_default_argument_missing);
697 
698       LastMissingDefaultArg = p;
699     }
700   }
701 
702   if (LastMissingDefaultArg > 0) {
703     // Some default arguments were missing. Clear out all of the
704     // default arguments up to (and including) the last missing
705     // default argument, so that we leave the function parameters
706     // in a semantically valid state.
707     for (p = 0; p <= LastMissingDefaultArg; ++p) {
708       ParmVarDecl *Param = FD->getParamDecl(p);
709       if (Param->hasDefaultArg()) {
710         Param->setDefaultArg(0);
711       }
712     }
713   }
714 }
715 
716 // CheckConstexprParameterTypes - Check whether a function's parameter types
717 // are all literal types. If so, return true. If not, produce a suitable
718 // diagnostic and return false.
719 static bool CheckConstexprParameterTypes(Sema &SemaRef,
720                                          const FunctionDecl *FD) {
721   unsigned ArgIndex = 0;
722   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
723   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
724                                               e = FT->param_type_end();
725        i != e; ++i, ++ArgIndex) {
726     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
727     SourceLocation ParamLoc = PD->getLocation();
728     if (!(*i)->isDependentType() &&
729         SemaRef.RequireLiteralType(ParamLoc, *i,
730                                    diag::err_constexpr_non_literal_param,
731                                    ArgIndex+1, PD->getSourceRange(),
732                                    isa<CXXConstructorDecl>(FD)))
733       return false;
734   }
735   return true;
736 }
737 
738 /// \brief Get diagnostic %select index for tag kind for
739 /// record diagnostic message.
740 /// WARNING: Indexes apply to particular diagnostics only!
741 ///
742 /// \returns diagnostic %select index.
743 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
744   switch (Tag) {
745   case TTK_Struct: return 0;
746   case TTK_Interface: return 1;
747   case TTK_Class:  return 2;
748   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
749   }
750 }
751 
752 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
753 // the requirements of a constexpr function definition or a constexpr
754 // constructor definition. If so, return true. If not, produce appropriate
755 // diagnostics and return false.
756 //
757 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
758 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
759   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
760   if (MD && MD->isInstance()) {
761     // C++11 [dcl.constexpr]p4:
762     //  The definition of a constexpr constructor shall satisfy the following
763     //  constraints:
764     //  - the class shall not have any virtual base classes;
765     const CXXRecordDecl *RD = MD->getParent();
766     if (RD->getNumVBases()) {
767       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
768         << isa<CXXConstructorDecl>(NewFD)
769         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
770       for (const auto &I : RD->vbases())
771         Diag(I.getLocStart(),
772              diag::note_constexpr_virtual_base_here) << I.getSourceRange();
773       return false;
774     }
775   }
776 
777   if (!isa<CXXConstructorDecl>(NewFD)) {
778     // C++11 [dcl.constexpr]p3:
779     //  The definition of a constexpr function shall satisfy the following
780     //  constraints:
781     // - it shall not be virtual;
782     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
783     if (Method && Method->isVirtual()) {
784       Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
785 
786       // If it's not obvious why this function is virtual, find an overridden
787       // function which uses the 'virtual' keyword.
788       const CXXMethodDecl *WrittenVirtual = Method;
789       while (!WrittenVirtual->isVirtualAsWritten())
790         WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
791       if (WrittenVirtual != Method)
792         Diag(WrittenVirtual->getLocation(),
793              diag::note_overridden_virtual_function);
794       return false;
795     }
796 
797     // - its return type shall be a literal type;
798     QualType RT = NewFD->getReturnType();
799     if (!RT->isDependentType() &&
800         RequireLiteralType(NewFD->getLocation(), RT,
801                            diag::err_constexpr_non_literal_return))
802       return false;
803   }
804 
805   // - each of its parameter types shall be a literal type;
806   if (!CheckConstexprParameterTypes(*this, NewFD))
807     return false;
808 
809   return true;
810 }
811 
812 /// Check the given declaration statement is legal within a constexpr function
813 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
814 ///
815 /// \return true if the body is OK (maybe only as an extension), false if we
816 ///         have diagnosed a problem.
817 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
818                                    DeclStmt *DS, SourceLocation &Cxx1yLoc) {
819   // C++11 [dcl.constexpr]p3 and p4:
820   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
821   //  contain only
822   for (const auto *DclIt : DS->decls()) {
823     switch (DclIt->getKind()) {
824     case Decl::StaticAssert:
825     case Decl::Using:
826     case Decl::UsingShadow:
827     case Decl::UsingDirective:
828     case Decl::UnresolvedUsingTypename:
829     case Decl::UnresolvedUsingValue:
830       //   - static_assert-declarations
831       //   - using-declarations,
832       //   - using-directives,
833       continue;
834 
835     case Decl::Typedef:
836     case Decl::TypeAlias: {
837       //   - typedef declarations and alias-declarations that do not define
838       //     classes or enumerations,
839       const auto *TN = cast<TypedefNameDecl>(DclIt);
840       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
841         // Don't allow variably-modified types in constexpr functions.
842         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
843         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
844           << TL.getSourceRange() << TL.getType()
845           << isa<CXXConstructorDecl>(Dcl);
846         return false;
847       }
848       continue;
849     }
850 
851     case Decl::Enum:
852     case Decl::CXXRecord:
853       // C++1y allows types to be defined, not just declared.
854       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
855         SemaRef.Diag(DS->getLocStart(),
856                      SemaRef.getLangOpts().CPlusPlus1y
857                        ? diag::warn_cxx11_compat_constexpr_type_definition
858                        : diag::ext_constexpr_type_definition)
859           << isa<CXXConstructorDecl>(Dcl);
860       continue;
861 
862     case Decl::EnumConstant:
863     case Decl::IndirectField:
864     case Decl::ParmVar:
865       // These can only appear with other declarations which are banned in
866       // C++11 and permitted in C++1y, so ignore them.
867       continue;
868 
869     case Decl::Var: {
870       // C++1y [dcl.constexpr]p3 allows anything except:
871       //   a definition of a variable of non-literal type or of static or
872       //   thread storage duration or for which no initialization is performed.
873       const auto *VD = cast<VarDecl>(DclIt);
874       if (VD->isThisDeclarationADefinition()) {
875         if (VD->isStaticLocal()) {
876           SemaRef.Diag(VD->getLocation(),
877                        diag::err_constexpr_local_var_static)
878             << isa<CXXConstructorDecl>(Dcl)
879             << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
880           return false;
881         }
882         if (!VD->getType()->isDependentType() &&
883             SemaRef.RequireLiteralType(
884               VD->getLocation(), VD->getType(),
885               diag::err_constexpr_local_var_non_literal_type,
886               isa<CXXConstructorDecl>(Dcl)))
887           return false;
888         if (!VD->getType()->isDependentType() &&
889             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
890           SemaRef.Diag(VD->getLocation(),
891                        diag::err_constexpr_local_var_no_init)
892             << isa<CXXConstructorDecl>(Dcl);
893           return false;
894         }
895       }
896       SemaRef.Diag(VD->getLocation(),
897                    SemaRef.getLangOpts().CPlusPlus1y
898                     ? diag::warn_cxx11_compat_constexpr_local_var
899                     : diag::ext_constexpr_local_var)
900         << isa<CXXConstructorDecl>(Dcl);
901       continue;
902     }
903 
904     case Decl::NamespaceAlias:
905     case Decl::Function:
906       // These are disallowed in C++11 and permitted in C++1y. Allow them
907       // everywhere as an extension.
908       if (!Cxx1yLoc.isValid())
909         Cxx1yLoc = DS->getLocStart();
910       continue;
911 
912     default:
913       SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
914         << isa<CXXConstructorDecl>(Dcl);
915       return false;
916     }
917   }
918 
919   return true;
920 }
921 
922 /// Check that the given field is initialized within a constexpr constructor.
923 ///
924 /// \param Dcl The constexpr constructor being checked.
925 /// \param Field The field being checked. This may be a member of an anonymous
926 ///        struct or union nested within the class being checked.
927 /// \param Inits All declarations, including anonymous struct/union members and
928 ///        indirect members, for which any initialization was provided.
929 /// \param Diagnosed Set to true if an error is produced.
930 static void CheckConstexprCtorInitializer(Sema &SemaRef,
931                                           const FunctionDecl *Dcl,
932                                           FieldDecl *Field,
933                                           llvm::SmallSet<Decl*, 16> &Inits,
934                                           bool &Diagnosed) {
935   if (Field->isInvalidDecl())
936     return;
937 
938   if (Field->isUnnamedBitfield())
939     return;
940 
941   // Anonymous unions with no variant members and empty anonymous structs do not
942   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
943   // indirect fields don't need initializing.
944   if (Field->isAnonymousStructOrUnion() &&
945       (Field->getType()->isUnionType()
946            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
947            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
948     return;
949 
950   if (!Inits.count(Field)) {
951     if (!Diagnosed) {
952       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
953       Diagnosed = true;
954     }
955     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
956   } else if (Field->isAnonymousStructOrUnion()) {
957     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
958     for (auto *I : RD->fields())
959       // If an anonymous union contains an anonymous struct of which any member
960       // is initialized, all members must be initialized.
961       if (!RD->isUnion() || Inits.count(I))
962         CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
963   }
964 }
965 
966 /// Check the provided statement is allowed in a constexpr function
967 /// definition.
968 static bool
969 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
970                            SmallVectorImpl<SourceLocation> &ReturnStmts,
971                            SourceLocation &Cxx1yLoc) {
972   // - its function-body shall be [...] a compound-statement that contains only
973   switch (S->getStmtClass()) {
974   case Stmt::NullStmtClass:
975     //   - null statements,
976     return true;
977 
978   case Stmt::DeclStmtClass:
979     //   - static_assert-declarations
980     //   - using-declarations,
981     //   - using-directives,
982     //   - typedef declarations and alias-declarations that do not define
983     //     classes or enumerations,
984     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
985       return false;
986     return true;
987 
988   case Stmt::ReturnStmtClass:
989     //   - and exactly one return statement;
990     if (isa<CXXConstructorDecl>(Dcl)) {
991       // C++1y allows return statements in constexpr constructors.
992       if (!Cxx1yLoc.isValid())
993         Cxx1yLoc = S->getLocStart();
994       return true;
995     }
996 
997     ReturnStmts.push_back(S->getLocStart());
998     return true;
999 
1000   case Stmt::CompoundStmtClass: {
1001     // C++1y allows compound-statements.
1002     if (!Cxx1yLoc.isValid())
1003       Cxx1yLoc = S->getLocStart();
1004 
1005     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1006     for (auto *BodyIt : CompStmt->body()) {
1007       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1008                                       Cxx1yLoc))
1009         return false;
1010     }
1011     return true;
1012   }
1013 
1014   case Stmt::AttributedStmtClass:
1015     if (!Cxx1yLoc.isValid())
1016       Cxx1yLoc = S->getLocStart();
1017     return true;
1018 
1019   case Stmt::IfStmtClass: {
1020     // C++1y allows if-statements.
1021     if (!Cxx1yLoc.isValid())
1022       Cxx1yLoc = S->getLocStart();
1023 
1024     IfStmt *If = cast<IfStmt>(S);
1025     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1026                                     Cxx1yLoc))
1027       return false;
1028     if (If->getElse() &&
1029         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1030                                     Cxx1yLoc))
1031       return false;
1032     return true;
1033   }
1034 
1035   case Stmt::WhileStmtClass:
1036   case Stmt::DoStmtClass:
1037   case Stmt::ForStmtClass:
1038   case Stmt::CXXForRangeStmtClass:
1039   case Stmt::ContinueStmtClass:
1040     // C++1y allows all of these. We don't allow them as extensions in C++11,
1041     // because they don't make sense without variable mutation.
1042     if (!SemaRef.getLangOpts().CPlusPlus1y)
1043       break;
1044     if (!Cxx1yLoc.isValid())
1045       Cxx1yLoc = S->getLocStart();
1046     for (Stmt::child_range Children = S->children(); Children; ++Children)
1047       if (*Children &&
1048           !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1049                                       Cxx1yLoc))
1050         return false;
1051     return true;
1052 
1053   case Stmt::SwitchStmtClass:
1054   case Stmt::CaseStmtClass:
1055   case Stmt::DefaultStmtClass:
1056   case Stmt::BreakStmtClass:
1057     // C++1y allows switch-statements, and since they don't need variable
1058     // mutation, we can reasonably allow them in C++11 as an extension.
1059     if (!Cxx1yLoc.isValid())
1060       Cxx1yLoc = S->getLocStart();
1061     for (Stmt::child_range Children = S->children(); Children; ++Children)
1062       if (*Children &&
1063           !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1064                                       Cxx1yLoc))
1065         return false;
1066     return true;
1067 
1068   default:
1069     if (!isa<Expr>(S))
1070       break;
1071 
1072     // C++1y allows expression-statements.
1073     if (!Cxx1yLoc.isValid())
1074       Cxx1yLoc = S->getLocStart();
1075     return true;
1076   }
1077 
1078   SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1079     << isa<CXXConstructorDecl>(Dcl);
1080   return false;
1081 }
1082 
1083 /// Check the body for the given constexpr function declaration only contains
1084 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1085 ///
1086 /// \return true if the body is OK, false if we have diagnosed a problem.
1087 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1088   if (isa<CXXTryStmt>(Body)) {
1089     // C++11 [dcl.constexpr]p3:
1090     //  The definition of a constexpr function shall satisfy the following
1091     //  constraints: [...]
1092     // - its function-body shall be = delete, = default, or a
1093     //   compound-statement
1094     //
1095     // C++11 [dcl.constexpr]p4:
1096     //  In the definition of a constexpr constructor, [...]
1097     // - its function-body shall not be a function-try-block;
1098     Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1099       << isa<CXXConstructorDecl>(Dcl);
1100     return false;
1101   }
1102 
1103   SmallVector<SourceLocation, 4> ReturnStmts;
1104 
1105   // - its function-body shall be [...] a compound-statement that contains only
1106   //   [... list of cases ...]
1107   CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1108   SourceLocation Cxx1yLoc;
1109   for (auto *BodyIt : CompBody->body()) {
1110     if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
1111       return false;
1112   }
1113 
1114   if (Cxx1yLoc.isValid())
1115     Diag(Cxx1yLoc,
1116          getLangOpts().CPlusPlus1y
1117            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1118            : diag::ext_constexpr_body_invalid_stmt)
1119       << isa<CXXConstructorDecl>(Dcl);
1120 
1121   if (const CXXConstructorDecl *Constructor
1122         = dyn_cast<CXXConstructorDecl>(Dcl)) {
1123     const CXXRecordDecl *RD = Constructor->getParent();
1124     // DR1359:
1125     // - every non-variant non-static data member and base class sub-object
1126     //   shall be initialized;
1127     // DR1460:
1128     // - if the class is a union having variant members, exactly one of them
1129     //   shall be initialized;
1130     if (RD->isUnion()) {
1131       if (Constructor->getNumCtorInitializers() == 0 &&
1132           RD->hasVariantMembers()) {
1133         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1134         return false;
1135       }
1136     } else if (!Constructor->isDependentContext() &&
1137                !Constructor->isDelegatingConstructor()) {
1138       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1139 
1140       // Skip detailed checking if we have enough initializers, and we would
1141       // allow at most one initializer per member.
1142       bool AnyAnonStructUnionMembers = false;
1143       unsigned Fields = 0;
1144       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1145            E = RD->field_end(); I != E; ++I, ++Fields) {
1146         if (I->isAnonymousStructOrUnion()) {
1147           AnyAnonStructUnionMembers = true;
1148           break;
1149         }
1150       }
1151       // DR1460:
1152       // - if the class is a union-like class, but is not a union, for each of
1153       //   its anonymous union members having variant members, exactly one of
1154       //   them shall be initialized;
1155       if (AnyAnonStructUnionMembers ||
1156           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1157         // Check initialization of non-static data members. Base classes are
1158         // always initialized so do not need to be checked. Dependent bases
1159         // might not have initializers in the member initializer list.
1160         llvm::SmallSet<Decl*, 16> Inits;
1161         for (const auto *I: Constructor->inits()) {
1162           if (FieldDecl *FD = I->getMember())
1163             Inits.insert(FD);
1164           else if (IndirectFieldDecl *ID = I->getIndirectMember())
1165             Inits.insert(ID->chain_begin(), ID->chain_end());
1166         }
1167 
1168         bool Diagnosed = false;
1169         for (auto *I : RD->fields())
1170           CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
1171         if (Diagnosed)
1172           return false;
1173       }
1174     }
1175   } else {
1176     if (ReturnStmts.empty()) {
1177       // C++1y doesn't require constexpr functions to contain a 'return'
1178       // statement. We still do, unless the return type is void, because
1179       // otherwise if there's no return statement, the function cannot
1180       // be used in a core constant expression.
1181       bool OK = getLangOpts().CPlusPlus1y && Dcl->getReturnType()->isVoidType();
1182       Diag(Dcl->getLocation(),
1183            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1184               : diag::err_constexpr_body_no_return);
1185       return OK;
1186     }
1187     if (ReturnStmts.size() > 1) {
1188       Diag(ReturnStmts.back(),
1189            getLangOpts().CPlusPlus1y
1190              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1191              : diag::ext_constexpr_body_multiple_return);
1192       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1193         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
1194     }
1195   }
1196 
1197   // C++11 [dcl.constexpr]p5:
1198   //   if no function argument values exist such that the function invocation
1199   //   substitution would produce a constant expression, the program is
1200   //   ill-formed; no diagnostic required.
1201   // C++11 [dcl.constexpr]p3:
1202   //   - every constructor call and implicit conversion used in initializing the
1203   //     return value shall be one of those allowed in a constant expression.
1204   // C++11 [dcl.constexpr]p4:
1205   //   - every constructor involved in initializing non-static data members and
1206   //     base class sub-objects shall be a constexpr constructor.
1207   SmallVector<PartialDiagnosticAt, 8> Diags;
1208   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
1209     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
1210       << isa<CXXConstructorDecl>(Dcl);
1211     for (size_t I = 0, N = Diags.size(); I != N; ++I)
1212       Diag(Diags[I].first, Diags[I].second);
1213     // Don't return false here: we allow this for compatibility in
1214     // system headers.
1215   }
1216 
1217   return true;
1218 }
1219 
1220 /// isCurrentClassName - Determine whether the identifier II is the
1221 /// name of the class type currently being defined. In the case of
1222 /// nested classes, this will only return true if II is the name of
1223 /// the innermost class.
1224 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1225                               const CXXScopeSpec *SS) {
1226   assert(getLangOpts().CPlusPlus && "No class names in C!");
1227 
1228   CXXRecordDecl *CurDecl;
1229   if (SS && SS->isSet() && !SS->isInvalid()) {
1230     DeclContext *DC = computeDeclContext(*SS, true);
1231     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1232   } else
1233     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1234 
1235   if (CurDecl && CurDecl->getIdentifier())
1236     return &II == CurDecl->getIdentifier();
1237   return false;
1238 }
1239 
1240 /// \brief Determine whether the identifier II is a typo for the name of
1241 /// the class type currently being defined. If so, update it to the identifier
1242 /// that should have been used.
1243 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1244   assert(getLangOpts().CPlusPlus && "No class names in C!");
1245 
1246   if (!getLangOpts().SpellChecking)
1247     return false;
1248 
1249   CXXRecordDecl *CurDecl;
1250   if (SS && SS->isSet() && !SS->isInvalid()) {
1251     DeclContext *DC = computeDeclContext(*SS, true);
1252     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1253   } else
1254     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1255 
1256   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1257       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1258           < II->getLength()) {
1259     II = CurDecl->getIdentifier();
1260     return true;
1261   }
1262 
1263   return false;
1264 }
1265 
1266 /// \brief Determine whether the given class is a base class of the given
1267 /// class, including looking at dependent bases.
1268 static bool findCircularInheritance(const CXXRecordDecl *Class,
1269                                     const CXXRecordDecl *Current) {
1270   SmallVector<const CXXRecordDecl*, 8> Queue;
1271 
1272   Class = Class->getCanonicalDecl();
1273   while (true) {
1274     for (const auto &I : Current->bases()) {
1275       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
1276       if (!Base)
1277         continue;
1278 
1279       Base = Base->getDefinition();
1280       if (!Base)
1281         continue;
1282 
1283       if (Base->getCanonicalDecl() == Class)
1284         return true;
1285 
1286       Queue.push_back(Base);
1287     }
1288 
1289     if (Queue.empty())
1290       return false;
1291 
1292     Current = Queue.pop_back_val();
1293   }
1294 
1295   return false;
1296 }
1297 
1298 /// \brief Check the validity of a C++ base class specifier.
1299 ///
1300 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1301 /// and returns NULL otherwise.
1302 CXXBaseSpecifier *
1303 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1304                          SourceRange SpecifierRange,
1305                          bool Virtual, AccessSpecifier Access,
1306                          TypeSourceInfo *TInfo,
1307                          SourceLocation EllipsisLoc) {
1308   QualType BaseType = TInfo->getType();
1309 
1310   // C++ [class.union]p1:
1311   //   A union shall not have base classes.
1312   if (Class->isUnion()) {
1313     Diag(Class->getLocation(), diag::err_base_clause_on_union)
1314       << SpecifierRange;
1315     return 0;
1316   }
1317 
1318   if (EllipsisLoc.isValid() &&
1319       !TInfo->getType()->containsUnexpandedParameterPack()) {
1320     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1321       << TInfo->getTypeLoc().getSourceRange();
1322     EllipsisLoc = SourceLocation();
1323   }
1324 
1325   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1326 
1327   if (BaseType->isDependentType()) {
1328     // Make sure that we don't have circular inheritance among our dependent
1329     // bases. For non-dependent bases, the check for completeness below handles
1330     // this.
1331     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1332       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1333           ((BaseDecl = BaseDecl->getDefinition()) &&
1334            findCircularInheritance(Class, BaseDecl))) {
1335         Diag(BaseLoc, diag::err_circular_inheritance)
1336           << BaseType << Context.getTypeDeclType(Class);
1337 
1338         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1339           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1340             << BaseType;
1341 
1342         return 0;
1343       }
1344     }
1345 
1346     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1347                                           Class->getTagKind() == TTK_Class,
1348                                           Access, TInfo, EllipsisLoc);
1349   }
1350 
1351   // Base specifiers must be record types.
1352   if (!BaseType->isRecordType()) {
1353     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1354     return 0;
1355   }
1356 
1357   // C++ [class.union]p1:
1358   //   A union shall not be used as a base class.
1359   if (BaseType->isUnionType()) {
1360     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1361     return 0;
1362   }
1363 
1364   // C++ [class.derived]p2:
1365   //   The class-name in a base-specifier shall not be an incompletely
1366   //   defined class.
1367   if (RequireCompleteType(BaseLoc, BaseType,
1368                           diag::err_incomplete_base_class, SpecifierRange)) {
1369     Class->setInvalidDecl();
1370     return 0;
1371   }
1372 
1373   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1374   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1375   assert(BaseDecl && "Record type has no declaration");
1376   BaseDecl = BaseDecl->getDefinition();
1377   assert(BaseDecl && "Base type is not incomplete, but has no definition");
1378   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1379   assert(CXXBaseDecl && "Base type is not a C++ type");
1380 
1381   // A class which contains a flexible array member is not suitable for use as a
1382   // base class:
1383   //   - If the layout determines that a base comes before another base,
1384   //     the flexible array member would index into the subsequent base.
1385   //   - If the layout determines that base comes before the derived class,
1386   //     the flexible array member would index into the derived class.
1387   if (CXXBaseDecl->hasFlexibleArrayMember()) {
1388     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1389       << CXXBaseDecl->getDeclName();
1390     return 0;
1391   }
1392 
1393   // C++ [class]p3:
1394   //   If a class is marked final and it appears as a base-type-specifier in
1395   //   base-clause, the program is ill-formed.
1396   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
1397     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1398       << CXXBaseDecl->getDeclName()
1399       << FA->isSpelledAsSealed();
1400     Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1401       << CXXBaseDecl->getDeclName();
1402     return 0;
1403   }
1404 
1405   if (BaseDecl->isInvalidDecl())
1406     Class->setInvalidDecl();
1407 
1408   // Create the base specifier.
1409   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1410                                         Class->getTagKind() == TTK_Class,
1411                                         Access, TInfo, EllipsisLoc);
1412 }
1413 
1414 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1415 /// one entry in the base class list of a class specifier, for
1416 /// example:
1417 ///    class foo : public bar, virtual private baz {
1418 /// 'public bar' and 'virtual private baz' are each base-specifiers.
1419 BaseResult
1420 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1421                          ParsedAttributes &Attributes,
1422                          bool Virtual, AccessSpecifier Access,
1423                          ParsedType basetype, SourceLocation BaseLoc,
1424                          SourceLocation EllipsisLoc) {
1425   if (!classdecl)
1426     return true;
1427 
1428   AdjustDeclIfTemplate(classdecl);
1429   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1430   if (!Class)
1431     return true;
1432 
1433   // We do not support any C++11 attributes on base-specifiers yet.
1434   // Diagnose any attributes we see.
1435   if (!Attributes.empty()) {
1436     for (AttributeList *Attr = Attributes.getList(); Attr;
1437          Attr = Attr->getNext()) {
1438       if (Attr->isInvalid() ||
1439           Attr->getKind() == AttributeList::IgnoredAttribute)
1440         continue;
1441       Diag(Attr->getLoc(),
1442            Attr->getKind() == AttributeList::UnknownAttribute
1443              ? diag::warn_unknown_attribute_ignored
1444              : diag::err_base_specifier_attribute)
1445         << Attr->getName();
1446     }
1447   }
1448 
1449   TypeSourceInfo *TInfo = 0;
1450   GetTypeFromParser(basetype, &TInfo);
1451 
1452   if (EllipsisLoc.isInvalid() &&
1453       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1454                                       UPPC_BaseType))
1455     return true;
1456 
1457   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1458                                                       Virtual, Access, TInfo,
1459                                                       EllipsisLoc))
1460     return BaseSpec;
1461   else
1462     Class->setInvalidDecl();
1463 
1464   return true;
1465 }
1466 
1467 /// \brief Performs the actual work of attaching the given base class
1468 /// specifiers to a C++ class.
1469 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1470                                 unsigned NumBases) {
1471  if (NumBases == 0)
1472     return false;
1473 
1474   // Used to keep track of which base types we have already seen, so
1475   // that we can properly diagnose redundant direct base types. Note
1476   // that the key is always the unqualified canonical type of the base
1477   // class.
1478   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1479 
1480   // Copy non-redundant base specifiers into permanent storage.
1481   unsigned NumGoodBases = 0;
1482   bool Invalid = false;
1483   for (unsigned idx = 0; idx < NumBases; ++idx) {
1484     QualType NewBaseType
1485       = Context.getCanonicalType(Bases[idx]->getType());
1486     NewBaseType = NewBaseType.getLocalUnqualifiedType();
1487 
1488     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1489     if (KnownBase) {
1490       // C++ [class.mi]p3:
1491       //   A class shall not be specified as a direct base class of a
1492       //   derived class more than once.
1493       Diag(Bases[idx]->getLocStart(),
1494            diag::err_duplicate_base_class)
1495         << KnownBase->getType()
1496         << Bases[idx]->getSourceRange();
1497 
1498       // Delete the duplicate base class specifier; we're going to
1499       // overwrite its pointer later.
1500       Context.Deallocate(Bases[idx]);
1501 
1502       Invalid = true;
1503     } else {
1504       // Okay, add this new base class.
1505       KnownBase = Bases[idx];
1506       Bases[NumGoodBases++] = Bases[idx];
1507       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1508         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1509         if (Class->isInterface() &&
1510               (!RD->isInterface() ||
1511                KnownBase->getAccessSpecifier() != AS_public)) {
1512           // The Microsoft extension __interface does not permit bases that
1513           // are not themselves public interfaces.
1514           Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1515             << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1516             << RD->getSourceRange();
1517           Invalid = true;
1518         }
1519         if (RD->hasAttr<WeakAttr>())
1520           Class->addAttr(WeakAttr::CreateImplicit(Context));
1521       }
1522     }
1523   }
1524 
1525   // Attach the remaining base class specifiers to the derived class.
1526   Class->setBases(Bases, NumGoodBases);
1527 
1528   // Delete the remaining (good) base class specifiers, since their
1529   // data has been copied into the CXXRecordDecl.
1530   for (unsigned idx = 0; idx < NumGoodBases; ++idx)
1531     Context.Deallocate(Bases[idx]);
1532 
1533   return Invalid;
1534 }
1535 
1536 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
1537 /// class, after checking whether there are any duplicate base
1538 /// classes.
1539 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
1540                                unsigned NumBases) {
1541   if (!ClassDecl || !Bases || !NumBases)
1542     return;
1543 
1544   AdjustDeclIfTemplate(ClassDecl);
1545   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
1546 }
1547 
1548 /// \brief Determine whether the type \p Derived is a C++ class that is
1549 /// derived from the type \p Base.
1550 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1551   if (!getLangOpts().CPlusPlus)
1552     return false;
1553 
1554   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1555   if (!DerivedRD)
1556     return false;
1557 
1558   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1559   if (!BaseRD)
1560     return false;
1561 
1562   // If either the base or the derived type is invalid, don't try to
1563   // check whether one is derived from the other.
1564   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1565     return false;
1566 
1567   // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
1568   return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
1569 }
1570 
1571 /// \brief Determine whether the type \p Derived is a C++ class that is
1572 /// derived from the type \p Base.
1573 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1574   if (!getLangOpts().CPlusPlus)
1575     return false;
1576 
1577   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1578   if (!DerivedRD)
1579     return false;
1580 
1581   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1582   if (!BaseRD)
1583     return false;
1584 
1585   return DerivedRD->isDerivedFrom(BaseRD, Paths);
1586 }
1587 
1588 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1589                               CXXCastPath &BasePathArray) {
1590   assert(BasePathArray.empty() && "Base path array must be empty!");
1591   assert(Paths.isRecordingPaths() && "Must record paths!");
1592 
1593   const CXXBasePath &Path = Paths.front();
1594 
1595   // We first go backward and check if we have a virtual base.
1596   // FIXME: It would be better if CXXBasePath had the base specifier for
1597   // the nearest virtual base.
1598   unsigned Start = 0;
1599   for (unsigned I = Path.size(); I != 0; --I) {
1600     if (Path[I - 1].Base->isVirtual()) {
1601       Start = I - 1;
1602       break;
1603     }
1604   }
1605 
1606   // Now add all bases.
1607   for (unsigned I = Start, E = Path.size(); I != E; ++I)
1608     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1609 }
1610 
1611 /// \brief Determine whether the given base path includes a virtual
1612 /// base class.
1613 bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1614   for (CXXCastPath::const_iterator B = BasePath.begin(),
1615                                 BEnd = BasePath.end();
1616        B != BEnd; ++B)
1617     if ((*B)->isVirtual())
1618       return true;
1619 
1620   return false;
1621 }
1622 
1623 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1624 /// conversion (where Derived and Base are class types) is
1625 /// well-formed, meaning that the conversion is unambiguous (and
1626 /// that all of the base classes are accessible). Returns true
1627 /// and emits a diagnostic if the code is ill-formed, returns false
1628 /// otherwise. Loc is the location where this routine should point to
1629 /// if there is an error, and Range is the source range to highlight
1630 /// if there is an error.
1631 bool
1632 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1633                                    unsigned InaccessibleBaseID,
1634                                    unsigned AmbigiousBaseConvID,
1635                                    SourceLocation Loc, SourceRange Range,
1636                                    DeclarationName Name,
1637                                    CXXCastPath *BasePath) {
1638   // First, determine whether the path from Derived to Base is
1639   // ambiguous. This is slightly more expensive than checking whether
1640   // the Derived to Base conversion exists, because here we need to
1641   // explore multiple paths to determine if there is an ambiguity.
1642   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1643                      /*DetectVirtual=*/false);
1644   bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1645   assert(DerivationOkay &&
1646          "Can only be used with a derived-to-base conversion");
1647   (void)DerivationOkay;
1648 
1649   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1650     if (InaccessibleBaseID) {
1651       // Check that the base class can be accessed.
1652       switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1653                                    InaccessibleBaseID)) {
1654         case AR_inaccessible:
1655           return true;
1656         case AR_accessible:
1657         case AR_dependent:
1658         case AR_delayed:
1659           break;
1660       }
1661     }
1662 
1663     // Build a base path if necessary.
1664     if (BasePath)
1665       BuildBasePathArray(Paths, *BasePath);
1666     return false;
1667   }
1668 
1669   if (AmbigiousBaseConvID) {
1670     // We know that the derived-to-base conversion is ambiguous, and
1671     // we're going to produce a diagnostic. Perform the derived-to-base
1672     // search just one more time to compute all of the possible paths so
1673     // that we can print them out. This is more expensive than any of
1674     // the previous derived-to-base checks we've done, but at this point
1675     // performance isn't as much of an issue.
1676     Paths.clear();
1677     Paths.setRecordingPaths(true);
1678     bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1679     assert(StillOkay && "Can only be used with a derived-to-base conversion");
1680     (void)StillOkay;
1681 
1682     // Build up a textual representation of the ambiguous paths, e.g.,
1683     // D -> B -> A, that will be used to illustrate the ambiguous
1684     // conversions in the diagnostic. We only print one of the paths
1685     // to each base class subobject.
1686     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1687 
1688     Diag(Loc, AmbigiousBaseConvID)
1689     << Derived << Base << PathDisplayStr << Range << Name;
1690   }
1691   return true;
1692 }
1693 
1694 bool
1695 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1696                                    SourceLocation Loc, SourceRange Range,
1697                                    CXXCastPath *BasePath,
1698                                    bool IgnoreAccess) {
1699   return CheckDerivedToBaseConversion(Derived, Base,
1700                                       IgnoreAccess ? 0
1701                                        : diag::err_upcast_to_inaccessible_base,
1702                                       diag::err_ambiguous_derived_to_base_conv,
1703                                       Loc, Range, DeclarationName(),
1704                                       BasePath);
1705 }
1706 
1707 
1708 /// @brief Builds a string representing ambiguous paths from a
1709 /// specific derived class to different subobjects of the same base
1710 /// class.
1711 ///
1712 /// This function builds a string that can be used in error messages
1713 /// to show the different paths that one can take through the
1714 /// inheritance hierarchy to go from the derived class to different
1715 /// subobjects of a base class. The result looks something like this:
1716 /// @code
1717 /// struct D -> struct B -> struct A
1718 /// struct D -> struct C -> struct A
1719 /// @endcode
1720 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1721   std::string PathDisplayStr;
1722   std::set<unsigned> DisplayedPaths;
1723   for (CXXBasePaths::paths_iterator Path = Paths.begin();
1724        Path != Paths.end(); ++Path) {
1725     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1726       // We haven't displayed a path to this particular base
1727       // class subobject yet.
1728       PathDisplayStr += "\n    ";
1729       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1730       for (CXXBasePath::const_iterator Element = Path->begin();
1731            Element != Path->end(); ++Element)
1732         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1733     }
1734   }
1735 
1736   return PathDisplayStr;
1737 }
1738 
1739 //===----------------------------------------------------------------------===//
1740 // C++ class member Handling
1741 //===----------------------------------------------------------------------===//
1742 
1743 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1744 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1745                                 SourceLocation ASLoc,
1746                                 SourceLocation ColonLoc,
1747                                 AttributeList *Attrs) {
1748   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1749   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1750                                                   ASLoc, ColonLoc);
1751   CurContext->addHiddenDecl(ASDecl);
1752   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1753 }
1754 
1755 /// CheckOverrideControl - Check C++11 override control semantics.
1756 void Sema::CheckOverrideControl(NamedDecl *D) {
1757   if (D->isInvalidDecl())
1758     return;
1759 
1760   // We only care about "override" and "final" declarations.
1761   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1762     return;
1763 
1764   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1765 
1766   // We can't check dependent instance methods.
1767   if (MD && MD->isInstance() &&
1768       (MD->getParent()->hasAnyDependentBases() ||
1769        MD->getType()->isDependentType()))
1770     return;
1771 
1772   if (MD && !MD->isVirtual()) {
1773     // If we have a non-virtual method, check if if hides a virtual method.
1774     // (In that case, it's most likely the method has the wrong type.)
1775     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1776     FindHiddenVirtualMethods(MD, OverloadedMethods);
1777 
1778     if (!OverloadedMethods.empty()) {
1779       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1780         Diag(OA->getLocation(),
1781              diag::override_keyword_hides_virtual_member_function)
1782           << "override" << (OverloadedMethods.size() > 1);
1783       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1784         Diag(FA->getLocation(),
1785              diag::override_keyword_hides_virtual_member_function)
1786           << (FA->isSpelledAsSealed() ? "sealed" : "final")
1787           << (OverloadedMethods.size() > 1);
1788       }
1789       NoteHiddenVirtualMethods(MD, OverloadedMethods);
1790       MD->setInvalidDecl();
1791       return;
1792     }
1793     // Fall through into the general case diagnostic.
1794     // FIXME: We might want to attempt typo correction here.
1795   }
1796 
1797   if (!MD || !MD->isVirtual()) {
1798     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1799       Diag(OA->getLocation(),
1800            diag::override_keyword_only_allowed_on_virtual_member_functions)
1801         << "override" << FixItHint::CreateRemoval(OA->getLocation());
1802       D->dropAttr<OverrideAttr>();
1803     }
1804     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1805       Diag(FA->getLocation(),
1806            diag::override_keyword_only_allowed_on_virtual_member_functions)
1807         << (FA->isSpelledAsSealed() ? "sealed" : "final")
1808         << FixItHint::CreateRemoval(FA->getLocation());
1809       D->dropAttr<FinalAttr>();
1810     }
1811     return;
1812   }
1813 
1814   // C++11 [class.virtual]p5:
1815   //   If a virtual function is marked with the virt-specifier override and
1816   //   does not override a member function of a base class, the program is
1817   //   ill-formed.
1818   bool HasOverriddenMethods =
1819     MD->begin_overridden_methods() != MD->end_overridden_methods();
1820   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1821     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1822       << MD->getDeclName();
1823 }
1824 
1825 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1826 /// function overrides a virtual member function marked 'final', according to
1827 /// C++11 [class.virtual]p4.
1828 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1829                                                   const CXXMethodDecl *Old) {
1830   FinalAttr *FA = Old->getAttr<FinalAttr>();
1831   if (!FA)
1832     return false;
1833 
1834   Diag(New->getLocation(), diag::err_final_function_overridden)
1835     << New->getDeclName()
1836     << FA->isSpelledAsSealed();
1837   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1838   return true;
1839 }
1840 
1841 static bool InitializationHasSideEffects(const FieldDecl &FD) {
1842   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1843   // FIXME: Destruction of ObjC lifetime types has side-effects.
1844   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1845     return !RD->isCompleteDefinition() ||
1846            !RD->hasTrivialDefaultConstructor() ||
1847            !RD->hasTrivialDestructor();
1848   return false;
1849 }
1850 
1851 static AttributeList *getMSPropertyAttr(AttributeList *list) {
1852   for (AttributeList* it = list; it != 0; it = it->getNext())
1853     if (it->isDeclspecPropertyAttribute())
1854       return it;
1855   return 0;
1856 }
1857 
1858 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1859 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1860 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
1861 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1862 /// present (but parsing it has been deferred).
1863 NamedDecl *
1864 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1865                                MultiTemplateParamsArg TemplateParameterLists,
1866                                Expr *BW, const VirtSpecifiers &VS,
1867                                InClassInitStyle InitStyle) {
1868   const DeclSpec &DS = D.getDeclSpec();
1869   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1870   DeclarationName Name = NameInfo.getName();
1871   SourceLocation Loc = NameInfo.getLoc();
1872 
1873   // For anonymous bitfields, the location should point to the type.
1874   if (Loc.isInvalid())
1875     Loc = D.getLocStart();
1876 
1877   Expr *BitWidth = static_cast<Expr*>(BW);
1878 
1879   assert(isa<CXXRecordDecl>(CurContext));
1880   assert(!DS.isFriendSpecified());
1881 
1882   bool isFunc = D.isDeclarationOfFunction();
1883 
1884   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1885     // The Microsoft extension __interface only permits public member functions
1886     // and prohibits constructors, destructors, operators, non-public member
1887     // functions, static methods and data members.
1888     unsigned InvalidDecl;
1889     bool ShowDeclName = true;
1890     if (!isFunc)
1891       InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1892     else if (AS != AS_public)
1893       InvalidDecl = 2;
1894     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1895       InvalidDecl = 3;
1896     else switch (Name.getNameKind()) {
1897       case DeclarationName::CXXConstructorName:
1898         InvalidDecl = 4;
1899         ShowDeclName = false;
1900         break;
1901 
1902       case DeclarationName::CXXDestructorName:
1903         InvalidDecl = 5;
1904         ShowDeclName = false;
1905         break;
1906 
1907       case DeclarationName::CXXOperatorName:
1908       case DeclarationName::CXXConversionFunctionName:
1909         InvalidDecl = 6;
1910         break;
1911 
1912       default:
1913         InvalidDecl = 0;
1914         break;
1915     }
1916 
1917     if (InvalidDecl) {
1918       if (ShowDeclName)
1919         Diag(Loc, diag::err_invalid_member_in_interface)
1920           << (InvalidDecl-1) << Name;
1921       else
1922         Diag(Loc, diag::err_invalid_member_in_interface)
1923           << (InvalidDecl-1) << "";
1924       return 0;
1925     }
1926   }
1927 
1928   // C++ 9.2p6: A member shall not be declared to have automatic storage
1929   // duration (auto, register) or with the extern storage-class-specifier.
1930   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1931   // data members and cannot be applied to names declared const or static,
1932   // and cannot be applied to reference members.
1933   switch (DS.getStorageClassSpec()) {
1934   case DeclSpec::SCS_unspecified:
1935   case DeclSpec::SCS_typedef:
1936   case DeclSpec::SCS_static:
1937     break;
1938   case DeclSpec::SCS_mutable:
1939     if (isFunc) {
1940       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
1941 
1942       // FIXME: It would be nicer if the keyword was ignored only for this
1943       // declarator. Otherwise we could get follow-up errors.
1944       D.getMutableDeclSpec().ClearStorageClassSpecs();
1945     }
1946     break;
1947   default:
1948     Diag(DS.getStorageClassSpecLoc(),
1949          diag::err_storageclass_invalid_for_member);
1950     D.getMutableDeclSpec().ClearStorageClassSpecs();
1951     break;
1952   }
1953 
1954   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1955                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
1956                       !isFunc);
1957 
1958   if (DS.isConstexprSpecified() && isInstField) {
1959     SemaDiagnosticBuilder B =
1960         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1961     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1962     if (InitStyle == ICIS_NoInit) {
1963       B << 0 << 0;
1964       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
1965         B << FixItHint::CreateRemoval(ConstexprLoc);
1966       else {
1967         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
1968         D.getMutableDeclSpec().ClearConstexprSpec();
1969         const char *PrevSpec;
1970         unsigned DiagID;
1971         bool Failed = D.getMutableDeclSpec().SetTypeQual(
1972             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
1973         (void)Failed;
1974         assert(!Failed && "Making a constexpr member const shouldn't fail");
1975       }
1976     } else {
1977       B << 1;
1978       const char *PrevSpec;
1979       unsigned DiagID;
1980       if (D.getMutableDeclSpec().SetStorageClassSpec(
1981           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
1982           Context.getPrintingPolicy())) {
1983         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
1984                "This is the only DeclSpec that should fail to be applied");
1985         B << 1;
1986       } else {
1987         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1988         isInstField = false;
1989       }
1990     }
1991   }
1992 
1993   NamedDecl *Member;
1994   if (isInstField) {
1995     CXXScopeSpec &SS = D.getCXXScopeSpec();
1996 
1997     // Data members must have identifiers for names.
1998     if (!Name.isIdentifier()) {
1999       Diag(Loc, diag::err_bad_variable_name)
2000         << Name;
2001       return 0;
2002     }
2003 
2004     IdentifierInfo *II = Name.getAsIdentifierInfo();
2005 
2006     // Member field could not be with "template" keyword.
2007     // So TemplateParameterLists should be empty in this case.
2008     if (TemplateParameterLists.size()) {
2009       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
2010       if (TemplateParams->size()) {
2011         // There is no such thing as a member field template.
2012         Diag(D.getIdentifierLoc(), diag::err_template_member)
2013             << II
2014             << SourceRange(TemplateParams->getTemplateLoc(),
2015                 TemplateParams->getRAngleLoc());
2016       } else {
2017         // There is an extraneous 'template<>' for this member.
2018         Diag(TemplateParams->getTemplateLoc(),
2019             diag::err_template_member_noparams)
2020             << II
2021             << SourceRange(TemplateParams->getTemplateLoc(),
2022                 TemplateParams->getRAngleLoc());
2023       }
2024       return 0;
2025     }
2026 
2027     if (SS.isSet() && !SS.isInvalid()) {
2028       // The user provided a superfluous scope specifier inside a class
2029       // definition:
2030       //
2031       // class X {
2032       //   int X::member;
2033       // };
2034       if (DeclContext *DC = computeDeclContext(SS, false))
2035         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
2036       else
2037         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2038           << Name << SS.getRange();
2039 
2040       SS.clear();
2041     }
2042 
2043     AttributeList *MSPropertyAttr =
2044       getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
2045     if (MSPropertyAttr) {
2046       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2047                                 BitWidth, InitStyle, AS, MSPropertyAttr);
2048       if (!Member)
2049         return 0;
2050       isInstField = false;
2051     } else {
2052       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2053                                 BitWidth, InitStyle, AS);
2054       assert(Member && "HandleField never returns null");
2055     }
2056   } else {
2057     assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2058 
2059     Member = HandleDeclarator(S, D, TemplateParameterLists);
2060     if (!Member)
2061       return 0;
2062 
2063     // Non-instance-fields can't have a bitfield.
2064     if (BitWidth) {
2065       if (Member->isInvalidDecl()) {
2066         // don't emit another diagnostic.
2067       } else if (isa<VarDecl>(Member)) {
2068         // C++ 9.6p3: A bit-field shall not be a static member.
2069         // "static member 'A' cannot be a bit-field"
2070         Diag(Loc, diag::err_static_not_bitfield)
2071           << Name << BitWidth->getSourceRange();
2072       } else if (isa<TypedefDecl>(Member)) {
2073         // "typedef member 'x' cannot be a bit-field"
2074         Diag(Loc, diag::err_typedef_not_bitfield)
2075           << Name << BitWidth->getSourceRange();
2076       } else {
2077         // A function typedef ("typedef int f(); f a;").
2078         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2079         Diag(Loc, diag::err_not_integral_type_bitfield)
2080           << Name << cast<ValueDecl>(Member)->getType()
2081           << BitWidth->getSourceRange();
2082       }
2083 
2084       BitWidth = 0;
2085       Member->setInvalidDecl();
2086     }
2087 
2088     Member->setAccess(AS);
2089 
2090     // If we have declared a member function template or static data member
2091     // template, set the access of the templated declaration as well.
2092     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2093       FunTmpl->getTemplatedDecl()->setAccess(AS);
2094     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2095       VarTmpl->getTemplatedDecl()->setAccess(AS);
2096   }
2097 
2098   if (VS.isOverrideSpecified())
2099     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
2100   if (VS.isFinalSpecified())
2101     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2102                                             VS.isFinalSpelledSealed()));
2103 
2104   if (VS.getLastLocation().isValid()) {
2105     // Update the end location of a method that has a virt-specifiers.
2106     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2107       MD->setRangeEnd(VS.getLastLocation());
2108   }
2109 
2110   CheckOverrideControl(Member);
2111 
2112   assert((Name || isInstField) && "No identifier for non-field ?");
2113 
2114   if (isInstField) {
2115     FieldDecl *FD = cast<FieldDecl>(Member);
2116     FieldCollector->Add(FD);
2117 
2118     if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2119                                  FD->getLocation())
2120           != DiagnosticsEngine::Ignored) {
2121       // Remember all explicit private FieldDecls that have a name, no side
2122       // effects and are not part of a dependent type declaration.
2123       if (!FD->isImplicit() && FD->getDeclName() &&
2124           FD->getAccess() == AS_private &&
2125           !FD->hasAttr<UnusedAttr>() &&
2126           !FD->getParent()->isDependentContext() &&
2127           !InitializationHasSideEffects(*FD))
2128         UnusedPrivateFields.insert(FD);
2129     }
2130   }
2131 
2132   return Member;
2133 }
2134 
2135 namespace {
2136   class UninitializedFieldVisitor
2137       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2138     Sema &S;
2139     // List of Decls to generate a warning on.  Also remove Decls that become
2140     // initialized.
2141     llvm::SmallPtrSet<ValueDecl*, 4> &Decls;
2142     // If non-null, add a note to the warning pointing back to the constructor.
2143     const CXXConstructorDecl *Constructor;
2144   public:
2145     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2146     UninitializedFieldVisitor(Sema &S,
2147                               llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
2148                               const CXXConstructorDecl *Constructor)
2149       : Inherited(S.Context), S(S), Decls(Decls),
2150         Constructor(Constructor) { }
2151 
2152     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) {
2153       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2154         return;
2155 
2156       // FieldME is the inner-most MemberExpr that is not an anonymous struct
2157       // or union.
2158       MemberExpr *FieldME = ME;
2159 
2160       Expr *Base = ME;
2161       while (isa<MemberExpr>(Base)) {
2162         ME = cast<MemberExpr>(Base);
2163 
2164         if (isa<VarDecl>(ME->getMemberDecl()))
2165           return;
2166 
2167         if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2168           if (!FD->isAnonymousStructOrUnion())
2169             FieldME = ME;
2170 
2171         Base = ME->getBase();
2172       }
2173 
2174       if (!isa<CXXThisExpr>(Base))
2175         return;
2176 
2177       ValueDecl* FoundVD = FieldME->getMemberDecl();
2178 
2179       if (!Decls.count(FoundVD))
2180         return;
2181 
2182       const bool IsReference = FoundVD->getType()->isReferenceType();
2183 
2184       // Prevent double warnings on use of unbounded references.
2185       if (IsReference != CheckReferenceOnly)
2186         return;
2187 
2188       unsigned diag = IsReference
2189           ? diag::warn_reference_field_is_uninit
2190           : diag::warn_field_is_uninit;
2191       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2192       if (Constructor)
2193         S.Diag(Constructor->getLocation(),
2194                diag::note_uninit_in_this_constructor)
2195           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2196 
2197     }
2198 
2199     void HandleValue(Expr *E) {
2200       E = E->IgnoreParens();
2201 
2202       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2203         HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
2204         return;
2205       }
2206 
2207       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2208         HandleValue(CO->getTrueExpr());
2209         HandleValue(CO->getFalseExpr());
2210         return;
2211       }
2212 
2213       if (BinaryConditionalOperator *BCO =
2214               dyn_cast<BinaryConditionalOperator>(E)) {
2215         HandleValue(BCO->getCommon());
2216         HandleValue(BCO->getFalseExpr());
2217         return;
2218       }
2219 
2220       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2221         switch (BO->getOpcode()) {
2222         default:
2223           return;
2224         case(BO_PtrMemD):
2225         case(BO_PtrMemI):
2226           HandleValue(BO->getLHS());
2227           return;
2228         case(BO_Comma):
2229           HandleValue(BO->getRHS());
2230           return;
2231         }
2232       }
2233     }
2234 
2235     void VisitMemberExpr(MemberExpr *ME) {
2236       // All uses of unbounded reference fields will warn.
2237       HandleMemberExpr(ME, true /*CheckReferenceOnly*/);
2238 
2239       Inherited::VisitMemberExpr(ME);
2240     }
2241 
2242     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2243       if (E->getCastKind() == CK_LValueToRValue)
2244         HandleValue(E->getSubExpr());
2245 
2246       Inherited::VisitImplicitCastExpr(E);
2247     }
2248 
2249     void VisitCXXConstructExpr(CXXConstructExpr *E) {
2250       if (E->getConstructor()->isCopyConstructor())
2251         if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0)))
2252           if (ICE->getCastKind() == CK_NoOp)
2253             if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr()))
2254               HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
2255 
2256       Inherited::VisitCXXConstructExpr(E);
2257     }
2258 
2259     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2260       Expr *Callee = E->getCallee();
2261       if (isa<MemberExpr>(Callee))
2262         HandleValue(Callee);
2263 
2264       Inherited::VisitCXXMemberCallExpr(E);
2265     }
2266 
2267     void VisitBinaryOperator(BinaryOperator *E) {
2268       // If a field assignment is detected, remove the field from the
2269       // uninitiailized field set.
2270       if (E->getOpcode() == BO_Assign)
2271         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2272           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2273             if (!FD->getType()->isReferenceType())
2274               Decls.erase(FD);
2275 
2276       Inherited::VisitBinaryOperator(E);
2277     }
2278   };
2279   static void CheckInitExprContainsUninitializedFields(
2280       Sema &S, Expr *E, llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
2281       const CXXConstructorDecl *Constructor) {
2282     if (Decls.size() == 0)
2283       return;
2284 
2285     if (!E)
2286       return;
2287 
2288     if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(E)) {
2289       E = Default->getExpr();
2290       if (!E)
2291         return;
2292       // In class initializers will point to the constructor.
2293       UninitializedFieldVisitor(S, Decls, Constructor).Visit(E);
2294     } else {
2295       UninitializedFieldVisitor(S, Decls, 0).Visit(E);
2296     }
2297   }
2298 
2299   // Diagnose value-uses of fields to initialize themselves, e.g.
2300   //   foo(foo)
2301   // where foo is not also a parameter to the constructor.
2302   // Also diagnose across field uninitialized use such as
2303   //   x(y), y(x)
2304   // TODO: implement -Wuninitialized and fold this into that framework.
2305   static void DiagnoseUninitializedFields(
2306       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2307 
2308     if (SemaRef.getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit,
2309                                                     Constructor->getLocation())
2310         == DiagnosticsEngine::Ignored) {
2311       return;
2312     }
2313 
2314     if (Constructor->isInvalidDecl())
2315       return;
2316 
2317     const CXXRecordDecl *RD = Constructor->getParent();
2318 
2319     // Holds fields that are uninitialized.
2320     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2321 
2322     // At the beginning, all fields are uninitialized.
2323     for (auto *I : RD->decls()) {
2324       if (auto *FD = dyn_cast<FieldDecl>(I)) {
2325         UninitializedFields.insert(FD);
2326       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
2327         UninitializedFields.insert(IFD->getAnonField());
2328       }
2329     }
2330 
2331     for (const auto *FieldInit : Constructor->inits()) {
2332       Expr *InitExpr = FieldInit->getInit();
2333 
2334       CheckInitExprContainsUninitializedFields(
2335           SemaRef, InitExpr, UninitializedFields, Constructor);
2336 
2337       if (FieldDecl *Field = FieldInit->getAnyMember())
2338         UninitializedFields.erase(Field);
2339     }
2340   }
2341 } // namespace
2342 
2343 /// \brief Enter a new C++ default initializer scope. After calling this, the
2344 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2345 /// parsing or instantiating the initializer failed.
2346 void Sema::ActOnStartCXXInClassMemberInitializer() {
2347   // Create a synthetic function scope to represent the call to the constructor
2348   // that notionally surrounds a use of this initializer.
2349   PushFunctionScope();
2350 }
2351 
2352 /// \brief This is invoked after parsing an in-class initializer for a
2353 /// non-static C++ class member, and after instantiating an in-class initializer
2354 /// in a class template. Such actions are deferred until the class is complete.
2355 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2356                                                   SourceLocation InitLoc,
2357                                                   Expr *InitExpr) {
2358   // Pop the notional constructor scope we created earlier.
2359   PopFunctionScopeInfo(0, D);
2360 
2361   FieldDecl *FD = cast<FieldDecl>(D);
2362   assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2363          "must set init style when field is created");
2364 
2365   if (!InitExpr) {
2366     FD->setInvalidDecl();
2367     FD->removeInClassInitializer();
2368     return;
2369   }
2370 
2371   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2372     FD->setInvalidDecl();
2373     FD->removeInClassInitializer();
2374     return;
2375   }
2376 
2377   ExprResult Init = InitExpr;
2378   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
2379     InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
2380     InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
2381         ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
2382         : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
2383     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2384     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
2385     if (Init.isInvalid()) {
2386       FD->setInvalidDecl();
2387       return;
2388     }
2389   }
2390 
2391   // C++11 [class.base.init]p7:
2392   //   The initialization of each base and member constitutes a
2393   //   full-expression.
2394   Init = ActOnFinishFullExpr(Init.take(), InitLoc);
2395   if (Init.isInvalid()) {
2396     FD->setInvalidDecl();
2397     return;
2398   }
2399 
2400   InitExpr = Init.release();
2401 
2402   FD->setInClassInitializer(InitExpr);
2403 }
2404 
2405 /// \brief Find the direct and/or virtual base specifiers that
2406 /// correspond to the given base type, for use in base initialization
2407 /// within a constructor.
2408 static bool FindBaseInitializer(Sema &SemaRef,
2409                                 CXXRecordDecl *ClassDecl,
2410                                 QualType BaseType,
2411                                 const CXXBaseSpecifier *&DirectBaseSpec,
2412                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
2413   // First, check for a direct base class.
2414   DirectBaseSpec = 0;
2415   for (const auto &Base : ClassDecl->bases()) {
2416     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
2417       // We found a direct base of this type. That's what we're
2418       // initializing.
2419       DirectBaseSpec = &Base;
2420       break;
2421     }
2422   }
2423 
2424   // Check for a virtual base class.
2425   // FIXME: We might be able to short-circuit this if we know in advance that
2426   // there are no virtual bases.
2427   VirtualBaseSpec = 0;
2428   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2429     // We haven't found a base yet; search the class hierarchy for a
2430     // virtual base class.
2431     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2432                        /*DetectVirtual=*/false);
2433     if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2434                               BaseType, Paths)) {
2435       for (CXXBasePaths::paths_iterator Path = Paths.begin();
2436            Path != Paths.end(); ++Path) {
2437         if (Path->back().Base->isVirtual()) {
2438           VirtualBaseSpec = Path->back().Base;
2439           break;
2440         }
2441       }
2442     }
2443   }
2444 
2445   return DirectBaseSpec || VirtualBaseSpec;
2446 }
2447 
2448 /// \brief Handle a C++ member initializer using braced-init-list syntax.
2449 MemInitResult
2450 Sema::ActOnMemInitializer(Decl *ConstructorD,
2451                           Scope *S,
2452                           CXXScopeSpec &SS,
2453                           IdentifierInfo *MemberOrBase,
2454                           ParsedType TemplateTypeTy,
2455                           const DeclSpec &DS,
2456                           SourceLocation IdLoc,
2457                           Expr *InitList,
2458                           SourceLocation EllipsisLoc) {
2459   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2460                              DS, IdLoc, InitList,
2461                              EllipsisLoc);
2462 }
2463 
2464 /// \brief Handle a C++ member initializer using parentheses syntax.
2465 MemInitResult
2466 Sema::ActOnMemInitializer(Decl *ConstructorD,
2467                           Scope *S,
2468                           CXXScopeSpec &SS,
2469                           IdentifierInfo *MemberOrBase,
2470                           ParsedType TemplateTypeTy,
2471                           const DeclSpec &DS,
2472                           SourceLocation IdLoc,
2473                           SourceLocation LParenLoc,
2474                           ArrayRef<Expr *> Args,
2475                           SourceLocation RParenLoc,
2476                           SourceLocation EllipsisLoc) {
2477   Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2478                                            Args, RParenLoc);
2479   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2480                              DS, IdLoc, List, EllipsisLoc);
2481 }
2482 
2483 namespace {
2484 
2485 // Callback to only accept typo corrections that can be a valid C++ member
2486 // intializer: either a non-static field member or a base class.
2487 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2488 public:
2489   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2490       : ClassDecl(ClassDecl) {}
2491 
2492   bool ValidateCandidate(const TypoCorrection &candidate) override {
2493     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2494       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2495         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2496       return isa<TypeDecl>(ND);
2497     }
2498     return false;
2499   }
2500 
2501 private:
2502   CXXRecordDecl *ClassDecl;
2503 };
2504 
2505 }
2506 
2507 /// \brief Handle a C++ member initializer.
2508 MemInitResult
2509 Sema::BuildMemInitializer(Decl *ConstructorD,
2510                           Scope *S,
2511                           CXXScopeSpec &SS,
2512                           IdentifierInfo *MemberOrBase,
2513                           ParsedType TemplateTypeTy,
2514                           const DeclSpec &DS,
2515                           SourceLocation IdLoc,
2516                           Expr *Init,
2517                           SourceLocation EllipsisLoc) {
2518   if (!ConstructorD)
2519     return true;
2520 
2521   AdjustDeclIfTemplate(ConstructorD);
2522 
2523   CXXConstructorDecl *Constructor
2524     = dyn_cast<CXXConstructorDecl>(ConstructorD);
2525   if (!Constructor) {
2526     // The user wrote a constructor initializer on a function that is
2527     // not a C++ constructor. Ignore the error for now, because we may
2528     // have more member initializers coming; we'll diagnose it just
2529     // once in ActOnMemInitializers.
2530     return true;
2531   }
2532 
2533   CXXRecordDecl *ClassDecl = Constructor->getParent();
2534 
2535   // C++ [class.base.init]p2:
2536   //   Names in a mem-initializer-id are looked up in the scope of the
2537   //   constructor's class and, if not found in that scope, are looked
2538   //   up in the scope containing the constructor's definition.
2539   //   [Note: if the constructor's class contains a member with the
2540   //   same name as a direct or virtual base class of the class, a
2541   //   mem-initializer-id naming the member or base class and composed
2542   //   of a single identifier refers to the class member. A
2543   //   mem-initializer-id for the hidden base class may be specified
2544   //   using a qualified name. ]
2545   if (!SS.getScopeRep() && !TemplateTypeTy) {
2546     // Look for a member, first.
2547     DeclContext::lookup_result Result
2548       = ClassDecl->lookup(MemberOrBase);
2549     if (!Result.empty()) {
2550       ValueDecl *Member;
2551       if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2552           (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
2553         if (EllipsisLoc.isValid())
2554           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
2555             << MemberOrBase
2556             << SourceRange(IdLoc, Init->getSourceRange().getEnd());
2557 
2558         return BuildMemberInitializer(Member, Init, IdLoc);
2559       }
2560     }
2561   }
2562   // It didn't name a member, so see if it names a class.
2563   QualType BaseType;
2564   TypeSourceInfo *TInfo = 0;
2565 
2566   if (TemplateTypeTy) {
2567     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
2568   } else if (DS.getTypeSpecType() == TST_decltype) {
2569     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
2570   } else {
2571     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2572     LookupParsedName(R, S, &SS);
2573 
2574     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2575     if (!TyD) {
2576       if (R.isAmbiguous()) return true;
2577 
2578       // We don't want access-control diagnostics here.
2579       R.suppressDiagnostics();
2580 
2581       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2582         bool NotUnknownSpecialization = false;
2583         DeclContext *DC = computeDeclContext(SS, false);
2584         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2585           NotUnknownSpecialization = !Record->hasAnyDependentBases();
2586 
2587         if (!NotUnknownSpecialization) {
2588           // When the scope specifier can refer to a member of an unknown
2589           // specialization, we take it as a type name.
2590           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2591                                        SS.getWithLocInContext(Context),
2592                                        *MemberOrBase, IdLoc);
2593           if (BaseType.isNull())
2594             return true;
2595 
2596           R.clear();
2597           R.setLookupName(MemberOrBase);
2598         }
2599       }
2600 
2601       // If no results were found, try to correct typos.
2602       TypoCorrection Corr;
2603       MemInitializerValidatorCCC Validator(ClassDecl);
2604       if (R.empty() && BaseType.isNull() &&
2605           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2606                               Validator, ClassDecl))) {
2607         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
2608           // We have found a non-static data member with a similar
2609           // name to what was typed; complain and initialize that
2610           // member.
2611           diagnoseTypo(Corr,
2612                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
2613                          << MemberOrBase << true);
2614           return BuildMemberInitializer(Member, Init, IdLoc);
2615         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
2616           const CXXBaseSpecifier *DirectBaseSpec;
2617           const CXXBaseSpecifier *VirtualBaseSpec;
2618           if (FindBaseInitializer(*this, ClassDecl,
2619                                   Context.getTypeDeclType(Type),
2620                                   DirectBaseSpec, VirtualBaseSpec)) {
2621             // We have found a direct or virtual base class with a
2622             // similar name to what was typed; complain and initialize
2623             // that base class.
2624             diagnoseTypo(Corr,
2625                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
2626                            << MemberOrBase << false,
2627                          PDiag() /*Suppress note, we provide our own.*/);
2628 
2629             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2630                                                               : VirtualBaseSpec;
2631             Diag(BaseSpec->getLocStart(),
2632                  diag::note_base_class_specified_here)
2633               << BaseSpec->getType()
2634               << BaseSpec->getSourceRange();
2635 
2636             TyD = Type;
2637           }
2638         }
2639       }
2640 
2641       if (!TyD && BaseType.isNull()) {
2642         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
2643           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
2644         return true;
2645       }
2646     }
2647 
2648     if (BaseType.isNull()) {
2649       BaseType = Context.getTypeDeclType(TyD);
2650       if (SS.isSet())
2651         // FIXME: preserve source range information
2652         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2653                                              BaseType);
2654     }
2655   }
2656 
2657   if (!TInfo)
2658     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
2659 
2660   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
2661 }
2662 
2663 /// Checks a member initializer expression for cases where reference (or
2664 /// pointer) members are bound to by-value parameters (or their addresses).
2665 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2666                                                Expr *Init,
2667                                                SourceLocation IdLoc) {
2668   QualType MemberTy = Member->getType();
2669 
2670   // We only handle pointers and references currently.
2671   // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2672   if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2673     return;
2674 
2675   const bool IsPointer = MemberTy->isPointerType();
2676   if (IsPointer) {
2677     if (const UnaryOperator *Op
2678           = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2679       // The only case we're worried about with pointers requires taking the
2680       // address.
2681       if (Op->getOpcode() != UO_AddrOf)
2682         return;
2683 
2684       Init = Op->getSubExpr();
2685     } else {
2686       // We only handle address-of expression initializers for pointers.
2687       return;
2688     }
2689   }
2690 
2691   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2692     // We only warn when referring to a non-reference parameter declaration.
2693     const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2694     if (!Parameter || Parameter->getType()->isReferenceType())
2695       return;
2696 
2697     S.Diag(Init->getExprLoc(),
2698            IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2699                      : diag::warn_bind_ref_member_to_parameter)
2700       << Member << Parameter << Init->getSourceRange();
2701   } else {
2702     // Other initializers are fine.
2703     return;
2704   }
2705 
2706   S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2707     << (unsigned)IsPointer;
2708 }
2709 
2710 MemInitResult
2711 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
2712                              SourceLocation IdLoc) {
2713   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2714   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2715   assert((DirectMember || IndirectMember) &&
2716          "Member must be a FieldDecl or IndirectFieldDecl");
2717 
2718   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2719     return true;
2720 
2721   if (Member->isInvalidDecl())
2722     return true;
2723 
2724   MultiExprArg Args;
2725   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2726     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2727   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2728     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
2729   } else {
2730     // Template instantiation doesn't reconstruct ParenListExprs for us.
2731     Args = Init;
2732   }
2733 
2734   SourceRange InitRange = Init->getSourceRange();
2735 
2736   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
2737     // Can't check initialization for a member of dependent type or when
2738     // any of the arguments are type-dependent expressions.
2739     DiscardCleanupsInEvaluationContext();
2740   } else {
2741     bool InitList = false;
2742     if (isa<InitListExpr>(Init)) {
2743       InitList = true;
2744       Args = Init;
2745     }
2746 
2747     // Initialize the member.
2748     InitializedEntity MemberEntity =
2749       DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2750                    : InitializedEntity::InitializeMember(IndirectMember, 0);
2751     InitializationKind Kind =
2752       InitList ? InitializationKind::CreateDirectList(IdLoc)
2753                : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2754                                                   InitRange.getEnd());
2755 
2756     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2757     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
2758     if (MemberInit.isInvalid())
2759       return true;
2760 
2761     CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2762 
2763     // C++11 [class.base.init]p7:
2764     //   The initialization of each base and member constitutes a
2765     //   full-expression.
2766     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
2767     if (MemberInit.isInvalid())
2768       return true;
2769 
2770     Init = MemberInit.get();
2771   }
2772 
2773   if (DirectMember) {
2774     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2775                                             InitRange.getBegin(), Init,
2776                                             InitRange.getEnd());
2777   } else {
2778     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2779                                             InitRange.getBegin(), Init,
2780                                             InitRange.getEnd());
2781   }
2782 }
2783 
2784 MemInitResult
2785 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
2786                                  CXXRecordDecl *ClassDecl) {
2787   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
2788   if (!LangOpts.CPlusPlus11)
2789     return Diag(NameLoc, diag::err_delegating_ctor)
2790       << TInfo->getTypeLoc().getLocalSourceRange();
2791   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
2792 
2793   bool InitList = true;
2794   MultiExprArg Args = Init;
2795   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2796     InitList = false;
2797     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2798   }
2799 
2800   SourceRange InitRange = Init->getSourceRange();
2801   // Initialize the object.
2802   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2803                                      QualType(ClassDecl->getTypeForDecl(), 0));
2804   InitializationKind Kind =
2805     InitList ? InitializationKind::CreateDirectList(NameLoc)
2806              : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2807                                                 InitRange.getEnd());
2808   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
2809   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2810                                               Args, 0);
2811   if (DelegationInit.isInvalid())
2812     return true;
2813 
2814   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2815          "Delegating constructor with no target?");
2816 
2817   // C++11 [class.base.init]p7:
2818   //   The initialization of each base and member constitutes a
2819   //   full-expression.
2820   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2821                                        InitRange.getBegin());
2822   if (DelegationInit.isInvalid())
2823     return true;
2824 
2825   // If we are in a dependent context, template instantiation will
2826   // perform this type-checking again. Just save the arguments that we
2827   // received in a ParenListExpr.
2828   // FIXME: This isn't quite ideal, since our ASTs don't capture all
2829   // of the information that we have about the base
2830   // initializer. However, deconstructing the ASTs is a dicey process,
2831   // and this approach is far more likely to get the corner cases right.
2832   if (CurContext->isDependentContext())
2833     DelegationInit = Owned(Init);
2834 
2835   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
2836                                           DelegationInit.takeAs<Expr>(),
2837                                           InitRange.getEnd());
2838 }
2839 
2840 MemInitResult
2841 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
2842                            Expr *Init, CXXRecordDecl *ClassDecl,
2843                            SourceLocation EllipsisLoc) {
2844   SourceLocation BaseLoc
2845     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
2846 
2847   if (!BaseType->isDependentType() && !BaseType->isRecordType())
2848     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2849              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2850 
2851   // C++ [class.base.init]p2:
2852   //   [...] Unless the mem-initializer-id names a nonstatic data
2853   //   member of the constructor's class or a direct or virtual base
2854   //   of that class, the mem-initializer is ill-formed. A
2855   //   mem-initializer-list can initialize a base class using any
2856   //   name that denotes that base class type.
2857   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
2858 
2859   SourceRange InitRange = Init->getSourceRange();
2860   if (EllipsisLoc.isValid()) {
2861     // This is a pack expansion.
2862     if (!BaseType->containsUnexpandedParameterPack())  {
2863       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2864         << SourceRange(BaseLoc, InitRange.getEnd());
2865 
2866       EllipsisLoc = SourceLocation();
2867     }
2868   } else {
2869     // Check for any unexpanded parameter packs.
2870     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2871       return true;
2872 
2873     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2874       return true;
2875   }
2876 
2877   // Check for direct and virtual base classes.
2878   const CXXBaseSpecifier *DirectBaseSpec = 0;
2879   const CXXBaseSpecifier *VirtualBaseSpec = 0;
2880   if (!Dependent) {
2881     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2882                                        BaseType))
2883       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
2884 
2885     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2886                         VirtualBaseSpec);
2887 
2888     // C++ [base.class.init]p2:
2889     // Unless the mem-initializer-id names a nonstatic data member of the
2890     // constructor's class or a direct or virtual base of that class, the
2891     // mem-initializer is ill-formed.
2892     if (!DirectBaseSpec && !VirtualBaseSpec) {
2893       // If the class has any dependent bases, then it's possible that
2894       // one of those types will resolve to the same type as
2895       // BaseType. Therefore, just treat this as a dependent base
2896       // class initialization.  FIXME: Should we try to check the
2897       // initialization anyway? It seems odd.
2898       if (ClassDecl->hasAnyDependentBases())
2899         Dependent = true;
2900       else
2901         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2902           << BaseType << Context.getTypeDeclType(ClassDecl)
2903           << BaseTInfo->getTypeLoc().getLocalSourceRange();
2904     }
2905   }
2906 
2907   if (Dependent) {
2908     DiscardCleanupsInEvaluationContext();
2909 
2910     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2911                                             /*IsVirtual=*/false,
2912                                             InitRange.getBegin(), Init,
2913                                             InitRange.getEnd(), EllipsisLoc);
2914   }
2915 
2916   // C++ [base.class.init]p2:
2917   //   If a mem-initializer-id is ambiguous because it designates both
2918   //   a direct non-virtual base class and an inherited virtual base
2919   //   class, the mem-initializer is ill-formed.
2920   if (DirectBaseSpec && VirtualBaseSpec)
2921     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
2922       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2923 
2924   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
2925   if (!BaseSpec)
2926     BaseSpec = VirtualBaseSpec;
2927 
2928   // Initialize the base.
2929   bool InitList = true;
2930   MultiExprArg Args = Init;
2931   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2932     InitList = false;
2933     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2934   }
2935 
2936   InitializedEntity BaseEntity =
2937     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2938   InitializationKind Kind =
2939     InitList ? InitializationKind::CreateDirectList(BaseLoc)
2940              : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2941                                                 InitRange.getEnd());
2942   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2943   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
2944   if (BaseInit.isInvalid())
2945     return true;
2946 
2947   // C++11 [class.base.init]p7:
2948   //   The initialization of each base and member constitutes a
2949   //   full-expression.
2950   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
2951   if (BaseInit.isInvalid())
2952     return true;
2953 
2954   // If we are in a dependent context, template instantiation will
2955   // perform this type-checking again. Just save the arguments that we
2956   // received in a ParenListExpr.
2957   // FIXME: This isn't quite ideal, since our ASTs don't capture all
2958   // of the information that we have about the base
2959   // initializer. However, deconstructing the ASTs is a dicey process,
2960   // and this approach is far more likely to get the corner cases right.
2961   if (CurContext->isDependentContext())
2962     BaseInit = Owned(Init);
2963 
2964   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2965                                           BaseSpec->isVirtual(),
2966                                           InitRange.getBegin(),
2967                                           BaseInit.takeAs<Expr>(),
2968                                           InitRange.getEnd(), EllipsisLoc);
2969 }
2970 
2971 // Create a static_cast\<T&&>(expr).
2972 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2973   if (T.isNull()) T = E->getType();
2974   QualType TargetType = SemaRef.BuildReferenceType(
2975       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
2976   SourceLocation ExprLoc = E->getLocStart();
2977   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2978       TargetType, ExprLoc);
2979 
2980   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2981                                    SourceRange(ExprLoc, ExprLoc),
2982                                    E->getSourceRange()).take();
2983 }
2984 
2985 /// ImplicitInitializerKind - How an implicit base or member initializer should
2986 /// initialize its base or member.
2987 enum ImplicitInitializerKind {
2988   IIK_Default,
2989   IIK_Copy,
2990   IIK_Move,
2991   IIK_Inherit
2992 };
2993 
2994 static bool
2995 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2996                              ImplicitInitializerKind ImplicitInitKind,
2997                              CXXBaseSpecifier *BaseSpec,
2998                              bool IsInheritedVirtualBase,
2999                              CXXCtorInitializer *&CXXBaseInit) {
3000   InitializedEntity InitEntity
3001     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3002                                         IsInheritedVirtualBase);
3003 
3004   ExprResult BaseInit;
3005 
3006   switch (ImplicitInitKind) {
3007   case IIK_Inherit: {
3008     const CXXRecordDecl *Inherited =
3009         Constructor->getInheritedConstructor()->getParent();
3010     const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3011     if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3012       // C++11 [class.inhctor]p8:
3013       //   Each expression in the expression-list is of the form
3014       //   static_cast<T&&>(p), where p is the name of the corresponding
3015       //   constructor parameter and T is the declared type of p.
3016       SmallVector<Expr*, 16> Args;
3017       for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3018         ParmVarDecl *PD = Constructor->getParamDecl(I);
3019         ExprResult ArgExpr =
3020             SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3021                                      VK_LValue, SourceLocation());
3022         if (ArgExpr.isInvalid())
3023           return true;
3024         Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
3025       }
3026 
3027       InitializationKind InitKind = InitializationKind::CreateDirect(
3028           Constructor->getLocation(), SourceLocation(), SourceLocation());
3029       InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
3030       BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3031       break;
3032     }
3033   }
3034   // Fall through.
3035   case IIK_Default: {
3036     InitializationKind InitKind
3037       = InitializationKind::CreateDefault(Constructor->getLocation());
3038     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3039     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3040     break;
3041   }
3042 
3043   case IIK_Move:
3044   case IIK_Copy: {
3045     bool Moving = ImplicitInitKind == IIK_Move;
3046     ParmVarDecl *Param = Constructor->getParamDecl(0);
3047     QualType ParamType = Param->getType().getNonReferenceType();
3048 
3049     Expr *CopyCtorArg =
3050       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3051                           SourceLocation(), Param, false,
3052                           Constructor->getLocation(), ParamType,
3053                           VK_LValue, 0);
3054 
3055     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3056 
3057     // Cast to the base class to avoid ambiguities.
3058     QualType ArgTy =
3059       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3060                                        ParamType.getQualifiers());
3061 
3062     if (Moving) {
3063       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3064     }
3065 
3066     CXXCastPath BasePath;
3067     BasePath.push_back(BaseSpec);
3068     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3069                                             CK_UncheckedDerivedToBase,
3070                                             Moving ? VK_XValue : VK_LValue,
3071                                             &BasePath).take();
3072 
3073     InitializationKind InitKind
3074       = InitializationKind::CreateDirect(Constructor->getLocation(),
3075                                          SourceLocation(), SourceLocation());
3076     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3077     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
3078     break;
3079   }
3080   }
3081 
3082   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
3083   if (BaseInit.isInvalid())
3084     return true;
3085 
3086   CXXBaseInit =
3087     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3088                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3089                                                         SourceLocation()),
3090                                              BaseSpec->isVirtual(),
3091                                              SourceLocation(),
3092                                              BaseInit.takeAs<Expr>(),
3093                                              SourceLocation(),
3094                                              SourceLocation());
3095 
3096   return false;
3097 }
3098 
3099 static bool RefersToRValueRef(Expr *MemRef) {
3100   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3101   return Referenced->getType()->isRValueReferenceType();
3102 }
3103 
3104 static bool
3105 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3106                                ImplicitInitializerKind ImplicitInitKind,
3107                                FieldDecl *Field, IndirectFieldDecl *Indirect,
3108                                CXXCtorInitializer *&CXXMemberInit) {
3109   if (Field->isInvalidDecl())
3110     return true;
3111 
3112   SourceLocation Loc = Constructor->getLocation();
3113 
3114   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3115     bool Moving = ImplicitInitKind == IIK_Move;
3116     ParmVarDecl *Param = Constructor->getParamDecl(0);
3117     QualType ParamType = Param->getType().getNonReferenceType();
3118 
3119     // Suppress copying zero-width bitfields.
3120     if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3121       return false;
3122 
3123     Expr *MemberExprBase =
3124       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3125                           SourceLocation(), Param, false,
3126                           Loc, ParamType, VK_LValue, 0);
3127 
3128     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3129 
3130     if (Moving) {
3131       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3132     }
3133 
3134     // Build a reference to this field within the parameter.
3135     CXXScopeSpec SS;
3136     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3137                               Sema::LookupMemberName);
3138     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3139                                   : cast<ValueDecl>(Field), AS_public);
3140     MemberLookup.resolveKind();
3141     ExprResult CtorArg
3142       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
3143                                          ParamType, Loc,
3144                                          /*IsArrow=*/false,
3145                                          SS,
3146                                          /*TemplateKWLoc=*/SourceLocation(),
3147                                          /*FirstQualifierInScope=*/0,
3148                                          MemberLookup,
3149                                          /*TemplateArgs=*/0);
3150     if (CtorArg.isInvalid())
3151       return true;
3152 
3153     // C++11 [class.copy]p15:
3154     //   - if a member m has rvalue reference type T&&, it is direct-initialized
3155     //     with static_cast<T&&>(x.m);
3156     if (RefersToRValueRef(CtorArg.get())) {
3157       CtorArg = CastForMoving(SemaRef, CtorArg.take());
3158     }
3159 
3160     // When the field we are copying is an array, create index variables for
3161     // each dimension of the array. We use these index variables to subscript
3162     // the source array, and other clients (e.g., CodeGen) will perform the
3163     // necessary iteration with these index variables.
3164     SmallVector<VarDecl *, 4> IndexVariables;
3165     QualType BaseType = Field->getType();
3166     QualType SizeType = SemaRef.Context.getSizeType();
3167     bool InitializingArray = false;
3168     while (const ConstantArrayType *Array
3169                           = SemaRef.Context.getAsConstantArrayType(BaseType)) {
3170       InitializingArray = true;
3171       // Create the iteration variable for this array index.
3172       IdentifierInfo *IterationVarName = 0;
3173       {
3174         SmallString<8> Str;
3175         llvm::raw_svector_ostream OS(Str);
3176         OS << "__i" << IndexVariables.size();
3177         IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3178       }
3179       VarDecl *IterationVar
3180         = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
3181                           IterationVarName, SizeType,
3182                         SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
3183                           SC_None);
3184       IndexVariables.push_back(IterationVar);
3185 
3186       // Create a reference to the iteration variable.
3187       ExprResult IterationVarRef
3188         = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
3189       assert(!IterationVarRef.isInvalid() &&
3190              "Reference to invented variable cannot fail!");
3191       IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3192       assert(!IterationVarRef.isInvalid() &&
3193              "Conversion of invented variable cannot fail!");
3194 
3195       // Subscript the array with this iteration variable.
3196       CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
3197                                                         IterationVarRef.take(),
3198                                                         Loc);
3199       if (CtorArg.isInvalid())
3200         return true;
3201 
3202       BaseType = Array->getElementType();
3203     }
3204 
3205     // The array subscript expression is an lvalue, which is wrong for moving.
3206     if (Moving && InitializingArray)
3207       CtorArg = CastForMoving(SemaRef, CtorArg.take());
3208 
3209     // Construct the entity that we will be initializing. For an array, this
3210     // will be first element in the array, which may require several levels
3211     // of array-subscript entities.
3212     SmallVector<InitializedEntity, 4> Entities;
3213     Entities.reserve(1 + IndexVariables.size());
3214     if (Indirect)
3215       Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3216     else
3217       Entities.push_back(InitializedEntity::InitializeMember(Field));
3218     for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3219       Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3220                                                               0,
3221                                                               Entities.back()));
3222 
3223     // Direct-initialize to use the copy constructor.
3224     InitializationKind InitKind =
3225       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3226 
3227     Expr *CtorArgE = CtorArg.takeAs<Expr>();
3228     InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
3229 
3230     ExprResult MemberInit
3231       = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
3232                         MultiExprArg(&CtorArgE, 1));
3233     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3234     if (MemberInit.isInvalid())
3235       return true;
3236 
3237     if (Indirect) {
3238       assert(IndexVariables.size() == 0 &&
3239              "Indirect field improperly initialized");
3240       CXXMemberInit
3241         = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3242                                                    Loc, Loc,
3243                                                    MemberInit.takeAs<Expr>(),
3244                                                    Loc);
3245     } else
3246       CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3247                                                  Loc, MemberInit.takeAs<Expr>(),
3248                                                  Loc,
3249                                                  IndexVariables.data(),
3250                                                  IndexVariables.size());
3251     return false;
3252   }
3253 
3254   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3255          "Unhandled implicit init kind!");
3256 
3257   QualType FieldBaseElementType =
3258     SemaRef.Context.getBaseElementType(Field->getType());
3259 
3260   if (FieldBaseElementType->isRecordType()) {
3261     InitializedEntity InitEntity
3262       = Indirect? InitializedEntity::InitializeMember(Indirect)
3263                 : InitializedEntity::InitializeMember(Field);
3264     InitializationKind InitKind =
3265       InitializationKind::CreateDefault(Loc);
3266 
3267     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3268     ExprResult MemberInit =
3269       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3270 
3271     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3272     if (MemberInit.isInvalid())
3273       return true;
3274 
3275     if (Indirect)
3276       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3277                                                                Indirect, Loc,
3278                                                                Loc,
3279                                                                MemberInit.get(),
3280                                                                Loc);
3281     else
3282       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3283                                                                Field, Loc, Loc,
3284                                                                MemberInit.get(),
3285                                                                Loc);
3286     return false;
3287   }
3288 
3289   if (!Field->getParent()->isUnion()) {
3290     if (FieldBaseElementType->isReferenceType()) {
3291       SemaRef.Diag(Constructor->getLocation(),
3292                    diag::err_uninitialized_member_in_ctor)
3293       << (int)Constructor->isImplicit()
3294       << SemaRef.Context.getTagDeclType(Constructor->getParent())
3295       << 0 << Field->getDeclName();
3296       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3297       return true;
3298     }
3299 
3300     if (FieldBaseElementType.isConstQualified()) {
3301       SemaRef.Diag(Constructor->getLocation(),
3302                    diag::err_uninitialized_member_in_ctor)
3303       << (int)Constructor->isImplicit()
3304       << SemaRef.Context.getTagDeclType(Constructor->getParent())
3305       << 1 << Field->getDeclName();
3306       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3307       return true;
3308     }
3309   }
3310 
3311   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
3312       FieldBaseElementType->isObjCRetainableType() &&
3313       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3314       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
3315     // ARC:
3316     //   Default-initialize Objective-C pointers to NULL.
3317     CXXMemberInit
3318       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3319                                                  Loc, Loc,
3320                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3321                                                  Loc);
3322     return false;
3323   }
3324 
3325   // Nothing to initialize.
3326   CXXMemberInit = 0;
3327   return false;
3328 }
3329 
3330 namespace {
3331 struct BaseAndFieldInfo {
3332   Sema &S;
3333   CXXConstructorDecl *Ctor;
3334   bool AnyErrorsInInits;
3335   ImplicitInitializerKind IIK;
3336   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
3337   SmallVector<CXXCtorInitializer*, 8> AllToInit;
3338   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
3339 
3340   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3341     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
3342     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3343     if (Generated && Ctor->isCopyConstructor())
3344       IIK = IIK_Copy;
3345     else if (Generated && Ctor->isMoveConstructor())
3346       IIK = IIK_Move;
3347     else if (Ctor->getInheritedConstructor())
3348       IIK = IIK_Inherit;
3349     else
3350       IIK = IIK_Default;
3351   }
3352 
3353   bool isImplicitCopyOrMove() const {
3354     switch (IIK) {
3355     case IIK_Copy:
3356     case IIK_Move:
3357       return true;
3358 
3359     case IIK_Default:
3360     case IIK_Inherit:
3361       return false;
3362     }
3363 
3364     llvm_unreachable("Invalid ImplicitInitializerKind!");
3365   }
3366 
3367   bool addFieldInitializer(CXXCtorInitializer *Init) {
3368     AllToInit.push_back(Init);
3369 
3370     // Check whether this initializer makes the field "used".
3371     if (Init->getInit()->HasSideEffects(S.Context))
3372       S.UnusedPrivateFields.remove(Init->getAnyMember());
3373 
3374     return false;
3375   }
3376 
3377   bool isInactiveUnionMember(FieldDecl *Field) {
3378     RecordDecl *Record = Field->getParent();
3379     if (!Record->isUnion())
3380       return false;
3381 
3382     if (FieldDecl *Active =
3383             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
3384       return Active != Field->getCanonicalDecl();
3385 
3386     // In an implicit copy or move constructor, ignore any in-class initializer.
3387     if (isImplicitCopyOrMove())
3388       return true;
3389 
3390     // If there's no explicit initialization, the field is active only if it
3391     // has an in-class initializer...
3392     if (Field->hasInClassInitializer())
3393       return false;
3394     // ... or it's an anonymous struct or union whose class has an in-class
3395     // initializer.
3396     if (!Field->isAnonymousStructOrUnion())
3397       return true;
3398     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3399     return !FieldRD->hasInClassInitializer();
3400   }
3401 
3402   /// \brief Determine whether the given field is, or is within, a union member
3403   /// that is inactive (because there was an initializer given for a different
3404   /// member of the union, or because the union was not initialized at all).
3405   bool isWithinInactiveUnionMember(FieldDecl *Field,
3406                                    IndirectFieldDecl *Indirect) {
3407     if (!Indirect)
3408       return isInactiveUnionMember(Field);
3409 
3410     for (auto *C : Indirect->chain()) {
3411       FieldDecl *Field = dyn_cast<FieldDecl>(C);
3412       if (Field && isInactiveUnionMember(Field))
3413         return true;
3414     }
3415     return false;
3416   }
3417 };
3418 }
3419 
3420 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
3421 /// array type.
3422 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3423   if (T->isIncompleteArrayType())
3424     return true;
3425 
3426   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3427     if (!ArrayT->getSize())
3428       return true;
3429 
3430     T = ArrayT->getElementType();
3431   }
3432 
3433   return false;
3434 }
3435 
3436 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
3437                                     FieldDecl *Field,
3438                                     IndirectFieldDecl *Indirect = 0) {
3439   if (Field->isInvalidDecl())
3440     return false;
3441 
3442   // Overwhelmingly common case: we have a direct initializer for this field.
3443   if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3444     return Info.addFieldInitializer(Init);
3445 
3446   // C++11 [class.base.init]p8:
3447   //   if the entity is a non-static data member that has a
3448   //   brace-or-equal-initializer and either
3449   //   -- the constructor's class is a union and no other variant member of that
3450   //      union is designated by a mem-initializer-id or
3451   //   -- the constructor's class is not a union, and, if the entity is a member
3452   //      of an anonymous union, no other member of that union is designated by
3453   //      a mem-initializer-id,
3454   //   the entity is initialized as specified in [dcl.init].
3455   //
3456   // We also apply the same rules to handle anonymous structs within anonymous
3457   // unions.
3458   if (Info.isWithinInactiveUnionMember(Field, Indirect))
3459     return false;
3460 
3461   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
3462     Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3463                                            Info.Ctor->getLocation(), Field);
3464     CXXCtorInitializer *Init;
3465     if (Indirect)
3466       Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3467                                                       SourceLocation(),
3468                                                       SourceLocation(), DIE,
3469                                                       SourceLocation());
3470     else
3471       Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3472                                                       SourceLocation(),
3473                                                       SourceLocation(), DIE,
3474                                                       SourceLocation());
3475     return Info.addFieldInitializer(Init);
3476   }
3477 
3478   // Don't initialize incomplete or zero-length arrays.
3479   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3480     return false;
3481 
3482   // Don't try to build an implicit initializer if there were semantic
3483   // errors in any of the initializers (and therefore we might be
3484   // missing some that the user actually wrote).
3485   if (Info.AnyErrorsInInits)
3486     return false;
3487 
3488   CXXCtorInitializer *Init = 0;
3489   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3490                                      Indirect, Init))
3491     return true;
3492 
3493   if (!Init)
3494     return false;
3495 
3496   return Info.addFieldInitializer(Init);
3497 }
3498 
3499 bool
3500 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3501                                CXXCtorInitializer *Initializer) {
3502   assert(Initializer->isDelegatingInitializer());
3503   Constructor->setNumCtorInitializers(1);
3504   CXXCtorInitializer **initializer =
3505     new (Context) CXXCtorInitializer*[1];
3506   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3507   Constructor->setCtorInitializers(initializer);
3508 
3509   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
3510     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
3511     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3512   }
3513 
3514   DelegatingCtorDecls.push_back(Constructor);
3515 
3516   return false;
3517 }
3518 
3519 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3520                                ArrayRef<CXXCtorInitializer *> Initializers) {
3521   if (Constructor->isDependentContext()) {
3522     // Just store the initializers as written, they will be checked during
3523     // instantiation.
3524     if (!Initializers.empty()) {
3525       Constructor->setNumCtorInitializers(Initializers.size());
3526       CXXCtorInitializer **baseOrMemberInitializers =
3527         new (Context) CXXCtorInitializer*[Initializers.size()];
3528       memcpy(baseOrMemberInitializers, Initializers.data(),
3529              Initializers.size() * sizeof(CXXCtorInitializer*));
3530       Constructor->setCtorInitializers(baseOrMemberInitializers);
3531     }
3532 
3533     // Let template instantiation know whether we had errors.
3534     if (AnyErrors)
3535       Constructor->setInvalidDecl();
3536 
3537     return false;
3538   }
3539 
3540   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
3541 
3542   // We need to build the initializer AST according to order of construction
3543   // and not what user specified in the Initializers list.
3544   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
3545   if (!ClassDecl)
3546     return true;
3547 
3548   bool HadError = false;
3549 
3550   for (unsigned i = 0; i < Initializers.size(); i++) {
3551     CXXCtorInitializer *Member = Initializers[i];
3552 
3553     if (Member->isBaseInitializer())
3554       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
3555     else {
3556       Info.AllBaseFields[Member->getAnyMember()] = Member;
3557 
3558       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
3559         for (auto *C : F->chain()) {
3560           FieldDecl *FD = dyn_cast<FieldDecl>(C);
3561           if (FD && FD->getParent()->isUnion())
3562             Info.ActiveUnionMember.insert(std::make_pair(
3563                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3564         }
3565       } else if (FieldDecl *FD = Member->getMember()) {
3566         if (FD->getParent()->isUnion())
3567           Info.ActiveUnionMember.insert(std::make_pair(
3568               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3569       }
3570     }
3571   }
3572 
3573   // Keep track of the direct virtual bases.
3574   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3575   for (auto &I : ClassDecl->bases()) {
3576     if (I.isVirtual())
3577       DirectVBases.insert(&I);
3578   }
3579 
3580   // Push virtual bases before others.
3581   for (auto &VBase : ClassDecl->vbases()) {
3582     if (CXXCtorInitializer *Value
3583         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
3584       // [class.base.init]p7, per DR257:
3585       //   A mem-initializer where the mem-initializer-id names a virtual base
3586       //   class is ignored during execution of a constructor of any class that
3587       //   is not the most derived class.
3588       if (ClassDecl->isAbstract()) {
3589         // FIXME: Provide a fixit to remove the base specifier. This requires
3590         // tracking the location of the associated comma for a base specifier.
3591         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3592           << VBase.getType() << ClassDecl;
3593         DiagnoseAbstractType(ClassDecl);
3594       }
3595 
3596       Info.AllToInit.push_back(Value);
3597     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3598       // [class.base.init]p8, per DR257:
3599       //   If a given [...] base class is not named by a mem-initializer-id
3600       //   [...] and the entity is not a virtual base class of an abstract
3601       //   class, then [...] the entity is default-initialized.
3602       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
3603       CXXCtorInitializer *CXXBaseInit;
3604       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3605                                        &VBase, IsInheritedVirtualBase,
3606                                        CXXBaseInit)) {
3607         HadError = true;
3608         continue;
3609       }
3610 
3611       Info.AllToInit.push_back(CXXBaseInit);
3612     }
3613   }
3614 
3615   // Non-virtual bases.
3616   for (auto &Base : ClassDecl->bases()) {
3617     // Virtuals are in the virtual base list and already constructed.
3618     if (Base.isVirtual())
3619       continue;
3620 
3621     if (CXXCtorInitializer *Value
3622           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
3623       Info.AllToInit.push_back(Value);
3624     } else if (!AnyErrors) {
3625       CXXCtorInitializer *CXXBaseInit;
3626       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3627                                        &Base, /*IsInheritedVirtualBase=*/false,
3628                                        CXXBaseInit)) {
3629         HadError = true;
3630         continue;
3631       }
3632 
3633       Info.AllToInit.push_back(CXXBaseInit);
3634     }
3635   }
3636 
3637   // Fields.
3638   for (auto *Mem : ClassDecl->decls()) {
3639     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
3640       // C++ [class.bit]p2:
3641       //   A declaration for a bit-field that omits the identifier declares an
3642       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
3643       //   initialized.
3644       if (F->isUnnamedBitfield())
3645         continue;
3646 
3647       // If we're not generating the implicit copy/move constructor, then we'll
3648       // handle anonymous struct/union fields based on their individual
3649       // indirect fields.
3650       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
3651         continue;
3652 
3653       if (CollectFieldInitializer(*this, Info, F))
3654         HadError = true;
3655       continue;
3656     }
3657 
3658     // Beyond this point, we only consider default initialization.
3659     if (Info.isImplicitCopyOrMove())
3660       continue;
3661 
3662     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
3663       if (F->getType()->isIncompleteArrayType()) {
3664         assert(ClassDecl->hasFlexibleArrayMember() &&
3665                "Incomplete array type is not valid");
3666         continue;
3667       }
3668 
3669       // Initialize each field of an anonymous struct individually.
3670       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3671         HadError = true;
3672 
3673       continue;
3674     }
3675   }
3676 
3677   unsigned NumInitializers = Info.AllToInit.size();
3678   if (NumInitializers > 0) {
3679     Constructor->setNumCtorInitializers(NumInitializers);
3680     CXXCtorInitializer **baseOrMemberInitializers =
3681       new (Context) CXXCtorInitializer*[NumInitializers];
3682     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
3683            NumInitializers * sizeof(CXXCtorInitializer*));
3684     Constructor->setCtorInitializers(baseOrMemberInitializers);
3685 
3686     // Constructors implicitly reference the base and member
3687     // destructors.
3688     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3689                                            Constructor->getParent());
3690   }
3691 
3692   return HadError;
3693 }
3694 
3695 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
3696   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
3697     const RecordDecl *RD = RT->getDecl();
3698     if (RD->isAnonymousStructOrUnion()) {
3699       for (auto *Field : RD->fields())
3700         PopulateKeysForFields(Field, IdealInits);
3701       return;
3702     }
3703   }
3704   IdealInits.push_back(Field);
3705 }
3706 
3707 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3708   return Context.getCanonicalType(BaseType).getTypePtr();
3709 }
3710 
3711 static const void *GetKeyForMember(ASTContext &Context,
3712                                    CXXCtorInitializer *Member) {
3713   if (!Member->isAnyMemberInitializer())
3714     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
3715 
3716   return Member->getAnyMember();
3717 }
3718 
3719 static void DiagnoseBaseOrMemInitializerOrder(
3720     Sema &SemaRef, const CXXConstructorDecl *Constructor,
3721     ArrayRef<CXXCtorInitializer *> Inits) {
3722   if (Constructor->getDeclContext()->isDependentContext())
3723     return;
3724 
3725   // Don't check initializers order unless the warning is enabled at the
3726   // location of at least one initializer.
3727   bool ShouldCheckOrder = false;
3728   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3729     CXXCtorInitializer *Init = Inits[InitIndex];
3730     if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3731                                          Init->getSourceLocation())
3732           != DiagnosticsEngine::Ignored) {
3733       ShouldCheckOrder = true;
3734       break;
3735     }
3736   }
3737   if (!ShouldCheckOrder)
3738     return;
3739 
3740   // Build the list of bases and members in the order that they'll
3741   // actually be initialized.  The explicit initializers should be in
3742   // this same order but may be missing things.
3743   SmallVector<const void*, 32> IdealInitKeys;
3744 
3745   const CXXRecordDecl *ClassDecl = Constructor->getParent();
3746 
3747   // 1. Virtual bases.
3748   for (const auto &VBase : ClassDecl->vbases())
3749     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
3750 
3751   // 2. Non-virtual bases.
3752   for (const auto &Base : ClassDecl->bases()) {
3753     if (Base.isVirtual())
3754       continue;
3755     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
3756   }
3757 
3758   // 3. Direct fields.
3759   for (auto *Field : ClassDecl->fields()) {
3760     if (Field->isUnnamedBitfield())
3761       continue;
3762 
3763     PopulateKeysForFields(Field, IdealInitKeys);
3764   }
3765 
3766   unsigned NumIdealInits = IdealInitKeys.size();
3767   unsigned IdealIndex = 0;
3768 
3769   CXXCtorInitializer *PrevInit = 0;
3770   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3771     CXXCtorInitializer *Init = Inits[InitIndex];
3772     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
3773 
3774     // Scan forward to try to find this initializer in the idealized
3775     // initializers list.
3776     for (; IdealIndex != NumIdealInits; ++IdealIndex)
3777       if (InitKey == IdealInitKeys[IdealIndex])
3778         break;
3779 
3780     // If we didn't find this initializer, it must be because we
3781     // scanned past it on a previous iteration.  That can only
3782     // happen if we're out of order;  emit a warning.
3783     if (IdealIndex == NumIdealInits && PrevInit) {
3784       Sema::SemaDiagnosticBuilder D =
3785         SemaRef.Diag(PrevInit->getSourceLocation(),
3786                      diag::warn_initializer_out_of_order);
3787 
3788       if (PrevInit->isAnyMemberInitializer())
3789         D << 0 << PrevInit->getAnyMember()->getDeclName();
3790       else
3791         D << 1 << PrevInit->getTypeSourceInfo()->getType();
3792 
3793       if (Init->isAnyMemberInitializer())
3794         D << 0 << Init->getAnyMember()->getDeclName();
3795       else
3796         D << 1 << Init->getTypeSourceInfo()->getType();
3797 
3798       // Move back to the initializer's location in the ideal list.
3799       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3800         if (InitKey == IdealInitKeys[IdealIndex])
3801           break;
3802 
3803       assert(IdealIndex != NumIdealInits &&
3804              "initializer not found in initializer list");
3805     }
3806 
3807     PrevInit = Init;
3808   }
3809 }
3810 
3811 namespace {
3812 bool CheckRedundantInit(Sema &S,
3813                         CXXCtorInitializer *Init,
3814                         CXXCtorInitializer *&PrevInit) {
3815   if (!PrevInit) {
3816     PrevInit = Init;
3817     return false;
3818   }
3819 
3820   if (FieldDecl *Field = Init->getAnyMember())
3821     S.Diag(Init->getSourceLocation(),
3822            diag::err_multiple_mem_initialization)
3823       << Field->getDeclName()
3824       << Init->getSourceRange();
3825   else {
3826     const Type *BaseClass = Init->getBaseClass();
3827     assert(BaseClass && "neither field nor base");
3828     S.Diag(Init->getSourceLocation(),
3829            diag::err_multiple_base_initialization)
3830       << QualType(BaseClass, 0)
3831       << Init->getSourceRange();
3832   }
3833   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3834     << 0 << PrevInit->getSourceRange();
3835 
3836   return true;
3837 }
3838 
3839 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
3840 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3841 
3842 bool CheckRedundantUnionInit(Sema &S,
3843                              CXXCtorInitializer *Init,
3844                              RedundantUnionMap &Unions) {
3845   FieldDecl *Field = Init->getAnyMember();
3846   RecordDecl *Parent = Field->getParent();
3847   NamedDecl *Child = Field;
3848 
3849   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
3850     if (Parent->isUnion()) {
3851       UnionEntry &En = Unions[Parent];
3852       if (En.first && En.first != Child) {
3853         S.Diag(Init->getSourceLocation(),
3854                diag::err_multiple_mem_union_initialization)
3855           << Field->getDeclName()
3856           << Init->getSourceRange();
3857         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3858           << 0 << En.second->getSourceRange();
3859         return true;
3860       }
3861       if (!En.first) {
3862         En.first = Child;
3863         En.second = Init;
3864       }
3865       if (!Parent->isAnonymousStructOrUnion())
3866         return false;
3867     }
3868 
3869     Child = Parent;
3870     Parent = cast<RecordDecl>(Parent->getDeclContext());
3871   }
3872 
3873   return false;
3874 }
3875 }
3876 
3877 /// ActOnMemInitializers - Handle the member initializers for a constructor.
3878 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
3879                                 SourceLocation ColonLoc,
3880                                 ArrayRef<CXXCtorInitializer*> MemInits,
3881                                 bool AnyErrors) {
3882   if (!ConstructorDecl)
3883     return;
3884 
3885   AdjustDeclIfTemplate(ConstructorDecl);
3886 
3887   CXXConstructorDecl *Constructor
3888     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
3889 
3890   if (!Constructor) {
3891     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3892     return;
3893   }
3894 
3895   // Mapping for the duplicate initializers check.
3896   // For member initializers, this is keyed with a FieldDecl*.
3897   // For base initializers, this is keyed with a Type*.
3898   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
3899 
3900   // Mapping for the inconsistent anonymous-union initializers check.
3901   RedundantUnionMap MemberUnions;
3902 
3903   bool HadError = false;
3904   for (unsigned i = 0; i < MemInits.size(); i++) {
3905     CXXCtorInitializer *Init = MemInits[i];
3906 
3907     // Set the source order index.
3908     Init->setSourceOrder(i);
3909 
3910     if (Init->isAnyMemberInitializer()) {
3911       FieldDecl *Field = Init->getAnyMember();
3912       if (CheckRedundantInit(*this, Init, Members[Field]) ||
3913           CheckRedundantUnionInit(*this, Init, MemberUnions))
3914         HadError = true;
3915     } else if (Init->isBaseInitializer()) {
3916       const void *Key =
3917           GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3918       if (CheckRedundantInit(*this, Init, Members[Key]))
3919         HadError = true;
3920     } else {
3921       assert(Init->isDelegatingInitializer());
3922       // This must be the only initializer
3923       if (MemInits.size() != 1) {
3924         Diag(Init->getSourceLocation(),
3925              diag::err_delegating_initializer_alone)
3926           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
3927         // We will treat this as being the only initializer.
3928       }
3929       SetDelegatingInitializer(Constructor, MemInits[i]);
3930       // Return immediately as the initializer is set.
3931       return;
3932     }
3933   }
3934 
3935   if (HadError)
3936     return;
3937 
3938   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
3939 
3940   SetCtorInitializers(Constructor, AnyErrors, MemInits);
3941 
3942   DiagnoseUninitializedFields(*this, Constructor);
3943 }
3944 
3945 void
3946 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3947                                              CXXRecordDecl *ClassDecl) {
3948   // Ignore dependent contexts. Also ignore unions, since their members never
3949   // have destructors implicitly called.
3950   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
3951     return;
3952 
3953   // FIXME: all the access-control diagnostics are positioned on the
3954   // field/base declaration.  That's probably good; that said, the
3955   // user might reasonably want to know why the destructor is being
3956   // emitted, and we currently don't say.
3957 
3958   // Non-static data members.
3959   for (auto *Field : ClassDecl->fields()) {
3960     if (Field->isInvalidDecl())
3961       continue;
3962 
3963     // Don't destroy incomplete or zero-length arrays.
3964     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3965       continue;
3966 
3967     QualType FieldType = Context.getBaseElementType(Field->getType());
3968 
3969     const RecordType* RT = FieldType->getAs<RecordType>();
3970     if (!RT)
3971       continue;
3972 
3973     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3974     if (FieldClassDecl->isInvalidDecl())
3975       continue;
3976     if (FieldClassDecl->hasIrrelevantDestructor())
3977       continue;
3978     // The destructor for an implicit anonymous union member is never invoked.
3979     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3980       continue;
3981 
3982     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
3983     assert(Dtor && "No dtor found for FieldClassDecl!");
3984     CheckDestructorAccess(Field->getLocation(), Dtor,
3985                           PDiag(diag::err_access_dtor_field)
3986                             << Field->getDeclName()
3987                             << FieldType);
3988 
3989     MarkFunctionReferenced(Location, Dtor);
3990     DiagnoseUseOfDecl(Dtor, Location);
3991   }
3992 
3993   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3994 
3995   // Bases.
3996   for (const auto &Base : ClassDecl->bases()) {
3997     // Bases are always records in a well-formed non-dependent class.
3998     const RecordType *RT = Base.getType()->getAs<RecordType>();
3999 
4000     // Remember direct virtual bases.
4001     if (Base.isVirtual())
4002       DirectVirtualBases.insert(RT);
4003 
4004     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4005     // If our base class is invalid, we probably can't get its dtor anyway.
4006     if (BaseClassDecl->isInvalidDecl())
4007       continue;
4008     if (BaseClassDecl->hasIrrelevantDestructor())
4009       continue;
4010 
4011     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4012     assert(Dtor && "No dtor found for BaseClassDecl!");
4013 
4014     // FIXME: caret should be on the start of the class name
4015     CheckDestructorAccess(Base.getLocStart(), Dtor,
4016                           PDiag(diag::err_access_dtor_base)
4017                             << Base.getType()
4018                             << Base.getSourceRange(),
4019                           Context.getTypeDeclType(ClassDecl));
4020 
4021     MarkFunctionReferenced(Location, Dtor);
4022     DiagnoseUseOfDecl(Dtor, Location);
4023   }
4024 
4025   // Virtual bases.
4026   for (const auto &VBase : ClassDecl->vbases()) {
4027     // Bases are always records in a well-formed non-dependent class.
4028     const RecordType *RT = VBase.getType()->castAs<RecordType>();
4029 
4030     // Ignore direct virtual bases.
4031     if (DirectVirtualBases.count(RT))
4032       continue;
4033 
4034     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4035     // If our base class is invalid, we probably can't get its dtor anyway.
4036     if (BaseClassDecl->isInvalidDecl())
4037       continue;
4038     if (BaseClassDecl->hasIrrelevantDestructor())
4039       continue;
4040 
4041     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4042     assert(Dtor && "No dtor found for BaseClassDecl!");
4043     if (CheckDestructorAccess(
4044             ClassDecl->getLocation(), Dtor,
4045             PDiag(diag::err_access_dtor_vbase)
4046                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
4047             Context.getTypeDeclType(ClassDecl)) ==
4048         AR_accessible) {
4049       CheckDerivedToBaseConversion(
4050           Context.getTypeDeclType(ClassDecl), VBase.getType(),
4051           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4052           SourceRange(), DeclarationName(), 0);
4053     }
4054 
4055     MarkFunctionReferenced(Location, Dtor);
4056     DiagnoseUseOfDecl(Dtor, Location);
4057   }
4058 }
4059 
4060 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
4061   if (!CDtorDecl)
4062     return;
4063 
4064   if (CXXConstructorDecl *Constructor
4065       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
4066     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
4067     DiagnoseUninitializedFields(*this, Constructor);
4068   }
4069 }
4070 
4071 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4072                                   unsigned DiagID, AbstractDiagSelID SelID) {
4073   class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4074     unsigned DiagID;
4075     AbstractDiagSelID SelID;
4076 
4077   public:
4078     NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4079       : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
4080 
4081     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
4082       if (Suppressed) return;
4083       if (SelID == -1)
4084         S.Diag(Loc, DiagID) << T;
4085       else
4086         S.Diag(Loc, DiagID) << SelID << T;
4087     }
4088   } Diagnoser(DiagID, SelID);
4089 
4090   return RequireNonAbstractType(Loc, T, Diagnoser);
4091 }
4092 
4093 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4094                                   TypeDiagnoser &Diagnoser) {
4095   if (!getLangOpts().CPlusPlus)
4096     return false;
4097 
4098   if (const ArrayType *AT = Context.getAsArrayType(T))
4099     return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4100 
4101   if (const PointerType *PT = T->getAs<PointerType>()) {
4102     // Find the innermost pointer type.
4103     while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
4104       PT = T;
4105 
4106     if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
4107       return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4108   }
4109 
4110   const RecordType *RT = T->getAs<RecordType>();
4111   if (!RT)
4112     return false;
4113 
4114   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4115 
4116   // We can't answer whether something is abstract until it has a
4117   // definition.  If it's currently being defined, we'll walk back
4118   // over all the declarations when we have a full definition.
4119   const CXXRecordDecl *Def = RD->getDefinition();
4120   if (!Def || Def->isBeingDefined())
4121     return false;
4122 
4123   if (!RD->isAbstract())
4124     return false;
4125 
4126   Diagnoser.diagnose(*this, Loc, T);
4127   DiagnoseAbstractType(RD);
4128 
4129   return true;
4130 }
4131 
4132 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4133   // Check if we've already emitted the list of pure virtual functions
4134   // for this class.
4135   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
4136     return;
4137 
4138   // If the diagnostic is suppressed, don't emit the notes. We're only
4139   // going to emit them once, so try to attach them to a diagnostic we're
4140   // actually going to show.
4141   if (Diags.isLastDiagnosticIgnored())
4142     return;
4143 
4144   CXXFinalOverriderMap FinalOverriders;
4145   RD->getFinalOverriders(FinalOverriders);
4146 
4147   // Keep a set of seen pure methods so we won't diagnose the same method
4148   // more than once.
4149   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4150 
4151   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4152                                    MEnd = FinalOverriders.end();
4153        M != MEnd;
4154        ++M) {
4155     for (OverridingMethods::iterator SO = M->second.begin(),
4156                                   SOEnd = M->second.end();
4157          SO != SOEnd; ++SO) {
4158       // C++ [class.abstract]p4:
4159       //   A class is abstract if it contains or inherits at least one
4160       //   pure virtual function for which the final overrider is pure
4161       //   virtual.
4162 
4163       //
4164       if (SO->second.size() != 1)
4165         continue;
4166 
4167       if (!SO->second.front().Method->isPure())
4168         continue;
4169 
4170       if (!SeenPureMethods.insert(SO->second.front().Method))
4171         continue;
4172 
4173       Diag(SO->second.front().Method->getLocation(),
4174            diag::note_pure_virtual_function)
4175         << SO->second.front().Method->getDeclName() << RD->getDeclName();
4176     }
4177   }
4178 
4179   if (!PureVirtualClassDiagSet)
4180     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4181   PureVirtualClassDiagSet->insert(RD);
4182 }
4183 
4184 namespace {
4185 struct AbstractUsageInfo {
4186   Sema &S;
4187   CXXRecordDecl *Record;
4188   CanQualType AbstractType;
4189   bool Invalid;
4190 
4191   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4192     : S(S), Record(Record),
4193       AbstractType(S.Context.getCanonicalType(
4194                    S.Context.getTypeDeclType(Record))),
4195       Invalid(false) {}
4196 
4197   void DiagnoseAbstractType() {
4198     if (Invalid) return;
4199     S.DiagnoseAbstractType(Record);
4200     Invalid = true;
4201   }
4202 
4203   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4204 };
4205 
4206 struct CheckAbstractUsage {
4207   AbstractUsageInfo &Info;
4208   const NamedDecl *Ctx;
4209 
4210   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4211     : Info(Info), Ctx(Ctx) {}
4212 
4213   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4214     switch (TL.getTypeLocClass()) {
4215 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4216 #define TYPELOC(CLASS, PARENT) \
4217     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
4218 #include "clang/AST/TypeLocNodes.def"
4219     }
4220   }
4221 
4222   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4223     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
4224     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4225       if (!TL.getParam(I))
4226         continue;
4227 
4228       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
4229       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
4230     }
4231   }
4232 
4233   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4234     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4235   }
4236 
4237   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4238     // Visit the type parameters from a permissive context.
4239     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4240       TemplateArgumentLoc TAL = TL.getArgLoc(I);
4241       if (TAL.getArgument().getKind() == TemplateArgument::Type)
4242         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4243           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4244       // TODO: other template argument types?
4245     }
4246   }
4247 
4248   // Visit pointee types from a permissive context.
4249 #define CheckPolymorphic(Type) \
4250   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4251     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4252   }
4253   CheckPolymorphic(PointerTypeLoc)
4254   CheckPolymorphic(ReferenceTypeLoc)
4255   CheckPolymorphic(MemberPointerTypeLoc)
4256   CheckPolymorphic(BlockPointerTypeLoc)
4257   CheckPolymorphic(AtomicTypeLoc)
4258 
4259   /// Handle all the types we haven't given a more specific
4260   /// implementation for above.
4261   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4262     // Every other kind of type that we haven't called out already
4263     // that has an inner type is either (1) sugar or (2) contains that
4264     // inner type in some way as a subobject.
4265     if (TypeLoc Next = TL.getNextTypeLoc())
4266       return Visit(Next, Sel);
4267 
4268     // If there's no inner type and we're in a permissive context,
4269     // don't diagnose.
4270     if (Sel == Sema::AbstractNone) return;
4271 
4272     // Check whether the type matches the abstract type.
4273     QualType T = TL.getType();
4274     if (T->isArrayType()) {
4275       Sel = Sema::AbstractArrayType;
4276       T = Info.S.Context.getBaseElementType(T);
4277     }
4278     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4279     if (CT != Info.AbstractType) return;
4280 
4281     // It matched; do some magic.
4282     if (Sel == Sema::AbstractArrayType) {
4283       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4284         << T << TL.getSourceRange();
4285     } else {
4286       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4287         << Sel << T << TL.getSourceRange();
4288     }
4289     Info.DiagnoseAbstractType();
4290   }
4291 };
4292 
4293 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4294                                   Sema::AbstractDiagSelID Sel) {
4295   CheckAbstractUsage(*this, D).Visit(TL, Sel);
4296 }
4297 
4298 }
4299 
4300 /// Check for invalid uses of an abstract type in a method declaration.
4301 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4302                                     CXXMethodDecl *MD) {
4303   // No need to do the check on definitions, which require that
4304   // the return/param types be complete.
4305   if (MD->doesThisDeclarationHaveABody())
4306     return;
4307 
4308   // For safety's sake, just ignore it if we don't have type source
4309   // information.  This should never happen for non-implicit methods,
4310   // but...
4311   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4312     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4313 }
4314 
4315 /// Check for invalid uses of an abstract type within a class definition.
4316 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4317                                     CXXRecordDecl *RD) {
4318   for (auto *D : RD->decls()) {
4319     if (D->isImplicit()) continue;
4320 
4321     // Methods and method templates.
4322     if (isa<CXXMethodDecl>(D)) {
4323       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4324     } else if (isa<FunctionTemplateDecl>(D)) {
4325       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4326       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4327 
4328     // Fields and static variables.
4329     } else if (isa<FieldDecl>(D)) {
4330       FieldDecl *FD = cast<FieldDecl>(D);
4331       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4332         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4333     } else if (isa<VarDecl>(D)) {
4334       VarDecl *VD = cast<VarDecl>(D);
4335       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4336         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4337 
4338     // Nested classes and class templates.
4339     } else if (isa<CXXRecordDecl>(D)) {
4340       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4341     } else if (isa<ClassTemplateDecl>(D)) {
4342       CheckAbstractClassUsage(Info,
4343                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4344     }
4345   }
4346 }
4347 
4348 /// \brief Perform semantic checks on a class definition that has been
4349 /// completing, introducing implicitly-declared members, checking for
4350 /// abstract types, etc.
4351 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
4352   if (!Record)
4353     return;
4354 
4355   if (Record->isAbstract() && !Record->isInvalidDecl()) {
4356     AbstractUsageInfo Info(*this, Record);
4357     CheckAbstractClassUsage(Info, Record);
4358   }
4359 
4360   // If this is not an aggregate type and has no user-declared constructor,
4361   // complain about any non-static data members of reference or const scalar
4362   // type, since they will never get initializers.
4363   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
4364       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4365       !Record->isLambda()) {
4366     bool Complained = false;
4367     for (const auto *F : Record->fields()) {
4368       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
4369         continue;
4370 
4371       if (F->getType()->isReferenceType() ||
4372           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
4373         if (!Complained) {
4374           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4375             << Record->getTagKind() << Record;
4376           Complained = true;
4377         }
4378 
4379         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4380           << F->getType()->isReferenceType()
4381           << F->getDeclName();
4382       }
4383     }
4384   }
4385 
4386   if (Record->isDynamicClass() && !Record->isDependentType())
4387     DynamicClasses.push_back(Record);
4388 
4389   if (Record->getIdentifier()) {
4390     // C++ [class.mem]p13:
4391     //   If T is the name of a class, then each of the following shall have a
4392     //   name different from T:
4393     //     - every member of every anonymous union that is a member of class T.
4394     //
4395     // C++ [class.mem]p14:
4396     //   In addition, if class T has a user-declared constructor (12.1), every
4397     //   non-static data member of class T shall have a name different from T.
4398     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4399     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4400          ++I) {
4401       NamedDecl *D = *I;
4402       if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4403           isa<IndirectFieldDecl>(D)) {
4404         Diag(D->getLocation(), diag::err_member_name_of_class)
4405           << D->getDeclName();
4406         break;
4407       }
4408     }
4409   }
4410 
4411   // Warn if the class has virtual methods but non-virtual public destructor.
4412   if (Record->isPolymorphic() && !Record->isDependentType()) {
4413     CXXDestructorDecl *dtor = Record->getDestructor();
4414     if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
4415       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4416            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4417   }
4418 
4419   if (Record->isAbstract()) {
4420     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4421       Diag(Record->getLocation(), diag::warn_abstract_final_class)
4422         << FA->isSpelledAsSealed();
4423       DiagnoseAbstractType(Record);
4424     }
4425   }
4426 
4427   if (!Record->isDependentType()) {
4428     for (auto *M : Record->methods()) {
4429       // See if a method overloads virtual methods in a base
4430       // class without overriding any.
4431       if (!M->isStatic())
4432         DiagnoseHiddenVirtualMethods(M);
4433 
4434       // Check whether the explicitly-defaulted special members are valid.
4435       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4436         CheckExplicitlyDefaultedSpecialMember(M);
4437 
4438       // For an explicitly defaulted or deleted special member, we defer
4439       // determining triviality until the class is complete. That time is now!
4440       if (!M->isImplicit() && !M->isUserProvided()) {
4441         CXXSpecialMember CSM = getSpecialMember(M);
4442         if (CSM != CXXInvalid) {
4443           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
4444 
4445           // Inform the class that we've finished declaring this member.
4446           Record->finishedDefaultedOrDeletedMember(M);
4447         }
4448       }
4449     }
4450   }
4451 
4452   // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4453   // function that is not a constructor declares that member function to be
4454   // const. [...] The class of which that function is a member shall be
4455   // a literal type.
4456   //
4457   // If the class has virtual bases, any constexpr members will already have
4458   // been diagnosed by the checks performed on the member declaration, so
4459   // suppress this (less useful) diagnostic.
4460   //
4461   // We delay this until we know whether an explicitly-defaulted (or deleted)
4462   // destructor for the class is trivial.
4463   if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
4464       !Record->isLiteral() && !Record->getNumVBases()) {
4465     for (const auto *M : Record->methods()) {
4466       if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) {
4467         switch (Record->getTemplateSpecializationKind()) {
4468         case TSK_ImplicitInstantiation:
4469         case TSK_ExplicitInstantiationDeclaration:
4470         case TSK_ExplicitInstantiationDefinition:
4471           // If a template instantiates to a non-literal type, but its members
4472           // instantiate to constexpr functions, the template is technically
4473           // ill-formed, but we allow it for sanity.
4474           continue;
4475 
4476         case TSK_Undeclared:
4477         case TSK_ExplicitSpecialization:
4478           RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4479                              diag::err_constexpr_method_non_literal);
4480           break;
4481         }
4482 
4483         // Only produce one error per class.
4484         break;
4485       }
4486     }
4487   }
4488 
4489   // ms_struct is a request to use the same ABI rules as MSVC.  Check
4490   // whether this class uses any C++ features that are implemented
4491   // completely differently in MSVC, and if so, emit a diagnostic.
4492   // That diagnostic defaults to an error, but we allow projects to
4493   // map it down to a warning (or ignore it).  It's a fairly common
4494   // practice among users of the ms_struct pragma to mass-annotate
4495   // headers, sweeping up a bunch of types that the project doesn't
4496   // really rely on MSVC-compatible layout for.  We must therefore
4497   // support "ms_struct except for C++ stuff" as a secondary ABI.
4498   if (Record->isMsStruct(Context) &&
4499       (Record->isPolymorphic() || Record->getNumBases())) {
4500     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
4501   }
4502 
4503   // Declare inheriting constructors. We do this eagerly here because:
4504   // - The standard requires an eager diagnostic for conflicting inheriting
4505   //   constructors from different classes.
4506   // - The lazy declaration of the other implicit constructors is so as to not
4507   //   waste space and performance on classes that are not meant to be
4508   //   instantiated (e.g. meta-functions). This doesn't apply to classes that
4509   //   have inheriting constructors.
4510   DeclareInheritingConstructors(Record);
4511 }
4512 
4513 /// Look up the special member function that would be called by a special
4514 /// member function for a subobject of class type.
4515 ///
4516 /// \param Class The class type of the subobject.
4517 /// \param CSM The kind of special member function.
4518 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4519 /// \param ConstRHS True if this is a copy operation with a const object
4520 ///        on its RHS, that is, if the argument to the outer special member
4521 ///        function is 'const' and this is not a field marked 'mutable'.
4522 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
4523     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
4524     unsigned FieldQuals, bool ConstRHS) {
4525   unsigned LHSQuals = 0;
4526   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
4527     LHSQuals = FieldQuals;
4528 
4529   unsigned RHSQuals = FieldQuals;
4530   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4531     RHSQuals = 0;
4532   else if (ConstRHS)
4533     RHSQuals |= Qualifiers::Const;
4534 
4535   return S.LookupSpecialMember(Class, CSM,
4536                                RHSQuals & Qualifiers::Const,
4537                                RHSQuals & Qualifiers::Volatile,
4538                                false,
4539                                LHSQuals & Qualifiers::Const,
4540                                LHSQuals & Qualifiers::Volatile);
4541 }
4542 
4543 /// Is the special member function which would be selected to perform the
4544 /// specified operation on the specified class type a constexpr constructor?
4545 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4546                                      Sema::CXXSpecialMember CSM,
4547                                      unsigned Quals, bool ConstRHS) {
4548   Sema::SpecialMemberOverloadResult *SMOR =
4549       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
4550   if (!SMOR || !SMOR->getMethod())
4551     // A constructor we wouldn't select can't be "involved in initializing"
4552     // anything.
4553     return true;
4554   return SMOR->getMethod()->isConstexpr();
4555 }
4556 
4557 /// Determine whether the specified special member function would be constexpr
4558 /// if it were implicitly defined.
4559 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4560                                               Sema::CXXSpecialMember CSM,
4561                                               bool ConstArg) {
4562   if (!S.getLangOpts().CPlusPlus11)
4563     return false;
4564 
4565   // C++11 [dcl.constexpr]p4:
4566   // In the definition of a constexpr constructor [...]
4567   bool Ctor = true;
4568   switch (CSM) {
4569   case Sema::CXXDefaultConstructor:
4570     // Since default constructor lookup is essentially trivial (and cannot
4571     // involve, for instance, template instantiation), we compute whether a
4572     // defaulted default constructor is constexpr directly within CXXRecordDecl.
4573     //
4574     // This is important for performance; we need to know whether the default
4575     // constructor is constexpr to determine whether the type is a literal type.
4576     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4577 
4578   case Sema::CXXCopyConstructor:
4579   case Sema::CXXMoveConstructor:
4580     // For copy or move constructors, we need to perform overload resolution.
4581     break;
4582 
4583   case Sema::CXXCopyAssignment:
4584   case Sema::CXXMoveAssignment:
4585     if (!S.getLangOpts().CPlusPlus1y)
4586       return false;
4587     // In C++1y, we need to perform overload resolution.
4588     Ctor = false;
4589     break;
4590 
4591   case Sema::CXXDestructor:
4592   case Sema::CXXInvalid:
4593     return false;
4594   }
4595 
4596   //   -- if the class is a non-empty union, or for each non-empty anonymous
4597   //      union member of a non-union class, exactly one non-static data member
4598   //      shall be initialized; [DR1359]
4599   //
4600   // If we squint, this is guaranteed, since exactly one non-static data member
4601   // will be initialized (if the constructor isn't deleted), we just don't know
4602   // which one.
4603   if (Ctor && ClassDecl->isUnion())
4604     return true;
4605 
4606   //   -- the class shall not have any virtual base classes;
4607   if (Ctor && ClassDecl->getNumVBases())
4608     return false;
4609 
4610   // C++1y [class.copy]p26:
4611   //   -- [the class] is a literal type, and
4612   if (!Ctor && !ClassDecl->isLiteral())
4613     return false;
4614 
4615   //   -- every constructor involved in initializing [...] base class
4616   //      sub-objects shall be a constexpr constructor;
4617   //   -- the assignment operator selected to copy/move each direct base
4618   //      class is a constexpr function, and
4619   for (const auto &B : ClassDecl->bases()) {
4620     const RecordType *BaseType = B.getType()->getAs<RecordType>();
4621     if (!BaseType) continue;
4622 
4623     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4624     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
4625       return false;
4626   }
4627 
4628   //   -- every constructor involved in initializing non-static data members
4629   //      [...] shall be a constexpr constructor;
4630   //   -- every non-static data member and base class sub-object shall be
4631   //      initialized
4632   //   -- for each non-static data member of X that is of class type (or array
4633   //      thereof), the assignment operator selected to copy/move that member is
4634   //      a constexpr function
4635   for (const auto *F : ClassDecl->fields()) {
4636     if (F->isInvalidDecl())
4637       continue;
4638     QualType BaseType = S.Context.getBaseElementType(F->getType());
4639     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
4640       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4641       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
4642                                     BaseType.getCVRQualifiers(),
4643                                     ConstArg && !F->isMutable()))
4644         return false;
4645     }
4646   }
4647 
4648   // All OK, it's constexpr!
4649   return true;
4650 }
4651 
4652 static Sema::ImplicitExceptionSpecification
4653 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4654   switch (S.getSpecialMember(MD)) {
4655   case Sema::CXXDefaultConstructor:
4656     return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4657   case Sema::CXXCopyConstructor:
4658     return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4659   case Sema::CXXCopyAssignment:
4660     return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4661   case Sema::CXXMoveConstructor:
4662     return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4663   case Sema::CXXMoveAssignment:
4664     return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4665   case Sema::CXXDestructor:
4666     return S.ComputeDefaultedDtorExceptionSpec(MD);
4667   case Sema::CXXInvalid:
4668     break;
4669   }
4670   assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4671          "only special members have implicit exception specs");
4672   return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
4673 }
4674 
4675 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4676                                                             CXXMethodDecl *MD) {
4677   FunctionProtoType::ExtProtoInfo EPI;
4678 
4679   // Build an exception specification pointing back at this member.
4680   EPI.ExceptionSpecType = EST_Unevaluated;
4681   EPI.ExceptionSpecDecl = MD;
4682 
4683   // Set the calling convention to the default for C++ instance methods.
4684   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4685       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4686                                             /*IsCXXMethod=*/true));
4687   return EPI;
4688 }
4689 
4690 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4691   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4692   if (FPT->getExceptionSpecType() != EST_Unevaluated)
4693     return;
4694 
4695   // Evaluate the exception specification.
4696   ImplicitExceptionSpecification ExceptSpec =
4697       computeImplicitExceptionSpec(*this, Loc, MD);
4698 
4699   FunctionProtoType::ExtProtoInfo EPI;
4700   ExceptSpec.getEPI(EPI);
4701 
4702   // Update the type of the special member to use it.
4703   UpdateExceptionSpec(MD, EPI);
4704 
4705   // A user-provided destructor can be defined outside the class. When that
4706   // happens, be sure to update the exception specification on both
4707   // declarations.
4708   const FunctionProtoType *CanonicalFPT =
4709     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4710   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4711     UpdateExceptionSpec(MD->getCanonicalDecl(), EPI);
4712 }
4713 
4714 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4715   CXXRecordDecl *RD = MD->getParent();
4716   CXXSpecialMember CSM = getSpecialMember(MD);
4717 
4718   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4719          "not an explicitly-defaulted special member");
4720 
4721   // Whether this was the first-declared instance of the constructor.
4722   // This affects whether we implicitly add an exception spec and constexpr.
4723   bool First = MD == MD->getCanonicalDecl();
4724 
4725   bool HadError = false;
4726 
4727   // C++11 [dcl.fct.def.default]p1:
4728   //   A function that is explicitly defaulted shall
4729   //     -- be a special member function (checked elsewhere),
4730   //     -- have the same type (except for ref-qualifiers, and except that a
4731   //        copy operation can take a non-const reference) as an implicit
4732   //        declaration, and
4733   //     -- not have default arguments.
4734   unsigned ExpectedParams = 1;
4735   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4736     ExpectedParams = 0;
4737   if (MD->getNumParams() != ExpectedParams) {
4738     // This also checks for default arguments: a copy or move constructor with a
4739     // default argument is classified as a default constructor, and assignment
4740     // operations and destructors can't have default arguments.
4741     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4742       << CSM << MD->getSourceRange();
4743     HadError = true;
4744   } else if (MD->isVariadic()) {
4745     Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4746       << CSM << MD->getSourceRange();
4747     HadError = true;
4748   }
4749 
4750   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
4751 
4752   bool CanHaveConstParam = false;
4753   if (CSM == CXXCopyConstructor)
4754     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
4755   else if (CSM == CXXCopyAssignment)
4756     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
4757 
4758   QualType ReturnType = Context.VoidTy;
4759   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4760     // Check for return type matching.
4761     ReturnType = Type->getReturnType();
4762     QualType ExpectedReturnType =
4763         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4764     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4765       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4766         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4767       HadError = true;
4768     }
4769 
4770     // A defaulted special member cannot have cv-qualifiers.
4771     if (Type->getTypeQuals()) {
4772       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4773         << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
4774       HadError = true;
4775     }
4776   }
4777 
4778   // Check for parameter type matching.
4779   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
4780   bool HasConstParam = false;
4781   if (ExpectedParams && ArgType->isReferenceType()) {
4782     // Argument must be reference to possibly-const T.
4783     QualType ReferentType = ArgType->getPointeeType();
4784     HasConstParam = ReferentType.isConstQualified();
4785 
4786     if (ReferentType.isVolatileQualified()) {
4787       Diag(MD->getLocation(),
4788            diag::err_defaulted_special_member_volatile_param) << CSM;
4789       HadError = true;
4790     }
4791 
4792     if (HasConstParam && !CanHaveConstParam) {
4793       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4794         Diag(MD->getLocation(),
4795              diag::err_defaulted_special_member_copy_const_param)
4796           << (CSM == CXXCopyAssignment);
4797         // FIXME: Explain why this special member can't be const.
4798       } else {
4799         Diag(MD->getLocation(),
4800              diag::err_defaulted_special_member_move_const_param)
4801           << (CSM == CXXMoveAssignment);
4802       }
4803       HadError = true;
4804     }
4805   } else if (ExpectedParams) {
4806     // A copy assignment operator can take its argument by value, but a
4807     // defaulted one cannot.
4808     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
4809     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
4810     HadError = true;
4811   }
4812 
4813   // C++11 [dcl.fct.def.default]p2:
4814   //   An explicitly-defaulted function may be declared constexpr only if it
4815   //   would have been implicitly declared as constexpr,
4816   // Do not apply this rule to members of class templates, since core issue 1358
4817   // makes such functions always instantiate to constexpr functions. For
4818   // functions which cannot be constexpr (for non-constructors in C++11 and for
4819   // destructors in C++1y), this is checked elsewhere.
4820   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4821                                                      HasConstParam);
4822   if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4823                                  : isa<CXXConstructorDecl>(MD)) &&
4824       MD->isConstexpr() && !Constexpr &&
4825       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4826     Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
4827     // FIXME: Explain why the special member can't be constexpr.
4828     HadError = true;
4829   }
4830 
4831   //   and may have an explicit exception-specification only if it is compatible
4832   //   with the exception-specification on the implicit declaration.
4833   if (Type->hasExceptionSpec()) {
4834     // Delay the check if this is the first declaration of the special member,
4835     // since we may not have parsed some necessary in-class initializers yet.
4836     if (First) {
4837       // If the exception specification needs to be instantiated, do so now,
4838       // before we clobber it with an EST_Unevaluated specification below.
4839       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4840         InstantiateExceptionSpec(MD->getLocStart(), MD);
4841         Type = MD->getType()->getAs<FunctionProtoType>();
4842       }
4843       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
4844     } else
4845       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4846   }
4847 
4848   //   If a function is explicitly defaulted on its first declaration,
4849   if (First) {
4850     //  -- it is implicitly considered to be constexpr if the implicit
4851     //     definition would be,
4852     MD->setConstexpr(Constexpr);
4853 
4854     //  -- it is implicitly considered to have the same exception-specification
4855     //     as if it had been implicitly declared,
4856     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4857     EPI.ExceptionSpecType = EST_Unevaluated;
4858     EPI.ExceptionSpecDecl = MD;
4859     MD->setType(Context.getFunctionType(ReturnType,
4860                                         ArrayRef<QualType>(&ArgType,
4861                                                            ExpectedParams),
4862                                         EPI));
4863   }
4864 
4865   if (ShouldDeleteSpecialMember(MD, CSM)) {
4866     if (First) {
4867       SetDeclDeleted(MD, MD->getLocation());
4868     } else {
4869       // C++11 [dcl.fct.def.default]p4:
4870       //   [For a] user-provided explicitly-defaulted function [...] if such a
4871       //   function is implicitly defined as deleted, the program is ill-formed.
4872       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4873       ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
4874       HadError = true;
4875     }
4876   }
4877 
4878   if (HadError)
4879     MD->setInvalidDecl();
4880 }
4881 
4882 /// Check whether the exception specification provided for an
4883 /// explicitly-defaulted special member matches the exception specification
4884 /// that would have been generated for an implicit special member, per
4885 /// C++11 [dcl.fct.def.default]p2.
4886 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4887     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4888   // Compute the implicit exception specification.
4889   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4890                                                        /*IsCXXMethod=*/true);
4891   FunctionProtoType::ExtProtoInfo EPI(CC);
4892   computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4893   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
4894     Context.getFunctionType(Context.VoidTy, None, EPI));
4895 
4896   // Ensure that it matches.
4897   CheckEquivalentExceptionSpec(
4898     PDiag(diag::err_incorrect_defaulted_exception_spec)
4899       << getSpecialMember(MD), PDiag(),
4900     ImplicitType, SourceLocation(),
4901     SpecifiedType, MD->getLocation());
4902 }
4903 
4904 void Sema::CheckDelayedMemberExceptionSpecs() {
4905   SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
4906               2> Checks;
4907   SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
4908 
4909   std::swap(Checks, DelayedDestructorExceptionSpecChecks);
4910   std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
4911 
4912   // Perform any deferred checking of exception specifications for virtual
4913   // destructors.
4914   for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
4915     const CXXDestructorDecl *Dtor = Checks[i].first;
4916     assert(!Dtor->getParent()->isDependentType() &&
4917            "Should not ever add destructors of templates into the list.");
4918     CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
4919   }
4920 
4921   // Check that any explicitly-defaulted methods have exception specifications
4922   // compatible with their implicit exception specifications.
4923   for (unsigned I = 0, N = Specs.size(); I != N; ++I)
4924     CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
4925                                                 Specs[I].second);
4926 }
4927 
4928 namespace {
4929 struct SpecialMemberDeletionInfo {
4930   Sema &S;
4931   CXXMethodDecl *MD;
4932   Sema::CXXSpecialMember CSM;
4933   bool Diagnose;
4934 
4935   // Properties of the special member, computed for convenience.
4936   bool IsConstructor, IsAssignment, IsMove, ConstArg;
4937   SourceLocation Loc;
4938 
4939   bool AllFieldsAreConst;
4940 
4941   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
4942                             Sema::CXXSpecialMember CSM, bool Diagnose)
4943     : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
4944       IsConstructor(false), IsAssignment(false), IsMove(false),
4945       ConstArg(false), Loc(MD->getLocation()),
4946       AllFieldsAreConst(true) {
4947     switch (CSM) {
4948       case Sema::CXXDefaultConstructor:
4949       case Sema::CXXCopyConstructor:
4950         IsConstructor = true;
4951         break;
4952       case Sema::CXXMoveConstructor:
4953         IsConstructor = true;
4954         IsMove = true;
4955         break;
4956       case Sema::CXXCopyAssignment:
4957         IsAssignment = true;
4958         break;
4959       case Sema::CXXMoveAssignment:
4960         IsAssignment = true;
4961         IsMove = true;
4962         break;
4963       case Sema::CXXDestructor:
4964         break;
4965       case Sema::CXXInvalid:
4966         llvm_unreachable("invalid special member kind");
4967     }
4968 
4969     if (MD->getNumParams()) {
4970       if (const ReferenceType *RT =
4971               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
4972         ConstArg = RT->getPointeeType().isConstQualified();
4973     }
4974   }
4975 
4976   bool inUnion() const { return MD->getParent()->isUnion(); }
4977 
4978   /// Look up the corresponding special member in the given class.
4979   Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4980                                               unsigned Quals, bool IsMutable) {
4981     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
4982                                        ConstArg && !IsMutable);
4983   }
4984 
4985   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
4986 
4987   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
4988   bool shouldDeleteForField(FieldDecl *FD);
4989   bool shouldDeleteForAllConstMembers();
4990 
4991   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4992                                      unsigned Quals);
4993   bool shouldDeleteForSubobjectCall(Subobject Subobj,
4994                                     Sema::SpecialMemberOverloadResult *SMOR,
4995                                     bool IsDtorCallInCtor);
4996 
4997   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
4998 };
4999 }
5000 
5001 /// Is the given special member inaccessible when used on the given
5002 /// sub-object.
5003 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5004                                              CXXMethodDecl *target) {
5005   /// If we're operating on a base class, the object type is the
5006   /// type of this special member.
5007   QualType objectTy;
5008   AccessSpecifier access = target->getAccess();
5009   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5010     objectTy = S.Context.getTypeDeclType(MD->getParent());
5011     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5012 
5013   // If we're operating on a field, the object type is the type of the field.
5014   } else {
5015     objectTy = S.Context.getTypeDeclType(target->getParent());
5016   }
5017 
5018   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5019 }
5020 
5021 /// Check whether we should delete a special member due to the implicit
5022 /// definition containing a call to a special member of a subobject.
5023 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5024     Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5025     bool IsDtorCallInCtor) {
5026   CXXMethodDecl *Decl = SMOR->getMethod();
5027   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5028 
5029   int DiagKind = -1;
5030 
5031   if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5032     DiagKind = !Decl ? 0 : 1;
5033   else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5034     DiagKind = 2;
5035   else if (!isAccessible(Subobj, Decl))
5036     DiagKind = 3;
5037   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5038            !Decl->isTrivial()) {
5039     // A member of a union must have a trivial corresponding special member.
5040     // As a weird special case, a destructor call from a union's constructor
5041     // must be accessible and non-deleted, but need not be trivial. Such a
5042     // destructor is never actually called, but is semantically checked as
5043     // if it were.
5044     DiagKind = 4;
5045   }
5046 
5047   if (DiagKind == -1)
5048     return false;
5049 
5050   if (Diagnose) {
5051     if (Field) {
5052       S.Diag(Field->getLocation(),
5053              diag::note_deleted_special_member_class_subobject)
5054         << CSM << MD->getParent() << /*IsField*/true
5055         << Field << DiagKind << IsDtorCallInCtor;
5056     } else {
5057       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5058       S.Diag(Base->getLocStart(),
5059              diag::note_deleted_special_member_class_subobject)
5060         << CSM << MD->getParent() << /*IsField*/false
5061         << Base->getType() << DiagKind << IsDtorCallInCtor;
5062     }
5063 
5064     if (DiagKind == 1)
5065       S.NoteDeletedFunction(Decl);
5066     // FIXME: Explain inaccessibility if DiagKind == 3.
5067   }
5068 
5069   return true;
5070 }
5071 
5072 /// Check whether we should delete a special member function due to having a
5073 /// direct or virtual base class or non-static data member of class type M.
5074 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
5075     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
5076   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5077   bool IsMutable = Field && Field->isMutable();
5078 
5079   // C++11 [class.ctor]p5:
5080   // -- any direct or virtual base class, or non-static data member with no
5081   //    brace-or-equal-initializer, has class type M (or array thereof) and
5082   //    either M has no default constructor or overload resolution as applied
5083   //    to M's default constructor results in an ambiguity or in a function
5084   //    that is deleted or inaccessible
5085   // C++11 [class.copy]p11, C++11 [class.copy]p23:
5086   // -- a direct or virtual base class B that cannot be copied/moved because
5087   //    overload resolution, as applied to B's corresponding special member,
5088   //    results in an ambiguity or a function that is deleted or inaccessible
5089   //    from the defaulted special member
5090   // C++11 [class.dtor]p5:
5091   // -- any direct or virtual base class [...] has a type with a destructor
5092   //    that is deleted or inaccessible
5093   if (!(CSM == Sema::CXXDefaultConstructor &&
5094         Field && Field->hasInClassInitializer()) &&
5095       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5096                                    false))
5097     return true;
5098 
5099   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5100   // -- any direct or virtual base class or non-static data member has a
5101   //    type with a destructor that is deleted or inaccessible
5102   if (IsConstructor) {
5103     Sema::SpecialMemberOverloadResult *SMOR =
5104         S.LookupSpecialMember(Class, Sema::CXXDestructor,
5105                               false, false, false, false, false);
5106     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5107       return true;
5108   }
5109 
5110   return false;
5111 }
5112 
5113 /// Check whether we should delete a special member function due to the class
5114 /// having a particular direct or virtual base class.
5115 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
5116   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
5117   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
5118 }
5119 
5120 /// Check whether we should delete a special member function due to the class
5121 /// having a particular non-static data member.
5122 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5123   QualType FieldType = S.Context.getBaseElementType(FD->getType());
5124   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5125 
5126   if (CSM == Sema::CXXDefaultConstructor) {
5127     // For a default constructor, all references must be initialized in-class
5128     // and, if a union, it must have a non-const member.
5129     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5130       if (Diagnose)
5131         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5132           << MD->getParent() << FD << FieldType << /*Reference*/0;
5133       return true;
5134     }
5135     // C++11 [class.ctor]p5: any non-variant non-static data member of
5136     // const-qualified type (or array thereof) with no
5137     // brace-or-equal-initializer does not have a user-provided default
5138     // constructor.
5139     if (!inUnion() && FieldType.isConstQualified() &&
5140         !FD->hasInClassInitializer() &&
5141         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5142       if (Diagnose)
5143         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5144           << MD->getParent() << FD << FD->getType() << /*Const*/1;
5145       return true;
5146     }
5147 
5148     if (inUnion() && !FieldType.isConstQualified())
5149       AllFieldsAreConst = false;
5150   } else if (CSM == Sema::CXXCopyConstructor) {
5151     // For a copy constructor, data members must not be of rvalue reference
5152     // type.
5153     if (FieldType->isRValueReferenceType()) {
5154       if (Diagnose)
5155         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5156           << MD->getParent() << FD << FieldType;
5157       return true;
5158     }
5159   } else if (IsAssignment) {
5160     // For an assignment operator, data members must not be of reference type.
5161     if (FieldType->isReferenceType()) {
5162       if (Diagnose)
5163         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5164           << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
5165       return true;
5166     }
5167     if (!FieldRecord && FieldType.isConstQualified()) {
5168       // C++11 [class.copy]p23:
5169       // -- a non-static data member of const non-class type (or array thereof)
5170       if (Diagnose)
5171         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5172           << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
5173       return true;
5174     }
5175   }
5176 
5177   if (FieldRecord) {
5178     // Some additional restrictions exist on the variant members.
5179     if (!inUnion() && FieldRecord->isUnion() &&
5180         FieldRecord->isAnonymousStructOrUnion()) {
5181       bool AllVariantFieldsAreConst = true;
5182 
5183       // FIXME: Handle anonymous unions declared within anonymous unions.
5184       for (auto *UI : FieldRecord->fields()) {
5185         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
5186 
5187         if (!UnionFieldType.isConstQualified())
5188           AllVariantFieldsAreConst = false;
5189 
5190         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5191         if (UnionFieldRecord &&
5192             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
5193                                           UnionFieldType.getCVRQualifiers()))
5194           return true;
5195       }
5196 
5197       // At least one member in each anonymous union must be non-const
5198       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
5199           !FieldRecord->field_empty()) {
5200         if (Diagnose)
5201           S.Diag(FieldRecord->getLocation(),
5202                  diag::note_deleted_default_ctor_all_const)
5203             << MD->getParent() << /*anonymous union*/1;
5204         return true;
5205       }
5206 
5207       // Don't check the implicit member of the anonymous union type.
5208       // This is technically non-conformant, but sanity demands it.
5209       return false;
5210     }
5211 
5212     if (shouldDeleteForClassSubobject(FieldRecord, FD,
5213                                       FieldType.getCVRQualifiers()))
5214       return true;
5215   }
5216 
5217   return false;
5218 }
5219 
5220 /// C++11 [class.ctor] p5:
5221 ///   A defaulted default constructor for a class X is defined as deleted if
5222 /// X is a union and all of its variant members are of const-qualified type.
5223 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
5224   // This is a silly definition, because it gives an empty union a deleted
5225   // default constructor. Don't do that.
5226   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5227       !MD->getParent()->field_empty()) {
5228     if (Diagnose)
5229       S.Diag(MD->getParent()->getLocation(),
5230              diag::note_deleted_default_ctor_all_const)
5231         << MD->getParent() << /*not anonymous union*/0;
5232     return true;
5233   }
5234   return false;
5235 }
5236 
5237 /// Determine whether a defaulted special member function should be defined as
5238 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5239 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
5240 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5241                                      bool Diagnose) {
5242   if (MD->isInvalidDecl())
5243     return false;
5244   CXXRecordDecl *RD = MD->getParent();
5245   assert(!RD->isDependentType() && "do deletion after instantiation");
5246   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
5247     return false;
5248 
5249   // C++11 [expr.lambda.prim]p19:
5250   //   The closure type associated with a lambda-expression has a
5251   //   deleted (8.4.3) default constructor and a deleted copy
5252   //   assignment operator.
5253   if (RD->isLambda() &&
5254       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5255     if (Diagnose)
5256       Diag(RD->getLocation(), diag::note_lambda_decl);
5257     return true;
5258   }
5259 
5260   // For an anonymous struct or union, the copy and assignment special members
5261   // will never be used, so skip the check. For an anonymous union declared at
5262   // namespace scope, the constructor and destructor are used.
5263   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5264       RD->isAnonymousStructOrUnion())
5265     return false;
5266 
5267   // C++11 [class.copy]p7, p18:
5268   //   If the class definition declares a move constructor or move assignment
5269   //   operator, an implicitly declared copy constructor or copy assignment
5270   //   operator is defined as deleted.
5271   if (MD->isImplicit() &&
5272       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5273     CXXMethodDecl *UserDeclaredMove = 0;
5274 
5275     // In Microsoft mode, a user-declared move only causes the deletion of the
5276     // corresponding copy operation, not both copy operations.
5277     if (RD->hasUserDeclaredMoveConstructor() &&
5278         (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
5279       if (!Diagnose) return true;
5280 
5281       // Find any user-declared move constructor.
5282       for (auto *I : RD->ctors()) {
5283         if (I->isMoveConstructor()) {
5284           UserDeclaredMove = I;
5285           break;
5286         }
5287       }
5288       assert(UserDeclaredMove);
5289     } else if (RD->hasUserDeclaredMoveAssignment() &&
5290                (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
5291       if (!Diagnose) return true;
5292 
5293       // Find any user-declared move assignment operator.
5294       for (auto *I : RD->methods()) {
5295         if (I->isMoveAssignmentOperator()) {
5296           UserDeclaredMove = I;
5297           break;
5298         }
5299       }
5300       assert(UserDeclaredMove);
5301     }
5302 
5303     if (UserDeclaredMove) {
5304       Diag(UserDeclaredMove->getLocation(),
5305            diag::note_deleted_copy_user_declared_move)
5306         << (CSM == CXXCopyAssignment) << RD
5307         << UserDeclaredMove->isMoveAssignmentOperator();
5308       return true;
5309     }
5310   }
5311 
5312   // Do access control from the special member function
5313   ContextRAII MethodContext(*this, MD);
5314 
5315   // C++11 [class.dtor]p5:
5316   // -- for a virtual destructor, lookup of the non-array deallocation function
5317   //    results in an ambiguity or in a function that is deleted or inaccessible
5318   if (CSM == CXXDestructor && MD->isVirtual()) {
5319     FunctionDecl *OperatorDelete = 0;
5320     DeclarationName Name =
5321       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5322     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
5323                                  OperatorDelete, false)) {
5324       if (Diagnose)
5325         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
5326       return true;
5327     }
5328   }
5329 
5330   SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
5331 
5332   for (auto &BI : RD->bases())
5333     if (!BI.isVirtual() &&
5334         SMI.shouldDeleteForBase(&BI))
5335       return true;
5336 
5337   // Per DR1611, do not consider virtual bases of constructors of abstract
5338   // classes, since we are not going to construct them.
5339   if (!RD->isAbstract() || !SMI.IsConstructor) {
5340     for (auto &BI : RD->vbases())
5341       if (SMI.shouldDeleteForBase(&BI))
5342         return true;
5343   }
5344 
5345   for (auto *FI : RD->fields())
5346     if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
5347         SMI.shouldDeleteForField(FI))
5348       return true;
5349 
5350   if (SMI.shouldDeleteForAllConstMembers())
5351     return true;
5352 
5353   return false;
5354 }
5355 
5356 /// Perform lookup for a special member of the specified kind, and determine
5357 /// whether it is trivial. If the triviality can be determined without the
5358 /// lookup, skip it. This is intended for use when determining whether a
5359 /// special member of a containing object is trivial, and thus does not ever
5360 /// perform overload resolution for default constructors.
5361 ///
5362 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5363 /// member that was most likely to be intended to be trivial, if any.
5364 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5365                                      Sema::CXXSpecialMember CSM, unsigned Quals,
5366                                      bool ConstRHS, CXXMethodDecl **Selected) {
5367   if (Selected)
5368     *Selected = 0;
5369 
5370   switch (CSM) {
5371   case Sema::CXXInvalid:
5372     llvm_unreachable("not a special member");
5373 
5374   case Sema::CXXDefaultConstructor:
5375     // C++11 [class.ctor]p5:
5376     //   A default constructor is trivial if:
5377     //    - all the [direct subobjects] have trivial default constructors
5378     //
5379     // Note, no overload resolution is performed in this case.
5380     if (RD->hasTrivialDefaultConstructor())
5381       return true;
5382 
5383     if (Selected) {
5384       // If there's a default constructor which could have been trivial, dig it
5385       // out. Otherwise, if there's any user-provided default constructor, point
5386       // to that as an example of why there's not a trivial one.
5387       CXXConstructorDecl *DefCtor = 0;
5388       if (RD->needsImplicitDefaultConstructor())
5389         S.DeclareImplicitDefaultConstructor(RD);
5390       for (auto *CI : RD->ctors()) {
5391         if (!CI->isDefaultConstructor())
5392           continue;
5393         DefCtor = CI;
5394         if (!DefCtor->isUserProvided())
5395           break;
5396       }
5397 
5398       *Selected = DefCtor;
5399     }
5400 
5401     return false;
5402 
5403   case Sema::CXXDestructor:
5404     // C++11 [class.dtor]p5:
5405     //   A destructor is trivial if:
5406     //    - all the direct [subobjects] have trivial destructors
5407     if (RD->hasTrivialDestructor())
5408       return true;
5409 
5410     if (Selected) {
5411       if (RD->needsImplicitDestructor())
5412         S.DeclareImplicitDestructor(RD);
5413       *Selected = RD->getDestructor();
5414     }
5415 
5416     return false;
5417 
5418   case Sema::CXXCopyConstructor:
5419     // C++11 [class.copy]p12:
5420     //   A copy constructor is trivial if:
5421     //    - the constructor selected to copy each direct [subobject] is trivial
5422     if (RD->hasTrivialCopyConstructor()) {
5423       if (Quals == Qualifiers::Const)
5424         // We must either select the trivial copy constructor or reach an
5425         // ambiguity; no need to actually perform overload resolution.
5426         return true;
5427     } else if (!Selected) {
5428       return false;
5429     }
5430     // In C++98, we are not supposed to perform overload resolution here, but we
5431     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5432     // cases like B as having a non-trivial copy constructor:
5433     //   struct A { template<typename T> A(T&); };
5434     //   struct B { mutable A a; };
5435     goto NeedOverloadResolution;
5436 
5437   case Sema::CXXCopyAssignment:
5438     // C++11 [class.copy]p25:
5439     //   A copy assignment operator is trivial if:
5440     //    - the assignment operator selected to copy each direct [subobject] is
5441     //      trivial
5442     if (RD->hasTrivialCopyAssignment()) {
5443       if (Quals == Qualifiers::Const)
5444         return true;
5445     } else if (!Selected) {
5446       return false;
5447     }
5448     // In C++98, we are not supposed to perform overload resolution here, but we
5449     // treat that as a language defect.
5450     goto NeedOverloadResolution;
5451 
5452   case Sema::CXXMoveConstructor:
5453   case Sema::CXXMoveAssignment:
5454   NeedOverloadResolution:
5455     Sema::SpecialMemberOverloadResult *SMOR =
5456         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
5457 
5458     // The standard doesn't describe how to behave if the lookup is ambiguous.
5459     // We treat it as not making the member non-trivial, just like the standard
5460     // mandates for the default constructor. This should rarely matter, because
5461     // the member will also be deleted.
5462     if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5463       return true;
5464 
5465     if (!SMOR->getMethod()) {
5466       assert(SMOR->getKind() ==
5467              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5468       return false;
5469     }
5470 
5471     // We deliberately don't check if we found a deleted special member. We're
5472     // not supposed to!
5473     if (Selected)
5474       *Selected = SMOR->getMethod();
5475     return SMOR->getMethod()->isTrivial();
5476   }
5477 
5478   llvm_unreachable("unknown special method kind");
5479 }
5480 
5481 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
5482   for (auto *CI : RD->ctors())
5483     if (!CI->isImplicit())
5484       return CI;
5485 
5486   // Look for constructor templates.
5487   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5488   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5489     if (CXXConstructorDecl *CD =
5490           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5491       return CD;
5492   }
5493 
5494   return 0;
5495 }
5496 
5497 /// The kind of subobject we are checking for triviality. The values of this
5498 /// enumeration are used in diagnostics.
5499 enum TrivialSubobjectKind {
5500   /// The subobject is a base class.
5501   TSK_BaseClass,
5502   /// The subobject is a non-static data member.
5503   TSK_Field,
5504   /// The object is actually the complete object.
5505   TSK_CompleteObject
5506 };
5507 
5508 /// Check whether the special member selected for a given type would be trivial.
5509 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5510                                       QualType SubType, bool ConstRHS,
5511                                       Sema::CXXSpecialMember CSM,
5512                                       TrivialSubobjectKind Kind,
5513                                       bool Diagnose) {
5514   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5515   if (!SubRD)
5516     return true;
5517 
5518   CXXMethodDecl *Selected;
5519   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5520                                ConstRHS, Diagnose ? &Selected : 0))
5521     return true;
5522 
5523   if (Diagnose) {
5524     if (ConstRHS)
5525       SubType.addConst();
5526 
5527     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5528       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5529         << Kind << SubType.getUnqualifiedType();
5530       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5531         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5532     } else if (!Selected)
5533       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5534         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5535     else if (Selected->isUserProvided()) {
5536       if (Kind == TSK_CompleteObject)
5537         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5538           << Kind << SubType.getUnqualifiedType() << CSM;
5539       else {
5540         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5541           << Kind << SubType.getUnqualifiedType() << CSM;
5542         S.Diag(Selected->getLocation(), diag::note_declared_at);
5543       }
5544     } else {
5545       if (Kind != TSK_CompleteObject)
5546         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5547           << Kind << SubType.getUnqualifiedType() << CSM;
5548 
5549       // Explain why the defaulted or deleted special member isn't trivial.
5550       S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5551     }
5552   }
5553 
5554   return false;
5555 }
5556 
5557 /// Check whether the members of a class type allow a special member to be
5558 /// trivial.
5559 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5560                                      Sema::CXXSpecialMember CSM,
5561                                      bool ConstArg, bool Diagnose) {
5562   for (const auto *FI : RD->fields()) {
5563     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5564       continue;
5565 
5566     QualType FieldType = S.Context.getBaseElementType(FI->getType());
5567 
5568     // Pretend anonymous struct or union members are members of this class.
5569     if (FI->isAnonymousStructOrUnion()) {
5570       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5571                                     CSM, ConstArg, Diagnose))
5572         return false;
5573       continue;
5574     }
5575 
5576     // C++11 [class.ctor]p5:
5577     //   A default constructor is trivial if [...]
5578     //    -- no non-static data member of its class has a
5579     //       brace-or-equal-initializer
5580     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5581       if (Diagnose)
5582         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
5583       return false;
5584     }
5585 
5586     // Objective C ARC 4.3.5:
5587     //   [...] nontrivally ownership-qualified types are [...] not trivially
5588     //   default constructible, copy constructible, move constructible, copy
5589     //   assignable, move assignable, or destructible [...]
5590     if (S.getLangOpts().ObjCAutoRefCount &&
5591         FieldType.hasNonTrivialObjCLifetime()) {
5592       if (Diagnose)
5593         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5594           << RD << FieldType.getObjCLifetime();
5595       return false;
5596     }
5597 
5598     bool ConstRHS = ConstArg && !FI->isMutable();
5599     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
5600                                    CSM, TSK_Field, Diagnose))
5601       return false;
5602   }
5603 
5604   return true;
5605 }
5606 
5607 /// Diagnose why the specified class does not have a trivial special member of
5608 /// the given kind.
5609 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5610   QualType Ty = Context.getRecordType(RD);
5611 
5612   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
5613   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
5614                             TSK_CompleteObject, /*Diagnose*/true);
5615 }
5616 
5617 /// Determine whether a defaulted or deleted special member function is trivial,
5618 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5619 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5620 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5621                                   bool Diagnose) {
5622   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5623 
5624   CXXRecordDecl *RD = MD->getParent();
5625 
5626   bool ConstArg = false;
5627 
5628   // C++11 [class.copy]p12, p25: [DR1593]
5629   //   A [special member] is trivial if [...] its parameter-type-list is
5630   //   equivalent to the parameter-type-list of an implicit declaration [...]
5631   switch (CSM) {
5632   case CXXDefaultConstructor:
5633   case CXXDestructor:
5634     // Trivial default constructors and destructors cannot have parameters.
5635     break;
5636 
5637   case CXXCopyConstructor:
5638   case CXXCopyAssignment: {
5639     // Trivial copy operations always have const, non-volatile parameter types.
5640     ConstArg = true;
5641     const ParmVarDecl *Param0 = MD->getParamDecl(0);
5642     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5643     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5644       if (Diagnose)
5645         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5646           << Param0->getSourceRange() << Param0->getType()
5647           << Context.getLValueReferenceType(
5648                Context.getRecordType(RD).withConst());
5649       return false;
5650     }
5651     break;
5652   }
5653 
5654   case CXXMoveConstructor:
5655   case CXXMoveAssignment: {
5656     // Trivial move operations always have non-cv-qualified parameters.
5657     const ParmVarDecl *Param0 = MD->getParamDecl(0);
5658     const RValueReferenceType *RT =
5659       Param0->getType()->getAs<RValueReferenceType>();
5660     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5661       if (Diagnose)
5662         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5663           << Param0->getSourceRange() << Param0->getType()
5664           << Context.getRValueReferenceType(Context.getRecordType(RD));
5665       return false;
5666     }
5667     break;
5668   }
5669 
5670   case CXXInvalid:
5671     llvm_unreachable("not a special member");
5672   }
5673 
5674   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5675     if (Diagnose)
5676       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5677            diag::note_nontrivial_default_arg)
5678         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5679     return false;
5680   }
5681   if (MD->isVariadic()) {
5682     if (Diagnose)
5683       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5684     return false;
5685   }
5686 
5687   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5688   //   A copy/move [constructor or assignment operator] is trivial if
5689   //    -- the [member] selected to copy/move each direct base class subobject
5690   //       is trivial
5691   //
5692   // C++11 [class.copy]p12, C++11 [class.copy]p25:
5693   //   A [default constructor or destructor] is trivial if
5694   //    -- all the direct base classes have trivial [default constructors or
5695   //       destructors]
5696   for (const auto &BI : RD->bases())
5697     if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
5698                                    ConstArg, CSM, TSK_BaseClass, Diagnose))
5699       return false;
5700 
5701   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5702   //   A copy/move [constructor or assignment operator] for a class X is
5703   //   trivial if
5704   //    -- for each non-static data member of X that is of class type (or array
5705   //       thereof), the constructor selected to copy/move that member is
5706   //       trivial
5707   //
5708   // C++11 [class.copy]p12, C++11 [class.copy]p25:
5709   //   A [default constructor or destructor] is trivial if
5710   //    -- for all of the non-static data members of its class that are of class
5711   //       type (or array thereof), each such class has a trivial [default
5712   //       constructor or destructor]
5713   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5714     return false;
5715 
5716   // C++11 [class.dtor]p5:
5717   //   A destructor is trivial if [...]
5718   //    -- the destructor is not virtual
5719   if (CSM == CXXDestructor && MD->isVirtual()) {
5720     if (Diagnose)
5721       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5722     return false;
5723   }
5724 
5725   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5726   //   A [special member] for class X is trivial if [...]
5727   //    -- class X has no virtual functions and no virtual base classes
5728   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5729     if (!Diagnose)
5730       return false;
5731 
5732     if (RD->getNumVBases()) {
5733       // Check for virtual bases. We already know that the corresponding
5734       // member in all bases is trivial, so vbases must all be direct.
5735       CXXBaseSpecifier &BS = *RD->vbases_begin();
5736       assert(BS.isVirtual());
5737       Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5738       return false;
5739     }
5740 
5741     // Must have a virtual method.
5742     for (const auto *MI : RD->methods()) {
5743       if (MI->isVirtual()) {
5744         SourceLocation MLoc = MI->getLocStart();
5745         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5746         return false;
5747       }
5748     }
5749 
5750     llvm_unreachable("dynamic class with no vbases and no virtual functions");
5751   }
5752 
5753   // Looks like it's trivial!
5754   return true;
5755 }
5756 
5757 /// \brief Data used with FindHiddenVirtualMethod
5758 namespace {
5759   struct FindHiddenVirtualMethodData {
5760     Sema *S;
5761     CXXMethodDecl *Method;
5762     llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
5763     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5764   };
5765 }
5766 
5767 /// \brief Check whether any most overriden method from MD in Methods
5768 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5769                    const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5770   if (MD->size_overridden_methods() == 0)
5771     return Methods.count(MD->getCanonicalDecl());
5772   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5773                                       E = MD->end_overridden_methods();
5774        I != E; ++I)
5775     if (CheckMostOverridenMethods(*I, Methods))
5776       return true;
5777   return false;
5778 }
5779 
5780 /// \brief Member lookup function that determines whether a given C++
5781 /// method overloads virtual methods in a base class without overriding any,
5782 /// to be used with CXXRecordDecl::lookupInBases().
5783 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5784                                     CXXBasePath &Path,
5785                                     void *UserData) {
5786   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5787 
5788   FindHiddenVirtualMethodData &Data
5789     = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5790 
5791   DeclarationName Name = Data.Method->getDeclName();
5792   assert(Name.getNameKind() == DeclarationName::Identifier);
5793 
5794   bool foundSameNameMethod = false;
5795   SmallVector<CXXMethodDecl *, 8> overloadedMethods;
5796   for (Path.Decls = BaseRecord->lookup(Name);
5797        !Path.Decls.empty();
5798        Path.Decls = Path.Decls.slice(1)) {
5799     NamedDecl *D = Path.Decls.front();
5800     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5801       MD = MD->getCanonicalDecl();
5802       foundSameNameMethod = true;
5803       // Interested only in hidden virtual methods.
5804       if (!MD->isVirtual())
5805         continue;
5806       // If the method we are checking overrides a method from its base
5807       // don't warn about the other overloaded methods.
5808       if (!Data.S->IsOverload(Data.Method, MD, false))
5809         return true;
5810       // Collect the overload only if its hidden.
5811       if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
5812         overloadedMethods.push_back(MD);
5813     }
5814   }
5815 
5816   if (foundSameNameMethod)
5817     Data.OverloadedMethods.append(overloadedMethods.begin(),
5818                                    overloadedMethods.end());
5819   return foundSameNameMethod;
5820 }
5821 
5822 /// \brief Add the most overriden methods from MD to Methods
5823 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5824                          llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5825   if (MD->size_overridden_methods() == 0)
5826     Methods.insert(MD->getCanonicalDecl());
5827   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5828                                       E = MD->end_overridden_methods();
5829        I != E; ++I)
5830     AddMostOverridenMethods(*I, Methods);
5831 }
5832 
5833 /// \brief Check if a method overloads virtual methods in a base class without
5834 /// overriding any.
5835 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
5836                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
5837   if (!MD->getDeclName().isIdentifier())
5838     return;
5839 
5840   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5841                      /*bool RecordPaths=*/false,
5842                      /*bool DetectVirtual=*/false);
5843   FindHiddenVirtualMethodData Data;
5844   Data.Method = MD;
5845   Data.S = this;
5846 
5847   // Keep the base methods that were overriden or introduced in the subclass
5848   // by 'using' in a set. A base method not in this set is hidden.
5849   CXXRecordDecl *DC = MD->getParent();
5850   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5851   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5852     NamedDecl *ND = *I;
5853     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
5854       ND = shad->getTargetDecl();
5855     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5856       AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
5857   }
5858 
5859   if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
5860     OverloadedMethods = Data.OverloadedMethods;
5861 }
5862 
5863 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
5864                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
5865   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
5866     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
5867     PartialDiagnostic PD = PDiag(
5868          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5869     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5870     Diag(overloadedMD->getLocation(), PD);
5871   }
5872 }
5873 
5874 /// \brief Diagnose methods which overload virtual methods in a base class
5875 /// without overriding any.
5876 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
5877   if (MD->isInvalidDecl())
5878     return;
5879 
5880   if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
5881                                MD->getLocation()) == DiagnosticsEngine::Ignored)
5882     return;
5883 
5884   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5885   FindHiddenVirtualMethods(MD, OverloadedMethods);
5886   if (!OverloadedMethods.empty()) {
5887     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5888       << MD << (OverloadedMethods.size() > 1);
5889 
5890     NoteHiddenVirtualMethods(MD, OverloadedMethods);
5891   }
5892 }
5893 
5894 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5895                                              Decl *TagDecl,
5896                                              SourceLocation LBrac,
5897                                              SourceLocation RBrac,
5898                                              AttributeList *AttrList) {
5899   if (!TagDecl)
5900     return;
5901 
5902   AdjustDeclIfTemplate(TagDecl);
5903 
5904   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5905     if (l->getKind() != AttributeList::AT_Visibility)
5906       continue;
5907     l->setInvalid();
5908     Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5909       l->getName();
5910   }
5911 
5912   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
5913               // strict aliasing violation!
5914               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
5915               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
5916 
5917   CheckCompletedCXXClass(
5918                         dyn_cast_or_null<CXXRecordDecl>(TagDecl));
5919 }
5920 
5921 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5922 /// special functions, such as the default constructor, copy
5923 /// constructor, or destructor, to the given C++ class (C++
5924 /// [special]p1).  This routine can only be executed just before the
5925 /// definition of the class is complete.
5926 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
5927   if (!ClassDecl->hasUserDeclaredConstructor())
5928     ++ASTContext::NumImplicitDefaultConstructors;
5929 
5930   if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
5931     ++ASTContext::NumImplicitCopyConstructors;
5932 
5933     // If the properties or semantics of the copy constructor couldn't be
5934     // determined while the class was being declared, force a declaration
5935     // of it now.
5936     if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5937       DeclareImplicitCopyConstructor(ClassDecl);
5938   }
5939 
5940   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
5941     ++ASTContext::NumImplicitMoveConstructors;
5942 
5943     if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5944       DeclareImplicitMoveConstructor(ClassDecl);
5945   }
5946 
5947   if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5948     ++ASTContext::NumImplicitCopyAssignmentOperators;
5949 
5950     // If we have a dynamic class, then the copy assignment operator may be
5951     // virtual, so we have to declare it immediately. This ensures that, e.g.,
5952     // it shows up in the right place in the vtable and that we diagnose
5953     // problems with the implicit exception specification.
5954     if (ClassDecl->isDynamicClass() ||
5955         ClassDecl->needsOverloadResolutionForCopyAssignment())
5956       DeclareImplicitCopyAssignment(ClassDecl);
5957   }
5958 
5959   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
5960     ++ASTContext::NumImplicitMoveAssignmentOperators;
5961 
5962     // Likewise for the move assignment operator.
5963     if (ClassDecl->isDynamicClass() ||
5964         ClassDecl->needsOverloadResolutionForMoveAssignment())
5965       DeclareImplicitMoveAssignment(ClassDecl);
5966   }
5967 
5968   if (!ClassDecl->hasUserDeclaredDestructor()) {
5969     ++ASTContext::NumImplicitDestructors;
5970 
5971     // If we have a dynamic class, then the destructor may be virtual, so we
5972     // have to declare the destructor immediately. This ensures that, e.g., it
5973     // shows up in the right place in the vtable and that we diagnose problems
5974     // with the implicit exception specification.
5975     if (ClassDecl->isDynamicClass() ||
5976         ClassDecl->needsOverloadResolutionForDestructor())
5977       DeclareImplicitDestructor(ClassDecl);
5978   }
5979 }
5980 
5981 void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5982   if (!D)
5983     return;
5984 
5985   int NumParamList = D->getNumTemplateParameterLists();
5986   for (int i = 0; i < NumParamList; i++) {
5987     TemplateParameterList* Params = D->getTemplateParameterList(i);
5988     for (TemplateParameterList::iterator Param = Params->begin(),
5989                                       ParamEnd = Params->end();
5990           Param != ParamEnd; ++Param) {
5991       NamedDecl *Named = cast<NamedDecl>(*Param);
5992       if (Named->getDeclName()) {
5993         S->AddDecl(Named);
5994         IdResolver.AddDecl(Named);
5995       }
5996     }
5997   }
5998 }
5999 
6000 void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
6001   if (!D)
6002     return;
6003 
6004   TemplateParameterList *Params = 0;
6005   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
6006     Params = Template->getTemplateParameters();
6007   else if (ClassTemplatePartialSpecializationDecl *PartialSpec
6008            = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6009     Params = PartialSpec->getTemplateParameters();
6010   else
6011     return;
6012 
6013   for (TemplateParameterList::iterator Param = Params->begin(),
6014                                     ParamEnd = Params->end();
6015        Param != ParamEnd; ++Param) {
6016     NamedDecl *Named = cast<NamedDecl>(*Param);
6017     if (Named->getDeclName()) {
6018       S->AddDecl(Named);
6019       IdResolver.AddDecl(Named);
6020     }
6021   }
6022 }
6023 
6024 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6025   if (!RecordD) return;
6026   AdjustDeclIfTemplate(RecordD);
6027   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
6028   PushDeclContext(S, Record);
6029 }
6030 
6031 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6032   if (!RecordD) return;
6033   PopDeclContext();
6034 }
6035 
6036 /// This is used to implement the constant expression evaluation part of the
6037 /// attribute enable_if extension. There is nothing in standard C++ which would
6038 /// require reentering parameters.
6039 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6040   if (!Param)
6041     return;
6042 
6043   S->AddDecl(Param);
6044   if (Param->getDeclName())
6045     IdResolver.AddDecl(Param);
6046 }
6047 
6048 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
6049 /// parsing a top-level (non-nested) C++ class, and we are now
6050 /// parsing those parts of the given Method declaration that could
6051 /// not be parsed earlier (C++ [class.mem]p2), such as default
6052 /// arguments. This action should enter the scope of the given
6053 /// Method declaration as if we had just parsed the qualified method
6054 /// name. However, it should not bring the parameters into scope;
6055 /// that will be performed by ActOnDelayedCXXMethodParameter.
6056 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6057 }
6058 
6059 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
6060 /// C++ method declaration. We're (re-)introducing the given
6061 /// function parameter into scope for use in parsing later parts of
6062 /// the method declaration. For example, we could see an
6063 /// ActOnParamDefaultArgument event for this parameter.
6064 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
6065   if (!ParamD)
6066     return;
6067 
6068   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
6069 
6070   // If this parameter has an unparsed default argument, clear it out
6071   // to make way for the parsed default argument.
6072   if (Param->hasUnparsedDefaultArg())
6073     Param->setDefaultArg(0);
6074 
6075   S->AddDecl(Param);
6076   if (Param->getDeclName())
6077     IdResolver.AddDecl(Param);
6078 }
6079 
6080 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6081 /// processing the delayed method declaration for Method. The method
6082 /// declaration is now considered finished. There may be a separate
6083 /// ActOnStartOfFunctionDef action later (not necessarily
6084 /// immediately!) for this method, if it was also defined inside the
6085 /// class body.
6086 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6087   if (!MethodD)
6088     return;
6089 
6090   AdjustDeclIfTemplate(MethodD);
6091 
6092   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
6093 
6094   // Now that we have our default arguments, check the constructor
6095   // again. It could produce additional diagnostics or affect whether
6096   // the class has implicitly-declared destructors, among other
6097   // things.
6098   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6099     CheckConstructor(Constructor);
6100 
6101   // Check the default arguments, which we may have added.
6102   if (!Method->isInvalidDecl())
6103     CheckCXXDefaultArguments(Method);
6104 }
6105 
6106 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
6107 /// the well-formedness of the constructor declarator @p D with type @p
6108 /// R. If there are any errors in the declarator, this routine will
6109 /// emit diagnostics and set the invalid bit to true.  In any case, the type
6110 /// will be updated to reflect a well-formed type for the constructor and
6111 /// returned.
6112 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
6113                                           StorageClass &SC) {
6114   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6115 
6116   // C++ [class.ctor]p3:
6117   //   A constructor shall not be virtual (10.3) or static (9.4). A
6118   //   constructor can be invoked for a const, volatile or const
6119   //   volatile object. A constructor shall not be declared const,
6120   //   volatile, or const volatile (9.3.2).
6121   if (isVirtual) {
6122     if (!D.isInvalidType())
6123       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6124         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6125         << SourceRange(D.getIdentifierLoc());
6126     D.setInvalidType();
6127   }
6128   if (SC == SC_Static) {
6129     if (!D.isInvalidType())
6130       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6131         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6132         << SourceRange(D.getIdentifierLoc());
6133     D.setInvalidType();
6134     SC = SC_None;
6135   }
6136 
6137   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6138   if (FTI.TypeQuals != 0) {
6139     if (FTI.TypeQuals & Qualifiers::Const)
6140       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6141         << "const" << SourceRange(D.getIdentifierLoc());
6142     if (FTI.TypeQuals & Qualifiers::Volatile)
6143       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6144         << "volatile" << SourceRange(D.getIdentifierLoc());
6145     if (FTI.TypeQuals & Qualifiers::Restrict)
6146       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6147         << "restrict" << SourceRange(D.getIdentifierLoc());
6148     D.setInvalidType();
6149   }
6150 
6151   // C++0x [class.ctor]p4:
6152   //   A constructor shall not be declared with a ref-qualifier.
6153   if (FTI.hasRefQualifier()) {
6154     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6155       << FTI.RefQualifierIsLValueRef
6156       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6157     D.setInvalidType();
6158   }
6159 
6160   // Rebuild the function type "R" without any type qualifiers (in
6161   // case any of the errors above fired) and with "void" as the
6162   // return type, since constructors don't have return types.
6163   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6164   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
6165     return R;
6166 
6167   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6168   EPI.TypeQuals = 0;
6169   EPI.RefQualifier = RQ_None;
6170 
6171   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
6172 }
6173 
6174 /// CheckConstructor - Checks a fully-formed constructor for
6175 /// well-formedness, issuing any diagnostics required. Returns true if
6176 /// the constructor declarator is invalid.
6177 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
6178   CXXRecordDecl *ClassDecl
6179     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6180   if (!ClassDecl)
6181     return Constructor->setInvalidDecl();
6182 
6183   // C++ [class.copy]p3:
6184   //   A declaration of a constructor for a class X is ill-formed if
6185   //   its first parameter is of type (optionally cv-qualified) X and
6186   //   either there are no other parameters or else all other
6187   //   parameters have default arguments.
6188   if (!Constructor->isInvalidDecl() &&
6189       ((Constructor->getNumParams() == 1) ||
6190        (Constructor->getNumParams() > 1 &&
6191         Constructor->getParamDecl(1)->hasDefaultArg())) &&
6192       Constructor->getTemplateSpecializationKind()
6193                                               != TSK_ImplicitInstantiation) {
6194     QualType ParamType = Constructor->getParamDecl(0)->getType();
6195     QualType ClassTy = Context.getTagDeclType(ClassDecl);
6196     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
6197       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
6198       const char *ConstRef
6199         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6200                                                         : " const &";
6201       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
6202         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
6203 
6204       // FIXME: Rather that making the constructor invalid, we should endeavor
6205       // to fix the type.
6206       Constructor->setInvalidDecl();
6207     }
6208   }
6209 }
6210 
6211 /// CheckDestructor - Checks a fully-formed destructor definition for
6212 /// well-formedness, issuing any diagnostics required.  Returns true
6213 /// on error.
6214 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
6215   CXXRecordDecl *RD = Destructor->getParent();
6216 
6217   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
6218     SourceLocation Loc;
6219 
6220     if (!Destructor->isImplicit())
6221       Loc = Destructor->getLocation();
6222     else
6223       Loc = RD->getLocation();
6224 
6225     // If we have a virtual destructor, look up the deallocation function
6226     FunctionDecl *OperatorDelete = 0;
6227     DeclarationName Name =
6228     Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6229     if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
6230       return true;
6231     // If there's no class-specific operator delete, look up the global
6232     // non-array delete.
6233     if (!OperatorDelete)
6234       OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
6235 
6236     MarkFunctionReferenced(Loc, OperatorDelete);
6237 
6238     Destructor->setOperatorDelete(OperatorDelete);
6239   }
6240 
6241   return false;
6242 }
6243 
6244 static inline bool
6245 FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
6246   return (FTI.NumParams == 1 && !FTI.isVariadic && FTI.Params[0].Ident == 0 &&
6247           FTI.Params[0].Param &&
6248           cast<ParmVarDecl>(FTI.Params[0].Param)->getType()->isVoidType());
6249 }
6250 
6251 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6252 /// the well-formednes of the destructor declarator @p D with type @p
6253 /// R. If there are any errors in the declarator, this routine will
6254 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
6255 /// will be updated to reflect a well-formed type for the destructor and
6256 /// returned.
6257 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
6258                                          StorageClass& SC) {
6259   // C++ [class.dtor]p1:
6260   //   [...] A typedef-name that names a class is a class-name
6261   //   (7.1.3); however, a typedef-name that names a class shall not
6262   //   be used as the identifier in the declarator for a destructor
6263   //   declaration.
6264   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
6265   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
6266     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6267       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
6268   else if (const TemplateSpecializationType *TST =
6269              DeclaratorType->getAs<TemplateSpecializationType>())
6270     if (TST->isTypeAlias())
6271       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6272         << DeclaratorType << 1;
6273 
6274   // C++ [class.dtor]p2:
6275   //   A destructor is used to destroy objects of its class type. A
6276   //   destructor takes no parameters, and no return type can be
6277   //   specified for it (not even void). The address of a destructor
6278   //   shall not be taken. A destructor shall not be static. A
6279   //   destructor can be invoked for a const, volatile or const
6280   //   volatile object. A destructor shall not be declared const,
6281   //   volatile or const volatile (9.3.2).
6282   if (SC == SC_Static) {
6283     if (!D.isInvalidType())
6284       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6285         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6286         << SourceRange(D.getIdentifierLoc())
6287         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6288 
6289     SC = SC_None;
6290   }
6291   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
6292     // Destructors don't have return types, but the parser will
6293     // happily parse something like:
6294     //
6295     //   class X {
6296     //     float ~X();
6297     //   };
6298     //
6299     // The return type will be eliminated later.
6300     Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6301       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6302       << SourceRange(D.getIdentifierLoc());
6303   }
6304 
6305   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6306   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
6307     if (FTI.TypeQuals & Qualifiers::Const)
6308       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6309         << "const" << SourceRange(D.getIdentifierLoc());
6310     if (FTI.TypeQuals & Qualifiers::Volatile)
6311       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6312         << "volatile" << SourceRange(D.getIdentifierLoc());
6313     if (FTI.TypeQuals & Qualifiers::Restrict)
6314       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6315         << "restrict" << SourceRange(D.getIdentifierLoc());
6316     D.setInvalidType();
6317   }
6318 
6319   // C++0x [class.dtor]p2:
6320   //   A destructor shall not be declared with a ref-qualifier.
6321   if (FTI.hasRefQualifier()) {
6322     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6323       << FTI.RefQualifierIsLValueRef
6324       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6325     D.setInvalidType();
6326   }
6327 
6328   // Make sure we don't have any parameters.
6329   if (FTI.NumParams > 0 && !FTIHasSingleVoidArgument(FTI)) {
6330     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6331 
6332     // Delete the parameters.
6333     FTI.freeParams();
6334     D.setInvalidType();
6335   }
6336 
6337   // Make sure the destructor isn't variadic.
6338   if (FTI.isVariadic) {
6339     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
6340     D.setInvalidType();
6341   }
6342 
6343   // Rebuild the function type "R" without any type qualifiers or
6344   // parameters (in case any of the errors above fired) and with
6345   // "void" as the return type, since destructors don't have return
6346   // types.
6347   if (!D.isInvalidType())
6348     return R;
6349 
6350   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6351   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6352   EPI.Variadic = false;
6353   EPI.TypeQuals = 0;
6354   EPI.RefQualifier = RQ_None;
6355   return Context.getFunctionType(Context.VoidTy, None, EPI);
6356 }
6357 
6358 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6359 /// well-formednes of the conversion function declarator @p D with
6360 /// type @p R. If there are any errors in the declarator, this routine
6361 /// will emit diagnostics and return true. Otherwise, it will return
6362 /// false. Either way, the type @p R will be updated to reflect a
6363 /// well-formed type for the conversion operator.
6364 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
6365                                      StorageClass& SC) {
6366   // C++ [class.conv.fct]p1:
6367   //   Neither parameter types nor return type can be specified. The
6368   //   type of a conversion function (8.3.5) is "function taking no
6369   //   parameter returning conversion-type-id."
6370   if (SC == SC_Static) {
6371     if (!D.isInvalidType())
6372       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
6373         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6374         << D.getName().getSourceRange();
6375     D.setInvalidType();
6376     SC = SC_None;
6377   }
6378 
6379   QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6380 
6381   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
6382     // Conversion functions don't have return types, but the parser will
6383     // happily parse something like:
6384     //
6385     //   class X {
6386     //     float operator bool();
6387     //   };
6388     //
6389     // The return type will be changed later anyway.
6390     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6391       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6392       << SourceRange(D.getIdentifierLoc());
6393     D.setInvalidType();
6394   }
6395 
6396   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6397 
6398   // Make sure we don't have any parameters.
6399   if (Proto->getNumParams() > 0) {
6400     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6401 
6402     // Delete the parameters.
6403     D.getFunctionTypeInfo().freeParams();
6404     D.setInvalidType();
6405   } else if (Proto->isVariadic()) {
6406     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
6407     D.setInvalidType();
6408   }
6409 
6410   // Diagnose "&operator bool()" and other such nonsense.  This
6411   // is actually a gcc extension which we don't support.
6412   if (Proto->getReturnType() != ConvType) {
6413     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6414         << Proto->getReturnType();
6415     D.setInvalidType();
6416     ConvType = Proto->getReturnType();
6417   }
6418 
6419   // C++ [class.conv.fct]p4:
6420   //   The conversion-type-id shall not represent a function type nor
6421   //   an array type.
6422   if (ConvType->isArrayType()) {
6423     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6424     ConvType = Context.getPointerType(ConvType);
6425     D.setInvalidType();
6426   } else if (ConvType->isFunctionType()) {
6427     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6428     ConvType = Context.getPointerType(ConvType);
6429     D.setInvalidType();
6430   }
6431 
6432   // Rebuild the function type "R" without any parameters (in case any
6433   // of the errors above fired) and with the conversion type as the
6434   // return type.
6435   if (D.isInvalidType())
6436     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
6437 
6438   // C++0x explicit conversion operators.
6439   if (D.getDeclSpec().isExplicitSpecified())
6440     Diag(D.getDeclSpec().getExplicitSpecLoc(),
6441          getLangOpts().CPlusPlus11 ?
6442            diag::warn_cxx98_compat_explicit_conversion_functions :
6443            diag::ext_explicit_conversion_functions)
6444       << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
6445 }
6446 
6447 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6448 /// the declaration of the given C++ conversion function. This routine
6449 /// is responsible for recording the conversion function in the C++
6450 /// class, if possible.
6451 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
6452   assert(Conversion && "Expected to receive a conversion function declaration");
6453 
6454   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
6455 
6456   // Make sure we aren't redeclaring the conversion function.
6457   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
6458 
6459   // C++ [class.conv.fct]p1:
6460   //   [...] A conversion function is never used to convert a
6461   //   (possibly cv-qualified) object to the (possibly cv-qualified)
6462   //   same object type (or a reference to it), to a (possibly
6463   //   cv-qualified) base class of that type (or a reference to it),
6464   //   or to (possibly cv-qualified) void.
6465   // FIXME: Suppress this warning if the conversion function ends up being a
6466   // virtual function that overrides a virtual function in a base class.
6467   QualType ClassType
6468     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6469   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
6470     ConvType = ConvTypeRef->getPointeeType();
6471   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6472       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
6473     /* Suppress diagnostics for instantiations. */;
6474   else if (ConvType->isRecordType()) {
6475     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6476     if (ConvType == ClassType)
6477       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
6478         << ClassType;
6479     else if (IsDerivedFrom(ClassType, ConvType))
6480       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
6481         <<  ClassType << ConvType;
6482   } else if (ConvType->isVoidType()) {
6483     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
6484       << ClassType << ConvType;
6485   }
6486 
6487   if (FunctionTemplateDecl *ConversionTemplate
6488                                 = Conversion->getDescribedFunctionTemplate())
6489     return ConversionTemplate;
6490 
6491   return Conversion;
6492 }
6493 
6494 //===----------------------------------------------------------------------===//
6495 // Namespace Handling
6496 //===----------------------------------------------------------------------===//
6497 
6498 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6499 /// reopened.
6500 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6501                                             SourceLocation Loc,
6502                                             IdentifierInfo *II, bool *IsInline,
6503                                             NamespaceDecl *PrevNS) {
6504   assert(*IsInline != PrevNS->isInline());
6505 
6506   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6507   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6508   // inline namespaces, with the intention of bringing names into namespace std.
6509   //
6510   // We support this just well enough to get that case working; this is not
6511   // sufficient to support reopening namespaces as inline in general.
6512   if (*IsInline && II && II->getName().startswith("__atomic") &&
6513       S.getSourceManager().isInSystemHeader(Loc)) {
6514     // Mark all prior declarations of the namespace as inline.
6515     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6516          NS = NS->getPreviousDecl())
6517       NS->setInline(*IsInline);
6518     // Patch up the lookup table for the containing namespace. This isn't really
6519     // correct, but it's good enough for this particular case.
6520     for (auto *I : PrevNS->decls())
6521       if (auto *ND = dyn_cast<NamedDecl>(I))
6522         PrevNS->getParent()->makeDeclVisibleInContext(ND);
6523     return;
6524   }
6525 
6526   if (PrevNS->isInline())
6527     // The user probably just forgot the 'inline', so suggest that it
6528     // be added back.
6529     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6530       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6531   else
6532     S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
6533 
6534   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6535   *IsInline = PrevNS->isInline();
6536 }
6537 
6538 /// ActOnStartNamespaceDef - This is called at the start of a namespace
6539 /// definition.
6540 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
6541                                    SourceLocation InlineLoc,
6542                                    SourceLocation NamespaceLoc,
6543                                    SourceLocation IdentLoc,
6544                                    IdentifierInfo *II,
6545                                    SourceLocation LBrace,
6546                                    AttributeList *AttrList) {
6547   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6548   // For anonymous namespace, take the location of the left brace.
6549   SourceLocation Loc = II ? IdentLoc : LBrace;
6550   bool IsInline = InlineLoc.isValid();
6551   bool IsInvalid = false;
6552   bool IsStd = false;
6553   bool AddToKnown = false;
6554   Scope *DeclRegionScope = NamespcScope->getParent();
6555 
6556   NamespaceDecl *PrevNS = 0;
6557   if (II) {
6558     // C++ [namespace.def]p2:
6559     //   The identifier in an original-namespace-definition shall not
6560     //   have been previously defined in the declarative region in
6561     //   which the original-namespace-definition appears. The
6562     //   identifier in an original-namespace-definition is the name of
6563     //   the namespace. Subsequently in that declarative region, it is
6564     //   treated as an original-namespace-name.
6565     //
6566     // Since namespace names are unique in their scope, and we don't
6567     // look through using directives, just look for any ordinary names.
6568 
6569     const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
6570     Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6571     Decl::IDNS_Namespace;
6572     NamedDecl *PrevDecl = 0;
6573     DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6574     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6575          ++I) {
6576       if ((*I)->getIdentifierNamespace() & IDNS) {
6577         PrevDecl = *I;
6578         break;
6579       }
6580     }
6581 
6582     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6583 
6584     if (PrevNS) {
6585       // This is an extended namespace definition.
6586       if (IsInline != PrevNS->isInline())
6587         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6588                                         &IsInline, PrevNS);
6589     } else if (PrevDecl) {
6590       // This is an invalid name redefinition.
6591       Diag(Loc, diag::err_redefinition_different_kind)
6592         << II;
6593       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6594       IsInvalid = true;
6595       // Continue on to push Namespc as current DeclContext and return it.
6596     } else if (II->isStr("std") &&
6597                CurContext->getRedeclContext()->isTranslationUnit()) {
6598       // This is the first "real" definition of the namespace "std", so update
6599       // our cache of the "std" namespace to point at this definition.
6600       PrevNS = getStdNamespace();
6601       IsStd = true;
6602       AddToKnown = !IsInline;
6603     } else {
6604       // We've seen this namespace for the first time.
6605       AddToKnown = !IsInline;
6606     }
6607   } else {
6608     // Anonymous namespaces.
6609 
6610     // Determine whether the parent already has an anonymous namespace.
6611     DeclContext *Parent = CurContext->getRedeclContext();
6612     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6613       PrevNS = TU->getAnonymousNamespace();
6614     } else {
6615       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
6616       PrevNS = ND->getAnonymousNamespace();
6617     }
6618 
6619     if (PrevNS && IsInline != PrevNS->isInline())
6620       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6621                                       &IsInline, PrevNS);
6622   }
6623 
6624   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6625                                                  StartLoc, Loc, II, PrevNS);
6626   if (IsInvalid)
6627     Namespc->setInvalidDecl();
6628 
6629   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
6630 
6631   // FIXME: Should we be merging attributes?
6632   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
6633     PushNamespaceVisibilityAttr(Attr, Loc);
6634 
6635   if (IsStd)
6636     StdNamespace = Namespc;
6637   if (AddToKnown)
6638     KnownNamespaces[Namespc] = false;
6639 
6640   if (II) {
6641     PushOnScopeChains(Namespc, DeclRegionScope);
6642   } else {
6643     // Link the anonymous namespace into its parent.
6644     DeclContext *Parent = CurContext->getRedeclContext();
6645     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6646       TU->setAnonymousNamespace(Namespc);
6647     } else {
6648       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
6649     }
6650 
6651     CurContext->addDecl(Namespc);
6652 
6653     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
6654     //   behaves as if it were replaced by
6655     //     namespace unique { /* empty body */ }
6656     //     using namespace unique;
6657     //     namespace unique { namespace-body }
6658     //   where all occurrences of 'unique' in a translation unit are
6659     //   replaced by the same identifier and this identifier differs
6660     //   from all other identifiers in the entire program.
6661 
6662     // We just create the namespace with an empty name and then add an
6663     // implicit using declaration, just like the standard suggests.
6664     //
6665     // CodeGen enforces the "universally unique" aspect by giving all
6666     // declarations semantically contained within an anonymous
6667     // namespace internal linkage.
6668 
6669     if (!PrevNS) {
6670       UsingDirectiveDecl* UD
6671         = UsingDirectiveDecl::Create(Context, Parent,
6672                                      /* 'using' */ LBrace,
6673                                      /* 'namespace' */ SourceLocation(),
6674                                      /* qualifier */ NestedNameSpecifierLoc(),
6675                                      /* identifier */ SourceLocation(),
6676                                      Namespc,
6677                                      /* Ancestor */ Parent);
6678       UD->setImplicit();
6679       Parent->addDecl(UD);
6680     }
6681   }
6682 
6683   ActOnDocumentableDecl(Namespc);
6684 
6685   // Although we could have an invalid decl (i.e. the namespace name is a
6686   // redefinition), push it as current DeclContext and try to continue parsing.
6687   // FIXME: We should be able to push Namespc here, so that the each DeclContext
6688   // for the namespace has the declarations that showed up in that particular
6689   // namespace definition.
6690   PushDeclContext(NamespcScope, Namespc);
6691   return Namespc;
6692 }
6693 
6694 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6695 /// is a namespace alias, returns the namespace it points to.
6696 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6697   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6698     return AD->getNamespace();
6699   return dyn_cast_or_null<NamespaceDecl>(D);
6700 }
6701 
6702 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
6703 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
6704 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
6705   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6706   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
6707   Namespc->setRBraceLoc(RBrace);
6708   PopDeclContext();
6709   if (Namespc->hasAttr<VisibilityAttr>())
6710     PopPragmaVisibility(true, RBrace);
6711 }
6712 
6713 CXXRecordDecl *Sema::getStdBadAlloc() const {
6714   return cast_or_null<CXXRecordDecl>(
6715                                   StdBadAlloc.get(Context.getExternalSource()));
6716 }
6717 
6718 NamespaceDecl *Sema::getStdNamespace() const {
6719   return cast_or_null<NamespaceDecl>(
6720                                  StdNamespace.get(Context.getExternalSource()));
6721 }
6722 
6723 /// \brief Retrieve the special "std" namespace, which may require us to
6724 /// implicitly define the namespace.
6725 NamespaceDecl *Sema::getOrCreateStdNamespace() {
6726   if (!StdNamespace) {
6727     // The "std" namespace has not yet been defined, so build one implicitly.
6728     StdNamespace = NamespaceDecl::Create(Context,
6729                                          Context.getTranslationUnitDecl(),
6730                                          /*Inline=*/false,
6731                                          SourceLocation(), SourceLocation(),
6732                                          &PP.getIdentifierTable().get("std"),
6733                                          /*PrevDecl=*/0);
6734     getStdNamespace()->setImplicit(true);
6735   }
6736 
6737   return getStdNamespace();
6738 }
6739 
6740 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
6741   assert(getLangOpts().CPlusPlus &&
6742          "Looking for std::initializer_list outside of C++.");
6743 
6744   // We're looking for implicit instantiations of
6745   // template <typename E> class std::initializer_list.
6746 
6747   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6748     return false;
6749 
6750   ClassTemplateDecl *Template = 0;
6751   const TemplateArgument *Arguments = 0;
6752 
6753   if (const RecordType *RT = Ty->getAs<RecordType>()) {
6754 
6755     ClassTemplateSpecializationDecl *Specialization =
6756         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6757     if (!Specialization)
6758       return false;
6759 
6760     Template = Specialization->getSpecializedTemplate();
6761     Arguments = Specialization->getTemplateArgs().data();
6762   } else if (const TemplateSpecializationType *TST =
6763                  Ty->getAs<TemplateSpecializationType>()) {
6764     Template = dyn_cast_or_null<ClassTemplateDecl>(
6765         TST->getTemplateName().getAsTemplateDecl());
6766     Arguments = TST->getArgs();
6767   }
6768   if (!Template)
6769     return false;
6770 
6771   if (!StdInitializerList) {
6772     // Haven't recognized std::initializer_list yet, maybe this is it.
6773     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6774     if (TemplateClass->getIdentifier() !=
6775             &PP.getIdentifierTable().get("initializer_list") ||
6776         !getStdNamespace()->InEnclosingNamespaceSetOf(
6777             TemplateClass->getDeclContext()))
6778       return false;
6779     // This is a template called std::initializer_list, but is it the right
6780     // template?
6781     TemplateParameterList *Params = Template->getTemplateParameters();
6782     if (Params->getMinRequiredArguments() != 1)
6783       return false;
6784     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6785       return false;
6786 
6787     // It's the right template.
6788     StdInitializerList = Template;
6789   }
6790 
6791   if (Template != StdInitializerList)
6792     return false;
6793 
6794   // This is an instance of std::initializer_list. Find the argument type.
6795   if (Element)
6796     *Element = Arguments[0].getAsType();
6797   return true;
6798 }
6799 
6800 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6801   NamespaceDecl *Std = S.getStdNamespace();
6802   if (!Std) {
6803     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6804     return 0;
6805   }
6806 
6807   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6808                       Loc, Sema::LookupOrdinaryName);
6809   if (!S.LookupQualifiedName(Result, Std)) {
6810     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6811     return 0;
6812   }
6813   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6814   if (!Template) {
6815     Result.suppressDiagnostics();
6816     // We found something weird. Complain about the first thing we found.
6817     NamedDecl *Found = *Result.begin();
6818     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6819     return 0;
6820   }
6821 
6822   // We found some template called std::initializer_list. Now verify that it's
6823   // correct.
6824   TemplateParameterList *Params = Template->getTemplateParameters();
6825   if (Params->getMinRequiredArguments() != 1 ||
6826       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6827     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6828     return 0;
6829   }
6830 
6831   return Template;
6832 }
6833 
6834 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6835   if (!StdInitializerList) {
6836     StdInitializerList = LookupStdInitializerList(*this, Loc);
6837     if (!StdInitializerList)
6838       return QualType();
6839   }
6840 
6841   TemplateArgumentListInfo Args(Loc, Loc);
6842   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6843                                        Context.getTrivialTypeSourceInfo(Element,
6844                                                                         Loc)));
6845   return Context.getCanonicalType(
6846       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6847 }
6848 
6849 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6850   // C++ [dcl.init.list]p2:
6851   //   A constructor is an initializer-list constructor if its first parameter
6852   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
6853   //   std::initializer_list<E> for some type E, and either there are no other
6854   //   parameters or else all other parameters have default arguments.
6855   if (Ctor->getNumParams() < 1 ||
6856       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6857     return false;
6858 
6859   QualType ArgType = Ctor->getParamDecl(0)->getType();
6860   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6861     ArgType = RT->getPointeeType().getUnqualifiedType();
6862 
6863   return isStdInitializerList(ArgType, 0);
6864 }
6865 
6866 /// \brief Determine whether a using statement is in a context where it will be
6867 /// apply in all contexts.
6868 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6869   switch (CurContext->getDeclKind()) {
6870     case Decl::TranslationUnit:
6871       return true;
6872     case Decl::LinkageSpec:
6873       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6874     default:
6875       return false;
6876   }
6877 }
6878 
6879 namespace {
6880 
6881 // Callback to only accept typo corrections that are namespaces.
6882 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6883 public:
6884   bool ValidateCandidate(const TypoCorrection &candidate) override {
6885     if (NamedDecl *ND = candidate.getCorrectionDecl())
6886       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6887     return false;
6888   }
6889 };
6890 
6891 }
6892 
6893 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6894                                        CXXScopeSpec &SS,
6895                                        SourceLocation IdentLoc,
6896                                        IdentifierInfo *Ident) {
6897   NamespaceValidatorCCC Validator;
6898   R.clear();
6899   if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
6900                                                R.getLookupKind(), Sc, &SS,
6901                                                Validator)) {
6902     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
6903       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6904       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
6905                               Ident->getName().equals(CorrectedStr);
6906       S.diagnoseTypo(Corrected,
6907                      S.PDiag(diag::err_using_directive_member_suggest)
6908                        << Ident << DC << DroppedSpecifier << SS.getRange(),
6909                      S.PDiag(diag::note_namespace_defined_here));
6910     } else {
6911       S.diagnoseTypo(Corrected,
6912                      S.PDiag(diag::err_using_directive_suggest) << Ident,
6913                      S.PDiag(diag::note_namespace_defined_here));
6914     }
6915     R.addDecl(Corrected.getCorrectionDecl());
6916     return true;
6917   }
6918   return false;
6919 }
6920 
6921 Decl *Sema::ActOnUsingDirective(Scope *S,
6922                                           SourceLocation UsingLoc,
6923                                           SourceLocation NamespcLoc,
6924                                           CXXScopeSpec &SS,
6925                                           SourceLocation IdentLoc,
6926                                           IdentifierInfo *NamespcName,
6927                                           AttributeList *AttrList) {
6928   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6929   assert(NamespcName && "Invalid NamespcName.");
6930   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
6931 
6932   // This can only happen along a recovery path.
6933   while (S->getFlags() & Scope::TemplateParamScope)
6934     S = S->getParent();
6935   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
6936 
6937   UsingDirectiveDecl *UDir = 0;
6938   NestedNameSpecifier *Qualifier = 0;
6939   if (SS.isSet())
6940     Qualifier = SS.getScopeRep();
6941 
6942   // Lookup namespace name.
6943   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6944   LookupParsedName(R, S, &SS);
6945   if (R.isAmbiguous())
6946     return 0;
6947 
6948   if (R.empty()) {
6949     R.clear();
6950     // Allow "using namespace std;" or "using namespace ::std;" even if
6951     // "std" hasn't been defined yet, for GCC compatibility.
6952     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6953         NamespcName->isStr("std")) {
6954       Diag(IdentLoc, diag::ext_using_undefined_std);
6955       R.addDecl(getOrCreateStdNamespace());
6956       R.resolveKind();
6957     }
6958     // Otherwise, attempt typo correction.
6959     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
6960   }
6961 
6962   if (!R.empty()) {
6963     NamedDecl *Named = R.getFoundDecl();
6964     assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6965         && "expected namespace decl");
6966     // C++ [namespace.udir]p1:
6967     //   A using-directive specifies that the names in the nominated
6968     //   namespace can be used in the scope in which the
6969     //   using-directive appears after the using-directive. During
6970     //   unqualified name lookup (3.4.1), the names appear as if they
6971     //   were declared in the nearest enclosing namespace which
6972     //   contains both the using-directive and the nominated
6973     //   namespace. [Note: in this context, "contains" means "contains
6974     //   directly or indirectly". ]
6975 
6976     // Find enclosing context containing both using-directive and
6977     // nominated namespace.
6978     NamespaceDecl *NS = getNamespaceDecl(Named);
6979     DeclContext *CommonAncestor = cast<DeclContext>(NS);
6980     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6981       CommonAncestor = CommonAncestor->getParent();
6982 
6983     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
6984                                       SS.getWithLocInContext(Context),
6985                                       IdentLoc, Named, CommonAncestor);
6986 
6987     if (IsUsingDirectiveInToplevelContext(CurContext) &&
6988         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
6989       Diag(IdentLoc, diag::warn_using_directive_in_header);
6990     }
6991 
6992     PushUsingDirective(S, UDir);
6993   } else {
6994     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
6995   }
6996 
6997   if (UDir)
6998     ProcessDeclAttributeList(S, UDir, AttrList);
6999 
7000   return UDir;
7001 }
7002 
7003 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
7004   // If the scope has an associated entity and the using directive is at
7005   // namespace or translation unit scope, add the UsingDirectiveDecl into
7006   // its lookup structure so qualified name lookup can find it.
7007   DeclContext *Ctx = S->getEntity();
7008   if (Ctx && !Ctx->isFunctionOrMethod())
7009     Ctx->addDecl(UDir);
7010   else
7011     // Otherwise, it is at block sope. The using-directives will affect lookup
7012     // only to the end of the scope.
7013     S->PushUsingDirective(UDir);
7014 }
7015 
7016 
7017 Decl *Sema::ActOnUsingDeclaration(Scope *S,
7018                                   AccessSpecifier AS,
7019                                   bool HasUsingKeyword,
7020                                   SourceLocation UsingLoc,
7021                                   CXXScopeSpec &SS,
7022                                   UnqualifiedId &Name,
7023                                   AttributeList *AttrList,
7024                                   bool HasTypenameKeyword,
7025                                   SourceLocation TypenameLoc) {
7026   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7027 
7028   switch (Name.getKind()) {
7029   case UnqualifiedId::IK_ImplicitSelfParam:
7030   case UnqualifiedId::IK_Identifier:
7031   case UnqualifiedId::IK_OperatorFunctionId:
7032   case UnqualifiedId::IK_LiteralOperatorId:
7033   case UnqualifiedId::IK_ConversionFunctionId:
7034     break;
7035 
7036   case UnqualifiedId::IK_ConstructorName:
7037   case UnqualifiedId::IK_ConstructorTemplateId:
7038     // C++11 inheriting constructors.
7039     Diag(Name.getLocStart(),
7040          getLangOpts().CPlusPlus11 ?
7041            diag::warn_cxx98_compat_using_decl_constructor :
7042            diag::err_using_decl_constructor)
7043       << SS.getRange();
7044 
7045     if (getLangOpts().CPlusPlus11) break;
7046 
7047     return 0;
7048 
7049   case UnqualifiedId::IK_DestructorName:
7050     Diag(Name.getLocStart(), diag::err_using_decl_destructor)
7051       << SS.getRange();
7052     return 0;
7053 
7054   case UnqualifiedId::IK_TemplateId:
7055     Diag(Name.getLocStart(), diag::err_using_decl_template_id)
7056       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
7057     return 0;
7058   }
7059 
7060   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7061   DeclarationName TargetName = TargetNameInfo.getName();
7062   if (!TargetName)
7063     return 0;
7064 
7065   // Warn about access declarations.
7066   if (!HasUsingKeyword) {
7067     Diag(Name.getLocStart(),
7068          getLangOpts().CPlusPlus11 ? diag::err_access_decl
7069                                    : diag::warn_access_decl_deprecated)
7070       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
7071   }
7072 
7073   if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7074       DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7075     return 0;
7076 
7077   NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
7078                                         TargetNameInfo, AttrList,
7079                                         /* IsInstantiation */ false,
7080                                         HasTypenameKeyword, TypenameLoc);
7081   if (UD)
7082     PushOnScopeChains(UD, S, /*AddToContext*/ false);
7083 
7084   return UD;
7085 }
7086 
7087 /// \brief Determine whether a using declaration considers the given
7088 /// declarations as "equivalent", e.g., if they are redeclarations of
7089 /// the same entity or are both typedefs of the same type.
7090 static bool
7091 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7092   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
7093     return true;
7094 
7095   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
7096     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
7097       return Context.hasSameType(TD1->getUnderlyingType(),
7098                                  TD2->getUnderlyingType());
7099 
7100   return false;
7101 }
7102 
7103 
7104 /// Determines whether to create a using shadow decl for a particular
7105 /// decl, given the set of decls existing prior to this using lookup.
7106 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
7107                                 const LookupResult &Previous,
7108                                 UsingShadowDecl *&PrevShadow) {
7109   // Diagnose finding a decl which is not from a base class of the
7110   // current class.  We do this now because there are cases where this
7111   // function will silently decide not to build a shadow decl, which
7112   // will pre-empt further diagnostics.
7113   //
7114   // We don't need to do this in C++0x because we do the check once on
7115   // the qualifier.
7116   //
7117   // FIXME: diagnose the following if we care enough:
7118   //   struct A { int foo; };
7119   //   struct B : A { using A::foo; };
7120   //   template <class T> struct C : A {};
7121   //   template <class T> struct D : C<T> { using B::foo; } // <---
7122   // This is invalid (during instantiation) in C++03 because B::foo
7123   // resolves to the using decl in B, which is not a base class of D<T>.
7124   // We can't diagnose it immediately because C<T> is an unknown
7125   // specialization.  The UsingShadowDecl in D<T> then points directly
7126   // to A::foo, which will look well-formed when we instantiate.
7127   // The right solution is to not collapse the shadow-decl chain.
7128   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
7129     DeclContext *OrigDC = Orig->getDeclContext();
7130 
7131     // Handle enums and anonymous structs.
7132     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7133     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7134     while (OrigRec->isAnonymousStructOrUnion())
7135       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7136 
7137     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7138       if (OrigDC == CurContext) {
7139         Diag(Using->getLocation(),
7140              diag::err_using_decl_nested_name_specifier_is_current_class)
7141           << Using->getQualifierLoc().getSourceRange();
7142         Diag(Orig->getLocation(), diag::note_using_decl_target);
7143         return true;
7144       }
7145 
7146       Diag(Using->getQualifierLoc().getBeginLoc(),
7147            diag::err_using_decl_nested_name_specifier_is_not_base_class)
7148         << Using->getQualifier()
7149         << cast<CXXRecordDecl>(CurContext)
7150         << Using->getQualifierLoc().getSourceRange();
7151       Diag(Orig->getLocation(), diag::note_using_decl_target);
7152       return true;
7153     }
7154   }
7155 
7156   if (Previous.empty()) return false;
7157 
7158   NamedDecl *Target = Orig;
7159   if (isa<UsingShadowDecl>(Target))
7160     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7161 
7162   // If the target happens to be one of the previous declarations, we
7163   // don't have a conflict.
7164   //
7165   // FIXME: but we might be increasing its access, in which case we
7166   // should redeclare it.
7167   NamedDecl *NonTag = 0, *Tag = 0;
7168   bool FoundEquivalentDecl = false;
7169   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7170          I != E; ++I) {
7171     NamedDecl *D = (*I)->getUnderlyingDecl();
7172     if (IsEquivalentForUsingDecl(Context, D, Target)) {
7173       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7174         PrevShadow = Shadow;
7175       FoundEquivalentDecl = true;
7176     }
7177 
7178     (isa<TagDecl>(D) ? Tag : NonTag) = D;
7179   }
7180 
7181   if (FoundEquivalentDecl)
7182     return false;
7183 
7184   if (FunctionDecl *FD = Target->getAsFunction()) {
7185     NamedDecl *OldDecl = 0;
7186     switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
7187     case Ovl_Overload:
7188       return false;
7189 
7190     case Ovl_NonFunction:
7191       Diag(Using->getLocation(), diag::err_using_decl_conflict);
7192       break;
7193 
7194     // We found a decl with the exact signature.
7195     case Ovl_Match:
7196       // If we're in a record, we want to hide the target, so we
7197       // return true (without a diagnostic) to tell the caller not to
7198       // build a shadow decl.
7199       if (CurContext->isRecord())
7200         return true;
7201 
7202       // If we're not in a record, this is an error.
7203       Diag(Using->getLocation(), diag::err_using_decl_conflict);
7204       break;
7205     }
7206 
7207     Diag(Target->getLocation(), diag::note_using_decl_target);
7208     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7209     return true;
7210   }
7211 
7212   // Target is not a function.
7213 
7214   if (isa<TagDecl>(Target)) {
7215     // No conflict between a tag and a non-tag.
7216     if (!Tag) return false;
7217 
7218     Diag(Using->getLocation(), diag::err_using_decl_conflict);
7219     Diag(Target->getLocation(), diag::note_using_decl_target);
7220     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7221     return true;
7222   }
7223 
7224   // No conflict between a tag and a non-tag.
7225   if (!NonTag) return false;
7226 
7227   Diag(Using->getLocation(), diag::err_using_decl_conflict);
7228   Diag(Target->getLocation(), diag::note_using_decl_target);
7229   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7230   return true;
7231 }
7232 
7233 /// Builds a shadow declaration corresponding to a 'using' declaration.
7234 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
7235                                             UsingDecl *UD,
7236                                             NamedDecl *Orig,
7237                                             UsingShadowDecl *PrevDecl) {
7238 
7239   // If we resolved to another shadow declaration, just coalesce them.
7240   NamedDecl *Target = Orig;
7241   if (isa<UsingShadowDecl>(Target)) {
7242     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7243     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
7244   }
7245 
7246   UsingShadowDecl *Shadow
7247     = UsingShadowDecl::Create(Context, CurContext,
7248                               UD->getLocation(), UD, Target);
7249   UD->addShadowDecl(Shadow);
7250 
7251   Shadow->setAccess(UD->getAccess());
7252   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7253     Shadow->setInvalidDecl();
7254 
7255   Shadow->setPreviousDecl(PrevDecl);
7256 
7257   if (S)
7258     PushOnScopeChains(Shadow, S);
7259   else
7260     CurContext->addDecl(Shadow);
7261 
7262 
7263   return Shadow;
7264 }
7265 
7266 /// Hides a using shadow declaration.  This is required by the current
7267 /// using-decl implementation when a resolvable using declaration in a
7268 /// class is followed by a declaration which would hide or override
7269 /// one or more of the using decl's targets; for example:
7270 ///
7271 ///   struct Base { void foo(int); };
7272 ///   struct Derived : Base {
7273 ///     using Base::foo;
7274 ///     void foo(int);
7275 ///   };
7276 ///
7277 /// The governing language is C++03 [namespace.udecl]p12:
7278 ///
7279 ///   When a using-declaration brings names from a base class into a
7280 ///   derived class scope, member functions in the derived class
7281 ///   override and/or hide member functions with the same name and
7282 ///   parameter types in a base class (rather than conflicting).
7283 ///
7284 /// There are two ways to implement this:
7285 ///   (1) optimistically create shadow decls when they're not hidden
7286 ///       by existing declarations, or
7287 ///   (2) don't create any shadow decls (or at least don't make them
7288 ///       visible) until we've fully parsed/instantiated the class.
7289 /// The problem with (1) is that we might have to retroactively remove
7290 /// a shadow decl, which requires several O(n) operations because the
7291 /// decl structures are (very reasonably) not designed for removal.
7292 /// (2) avoids this but is very fiddly and phase-dependent.
7293 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
7294   if (Shadow->getDeclName().getNameKind() ==
7295         DeclarationName::CXXConversionFunctionName)
7296     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7297 
7298   // Remove it from the DeclContext...
7299   Shadow->getDeclContext()->removeDecl(Shadow);
7300 
7301   // ...and the scope, if applicable...
7302   if (S) {
7303     S->RemoveDecl(Shadow);
7304     IdResolver.RemoveDecl(Shadow);
7305   }
7306 
7307   // ...and the using decl.
7308   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7309 
7310   // TODO: complain somehow if Shadow was used.  It shouldn't
7311   // be possible for this to happen, because...?
7312 }
7313 
7314 namespace {
7315 class UsingValidatorCCC : public CorrectionCandidateCallback {
7316 public:
7317   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
7318                     bool RequireMember)
7319       : HasTypenameKeyword(HasTypenameKeyword),
7320         IsInstantiation(IsInstantiation), RequireMember(RequireMember) {}
7321 
7322   bool ValidateCandidate(const TypoCorrection &Candidate) override {
7323     NamedDecl *ND = Candidate.getCorrectionDecl();
7324 
7325     // Keywords are not valid here.
7326     if (!ND || isa<NamespaceDecl>(ND))
7327       return false;
7328 
7329     if (RequireMember && !isa<FieldDecl>(ND) && !isa<CXXMethodDecl>(ND) &&
7330         !isa<TypeDecl>(ND))
7331       return false;
7332 
7333     // Completely unqualified names are invalid for a 'using' declaration.
7334     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7335       return false;
7336 
7337     if (isa<TypeDecl>(ND))
7338       return HasTypenameKeyword || !IsInstantiation;
7339 
7340     return !HasTypenameKeyword;
7341   }
7342 
7343 private:
7344   bool HasTypenameKeyword;
7345   bool IsInstantiation;
7346   bool RequireMember;
7347 };
7348 } // end anonymous namespace
7349 
7350 /// Builds a using declaration.
7351 ///
7352 /// \param IsInstantiation - Whether this call arises from an
7353 ///   instantiation of an unresolved using declaration.  We treat
7354 ///   the lookup differently for these declarations.
7355 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7356                                        SourceLocation UsingLoc,
7357                                        CXXScopeSpec &SS,
7358                                        const DeclarationNameInfo &NameInfo,
7359                                        AttributeList *AttrList,
7360                                        bool IsInstantiation,
7361                                        bool HasTypenameKeyword,
7362                                        SourceLocation TypenameLoc) {
7363   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7364   SourceLocation IdentLoc = NameInfo.getLoc();
7365   assert(IdentLoc.isValid() && "Invalid TargetName location.");
7366 
7367   // FIXME: We ignore attributes for now.
7368 
7369   if (SS.isEmpty()) {
7370     Diag(IdentLoc, diag::err_using_requires_qualname);
7371     return 0;
7372   }
7373 
7374   // Do the redeclaration lookup in the current scope.
7375   LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
7376                         ForRedeclaration);
7377   Previous.setHideTags(false);
7378   if (S) {
7379     LookupName(Previous, S);
7380 
7381     // It is really dumb that we have to do this.
7382     LookupResult::Filter F = Previous.makeFilter();
7383     while (F.hasNext()) {
7384       NamedDecl *D = F.next();
7385       if (!isDeclInScope(D, CurContext, S))
7386         F.erase();
7387       // If we found a local extern declaration that's not ordinarily visible,
7388       // and this declaration is being added to a non-block scope, ignore it.
7389       // We're only checking for scope conflicts here, not also for violations
7390       // of the linkage rules.
7391       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
7392                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
7393         F.erase();
7394     }
7395     F.done();
7396   } else {
7397     assert(IsInstantiation && "no scope in non-instantiation");
7398     assert(CurContext->isRecord() && "scope not record in instantiation");
7399     LookupQualifiedName(Previous, CurContext);
7400   }
7401 
7402   // Check for invalid redeclarations.
7403   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7404                                   SS, IdentLoc, Previous))
7405     return 0;
7406 
7407   // Check for bad qualifiers.
7408   if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
7409     return 0;
7410 
7411   DeclContext *LookupContext = computeDeclContext(SS);
7412   NamedDecl *D;
7413   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
7414   if (!LookupContext) {
7415     if (HasTypenameKeyword) {
7416       // FIXME: not all declaration name kinds are legal here
7417       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7418                                               UsingLoc, TypenameLoc,
7419                                               QualifierLoc,
7420                                               IdentLoc, NameInfo.getName());
7421     } else {
7422       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7423                                            QualifierLoc, NameInfo);
7424     }
7425   } else {
7426     D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
7427                           NameInfo, HasTypenameKeyword);
7428   }
7429   D->setAccess(AS);
7430   CurContext->addDecl(D);
7431 
7432   if (!LookupContext) return D;
7433   UsingDecl *UD = cast<UsingDecl>(D);
7434 
7435   if (RequireCompleteDeclContext(SS, LookupContext)) {
7436     UD->setInvalidDecl();
7437     return UD;
7438   }
7439 
7440   // The normal rules do not apply to inheriting constructor declarations.
7441   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
7442     if (CheckInheritingConstructorUsingDecl(UD))
7443       UD->setInvalidDecl();
7444     return UD;
7445   }
7446 
7447   // Otherwise, look up the target name.
7448 
7449   LookupResult R(*this, NameInfo, LookupOrdinaryName);
7450 
7451   // Unlike most lookups, we don't always want to hide tag
7452   // declarations: tag names are visible through the using declaration
7453   // even if hidden by ordinary names, *except* in a dependent context
7454   // where it's important for the sanity of two-phase lookup.
7455   if (!IsInstantiation)
7456     R.setHideTags(false);
7457 
7458   // For the purposes of this lookup, we have a base object type
7459   // equal to that of the current context.
7460   if (CurContext->isRecord()) {
7461     R.setBaseObjectType(
7462                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7463   }
7464 
7465   LookupQualifiedName(R, LookupContext);
7466 
7467   // Try to correct typos if possible.
7468   if (R.empty()) {
7469     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation,
7470                           CurContext->isRecord());
7471     if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
7472                                                R.getLookupKind(), S, &SS, CCC)){
7473       // We reject any correction for which ND would be NULL.
7474       NamedDecl *ND = Corrected.getCorrectionDecl();
7475       R.setLookupName(Corrected.getCorrection());
7476       R.addDecl(ND);
7477       // We reject candidates where DroppedSpecifier == true, hence the
7478       // literal '0' below.
7479       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7480                                 << NameInfo.getName() << LookupContext << 0
7481                                 << SS.getRange());
7482     } else {
7483       Diag(IdentLoc, diag::err_no_member)
7484         << NameInfo.getName() << LookupContext << SS.getRange();
7485       UD->setInvalidDecl();
7486       return UD;
7487     }
7488   }
7489 
7490   if (R.isAmbiguous()) {
7491     UD->setInvalidDecl();
7492     return UD;
7493   }
7494 
7495   if (HasTypenameKeyword) {
7496     // If we asked for a typename and got a non-type decl, error out.
7497     if (!R.getAsSingle<TypeDecl>()) {
7498       Diag(IdentLoc, diag::err_using_typename_non_type);
7499       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7500         Diag((*I)->getUnderlyingDecl()->getLocation(),
7501              diag::note_using_decl_target);
7502       UD->setInvalidDecl();
7503       return UD;
7504     }
7505   } else {
7506     // If we asked for a non-typename and we got a type, error out,
7507     // but only if this is an instantiation of an unresolved using
7508     // decl.  Otherwise just silently find the type name.
7509     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
7510       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7511       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
7512       UD->setInvalidDecl();
7513       return UD;
7514     }
7515   }
7516 
7517   // C++0x N2914 [namespace.udecl]p6:
7518   // A using-declaration shall not name a namespace.
7519   if (R.getAsSingle<NamespaceDecl>()) {
7520     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7521       << SS.getRange();
7522     UD->setInvalidDecl();
7523     return UD;
7524   }
7525 
7526   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7527     UsingShadowDecl *PrevDecl = 0;
7528     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
7529       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
7530   }
7531 
7532   return UD;
7533 }
7534 
7535 /// Additional checks for a using declaration referring to a constructor name.
7536 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
7537   assert(!UD->hasTypename() && "expecting a constructor name");
7538 
7539   const Type *SourceType = UD->getQualifier()->getAsType();
7540   assert(SourceType &&
7541          "Using decl naming constructor doesn't have type in scope spec.");
7542   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7543 
7544   // Check whether the named type is a direct base class.
7545   CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7546   CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7547   for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7548        BaseIt != BaseE; ++BaseIt) {
7549     CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7550     if (CanonicalSourceType == BaseType)
7551       break;
7552     if (BaseIt->getType()->isDependentType())
7553       break;
7554   }
7555 
7556   if (BaseIt == BaseE) {
7557     // Did not find SourceType in the bases.
7558     Diag(UD->getUsingLoc(),
7559          diag::err_using_decl_constructor_not_in_direct_base)
7560       << UD->getNameInfo().getSourceRange()
7561       << QualType(SourceType, 0) << TargetClass;
7562     return true;
7563   }
7564 
7565   if (!CurContext->isDependentContext())
7566     BaseIt->setInheritConstructors();
7567 
7568   return false;
7569 }
7570 
7571 /// Checks that the given using declaration is not an invalid
7572 /// redeclaration.  Note that this is checking only for the using decl
7573 /// itself, not for any ill-formedness among the UsingShadowDecls.
7574 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7575                                        bool HasTypenameKeyword,
7576                                        const CXXScopeSpec &SS,
7577                                        SourceLocation NameLoc,
7578                                        const LookupResult &Prev) {
7579   // C++03 [namespace.udecl]p8:
7580   // C++0x [namespace.udecl]p10:
7581   //   A using-declaration is a declaration and can therefore be used
7582   //   repeatedly where (and only where) multiple declarations are
7583   //   allowed.
7584   //
7585   // That's in non-member contexts.
7586   if (!CurContext->getRedeclContext()->isRecord())
7587     return false;
7588 
7589   NestedNameSpecifier *Qual = SS.getScopeRep();
7590 
7591   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7592     NamedDecl *D = *I;
7593 
7594     bool DTypename;
7595     NestedNameSpecifier *DQual;
7596     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7597       DTypename = UD->hasTypename();
7598       DQual = UD->getQualifier();
7599     } else if (UnresolvedUsingValueDecl *UD
7600                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7601       DTypename = false;
7602       DQual = UD->getQualifier();
7603     } else if (UnresolvedUsingTypenameDecl *UD
7604                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7605       DTypename = true;
7606       DQual = UD->getQualifier();
7607     } else continue;
7608 
7609     // using decls differ if one says 'typename' and the other doesn't.
7610     // FIXME: non-dependent using decls?
7611     if (HasTypenameKeyword != DTypename) continue;
7612 
7613     // using decls differ if they name different scopes (but note that
7614     // template instantiation can cause this check to trigger when it
7615     // didn't before instantiation).
7616     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7617         Context.getCanonicalNestedNameSpecifier(DQual))
7618       continue;
7619 
7620     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
7621     Diag(D->getLocation(), diag::note_using_decl) << 1;
7622     return true;
7623   }
7624 
7625   return false;
7626 }
7627 
7628 
7629 /// Checks that the given nested-name qualifier used in a using decl
7630 /// in the current context is appropriately related to the current
7631 /// scope.  If an error is found, diagnoses it and returns true.
7632 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7633                                    const CXXScopeSpec &SS,
7634                                    const DeclarationNameInfo &NameInfo,
7635                                    SourceLocation NameLoc) {
7636   DeclContext *NamedContext = computeDeclContext(SS);
7637 
7638   if (!CurContext->isRecord()) {
7639     // C++03 [namespace.udecl]p3:
7640     // C++0x [namespace.udecl]p8:
7641     //   A using-declaration for a class member shall be a member-declaration.
7642 
7643     // If we weren't able to compute a valid scope, it must be a
7644     // dependent class scope.
7645     if (!NamedContext || NamedContext->isRecord()) {
7646       auto *RD = dyn_cast<CXXRecordDecl>(NamedContext);
7647       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
7648         RD = 0;
7649 
7650       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7651         << SS.getRange();
7652 
7653       // If we have a complete, non-dependent source type, try to suggest a
7654       // way to get the same effect.
7655       if (!RD)
7656         return true;
7657 
7658       // Find what this using-declaration was referring to.
7659       LookupResult R(*this, NameInfo, LookupOrdinaryName);
7660       R.setHideTags(false);
7661       R.suppressDiagnostics();
7662       LookupQualifiedName(R, RD);
7663 
7664       if (R.getAsSingle<TypeDecl>()) {
7665         if (getLangOpts().CPlusPlus11) {
7666           // Convert 'using X::Y;' to 'using Y = X::Y;'.
7667           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
7668             << 0 // alias declaration
7669             << FixItHint::CreateInsertion(SS.getBeginLoc(),
7670                                           NameInfo.getName().getAsString() +
7671                                               " = ");
7672         } else {
7673           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
7674           SourceLocation InsertLoc =
7675               PP.getLocForEndOfToken(NameInfo.getLocEnd());
7676           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
7677             << 1 // typedef declaration
7678             << FixItHint::CreateReplacement(UsingLoc, "typedef")
7679             << FixItHint::CreateInsertion(
7680                    InsertLoc, " " + NameInfo.getName().getAsString());
7681         }
7682       } else if (R.getAsSingle<VarDecl>()) {
7683         // Don't provide a fixit outside C++11 mode; we don't want to suggest
7684         // repeating the type of the static data member here.
7685         FixItHint FixIt;
7686         if (getLangOpts().CPlusPlus11) {
7687           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
7688           FixIt = FixItHint::CreateReplacement(
7689               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
7690         }
7691 
7692         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
7693           << 2 // reference declaration
7694           << FixIt;
7695       }
7696       return true;
7697     }
7698 
7699     // Otherwise, everything is known to be fine.
7700     return false;
7701   }
7702 
7703   // The current scope is a record.
7704 
7705   // If the named context is dependent, we can't decide much.
7706   if (!NamedContext) {
7707     // FIXME: in C++0x, we can diagnose if we can prove that the
7708     // nested-name-specifier does not refer to a base class, which is
7709     // still possible in some cases.
7710 
7711     // Otherwise we have to conservatively report that things might be
7712     // okay.
7713     return false;
7714   }
7715 
7716   if (!NamedContext->isRecord()) {
7717     // Ideally this would point at the last name in the specifier,
7718     // but we don't have that level of source info.
7719     Diag(SS.getRange().getBegin(),
7720          diag::err_using_decl_nested_name_specifier_is_not_class)
7721       << SS.getScopeRep() << SS.getRange();
7722     return true;
7723   }
7724 
7725   if (!NamedContext->isDependentContext() &&
7726       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7727     return true;
7728 
7729   if (getLangOpts().CPlusPlus11) {
7730     // C++0x [namespace.udecl]p3:
7731     //   In a using-declaration used as a member-declaration, the
7732     //   nested-name-specifier shall name a base class of the class
7733     //   being defined.
7734 
7735     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7736                                  cast<CXXRecordDecl>(NamedContext))) {
7737       if (CurContext == NamedContext) {
7738         Diag(NameLoc,
7739              diag::err_using_decl_nested_name_specifier_is_current_class)
7740           << SS.getRange();
7741         return true;
7742       }
7743 
7744       Diag(SS.getRange().getBegin(),
7745            diag::err_using_decl_nested_name_specifier_is_not_base_class)
7746         << SS.getScopeRep()
7747         << cast<CXXRecordDecl>(CurContext)
7748         << SS.getRange();
7749       return true;
7750     }
7751 
7752     return false;
7753   }
7754 
7755   // C++03 [namespace.udecl]p4:
7756   //   A using-declaration used as a member-declaration shall refer
7757   //   to a member of a base class of the class being defined [etc.].
7758 
7759   // Salient point: SS doesn't have to name a base class as long as
7760   // lookup only finds members from base classes.  Therefore we can
7761   // diagnose here only if we can prove that that can't happen,
7762   // i.e. if the class hierarchies provably don't intersect.
7763 
7764   // TODO: it would be nice if "definitely valid" results were cached
7765   // in the UsingDecl and UsingShadowDecl so that these checks didn't
7766   // need to be repeated.
7767 
7768   struct UserData {
7769     llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
7770 
7771     static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7772       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7773       Data->Bases.insert(Base);
7774       return true;
7775     }
7776 
7777     bool hasDependentBases(const CXXRecordDecl *Class) {
7778       return !Class->forallBases(collect, this);
7779     }
7780 
7781     /// Returns true if the base is dependent or is one of the
7782     /// accumulated base classes.
7783     static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7784       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7785       return !Data->Bases.count(Base);
7786     }
7787 
7788     bool mightShareBases(const CXXRecordDecl *Class) {
7789       return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7790     }
7791   };
7792 
7793   UserData Data;
7794 
7795   // Returns false if we find a dependent base.
7796   if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7797     return false;
7798 
7799   // Returns false if the class has a dependent base or if it or one
7800   // of its bases is present in the base set of the current context.
7801   if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7802     return false;
7803 
7804   Diag(SS.getRange().getBegin(),
7805        diag::err_using_decl_nested_name_specifier_is_not_base_class)
7806     << SS.getScopeRep()
7807     << cast<CXXRecordDecl>(CurContext)
7808     << SS.getRange();
7809 
7810   return true;
7811 }
7812 
7813 Decl *Sema::ActOnAliasDeclaration(Scope *S,
7814                                   AccessSpecifier AS,
7815                                   MultiTemplateParamsArg TemplateParamLists,
7816                                   SourceLocation UsingLoc,
7817                                   UnqualifiedId &Name,
7818                                   AttributeList *AttrList,
7819                                   TypeResult Type) {
7820   // Skip up to the relevant declaration scope.
7821   while (S->getFlags() & Scope::TemplateParamScope)
7822     S = S->getParent();
7823   assert((S->getFlags() & Scope::DeclScope) &&
7824          "got alias-declaration outside of declaration scope");
7825 
7826   if (Type.isInvalid())
7827     return 0;
7828 
7829   bool Invalid = false;
7830   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7831   TypeSourceInfo *TInfo = 0;
7832   GetTypeFromParser(Type.get(), &TInfo);
7833 
7834   if (DiagnoseClassNameShadow(CurContext, NameInfo))
7835     return 0;
7836 
7837   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
7838                                       UPPC_DeclarationType)) {
7839     Invalid = true;
7840     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7841                                              TInfo->getTypeLoc().getBeginLoc());
7842   }
7843 
7844   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7845   LookupName(Previous, S);
7846 
7847   // Warn about shadowing the name of a template parameter.
7848   if (Previous.isSingleResult() &&
7849       Previous.getFoundDecl()->isTemplateParameter()) {
7850     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
7851     Previous.clear();
7852   }
7853 
7854   assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7855          "name in alias declaration must be an identifier");
7856   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7857                                                Name.StartLocation,
7858                                                Name.Identifier, TInfo);
7859 
7860   NewTD->setAccess(AS);
7861 
7862   if (Invalid)
7863     NewTD->setInvalidDecl();
7864 
7865   ProcessDeclAttributeList(S, NewTD, AttrList);
7866 
7867   CheckTypedefForVariablyModifiedType(S, NewTD);
7868   Invalid |= NewTD->isInvalidDecl();
7869 
7870   bool Redeclaration = false;
7871 
7872   NamedDecl *NewND;
7873   if (TemplateParamLists.size()) {
7874     TypeAliasTemplateDecl *OldDecl = 0;
7875     TemplateParameterList *OldTemplateParams = 0;
7876 
7877     if (TemplateParamLists.size() != 1) {
7878       Diag(UsingLoc, diag::err_alias_template_extra_headers)
7879         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7880          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
7881     }
7882     TemplateParameterList *TemplateParams = TemplateParamLists[0];
7883 
7884     // Only consider previous declarations in the same scope.
7885     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7886                          /*ExplicitInstantiationOrSpecialization*/false);
7887     if (!Previous.empty()) {
7888       Redeclaration = true;
7889 
7890       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7891       if (!OldDecl && !Invalid) {
7892         Diag(UsingLoc, diag::err_redefinition_different_kind)
7893           << Name.Identifier;
7894 
7895         NamedDecl *OldD = Previous.getRepresentativeDecl();
7896         if (OldD->getLocation().isValid())
7897           Diag(OldD->getLocation(), diag::note_previous_definition);
7898 
7899         Invalid = true;
7900       }
7901 
7902       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7903         if (TemplateParameterListsAreEqual(TemplateParams,
7904                                            OldDecl->getTemplateParameters(),
7905                                            /*Complain=*/true,
7906                                            TPL_TemplateMatch))
7907           OldTemplateParams = OldDecl->getTemplateParameters();
7908         else
7909           Invalid = true;
7910 
7911         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7912         if (!Invalid &&
7913             !Context.hasSameType(OldTD->getUnderlyingType(),
7914                                  NewTD->getUnderlyingType())) {
7915           // FIXME: The C++0x standard does not clearly say this is ill-formed,
7916           // but we can't reasonably accept it.
7917           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7918             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7919           if (OldTD->getLocation().isValid())
7920             Diag(OldTD->getLocation(), diag::note_previous_definition);
7921           Invalid = true;
7922         }
7923       }
7924     }
7925 
7926     // Merge any previous default template arguments into our parameters,
7927     // and check the parameter list.
7928     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7929                                    TPC_TypeAliasTemplate))
7930       return 0;
7931 
7932     TypeAliasTemplateDecl *NewDecl =
7933       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7934                                     Name.Identifier, TemplateParams,
7935                                     NewTD);
7936 
7937     NewDecl->setAccess(AS);
7938 
7939     if (Invalid)
7940       NewDecl->setInvalidDecl();
7941     else if (OldDecl)
7942       NewDecl->setPreviousDecl(OldDecl);
7943 
7944     NewND = NewDecl;
7945   } else {
7946     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7947     NewND = NewTD;
7948   }
7949 
7950   if (!Redeclaration)
7951     PushOnScopeChains(NewND, S);
7952 
7953   ActOnDocumentableDecl(NewND);
7954   return NewND;
7955 }
7956 
7957 Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
7958                                              SourceLocation NamespaceLoc,
7959                                              SourceLocation AliasLoc,
7960                                              IdentifierInfo *Alias,
7961                                              CXXScopeSpec &SS,
7962                                              SourceLocation IdentLoc,
7963                                              IdentifierInfo *Ident) {
7964 
7965   // Lookup the namespace name.
7966   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7967   LookupParsedName(R, S, &SS);
7968 
7969   // Check if we have a previous declaration with the same name.
7970   NamedDecl *PrevDecl
7971     = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7972                        ForRedeclaration);
7973   if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7974     PrevDecl = 0;
7975 
7976   if (PrevDecl) {
7977     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
7978       // We already have an alias with the same name that points to the same
7979       // namespace, so don't create a new one.
7980       // FIXME: At some point, we'll want to create the (redundant)
7981       // declaration to maintain better source information.
7982       if (!R.isAmbiguous() && !R.empty() &&
7983           AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
7984         return 0;
7985     }
7986 
7987     unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7988       diag::err_redefinition_different_kind;
7989     Diag(AliasLoc, DiagID) << Alias;
7990     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
7991     return 0;
7992   }
7993 
7994   if (R.isAmbiguous())
7995     return 0;
7996 
7997   if (R.empty()) {
7998     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
7999       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
8000       return 0;
8001     }
8002   }
8003 
8004   NamespaceAliasDecl *AliasDecl =
8005     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
8006                                Alias, SS.getWithLocInContext(Context),
8007                                IdentLoc, R.getFoundDecl());
8008 
8009   PushOnScopeChains(AliasDecl, S);
8010   return AliasDecl;
8011 }
8012 
8013 Sema::ImplicitExceptionSpecification
8014 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8015                                                CXXMethodDecl *MD) {
8016   CXXRecordDecl *ClassDecl = MD->getParent();
8017 
8018   // C++ [except.spec]p14:
8019   //   An implicitly declared special member function (Clause 12) shall have an
8020   //   exception-specification. [...]
8021   ImplicitExceptionSpecification ExceptSpec(*this);
8022   if (ClassDecl->isInvalidDecl())
8023     return ExceptSpec;
8024 
8025   // Direct base-class constructors.
8026   for (const auto &B : ClassDecl->bases()) {
8027     if (B.isVirtual()) // Handled below.
8028       continue;
8029 
8030     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8031       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8032       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8033       // If this is a deleted function, add it anyway. This might be conformant
8034       // with the standard. This might not. I'm not sure. It might not matter.
8035       if (Constructor)
8036         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8037     }
8038   }
8039 
8040   // Virtual base-class constructors.
8041   for (const auto &B : ClassDecl->vbases()) {
8042     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8043       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8044       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8045       // If this is a deleted function, add it anyway. This might be conformant
8046       // with the standard. This might not. I'm not sure. It might not matter.
8047       if (Constructor)
8048         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8049     }
8050   }
8051 
8052   // Field constructors.
8053   for (const auto *F : ClassDecl->fields()) {
8054     if (F->hasInClassInitializer()) {
8055       if (Expr *E = F->getInClassInitializer())
8056         ExceptSpec.CalledExpr(E);
8057       else if (!F->isInvalidDecl())
8058         // DR1351:
8059         //   If the brace-or-equal-initializer of a non-static data member
8060         //   invokes a defaulted default constructor of its class or of an
8061         //   enclosing class in a potentially evaluated subexpression, the
8062         //   program is ill-formed.
8063         //
8064         // This resolution is unworkable: the exception specification of the
8065         // default constructor can be needed in an unevaluated context, in
8066         // particular, in the operand of a noexcept-expression, and we can be
8067         // unable to compute an exception specification for an enclosed class.
8068         //
8069         // We do not allow an in-class initializer to require the evaluation
8070         // of the exception specification for any in-class initializer whose
8071         // definition is not lexically complete.
8072         Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
8073     } else if (const RecordType *RecordTy
8074               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8075       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8076       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8077       // If this is a deleted function, add it anyway. This might be conformant
8078       // with the standard. This might not. I'm not sure. It might not matter.
8079       // In particular, the problem is that this function never gets called. It
8080       // might just be ill-formed because this function attempts to refer to
8081       // a deleted function here.
8082       if (Constructor)
8083         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8084     }
8085   }
8086 
8087   return ExceptSpec;
8088 }
8089 
8090 Sema::ImplicitExceptionSpecification
8091 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8092   CXXRecordDecl *ClassDecl = CD->getParent();
8093 
8094   // C++ [except.spec]p14:
8095   //   An inheriting constructor [...] shall have an exception-specification. [...]
8096   ImplicitExceptionSpecification ExceptSpec(*this);
8097   if (ClassDecl->isInvalidDecl())
8098     return ExceptSpec;
8099 
8100   // Inherited constructor.
8101   const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8102   const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8103   // FIXME: Copying or moving the parameters could add extra exceptions to the
8104   // set, as could the default arguments for the inherited constructor. This
8105   // will be addressed when we implement the resolution of core issue 1351.
8106   ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8107 
8108   // Direct base-class constructors.
8109   for (const auto &B : ClassDecl->bases()) {
8110     if (B.isVirtual()) // Handled below.
8111       continue;
8112 
8113     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8114       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8115       if (BaseClassDecl == InheritedDecl)
8116         continue;
8117       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8118       if (Constructor)
8119         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8120     }
8121   }
8122 
8123   // Virtual base-class constructors.
8124   for (const auto &B : ClassDecl->vbases()) {
8125     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8126       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8127       if (BaseClassDecl == InheritedDecl)
8128         continue;
8129       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8130       if (Constructor)
8131         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8132     }
8133   }
8134 
8135   // Field constructors.
8136   for (const auto *F : ClassDecl->fields()) {
8137     if (F->hasInClassInitializer()) {
8138       if (Expr *E = F->getInClassInitializer())
8139         ExceptSpec.CalledExpr(E);
8140       else if (!F->isInvalidDecl())
8141         Diag(CD->getLocation(),
8142              diag::err_in_class_initializer_references_def_ctor) << CD;
8143     } else if (const RecordType *RecordTy
8144               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8145       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8146       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8147       if (Constructor)
8148         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8149     }
8150   }
8151 
8152   return ExceptSpec;
8153 }
8154 
8155 namespace {
8156 /// RAII object to register a special member as being currently declared.
8157 struct DeclaringSpecialMember {
8158   Sema &S;
8159   Sema::SpecialMemberDecl D;
8160   bool WasAlreadyBeingDeclared;
8161 
8162   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8163     : S(S), D(RD, CSM) {
8164     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8165     if (WasAlreadyBeingDeclared)
8166       // This almost never happens, but if it does, ensure that our cache
8167       // doesn't contain a stale result.
8168       S.SpecialMemberCache.clear();
8169 
8170     // FIXME: Register a note to be produced if we encounter an error while
8171     // declaring the special member.
8172   }
8173   ~DeclaringSpecialMember() {
8174     if (!WasAlreadyBeingDeclared)
8175       S.SpecialMembersBeingDeclared.erase(D);
8176   }
8177 
8178   /// \brief Are we already trying to declare this special member?
8179   bool isAlreadyBeingDeclared() const {
8180     return WasAlreadyBeingDeclared;
8181   }
8182 };
8183 }
8184 
8185 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8186                                                      CXXRecordDecl *ClassDecl) {
8187   // C++ [class.ctor]p5:
8188   //   A default constructor for a class X is a constructor of class X
8189   //   that can be called without an argument. If there is no
8190   //   user-declared constructor for class X, a default constructor is
8191   //   implicitly declared. An implicitly-declared default constructor
8192   //   is an inline public member of its class.
8193   assert(ClassDecl->needsImplicitDefaultConstructor() &&
8194          "Should not build implicit default constructor!");
8195 
8196   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8197   if (DSM.isAlreadyBeingDeclared())
8198     return 0;
8199 
8200   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8201                                                      CXXDefaultConstructor,
8202                                                      false);
8203 
8204   // Create the actual constructor declaration.
8205   CanQualType ClassType
8206     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8207   SourceLocation ClassLoc = ClassDecl->getLocation();
8208   DeclarationName Name
8209     = Context.DeclarationNames.getCXXConstructorName(ClassType);
8210   DeclarationNameInfo NameInfo(Name, ClassLoc);
8211   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
8212       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
8213       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8214       Constexpr);
8215   DefaultCon->setAccess(AS_public);
8216   DefaultCon->setDefaulted();
8217   DefaultCon->setImplicit();
8218 
8219   // Build an exception specification pointing back at this constructor.
8220   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
8221   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8222 
8223   // We don't need to use SpecialMemberIsTrivial here; triviality for default
8224   // constructors is easy to compute.
8225   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8226 
8227   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
8228     SetDeclDeleted(DefaultCon, ClassLoc);
8229 
8230   // Note that we have declared this constructor.
8231   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
8232 
8233   if (Scope *S = getScopeForContext(ClassDecl))
8234     PushOnScopeChains(DefaultCon, S, false);
8235   ClassDecl->addDecl(DefaultCon);
8236 
8237   return DefaultCon;
8238 }
8239 
8240 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8241                                             CXXConstructorDecl *Constructor) {
8242   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
8243           !Constructor->doesThisDeclarationHaveABody() &&
8244           !Constructor->isDeleted()) &&
8245     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
8246 
8247   CXXRecordDecl *ClassDecl = Constructor->getParent();
8248   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
8249 
8250   SynthesizedFunctionScope Scope(*this, Constructor);
8251   DiagnosticErrorTrap Trap(Diags);
8252   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8253       Trap.hasErrorOccurred()) {
8254     Diag(CurrentLocation, diag::note_member_synthesized_at)
8255       << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
8256     Constructor->setInvalidDecl();
8257     return;
8258   }
8259 
8260   SourceLocation Loc = Constructor->getLocation();
8261   Constructor->setBody(new (Context) CompoundStmt(Loc));
8262 
8263   Constructor->markUsed(Context);
8264   MarkVTableUsed(CurrentLocation, ClassDecl);
8265 
8266   if (ASTMutationListener *L = getASTMutationListener()) {
8267     L->CompletedImplicitDefinition(Constructor);
8268   }
8269 
8270   DiagnoseUninitializedFields(*this, Constructor);
8271 }
8272 
8273 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
8274   // Perform any delayed checks on exception specifications.
8275   CheckDelayedMemberExceptionSpecs();
8276 }
8277 
8278 namespace {
8279 /// Information on inheriting constructors to declare.
8280 class InheritingConstructorInfo {
8281 public:
8282   InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8283       : SemaRef(SemaRef), Derived(Derived) {
8284     // Mark the constructors that we already have in the derived class.
8285     //
8286     // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8287     //   unless there is a user-declared constructor with the same signature in
8288     //   the class where the using-declaration appears.
8289     visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8290   }
8291 
8292   void inheritAll(CXXRecordDecl *RD) {
8293     visitAll(RD, &InheritingConstructorInfo::inherit);
8294   }
8295 
8296 private:
8297   /// Information about an inheriting constructor.
8298   struct InheritingConstructor {
8299     InheritingConstructor()
8300       : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
8301 
8302     /// If \c true, a constructor with this signature is already declared
8303     /// in the derived class.
8304     bool DeclaredInDerived;
8305 
8306     /// The constructor which is inherited.
8307     const CXXConstructorDecl *BaseCtor;
8308 
8309     /// The derived constructor we declared.
8310     CXXConstructorDecl *DerivedCtor;
8311   };
8312 
8313   /// Inheriting constructors with a given canonical type. There can be at
8314   /// most one such non-template constructor, and any number of templated
8315   /// constructors.
8316   struct InheritingConstructorsForType {
8317     InheritingConstructor NonTemplate;
8318     SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8319         Templates;
8320 
8321     InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8322       if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8323         TemplateParameterList *ParamList = FTD->getTemplateParameters();
8324         for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8325           if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8326                                                false, S.TPL_TemplateMatch))
8327             return Templates[I].second;
8328         Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8329         return Templates.back().second;
8330       }
8331 
8332       return NonTemplate;
8333     }
8334   };
8335 
8336   /// Get or create the inheriting constructor record for a constructor.
8337   InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8338                                   QualType CtorType) {
8339     return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8340         .getEntry(SemaRef, Ctor);
8341   }
8342 
8343   typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8344 
8345   /// Process all constructors for a class.
8346   void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
8347     for (const auto *Ctor : RD->ctors())
8348       (this->*Callback)(Ctor);
8349     for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8350              I(RD->decls_begin()), E(RD->decls_end());
8351          I != E; ++I) {
8352       const FunctionDecl *FD = (*I)->getTemplatedDecl();
8353       if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8354         (this->*Callback)(CD);
8355     }
8356   }
8357 
8358   /// Note that a constructor (or constructor template) was declared in Derived.
8359   void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8360     getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8361   }
8362 
8363   /// Inherit a single constructor.
8364   void inherit(const CXXConstructorDecl *Ctor) {
8365     const FunctionProtoType *CtorType =
8366         Ctor->getType()->castAs<FunctionProtoType>();
8367     ArrayRef<QualType> ArgTypes(CtorType->getParamTypes());
8368     FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8369 
8370     SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8371 
8372     // Core issue (no number yet): the ellipsis is always discarded.
8373     if (EPI.Variadic) {
8374       SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8375       SemaRef.Diag(Ctor->getLocation(),
8376                    diag::note_using_decl_constructor_ellipsis);
8377       EPI.Variadic = false;
8378     }
8379 
8380     // Declare a constructor for each number of parameters.
8381     //
8382     // C++11 [class.inhctor]p1:
8383     //   The candidate set of inherited constructors from the class X named in
8384     //   the using-declaration consists of [... modulo defects ...] for each
8385     //   constructor or constructor template of X, the set of constructors or
8386     //   constructor templates that results from omitting any ellipsis parameter
8387     //   specification and successively omitting parameters with a default
8388     //   argument from the end of the parameter-type-list
8389     unsigned MinParams = minParamsToInherit(Ctor);
8390     unsigned Params = Ctor->getNumParams();
8391     if (Params >= MinParams) {
8392       do
8393         declareCtor(UsingLoc, Ctor,
8394                     SemaRef.Context.getFunctionType(
8395                         Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
8396       while (Params > MinParams &&
8397              Ctor->getParamDecl(--Params)->hasDefaultArg());
8398     }
8399   }
8400 
8401   /// Find the using-declaration which specified that we should inherit the
8402   /// constructors of \p Base.
8403   SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8404     // No fancy lookup required; just look for the base constructor name
8405     // directly within the derived class.
8406     ASTContext &Context = SemaRef.Context;
8407     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8408         Context.getCanonicalType(Context.getRecordType(Base)));
8409     DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8410     return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8411   }
8412 
8413   unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8414     // C++11 [class.inhctor]p3:
8415     //   [F]or each constructor template in the candidate set of inherited
8416     //   constructors, a constructor template is implicitly declared
8417     if (Ctor->getDescribedFunctionTemplate())
8418       return 0;
8419 
8420     //   For each non-template constructor in the candidate set of inherited
8421     //   constructors other than a constructor having no parameters or a
8422     //   copy/move constructor having a single parameter, a constructor is
8423     //   implicitly declared [...]
8424     if (Ctor->getNumParams() == 0)
8425       return 1;
8426     if (Ctor->isCopyOrMoveConstructor())
8427       return 2;
8428 
8429     // Per discussion on core reflector, never inherit a constructor which
8430     // would become a default, copy, or move constructor of Derived either.
8431     const ParmVarDecl *PD = Ctor->getParamDecl(0);
8432     const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8433     return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8434   }
8435 
8436   /// Declare a single inheriting constructor, inheriting the specified
8437   /// constructor, with the given type.
8438   void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8439                    QualType DerivedType) {
8440     InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8441 
8442     // C++11 [class.inhctor]p3:
8443     //   ... a constructor is implicitly declared with the same constructor
8444     //   characteristics unless there is a user-declared constructor with
8445     //   the same signature in the class where the using-declaration appears
8446     if (Entry.DeclaredInDerived)
8447       return;
8448 
8449     // C++11 [class.inhctor]p7:
8450     //   If two using-declarations declare inheriting constructors with the
8451     //   same signature, the program is ill-formed
8452     if (Entry.DerivedCtor) {
8453       if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8454         // Only diagnose this once per constructor.
8455         if (Entry.DerivedCtor->isInvalidDecl())
8456           return;
8457         Entry.DerivedCtor->setInvalidDecl();
8458 
8459         SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8460         SemaRef.Diag(BaseCtor->getLocation(),
8461                      diag::note_using_decl_constructor_conflict_current_ctor);
8462         SemaRef.Diag(Entry.BaseCtor->getLocation(),
8463                      diag::note_using_decl_constructor_conflict_previous_ctor);
8464         SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8465                      diag::note_using_decl_constructor_conflict_previous_using);
8466       } else {
8467         // Core issue (no number): if the same inheriting constructor is
8468         // produced by multiple base class constructors from the same base
8469         // class, the inheriting constructor is defined as deleted.
8470         SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8471       }
8472 
8473       return;
8474     }
8475 
8476     ASTContext &Context = SemaRef.Context;
8477     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8478         Context.getCanonicalType(Context.getRecordType(Derived)));
8479     DeclarationNameInfo NameInfo(Name, UsingLoc);
8480 
8481     TemplateParameterList *TemplateParams = 0;
8482     if (const FunctionTemplateDecl *FTD =
8483             BaseCtor->getDescribedFunctionTemplate()) {
8484       TemplateParams = FTD->getTemplateParameters();
8485       // We're reusing template parameters from a different DeclContext. This
8486       // is questionable at best, but works out because the template depth in
8487       // both places is guaranteed to be 0.
8488       // FIXME: Rebuild the template parameters in the new context, and
8489       // transform the function type to refer to them.
8490     }
8491 
8492     // Build type source info pointing at the using-declaration. This is
8493     // required by template instantiation.
8494     TypeSourceInfo *TInfo =
8495         Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8496     FunctionProtoTypeLoc ProtoLoc =
8497         TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8498 
8499     CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8500         Context, Derived, UsingLoc, NameInfo, DerivedType,
8501         TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8502         /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8503 
8504     // Build an unevaluated exception specification for this constructor.
8505     const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8506     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8507     EPI.ExceptionSpecType = EST_Unevaluated;
8508     EPI.ExceptionSpecDecl = DerivedCtor;
8509     DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
8510                                                  FPT->getParamTypes(), EPI));
8511 
8512     // Build the parameter declarations.
8513     SmallVector<ParmVarDecl *, 16> ParamDecls;
8514     for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
8515       TypeSourceInfo *TInfo =
8516           Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
8517       ParmVarDecl *PD = ParmVarDecl::Create(
8518           Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
8519           FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/0);
8520       PD->setScopeInfo(0, I);
8521       PD->setImplicit();
8522       ParamDecls.push_back(PD);
8523       ProtoLoc.setParam(I, PD);
8524     }
8525 
8526     // Set up the new constructor.
8527     DerivedCtor->setAccess(BaseCtor->getAccess());
8528     DerivedCtor->setParams(ParamDecls);
8529     DerivedCtor->setInheritedConstructor(BaseCtor);
8530     if (BaseCtor->isDeleted())
8531       SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8532 
8533     // If this is a constructor template, build the template declaration.
8534     if (TemplateParams) {
8535       FunctionTemplateDecl *DerivedTemplate =
8536           FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8537                                        TemplateParams, DerivedCtor);
8538       DerivedTemplate->setAccess(BaseCtor->getAccess());
8539       DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8540       Derived->addDecl(DerivedTemplate);
8541     } else {
8542       Derived->addDecl(DerivedCtor);
8543     }
8544 
8545     Entry.BaseCtor = BaseCtor;
8546     Entry.DerivedCtor = DerivedCtor;
8547   }
8548 
8549   Sema &SemaRef;
8550   CXXRecordDecl *Derived;
8551   typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8552   MapType Map;
8553 };
8554 }
8555 
8556 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8557   // Defer declaring the inheriting constructors until the class is
8558   // instantiated.
8559   if (ClassDecl->isDependentContext())
8560     return;
8561 
8562   // Find base classes from which we might inherit constructors.
8563   SmallVector<CXXRecordDecl*, 4> InheritedBases;
8564   for (const auto &BaseIt : ClassDecl->bases())
8565     if (BaseIt.getInheritConstructors())
8566       InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
8567 
8568   // Go no further if we're not inheriting any constructors.
8569   if (InheritedBases.empty())
8570     return;
8571 
8572   // Declare the inherited constructors.
8573   InheritingConstructorInfo ICI(*this, ClassDecl);
8574   for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8575     ICI.inheritAll(InheritedBases[I]);
8576 }
8577 
8578 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8579                                        CXXConstructorDecl *Constructor) {
8580   CXXRecordDecl *ClassDecl = Constructor->getParent();
8581   assert(Constructor->getInheritedConstructor() &&
8582          !Constructor->doesThisDeclarationHaveABody() &&
8583          !Constructor->isDeleted());
8584 
8585   SynthesizedFunctionScope Scope(*this, Constructor);
8586   DiagnosticErrorTrap Trap(Diags);
8587   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8588       Trap.hasErrorOccurred()) {
8589     Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8590       << Context.getTagDeclType(ClassDecl);
8591     Constructor->setInvalidDecl();
8592     return;
8593   }
8594 
8595   SourceLocation Loc = Constructor->getLocation();
8596   Constructor->setBody(new (Context) CompoundStmt(Loc));
8597 
8598   Constructor->markUsed(Context);
8599   MarkVTableUsed(CurrentLocation, ClassDecl);
8600 
8601   if (ASTMutationListener *L = getASTMutationListener()) {
8602     L->CompletedImplicitDefinition(Constructor);
8603   }
8604 }
8605 
8606 
8607 Sema::ImplicitExceptionSpecification
8608 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8609   CXXRecordDecl *ClassDecl = MD->getParent();
8610 
8611   // C++ [except.spec]p14:
8612   //   An implicitly declared special member function (Clause 12) shall have
8613   //   an exception-specification.
8614   ImplicitExceptionSpecification ExceptSpec(*this);
8615   if (ClassDecl->isInvalidDecl())
8616     return ExceptSpec;
8617 
8618   // Direct base-class destructors.
8619   for (const auto &B : ClassDecl->bases()) {
8620     if (B.isVirtual()) // Handled below.
8621       continue;
8622 
8623     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8624       ExceptSpec.CalledDecl(B.getLocStart(),
8625                    LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
8626   }
8627 
8628   // Virtual base-class destructors.
8629   for (const auto &B : ClassDecl->vbases()) {
8630     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8631       ExceptSpec.CalledDecl(B.getLocStart(),
8632                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
8633   }
8634 
8635   // Field destructors.
8636   for (const auto *F : ClassDecl->fields()) {
8637     if (const RecordType *RecordTy
8638         = Context.getBaseElementType(F->getType())->getAs<RecordType>())
8639       ExceptSpec.CalledDecl(F->getLocation(),
8640                   LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
8641   }
8642 
8643   return ExceptSpec;
8644 }
8645 
8646 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8647   // C++ [class.dtor]p2:
8648   //   If a class has no user-declared destructor, a destructor is
8649   //   declared implicitly. An implicitly-declared destructor is an
8650   //   inline public member of its class.
8651   assert(ClassDecl->needsImplicitDestructor());
8652 
8653   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8654   if (DSM.isAlreadyBeingDeclared())
8655     return 0;
8656 
8657   // Create the actual destructor declaration.
8658   CanQualType ClassType
8659     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8660   SourceLocation ClassLoc = ClassDecl->getLocation();
8661   DeclarationName Name
8662     = Context.DeclarationNames.getCXXDestructorName(ClassType);
8663   DeclarationNameInfo NameInfo(Name, ClassLoc);
8664   CXXDestructorDecl *Destructor
8665       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8666                                   QualType(), 0, /*isInline=*/true,
8667                                   /*isImplicitlyDeclared=*/true);
8668   Destructor->setAccess(AS_public);
8669   Destructor->setDefaulted();
8670   Destructor->setImplicit();
8671 
8672   // Build an exception specification pointing back at this destructor.
8673   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
8674   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8675 
8676   AddOverriddenMethods(ClassDecl, Destructor);
8677 
8678   // We don't need to use SpecialMemberIsTrivial here; triviality for
8679   // destructors is easy to compute.
8680   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8681 
8682   if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
8683     SetDeclDeleted(Destructor, ClassLoc);
8684 
8685   // Note that we have declared this destructor.
8686   ++ASTContext::NumImplicitDestructorsDeclared;
8687 
8688   // Introduce this destructor into its scope.
8689   if (Scope *S = getScopeForContext(ClassDecl))
8690     PushOnScopeChains(Destructor, S, false);
8691   ClassDecl->addDecl(Destructor);
8692 
8693   return Destructor;
8694 }
8695 
8696 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
8697                                     CXXDestructorDecl *Destructor) {
8698   assert((Destructor->isDefaulted() &&
8699           !Destructor->doesThisDeclarationHaveABody() &&
8700           !Destructor->isDeleted()) &&
8701          "DefineImplicitDestructor - call it for implicit default dtor");
8702   CXXRecordDecl *ClassDecl = Destructor->getParent();
8703   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
8704 
8705   if (Destructor->isInvalidDecl())
8706     return;
8707 
8708   SynthesizedFunctionScope Scope(*this, Destructor);
8709 
8710   DiagnosticErrorTrap Trap(Diags);
8711   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8712                                          Destructor->getParent());
8713 
8714   if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
8715     Diag(CurrentLocation, diag::note_member_synthesized_at)
8716       << CXXDestructor << Context.getTagDeclType(ClassDecl);
8717 
8718     Destructor->setInvalidDecl();
8719     return;
8720   }
8721 
8722   SourceLocation Loc = Destructor->getLocation();
8723   Destructor->setBody(new (Context) CompoundStmt(Loc));
8724   Destructor->markUsed(Context);
8725   MarkVTableUsed(CurrentLocation, ClassDecl);
8726 
8727   if (ASTMutationListener *L = getASTMutationListener()) {
8728     L->CompletedImplicitDefinition(Destructor);
8729   }
8730 }
8731 
8732 /// \brief Perform any semantic analysis which needs to be delayed until all
8733 /// pending class member declarations have been parsed.
8734 void Sema::ActOnFinishCXXMemberDecls() {
8735   // If the context is an invalid C++ class, just suppress these checks.
8736   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8737     if (Record->isInvalidDecl()) {
8738       DelayedDefaultedMemberExceptionSpecs.clear();
8739       DelayedDestructorExceptionSpecChecks.clear();
8740       return;
8741     }
8742   }
8743 }
8744 
8745 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8746                                          CXXDestructorDecl *Destructor) {
8747   assert(getLangOpts().CPlusPlus11 &&
8748          "adjusting dtor exception specs was introduced in c++11");
8749 
8750   // C++11 [class.dtor]p3:
8751   //   A declaration of a destructor that does not have an exception-
8752   //   specification is implicitly considered to have the same exception-
8753   //   specification as an implicit declaration.
8754   const FunctionProtoType *DtorType = Destructor->getType()->
8755                                         getAs<FunctionProtoType>();
8756   if (DtorType->hasExceptionSpec())
8757     return;
8758 
8759   // Replace the destructor's type, building off the existing one. Fortunately,
8760   // the only thing of interest in the destructor type is its extended info.
8761   // The return and arguments are fixed.
8762   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8763   EPI.ExceptionSpecType = EST_Unevaluated;
8764   EPI.ExceptionSpecDecl = Destructor;
8765   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8766 
8767   // FIXME: If the destructor has a body that could throw, and the newly created
8768   // spec doesn't allow exceptions, we should emit a warning, because this
8769   // change in behavior can break conforming C++03 programs at runtime.
8770   // However, we don't have a body or an exception specification yet, so it
8771   // needs to be done somewhere else.
8772 }
8773 
8774 namespace {
8775 /// \brief An abstract base class for all helper classes used in building the
8776 //  copy/move operators. These classes serve as factory functions and help us
8777 //  avoid using the same Expr* in the AST twice.
8778 class ExprBuilder {
8779   ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8780   ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8781 
8782 protected:
8783   static Expr *assertNotNull(Expr *E) {
8784     assert(E && "Expression construction must not fail.");
8785     return E;
8786   }
8787 
8788 public:
8789   ExprBuilder() {}
8790   virtual ~ExprBuilder() {}
8791 
8792   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
8793 };
8794 
8795 class RefBuilder: public ExprBuilder {
8796   VarDecl *Var;
8797   QualType VarType;
8798 
8799 public:
8800   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
8801     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).take());
8802   }
8803 
8804   RefBuilder(VarDecl *Var, QualType VarType)
8805       : Var(Var), VarType(VarType) {}
8806 };
8807 
8808 class ThisBuilder: public ExprBuilder {
8809 public:
8810   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
8811     return assertNotNull(S.ActOnCXXThis(Loc).takeAs<Expr>());
8812   }
8813 };
8814 
8815 class CastBuilder: public ExprBuilder {
8816   const ExprBuilder &Builder;
8817   QualType Type;
8818   ExprValueKind Kind;
8819   const CXXCastPath &Path;
8820 
8821 public:
8822   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
8823     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
8824                                              CK_UncheckedDerivedToBase, Kind,
8825                                              &Path).take());
8826   }
8827 
8828   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
8829               const CXXCastPath &Path)
8830       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
8831 };
8832 
8833 class DerefBuilder: public ExprBuilder {
8834   const ExprBuilder &Builder;
8835 
8836 public:
8837   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
8838     return assertNotNull(
8839         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).take());
8840   }
8841 
8842   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8843 };
8844 
8845 class MemberBuilder: public ExprBuilder {
8846   const ExprBuilder &Builder;
8847   QualType Type;
8848   CXXScopeSpec SS;
8849   bool IsArrow;
8850   LookupResult &MemberLookup;
8851 
8852 public:
8853   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
8854     return assertNotNull(S.BuildMemberReferenceExpr(
8855         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 0,
8856         MemberLookup, 0).take());
8857   }
8858 
8859   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
8860                 LookupResult &MemberLookup)
8861       : Builder(Builder), Type(Type), IsArrow(IsArrow),
8862         MemberLookup(MemberLookup) {}
8863 };
8864 
8865 class MoveCastBuilder: public ExprBuilder {
8866   const ExprBuilder &Builder;
8867 
8868 public:
8869   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
8870     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
8871   }
8872 
8873   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8874 };
8875 
8876 class LvalueConvBuilder: public ExprBuilder {
8877   const ExprBuilder &Builder;
8878 
8879 public:
8880   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
8881     return assertNotNull(
8882         S.DefaultLvalueConversion(Builder.build(S, Loc)).take());
8883   }
8884 
8885   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8886 };
8887 
8888 class SubscriptBuilder: public ExprBuilder {
8889   const ExprBuilder &Base;
8890   const ExprBuilder &Index;
8891 
8892 public:
8893   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
8894     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
8895         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).take());
8896   }
8897 
8898   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
8899       : Base(Base), Index(Index) {}
8900 };
8901 
8902 } // end anonymous namespace
8903 
8904 /// When generating a defaulted copy or move assignment operator, if a field
8905 /// should be copied with __builtin_memcpy rather than via explicit assignments,
8906 /// do so. This optimization only applies for arrays of scalars, and for arrays
8907 /// of class type where the selected copy/move-assignment operator is trivial.
8908 static StmtResult
8909 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
8910                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
8911   // Compute the size of the memory buffer to be copied.
8912   QualType SizeType = S.Context.getSizeType();
8913   llvm::APInt Size(S.Context.getTypeSize(SizeType),
8914                    S.Context.getTypeSizeInChars(T).getQuantity());
8915 
8916   // Take the address of the field references for "from" and "to". We
8917   // directly construct UnaryOperators here because semantic analysis
8918   // does not permit us to take the address of an xvalue.
8919   Expr *From = FromB.build(S, Loc);
8920   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8921                          S.Context.getPointerType(From->getType()),
8922                          VK_RValue, OK_Ordinary, Loc);
8923   Expr *To = ToB.build(S, Loc);
8924   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8925                        S.Context.getPointerType(To->getType()),
8926                        VK_RValue, OK_Ordinary, Loc);
8927 
8928   const Type *E = T->getBaseElementTypeUnsafe();
8929   bool NeedsCollectableMemCpy =
8930     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8931 
8932   // Create a reference to the __builtin_objc_memmove_collectable function
8933   StringRef MemCpyName = NeedsCollectableMemCpy ?
8934     "__builtin_objc_memmove_collectable" :
8935     "__builtin_memcpy";
8936   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8937                  Sema::LookupOrdinaryName);
8938   S.LookupName(R, S.TUScope, true);
8939 
8940   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8941   if (!MemCpy)
8942     // Something went horribly wrong earlier, and we will have complained
8943     // about it.
8944     return StmtError();
8945 
8946   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8947                                             VK_RValue, Loc, 0);
8948   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8949 
8950   Expr *CallArgs[] = {
8951     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8952   };
8953   ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8954                                     Loc, CallArgs, Loc);
8955 
8956   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8957   return S.Owned(Call.takeAs<Stmt>());
8958 }
8959 
8960 /// \brief Builds a statement that copies/moves the given entity from \p From to
8961 /// \c To.
8962 ///
8963 /// This routine is used to copy/move the members of a class with an
8964 /// implicitly-declared copy/move assignment operator. When the entities being
8965 /// copied are arrays, this routine builds for loops to copy them.
8966 ///
8967 /// \param S The Sema object used for type-checking.
8968 ///
8969 /// \param Loc The location where the implicit copy/move is being generated.
8970 ///
8971 /// \param T The type of the expressions being copied/moved. Both expressions
8972 /// must have this type.
8973 ///
8974 /// \param To The expression we are copying/moving to.
8975 ///
8976 /// \param From The expression we are copying/moving from.
8977 ///
8978 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
8979 /// Otherwise, it's a non-static member subobject.
8980 ///
8981 /// \param Copying Whether we're copying or moving.
8982 ///
8983 /// \param Depth Internal parameter recording the depth of the recursion.
8984 ///
8985 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8986 /// if a memcpy should be used instead.
8987 static StmtResult
8988 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8989                                  const ExprBuilder &To, const ExprBuilder &From,
8990                                  bool CopyingBaseSubobject, bool Copying,
8991                                  unsigned Depth = 0) {
8992   // C++11 [class.copy]p28:
8993   //   Each subobject is assigned in the manner appropriate to its type:
8994   //
8995   //     - if the subobject is of class type, as if by a call to operator= with
8996   //       the subobject as the object expression and the corresponding
8997   //       subobject of x as a single function argument (as if by explicit
8998   //       qualification; that is, ignoring any possible virtual overriding
8999   //       functions in more derived classes);
9000   //
9001   // C++03 [class.copy]p13:
9002   //     - if the subobject is of class type, the copy assignment operator for
9003   //       the class is used (as if by explicit qualification; that is,
9004   //       ignoring any possible virtual overriding functions in more derived
9005   //       classes);
9006   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9007     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9008 
9009     // Look for operator=.
9010     DeclarationName Name
9011       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9012     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9013     S.LookupQualifiedName(OpLookup, ClassDecl, false);
9014 
9015     // Prior to C++11, filter out any result that isn't a copy/move-assignment
9016     // operator.
9017     if (!S.getLangOpts().CPlusPlus11) {
9018       LookupResult::Filter F = OpLookup.makeFilter();
9019       while (F.hasNext()) {
9020         NamedDecl *D = F.next();
9021         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9022           if (Method->isCopyAssignmentOperator() ||
9023               (!Copying && Method->isMoveAssignmentOperator()))
9024             continue;
9025 
9026         F.erase();
9027       }
9028       F.done();
9029     }
9030 
9031     // Suppress the protected check (C++ [class.protected]) for each of the
9032     // assignment operators we found. This strange dance is required when
9033     // we're assigning via a base classes's copy-assignment operator. To
9034     // ensure that we're getting the right base class subobject (without
9035     // ambiguities), we need to cast "this" to that subobject type; to
9036     // ensure that we don't go through the virtual call mechanism, we need
9037     // to qualify the operator= name with the base class (see below). However,
9038     // this means that if the base class has a protected copy assignment
9039     // operator, the protected member access check will fail. So, we
9040     // rewrite "protected" access to "public" access in this case, since we
9041     // know by construction that we're calling from a derived class.
9042     if (CopyingBaseSubobject) {
9043       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9044            L != LEnd; ++L) {
9045         if (L.getAccess() == AS_protected)
9046           L.setAccess(AS_public);
9047       }
9048     }
9049 
9050     // Create the nested-name-specifier that will be used to qualify the
9051     // reference to operator=; this is required to suppress the virtual
9052     // call mechanism.
9053     CXXScopeSpec SS;
9054     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
9055     SS.MakeTrivial(S.Context,
9056                    NestedNameSpecifier::Create(S.Context, 0, false,
9057                                                CanonicalT),
9058                    Loc);
9059 
9060     // Create the reference to operator=.
9061     ExprResult OpEqualRef
9062       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9063                                    SS, /*TemplateKWLoc=*/SourceLocation(),
9064                                    /*FirstQualifierInScope=*/0,
9065                                    OpLookup,
9066                                    /*TemplateArgs=*/0,
9067                                    /*SuppressQualifierCheck=*/true);
9068     if (OpEqualRef.isInvalid())
9069       return StmtError();
9070 
9071     // Build the call to the assignment operator.
9072 
9073     Expr *FromInst = From.build(S, Loc);
9074     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
9075                                                   OpEqualRef.takeAs<Expr>(),
9076                                                   Loc, FromInst, Loc);
9077     if (Call.isInvalid())
9078       return StmtError();
9079 
9080     // If we built a call to a trivial 'operator=' while copying an array,
9081     // bail out. We'll replace the whole shebang with a memcpy.
9082     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9083     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9084       return StmtResult((Stmt*)0);
9085 
9086     // Convert to an expression-statement, and clean up any produced
9087     // temporaries.
9088     return S.ActOnExprStmt(Call);
9089   }
9090 
9091   //     - if the subobject is of scalar type, the built-in assignment
9092   //       operator is used.
9093   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
9094   if (!ArrayTy) {
9095     ExprResult Assignment = S.CreateBuiltinBinOp(
9096         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
9097     if (Assignment.isInvalid())
9098       return StmtError();
9099     return S.ActOnExprStmt(Assignment);
9100   }
9101 
9102   //     - if the subobject is an array, each element is assigned, in the
9103   //       manner appropriate to the element type;
9104 
9105   // Construct a loop over the array bounds, e.g.,
9106   //
9107   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9108   //
9109   // that will copy each of the array elements.
9110   QualType SizeType = S.Context.getSizeType();
9111 
9112   // Create the iteration variable.
9113   IdentifierInfo *IterationVarName = 0;
9114   {
9115     SmallString<8> Str;
9116     llvm::raw_svector_ostream OS(Str);
9117     OS << "__i" << Depth;
9118     IterationVarName = &S.Context.Idents.get(OS.str());
9119   }
9120   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
9121                                           IterationVarName, SizeType,
9122                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
9123                                           SC_None);
9124 
9125   // Initialize the iteration variable to zero.
9126   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
9127   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
9128 
9129   // Creates a reference to the iteration variable.
9130   RefBuilder IterationVarRef(IterationVar, SizeType);
9131   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
9132 
9133   // Create the DeclStmt that holds the iteration variable.
9134   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
9135 
9136   // Subscript the "from" and "to" expressions with the iteration variable.
9137   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9138   MoveCastBuilder FromIndexMove(FromIndexCopy);
9139   const ExprBuilder *FromIndex;
9140   if (Copying)
9141     FromIndex = &FromIndexCopy;
9142   else
9143     FromIndex = &FromIndexMove;
9144 
9145   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
9146 
9147   // Build the copy/move for an individual element of the array.
9148   StmtResult Copy =
9149     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
9150                                      ToIndex, *FromIndex, CopyingBaseSubobject,
9151                                      Copying, Depth + 1);
9152   // Bail out if copying fails or if we determined that we should use memcpy.
9153   if (Copy.isInvalid() || !Copy.get())
9154     return Copy;
9155 
9156   // Create the comparison against the array bound.
9157   llvm::APInt Upper
9158     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9159   Expr *Comparison
9160     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
9161                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9162                                      BO_NE, S.Context.BoolTy,
9163                                      VK_RValue, OK_Ordinary, Loc, false);
9164 
9165   // Create the pre-increment of the iteration variable.
9166   Expr *Increment
9167     = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9168                                     SizeType, VK_LValue, OK_Ordinary, Loc);
9169 
9170   // Construct the loop that copies all elements of this array.
9171   return S.ActOnForStmt(Loc, Loc, InitStmt,
9172                         S.MakeFullExpr(Comparison),
9173                         0, S.MakeFullDiscardedValueExpr(Increment),
9174                         Loc, Copy.take());
9175 }
9176 
9177 static StmtResult
9178 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
9179                       const ExprBuilder &To, const ExprBuilder &From,
9180                       bool CopyingBaseSubobject, bool Copying) {
9181   // Maybe we should use a memcpy?
9182   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9183       T.isTriviallyCopyableType(S.Context))
9184     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9185 
9186   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9187                                                      CopyingBaseSubobject,
9188                                                      Copying, 0));
9189 
9190   // If we ended up picking a trivial assignment operator for an array of a
9191   // non-trivially-copyable class type, just emit a memcpy.
9192   if (!Result.isInvalid() && !Result.get())
9193     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9194 
9195   return Result;
9196 }
9197 
9198 Sema::ImplicitExceptionSpecification
9199 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9200   CXXRecordDecl *ClassDecl = MD->getParent();
9201 
9202   ImplicitExceptionSpecification ExceptSpec(*this);
9203   if (ClassDecl->isInvalidDecl())
9204     return ExceptSpec;
9205 
9206   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9207   assert(T->getNumParams() == 1 && "not a copy assignment op");
9208   unsigned ArgQuals =
9209       T->getParamType(0).getNonReferenceType().getCVRQualifiers();
9210 
9211   // C++ [except.spec]p14:
9212   //   An implicitly declared special member function (Clause 12) shall have an
9213   //   exception-specification. [...]
9214 
9215   // It is unspecified whether or not an implicit copy assignment operator
9216   // attempts to deduplicate calls to assignment operators of virtual bases are
9217   // made. As such, this exception specification is effectively unspecified.
9218   // Based on a similar decision made for constness in C++0x, we're erring on
9219   // the side of assuming such calls to be made regardless of whether they
9220   // actually happen.
9221   for (const auto &Base : ClassDecl->bases()) {
9222     if (Base.isVirtual())
9223       continue;
9224 
9225     CXXRecordDecl *BaseClassDecl
9226       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9227     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9228                                                             ArgQuals, false, 0))
9229       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
9230   }
9231 
9232   for (const auto &Base : ClassDecl->vbases()) {
9233     CXXRecordDecl *BaseClassDecl
9234       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9235     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9236                                                             ArgQuals, false, 0))
9237       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
9238   }
9239 
9240   for (const auto *Field : ClassDecl->fields()) {
9241     QualType FieldType = Context.getBaseElementType(Field->getType());
9242     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9243       if (CXXMethodDecl *CopyAssign =
9244           LookupCopyingAssignment(FieldClassDecl,
9245                                   ArgQuals | FieldType.getCVRQualifiers(),
9246                                   false, 0))
9247         ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
9248     }
9249   }
9250 
9251   return ExceptSpec;
9252 }
9253 
9254 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9255   // Note: The following rules are largely analoguous to the copy
9256   // constructor rules. Note that virtual bases are not taken into account
9257   // for determining the argument type of the operator. Note also that
9258   // operators taking an object instead of a reference are allowed.
9259   assert(ClassDecl->needsImplicitCopyAssignment());
9260 
9261   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9262   if (DSM.isAlreadyBeingDeclared())
9263     return 0;
9264 
9265   QualType ArgType = Context.getTypeDeclType(ClassDecl);
9266   QualType RetType = Context.getLValueReferenceType(ArgType);
9267   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9268   if (Const)
9269     ArgType = ArgType.withConst();
9270   ArgType = Context.getLValueReferenceType(ArgType);
9271 
9272   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9273                                                      CXXCopyAssignment,
9274                                                      Const);
9275 
9276   //   An implicitly-declared copy assignment operator is an inline public
9277   //   member of its class.
9278   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9279   SourceLocation ClassLoc = ClassDecl->getLocation();
9280   DeclarationNameInfo NameInfo(Name, ClassLoc);
9281   CXXMethodDecl *CopyAssignment =
9282       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9283                             /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
9284                             /*isInline=*/ true, Constexpr, SourceLocation());
9285   CopyAssignment->setAccess(AS_public);
9286   CopyAssignment->setDefaulted();
9287   CopyAssignment->setImplicit();
9288 
9289   // Build an exception specification pointing back at this member.
9290   FunctionProtoType::ExtProtoInfo EPI =
9291       getImplicitMethodEPI(*this, CopyAssignment);
9292   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
9293 
9294   // Add the parameter to the operator.
9295   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
9296                                                ClassLoc, ClassLoc, /*Id=*/0,
9297                                                ArgType, /*TInfo=*/0,
9298                                                SC_None, 0);
9299   CopyAssignment->setParams(FromParam);
9300 
9301   AddOverriddenMethods(ClassDecl, CopyAssignment);
9302 
9303   CopyAssignment->setTrivial(
9304     ClassDecl->needsOverloadResolutionForCopyAssignment()
9305       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9306       : ClassDecl->hasTrivialCopyAssignment());
9307 
9308   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
9309     SetDeclDeleted(CopyAssignment, ClassLoc);
9310 
9311   // Note that we have added this copy-assignment operator.
9312   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9313 
9314   if (Scope *S = getScopeForContext(ClassDecl))
9315     PushOnScopeChains(CopyAssignment, S, false);
9316   ClassDecl->addDecl(CopyAssignment);
9317 
9318   return CopyAssignment;
9319 }
9320 
9321 /// Diagnose an implicit copy operation for a class which is odr-used, but
9322 /// which is deprecated because the class has a user-declared copy constructor,
9323 /// copy assignment operator, or destructor.
9324 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9325                                             SourceLocation UseLoc) {
9326   assert(CopyOp->isImplicit());
9327 
9328   CXXRecordDecl *RD = CopyOp->getParent();
9329   CXXMethodDecl *UserDeclaredOperation = 0;
9330 
9331   // In Microsoft mode, assignment operations don't affect constructors and
9332   // vice versa.
9333   if (RD->hasUserDeclaredDestructor()) {
9334     UserDeclaredOperation = RD->getDestructor();
9335   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9336              RD->hasUserDeclaredCopyConstructor() &&
9337              !S.getLangOpts().MSVCCompat) {
9338     // Find any user-declared copy constructor.
9339     for (auto *I : RD->ctors()) {
9340       if (I->isCopyConstructor()) {
9341         UserDeclaredOperation = I;
9342         break;
9343       }
9344     }
9345     assert(UserDeclaredOperation);
9346   } else if (isa<CXXConstructorDecl>(CopyOp) &&
9347              RD->hasUserDeclaredCopyAssignment() &&
9348              !S.getLangOpts().MSVCCompat) {
9349     // Find any user-declared move assignment operator.
9350     for (auto *I : RD->methods()) {
9351       if (I->isCopyAssignmentOperator()) {
9352         UserDeclaredOperation = I;
9353         break;
9354       }
9355     }
9356     assert(UserDeclaredOperation);
9357   }
9358 
9359   if (UserDeclaredOperation) {
9360     S.Diag(UserDeclaredOperation->getLocation(),
9361          diag::warn_deprecated_copy_operation)
9362       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9363       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9364     S.Diag(UseLoc, diag::note_member_synthesized_at)
9365       << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9366                                           : Sema::CXXCopyAssignment)
9367       << RD;
9368   }
9369 }
9370 
9371 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9372                                         CXXMethodDecl *CopyAssignOperator) {
9373   assert((CopyAssignOperator->isDefaulted() &&
9374           CopyAssignOperator->isOverloadedOperator() &&
9375           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
9376           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9377           !CopyAssignOperator->isDeleted()) &&
9378          "DefineImplicitCopyAssignment called for wrong function");
9379 
9380   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9381 
9382   if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9383     CopyAssignOperator->setInvalidDecl();
9384     return;
9385   }
9386 
9387   // C++11 [class.copy]p18:
9388   //   The [definition of an implicitly declared copy assignment operator] is
9389   //   deprecated if the class has a user-declared copy constructor or a
9390   //   user-declared destructor.
9391   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9392     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9393 
9394   CopyAssignOperator->markUsed(Context);
9395 
9396   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
9397   DiagnosticErrorTrap Trap(Diags);
9398 
9399   // C++0x [class.copy]p30:
9400   //   The implicitly-defined or explicitly-defaulted copy assignment operator
9401   //   for a non-union class X performs memberwise copy assignment of its
9402   //   subobjects. The direct base classes of X are assigned first, in the
9403   //   order of their declaration in the base-specifier-list, and then the
9404   //   immediate non-static data members of X are assigned, in the order in
9405   //   which they were declared in the class definition.
9406 
9407   // The statements that form the synthesized function body.
9408   SmallVector<Stmt*, 8> Statements;
9409 
9410   // The parameter for the "other" object, which we are copying from.
9411   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9412   Qualifiers OtherQuals = Other->getType().getQualifiers();
9413   QualType OtherRefType = Other->getType();
9414   if (const LValueReferenceType *OtherRef
9415                                 = OtherRefType->getAs<LValueReferenceType>()) {
9416     OtherRefType = OtherRef->getPointeeType();
9417     OtherQuals = OtherRefType.getQualifiers();
9418   }
9419 
9420   // Our location for everything implicitly-generated.
9421   SourceLocation Loc = CopyAssignOperator->getLocation();
9422 
9423   // Builds a DeclRefExpr for the "other" object.
9424   RefBuilder OtherRef(Other, OtherRefType);
9425 
9426   // Builds the "this" pointer.
9427   ThisBuilder This;
9428 
9429   // Assign base classes.
9430   bool Invalid = false;
9431   for (auto &Base : ClassDecl->bases()) {
9432     // Form the assignment:
9433     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
9434     QualType BaseType = Base.getType().getUnqualifiedType();
9435     if (!BaseType->isRecordType()) {
9436       Invalid = true;
9437       continue;
9438     }
9439 
9440     CXXCastPath BasePath;
9441     BasePath.push_back(&Base);
9442 
9443     // Construct the "from" expression, which is an implicit cast to the
9444     // appropriately-qualified base type.
9445     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9446                      VK_LValue, BasePath);
9447 
9448     // Dereference "this".
9449     DerefBuilder DerefThis(This);
9450     CastBuilder To(DerefThis,
9451                    Context.getCVRQualifiedType(
9452                        BaseType, CopyAssignOperator->getTypeQualifiers()),
9453                    VK_LValue, BasePath);
9454 
9455     // Build the copy.
9456     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
9457                                             To, From,
9458                                             /*CopyingBaseSubobject=*/true,
9459                                             /*Copying=*/true);
9460     if (Copy.isInvalid()) {
9461       Diag(CurrentLocation, diag::note_member_synthesized_at)
9462         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9463       CopyAssignOperator->setInvalidDecl();
9464       return;
9465     }
9466 
9467     // Success! Record the copy.
9468     Statements.push_back(Copy.takeAs<Expr>());
9469   }
9470 
9471   // Assign non-static members.
9472   for (auto *Field : ClassDecl->fields()) {
9473     if (Field->isUnnamedBitfield())
9474       continue;
9475 
9476     if (Field->isInvalidDecl()) {
9477       Invalid = true;
9478       continue;
9479     }
9480 
9481     // Check for members of reference type; we can't copy those.
9482     if (Field->getType()->isReferenceType()) {
9483       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9484         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9485       Diag(Field->getLocation(), diag::note_declared_at);
9486       Diag(CurrentLocation, diag::note_member_synthesized_at)
9487         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9488       Invalid = true;
9489       continue;
9490     }
9491 
9492     // Check for members of const-qualified, non-class type.
9493     QualType BaseType = Context.getBaseElementType(Field->getType());
9494     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9495       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9496         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9497       Diag(Field->getLocation(), diag::note_declared_at);
9498       Diag(CurrentLocation, diag::note_member_synthesized_at)
9499         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9500       Invalid = true;
9501       continue;
9502     }
9503 
9504     // Suppress assigning zero-width bitfields.
9505     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9506       continue;
9507 
9508     QualType FieldType = Field->getType().getNonReferenceType();
9509     if (FieldType->isIncompleteArrayType()) {
9510       assert(ClassDecl->hasFlexibleArrayMember() &&
9511              "Incomplete array type is not valid");
9512       continue;
9513     }
9514 
9515     // Build references to the field in the object we're copying from and to.
9516     CXXScopeSpec SS; // Intentionally empty
9517     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9518                               LookupMemberName);
9519     MemberLookup.addDecl(Field);
9520     MemberLookup.resolveKind();
9521 
9522     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9523 
9524     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
9525 
9526     // Build the copy of this field.
9527     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
9528                                             To, From,
9529                                             /*CopyingBaseSubobject=*/false,
9530                                             /*Copying=*/true);
9531     if (Copy.isInvalid()) {
9532       Diag(CurrentLocation, diag::note_member_synthesized_at)
9533         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9534       CopyAssignOperator->setInvalidDecl();
9535       return;
9536     }
9537 
9538     // Success! Record the copy.
9539     Statements.push_back(Copy.takeAs<Stmt>());
9540   }
9541 
9542   if (!Invalid) {
9543     // Add a "return *this;"
9544     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
9545 
9546     StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9547     if (Return.isInvalid())
9548       Invalid = true;
9549     else {
9550       Statements.push_back(Return.takeAs<Stmt>());
9551 
9552       if (Trap.hasErrorOccurred()) {
9553         Diag(CurrentLocation, diag::note_member_synthesized_at)
9554           << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9555         Invalid = true;
9556       }
9557     }
9558   }
9559 
9560   if (Invalid) {
9561     CopyAssignOperator->setInvalidDecl();
9562     return;
9563   }
9564 
9565   StmtResult Body;
9566   {
9567     CompoundScopeRAII CompoundScope(*this);
9568     Body = ActOnCompoundStmt(Loc, Loc, Statements,
9569                              /*isStmtExpr=*/false);
9570     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9571   }
9572   CopyAssignOperator->setBody(Body.takeAs<Stmt>());
9573 
9574   if (ASTMutationListener *L = getASTMutationListener()) {
9575     L->CompletedImplicitDefinition(CopyAssignOperator);
9576   }
9577 }
9578 
9579 Sema::ImplicitExceptionSpecification
9580 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9581   CXXRecordDecl *ClassDecl = MD->getParent();
9582 
9583   ImplicitExceptionSpecification ExceptSpec(*this);
9584   if (ClassDecl->isInvalidDecl())
9585     return ExceptSpec;
9586 
9587   // C++0x [except.spec]p14:
9588   //   An implicitly declared special member function (Clause 12) shall have an
9589   //   exception-specification. [...]
9590 
9591   // It is unspecified whether or not an implicit move assignment operator
9592   // attempts to deduplicate calls to assignment operators of virtual bases are
9593   // made. As such, this exception specification is effectively unspecified.
9594   // Based on a similar decision made for constness in C++0x, we're erring on
9595   // the side of assuming such calls to be made regardless of whether they
9596   // actually happen.
9597   // Note that a move constructor is not implicitly declared when there are
9598   // virtual bases, but it can still be user-declared and explicitly defaulted.
9599   for (const auto &Base : ClassDecl->bases()) {
9600     if (Base.isVirtual())
9601       continue;
9602 
9603     CXXRecordDecl *BaseClassDecl
9604       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9605     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
9606                                                            0, false, 0))
9607       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
9608   }
9609 
9610   for (const auto &Base : ClassDecl->vbases()) {
9611     CXXRecordDecl *BaseClassDecl
9612       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9613     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
9614                                                            0, false, 0))
9615       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
9616   }
9617 
9618   for (const auto *Field : ClassDecl->fields()) {
9619     QualType FieldType = Context.getBaseElementType(Field->getType());
9620     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9621       if (CXXMethodDecl *MoveAssign =
9622               LookupMovingAssignment(FieldClassDecl,
9623                                      FieldType.getCVRQualifiers(),
9624                                      false, 0))
9625         ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
9626     }
9627   }
9628 
9629   return ExceptSpec;
9630 }
9631 
9632 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
9633   assert(ClassDecl->needsImplicitMoveAssignment());
9634 
9635   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9636   if (DSM.isAlreadyBeingDeclared())
9637     return 0;
9638 
9639   // Note: The following rules are largely analoguous to the move
9640   // constructor rules.
9641 
9642   QualType ArgType = Context.getTypeDeclType(ClassDecl);
9643   QualType RetType = Context.getLValueReferenceType(ArgType);
9644   ArgType = Context.getRValueReferenceType(ArgType);
9645 
9646   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9647                                                      CXXMoveAssignment,
9648                                                      false);
9649 
9650   //   An implicitly-declared move assignment operator is an inline public
9651   //   member of its class.
9652   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9653   SourceLocation ClassLoc = ClassDecl->getLocation();
9654   DeclarationNameInfo NameInfo(Name, ClassLoc);
9655   CXXMethodDecl *MoveAssignment =
9656       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9657                             /*TInfo=*/0, /*StorageClass=*/SC_None,
9658                             /*isInline=*/true, Constexpr, SourceLocation());
9659   MoveAssignment->setAccess(AS_public);
9660   MoveAssignment->setDefaulted();
9661   MoveAssignment->setImplicit();
9662 
9663   // Build an exception specification pointing back at this member.
9664   FunctionProtoType::ExtProtoInfo EPI =
9665       getImplicitMethodEPI(*this, MoveAssignment);
9666   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
9667 
9668   // Add the parameter to the operator.
9669   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9670                                                ClassLoc, ClassLoc, /*Id=*/0,
9671                                                ArgType, /*TInfo=*/0,
9672                                                SC_None, 0);
9673   MoveAssignment->setParams(FromParam);
9674 
9675   AddOverriddenMethods(ClassDecl, MoveAssignment);
9676 
9677   MoveAssignment->setTrivial(
9678     ClassDecl->needsOverloadResolutionForMoveAssignment()
9679       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9680       : ClassDecl->hasTrivialMoveAssignment());
9681 
9682   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
9683     ClassDecl->setImplicitMoveAssignmentIsDeleted();
9684     SetDeclDeleted(MoveAssignment, ClassLoc);
9685   }
9686 
9687   // Note that we have added this copy-assignment operator.
9688   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9689 
9690   if (Scope *S = getScopeForContext(ClassDecl))
9691     PushOnScopeChains(MoveAssignment, S, false);
9692   ClassDecl->addDecl(MoveAssignment);
9693 
9694   return MoveAssignment;
9695 }
9696 
9697 /// Check if we're implicitly defining a move assignment operator for a class
9698 /// with virtual bases. Such a move assignment might move-assign the virtual
9699 /// base multiple times.
9700 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
9701                                                SourceLocation CurrentLocation) {
9702   assert(!Class->isDependentContext() && "should not define dependent move");
9703 
9704   // Only a virtual base could get implicitly move-assigned multiple times.
9705   // Only a non-trivial move assignment can observe this. We only want to
9706   // diagnose if we implicitly define an assignment operator that assigns
9707   // two base classes, both of which move-assign the same virtual base.
9708   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
9709       Class->getNumBases() < 2)
9710     return;
9711 
9712   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
9713   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
9714   VBaseMap VBases;
9715 
9716   for (auto &BI : Class->bases()) {
9717     Worklist.push_back(&BI);
9718     while (!Worklist.empty()) {
9719       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
9720       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
9721 
9722       // If the base has no non-trivial move assignment operators,
9723       // we don't care about moves from it.
9724       if (!Base->hasNonTrivialMoveAssignment())
9725         continue;
9726 
9727       // If there's nothing virtual here, skip it.
9728       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
9729         continue;
9730 
9731       // If we're not actually going to call a move assignment for this base,
9732       // or the selected move assignment is trivial, skip it.
9733       Sema::SpecialMemberOverloadResult *SMOR =
9734         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
9735                               /*ConstArg*/false, /*VolatileArg*/false,
9736                               /*RValueThis*/true, /*ConstThis*/false,
9737                               /*VolatileThis*/false);
9738       if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
9739           !SMOR->getMethod()->isMoveAssignmentOperator())
9740         continue;
9741 
9742       if (BaseSpec->isVirtual()) {
9743         // We're going to move-assign this virtual base, and its move
9744         // assignment operator is not trivial. If this can happen for
9745         // multiple distinct direct bases of Class, diagnose it. (If it
9746         // only happens in one base, we'll diagnose it when synthesizing
9747         // that base class's move assignment operator.)
9748         CXXBaseSpecifier *&Existing =
9749             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
9750                 .first->second;
9751         if (Existing && Existing != &BI) {
9752           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
9753             << Class << Base;
9754           S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
9755             << (Base->getCanonicalDecl() ==
9756                 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9757             << Base << Existing->getType() << Existing->getSourceRange();
9758           S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
9759             << (Base->getCanonicalDecl() ==
9760                 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9761             << Base << BI.getType() << BaseSpec->getSourceRange();
9762 
9763           // Only diagnose each vbase once.
9764           Existing = 0;
9765         }
9766       } else {
9767         // Only walk over bases that have defaulted move assignment operators.
9768         // We assume that any user-provided move assignment operator handles
9769         // the multiple-moves-of-vbase case itself somehow.
9770         if (!SMOR->getMethod()->isDefaulted())
9771           continue;
9772 
9773         // We're going to move the base classes of Base. Add them to the list.
9774         for (auto &BI : Base->bases())
9775           Worklist.push_back(&BI);
9776       }
9777     }
9778   }
9779 }
9780 
9781 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9782                                         CXXMethodDecl *MoveAssignOperator) {
9783   assert((MoveAssignOperator->isDefaulted() &&
9784           MoveAssignOperator->isOverloadedOperator() &&
9785           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
9786           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9787           !MoveAssignOperator->isDeleted()) &&
9788          "DefineImplicitMoveAssignment called for wrong function");
9789 
9790   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9791 
9792   if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9793     MoveAssignOperator->setInvalidDecl();
9794     return;
9795   }
9796 
9797   MoveAssignOperator->markUsed(Context);
9798 
9799   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
9800   DiagnosticErrorTrap Trap(Diags);
9801 
9802   // C++0x [class.copy]p28:
9803   //   The implicitly-defined or move assignment operator for a non-union class
9804   //   X performs memberwise move assignment of its subobjects. The direct base
9805   //   classes of X are assigned first, in the order of their declaration in the
9806   //   base-specifier-list, and then the immediate non-static data members of X
9807   //   are assigned, in the order in which they were declared in the class
9808   //   definition.
9809 
9810   // Issue a warning if our implicit move assignment operator will move
9811   // from a virtual base more than once.
9812   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
9813 
9814   // The statements that form the synthesized function body.
9815   SmallVector<Stmt*, 8> Statements;
9816 
9817   // The parameter for the "other" object, which we are move from.
9818   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9819   QualType OtherRefType = Other->getType()->
9820       getAs<RValueReferenceType>()->getPointeeType();
9821   assert(!OtherRefType.getQualifiers() &&
9822          "Bad argument type of defaulted move assignment");
9823 
9824   // Our location for everything implicitly-generated.
9825   SourceLocation Loc = MoveAssignOperator->getLocation();
9826 
9827   // Builds a reference to the "other" object.
9828   RefBuilder OtherRef(Other, OtherRefType);
9829   // Cast to rvalue.
9830   MoveCastBuilder MoveOther(OtherRef);
9831 
9832   // Builds the "this" pointer.
9833   ThisBuilder This;
9834 
9835   // Assign base classes.
9836   bool Invalid = false;
9837   for (auto &Base : ClassDecl->bases()) {
9838     // C++11 [class.copy]p28:
9839     //   It is unspecified whether subobjects representing virtual base classes
9840     //   are assigned more than once by the implicitly-defined copy assignment
9841     //   operator.
9842     // FIXME: Do not assign to a vbase that will be assigned by some other base
9843     // class. For a move-assignment, this can result in the vbase being moved
9844     // multiple times.
9845 
9846     // Form the assignment:
9847     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9848     QualType BaseType = Base.getType().getUnqualifiedType();
9849     if (!BaseType->isRecordType()) {
9850       Invalid = true;
9851       continue;
9852     }
9853 
9854     CXXCastPath BasePath;
9855     BasePath.push_back(&Base);
9856 
9857     // Construct the "from" expression, which is an implicit cast to the
9858     // appropriately-qualified base type.
9859     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
9860 
9861     // Dereference "this".
9862     DerefBuilder DerefThis(This);
9863 
9864     // Implicitly cast "this" to the appropriately-qualified base type.
9865     CastBuilder To(DerefThis,
9866                    Context.getCVRQualifiedType(
9867                        BaseType, MoveAssignOperator->getTypeQualifiers()),
9868                    VK_LValue, BasePath);
9869 
9870     // Build the move.
9871     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
9872                                             To, From,
9873                                             /*CopyingBaseSubobject=*/true,
9874                                             /*Copying=*/false);
9875     if (Move.isInvalid()) {
9876       Diag(CurrentLocation, diag::note_member_synthesized_at)
9877         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9878       MoveAssignOperator->setInvalidDecl();
9879       return;
9880     }
9881 
9882     // Success! Record the move.
9883     Statements.push_back(Move.takeAs<Expr>());
9884   }
9885 
9886   // Assign non-static members.
9887   for (auto *Field : ClassDecl->fields()) {
9888     if (Field->isUnnamedBitfield())
9889       continue;
9890 
9891     if (Field->isInvalidDecl()) {
9892       Invalid = true;
9893       continue;
9894     }
9895 
9896     // Check for members of reference type; we can't move those.
9897     if (Field->getType()->isReferenceType()) {
9898       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9899         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9900       Diag(Field->getLocation(), diag::note_declared_at);
9901       Diag(CurrentLocation, diag::note_member_synthesized_at)
9902         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9903       Invalid = true;
9904       continue;
9905     }
9906 
9907     // Check for members of const-qualified, non-class type.
9908     QualType BaseType = Context.getBaseElementType(Field->getType());
9909     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9910       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9911         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9912       Diag(Field->getLocation(), diag::note_declared_at);
9913       Diag(CurrentLocation, diag::note_member_synthesized_at)
9914         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9915       Invalid = true;
9916       continue;
9917     }
9918 
9919     // Suppress assigning zero-width bitfields.
9920     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9921       continue;
9922 
9923     QualType FieldType = Field->getType().getNonReferenceType();
9924     if (FieldType->isIncompleteArrayType()) {
9925       assert(ClassDecl->hasFlexibleArrayMember() &&
9926              "Incomplete array type is not valid");
9927       continue;
9928     }
9929 
9930     // Build references to the field in the object we're copying from and to.
9931     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9932                               LookupMemberName);
9933     MemberLookup.addDecl(Field);
9934     MemberLookup.resolveKind();
9935     MemberBuilder From(MoveOther, OtherRefType,
9936                        /*IsArrow=*/false, MemberLookup);
9937     MemberBuilder To(This, getCurrentThisType(),
9938                      /*IsArrow=*/true, MemberLookup);
9939 
9940     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
9941         "Member reference with rvalue base must be rvalue except for reference "
9942         "members, which aren't allowed for move assignment.");
9943 
9944     // Build the move of this field.
9945     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
9946                                             To, From,
9947                                             /*CopyingBaseSubobject=*/false,
9948                                             /*Copying=*/false);
9949     if (Move.isInvalid()) {
9950       Diag(CurrentLocation, diag::note_member_synthesized_at)
9951         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9952       MoveAssignOperator->setInvalidDecl();
9953       return;
9954     }
9955 
9956     // Success! Record the copy.
9957     Statements.push_back(Move.takeAs<Stmt>());
9958   }
9959 
9960   if (!Invalid) {
9961     // Add a "return *this;"
9962     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
9963 
9964     StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9965     if (Return.isInvalid())
9966       Invalid = true;
9967     else {
9968       Statements.push_back(Return.takeAs<Stmt>());
9969 
9970       if (Trap.hasErrorOccurred()) {
9971         Diag(CurrentLocation, diag::note_member_synthesized_at)
9972           << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9973         Invalid = true;
9974       }
9975     }
9976   }
9977 
9978   if (Invalid) {
9979     MoveAssignOperator->setInvalidDecl();
9980     return;
9981   }
9982 
9983   StmtResult Body;
9984   {
9985     CompoundScopeRAII CompoundScope(*this);
9986     Body = ActOnCompoundStmt(Loc, Loc, Statements,
9987                              /*isStmtExpr=*/false);
9988     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9989   }
9990   MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9991 
9992   if (ASTMutationListener *L = getASTMutationListener()) {
9993     L->CompletedImplicitDefinition(MoveAssignOperator);
9994   }
9995 }
9996 
9997 Sema::ImplicitExceptionSpecification
9998 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9999   CXXRecordDecl *ClassDecl = MD->getParent();
10000 
10001   ImplicitExceptionSpecification ExceptSpec(*this);
10002   if (ClassDecl->isInvalidDecl())
10003     return ExceptSpec;
10004 
10005   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
10006   assert(T->getNumParams() >= 1 && "not a copy ctor");
10007   unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
10008 
10009   // C++ [except.spec]p14:
10010   //   An implicitly declared special member function (Clause 12) shall have an
10011   //   exception-specification. [...]
10012   for (const auto &Base : ClassDecl->bases()) {
10013     // Virtual bases are handled below.
10014     if (Base.isVirtual())
10015       continue;
10016 
10017     CXXRecordDecl *BaseClassDecl
10018       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10019     if (CXXConstructorDecl *CopyConstructor =
10020           LookupCopyingConstructor(BaseClassDecl, Quals))
10021       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10022   }
10023   for (const auto &Base : ClassDecl->vbases()) {
10024     CXXRecordDecl *BaseClassDecl
10025       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10026     if (CXXConstructorDecl *CopyConstructor =
10027           LookupCopyingConstructor(BaseClassDecl, Quals))
10028       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10029   }
10030   for (const auto *Field : ClassDecl->fields()) {
10031     QualType FieldType = Context.getBaseElementType(Field->getType());
10032     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10033       if (CXXConstructorDecl *CopyConstructor =
10034               LookupCopyingConstructor(FieldClassDecl,
10035                                        Quals | FieldType.getCVRQualifiers()))
10036       ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
10037     }
10038   }
10039 
10040   return ExceptSpec;
10041 }
10042 
10043 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10044                                                     CXXRecordDecl *ClassDecl) {
10045   // C++ [class.copy]p4:
10046   //   If the class definition does not explicitly declare a copy
10047   //   constructor, one is declared implicitly.
10048   assert(ClassDecl->needsImplicitCopyConstructor());
10049 
10050   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10051   if (DSM.isAlreadyBeingDeclared())
10052     return 0;
10053 
10054   QualType ClassType = Context.getTypeDeclType(ClassDecl);
10055   QualType ArgType = ClassType;
10056   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
10057   if (Const)
10058     ArgType = ArgType.withConst();
10059   ArgType = Context.getLValueReferenceType(ArgType);
10060 
10061   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10062                                                      CXXCopyConstructor,
10063                                                      Const);
10064 
10065   DeclarationName Name
10066     = Context.DeclarationNames.getCXXConstructorName(
10067                                            Context.getCanonicalType(ClassType));
10068   SourceLocation ClassLoc = ClassDecl->getLocation();
10069   DeclarationNameInfo NameInfo(Name, ClassLoc);
10070 
10071   //   An implicitly-declared copy constructor is an inline public
10072   //   member of its class.
10073   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
10074       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
10075       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10076       Constexpr);
10077   CopyConstructor->setAccess(AS_public);
10078   CopyConstructor->setDefaulted();
10079 
10080   // Build an exception specification pointing back at this member.
10081   FunctionProtoType::ExtProtoInfo EPI =
10082       getImplicitMethodEPI(*this, CopyConstructor);
10083   CopyConstructor->setType(
10084       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10085 
10086   // Add the parameter to the constructor.
10087   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
10088                                                ClassLoc, ClassLoc,
10089                                                /*IdentifierInfo=*/0,
10090                                                ArgType, /*TInfo=*/0,
10091                                                SC_None, 0);
10092   CopyConstructor->setParams(FromParam);
10093 
10094   CopyConstructor->setTrivial(
10095     ClassDecl->needsOverloadResolutionForCopyConstructor()
10096       ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10097       : ClassDecl->hasTrivialCopyConstructor());
10098 
10099   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
10100     SetDeclDeleted(CopyConstructor, ClassLoc);
10101 
10102   // Note that we have declared this constructor.
10103   ++ASTContext::NumImplicitCopyConstructorsDeclared;
10104 
10105   if (Scope *S = getScopeForContext(ClassDecl))
10106     PushOnScopeChains(CopyConstructor, S, false);
10107   ClassDecl->addDecl(CopyConstructor);
10108 
10109   return CopyConstructor;
10110 }
10111 
10112 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
10113                                    CXXConstructorDecl *CopyConstructor) {
10114   assert((CopyConstructor->isDefaulted() &&
10115           CopyConstructor->isCopyConstructor() &&
10116           !CopyConstructor->doesThisDeclarationHaveABody() &&
10117           !CopyConstructor->isDeleted()) &&
10118          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
10119 
10120   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
10121   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
10122 
10123   // C++11 [class.copy]p7:
10124   //   The [definition of an implicitly declared copy constructor] is
10125   //   deprecated if the class has a user-declared copy assignment operator
10126   //   or a user-declared destructor.
10127   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10128     diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10129 
10130   SynthesizedFunctionScope Scope(*this, CopyConstructor);
10131   DiagnosticErrorTrap Trap(Diags);
10132 
10133   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
10134       Trap.hasErrorOccurred()) {
10135     Diag(CurrentLocation, diag::note_member_synthesized_at)
10136       << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
10137     CopyConstructor->setInvalidDecl();
10138   }  else {
10139     Sema::CompoundScopeRAII CompoundScope(*this);
10140     CopyConstructor->setBody(ActOnCompoundStmt(
10141         CopyConstructor->getLocation(), CopyConstructor->getLocation(), None,
10142         /*isStmtExpr=*/ false).takeAs<Stmt>());
10143   }
10144 
10145   CopyConstructor->markUsed(Context);
10146   if (ASTMutationListener *L = getASTMutationListener()) {
10147     L->CompletedImplicitDefinition(CopyConstructor);
10148   }
10149 }
10150 
10151 Sema::ImplicitExceptionSpecification
10152 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10153   CXXRecordDecl *ClassDecl = MD->getParent();
10154 
10155   // C++ [except.spec]p14:
10156   //   An implicitly declared special member function (Clause 12) shall have an
10157   //   exception-specification. [...]
10158   ImplicitExceptionSpecification ExceptSpec(*this);
10159   if (ClassDecl->isInvalidDecl())
10160     return ExceptSpec;
10161 
10162   // Direct base-class constructors.
10163   for (const auto &B : ClassDecl->bases()) {
10164     if (B.isVirtual()) // Handled below.
10165       continue;
10166 
10167     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
10168       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10169       CXXConstructorDecl *Constructor =
10170           LookupMovingConstructor(BaseClassDecl, 0);
10171       // If this is a deleted function, add it anyway. This might be conformant
10172       // with the standard. This might not. I'm not sure. It might not matter.
10173       if (Constructor)
10174         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
10175     }
10176   }
10177 
10178   // Virtual base-class constructors.
10179   for (const auto &B : ClassDecl->vbases()) {
10180     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
10181       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10182       CXXConstructorDecl *Constructor =
10183           LookupMovingConstructor(BaseClassDecl, 0);
10184       // If this is a deleted function, add it anyway. This might be conformant
10185       // with the standard. This might not. I'm not sure. It might not matter.
10186       if (Constructor)
10187         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
10188     }
10189   }
10190 
10191   // Field constructors.
10192   for (const auto *F : ClassDecl->fields()) {
10193     QualType FieldType = Context.getBaseElementType(F->getType());
10194     if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10195       CXXConstructorDecl *Constructor =
10196           LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
10197       // If this is a deleted function, add it anyway. This might be conformant
10198       // with the standard. This might not. I'm not sure. It might not matter.
10199       // In particular, the problem is that this function never gets called. It
10200       // might just be ill-formed because this function attempts to refer to
10201       // a deleted function here.
10202       if (Constructor)
10203         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
10204     }
10205   }
10206 
10207   return ExceptSpec;
10208 }
10209 
10210 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10211                                                     CXXRecordDecl *ClassDecl) {
10212   assert(ClassDecl->needsImplicitMoveConstructor());
10213 
10214   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10215   if (DSM.isAlreadyBeingDeclared())
10216     return 0;
10217 
10218   QualType ClassType = Context.getTypeDeclType(ClassDecl);
10219   QualType ArgType = Context.getRValueReferenceType(ClassType);
10220 
10221   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10222                                                      CXXMoveConstructor,
10223                                                      false);
10224 
10225   DeclarationName Name
10226     = Context.DeclarationNames.getCXXConstructorName(
10227                                            Context.getCanonicalType(ClassType));
10228   SourceLocation ClassLoc = ClassDecl->getLocation();
10229   DeclarationNameInfo NameInfo(Name, ClassLoc);
10230 
10231   // C++11 [class.copy]p11:
10232   //   An implicitly-declared copy/move constructor is an inline public
10233   //   member of its class.
10234   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
10235       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
10236       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10237       Constexpr);
10238   MoveConstructor->setAccess(AS_public);
10239   MoveConstructor->setDefaulted();
10240 
10241   // Build an exception specification pointing back at this member.
10242   FunctionProtoType::ExtProtoInfo EPI =
10243       getImplicitMethodEPI(*this, MoveConstructor);
10244   MoveConstructor->setType(
10245       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10246 
10247   // Add the parameter to the constructor.
10248   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10249                                                ClassLoc, ClassLoc,
10250                                                /*IdentifierInfo=*/0,
10251                                                ArgType, /*TInfo=*/0,
10252                                                SC_None, 0);
10253   MoveConstructor->setParams(FromParam);
10254 
10255   MoveConstructor->setTrivial(
10256     ClassDecl->needsOverloadResolutionForMoveConstructor()
10257       ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10258       : ClassDecl->hasTrivialMoveConstructor());
10259 
10260   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
10261     ClassDecl->setImplicitMoveConstructorIsDeleted();
10262     SetDeclDeleted(MoveConstructor, ClassLoc);
10263   }
10264 
10265   // Note that we have declared this constructor.
10266   ++ASTContext::NumImplicitMoveConstructorsDeclared;
10267 
10268   if (Scope *S = getScopeForContext(ClassDecl))
10269     PushOnScopeChains(MoveConstructor, S, false);
10270   ClassDecl->addDecl(MoveConstructor);
10271 
10272   return MoveConstructor;
10273 }
10274 
10275 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10276                                    CXXConstructorDecl *MoveConstructor) {
10277   assert((MoveConstructor->isDefaulted() &&
10278           MoveConstructor->isMoveConstructor() &&
10279           !MoveConstructor->doesThisDeclarationHaveABody() &&
10280           !MoveConstructor->isDeleted()) &&
10281          "DefineImplicitMoveConstructor - call it for implicit move ctor");
10282 
10283   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10284   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10285 
10286   SynthesizedFunctionScope Scope(*this, MoveConstructor);
10287   DiagnosticErrorTrap Trap(Diags);
10288 
10289   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
10290       Trap.hasErrorOccurred()) {
10291     Diag(CurrentLocation, diag::note_member_synthesized_at)
10292       << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10293     MoveConstructor->setInvalidDecl();
10294   }  else {
10295     Sema::CompoundScopeRAII CompoundScope(*this);
10296     MoveConstructor->setBody(ActOnCompoundStmt(
10297         MoveConstructor->getLocation(), MoveConstructor->getLocation(), None,
10298         /*isStmtExpr=*/ false).takeAs<Stmt>());
10299   }
10300 
10301   MoveConstructor->markUsed(Context);
10302 
10303   if (ASTMutationListener *L = getASTMutationListener()) {
10304     L->CompletedImplicitDefinition(MoveConstructor);
10305   }
10306 }
10307 
10308 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
10309   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
10310 }
10311 
10312 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
10313                             SourceLocation CurrentLocation,
10314                             CXXConversionDecl *Conv) {
10315   CXXRecordDecl *Lambda = Conv->getParent();
10316   CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10317   // If we are defining a specialization of a conversion to function-ptr
10318   // cache the deduced template arguments for this specialization
10319   // so that we can use them to retrieve the corresponding call-operator
10320   // and static-invoker.
10321   const TemplateArgumentList *DeducedTemplateArgs = 0;
10322 
10323 
10324   // Retrieve the corresponding call-operator specialization.
10325   if (Lambda->isGenericLambda()) {
10326     assert(Conv->isFunctionTemplateSpecialization());
10327     FunctionTemplateDecl *CallOpTemplate =
10328         CallOp->getDescribedFunctionTemplate();
10329     DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
10330     void *InsertPos = 0;
10331     FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
10332                                                 DeducedTemplateArgs->data(),
10333                                                 DeducedTemplateArgs->size(),
10334                                                 InsertPos);
10335     assert(CallOpSpec &&
10336           "Conversion operator must have a corresponding call operator");
10337     CallOp = cast<CXXMethodDecl>(CallOpSpec);
10338   }
10339   // Mark the call operator referenced (and add to pending instantiations
10340   // if necessary).
10341   // For both the conversion and static-invoker template specializations
10342   // we construct their body's in this function, so no need to add them
10343   // to the PendingInstantiations.
10344   MarkFunctionReferenced(CurrentLocation, CallOp);
10345 
10346   SynthesizedFunctionScope Scope(*this, Conv);
10347   DiagnosticErrorTrap Trap(Diags);
10348 
10349   // Retrieve the static invoker...
10350   CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10351   // ... and get the corresponding specialization for a generic lambda.
10352   if (Lambda->isGenericLambda()) {
10353     assert(DeducedTemplateArgs &&
10354       "Must have deduced template arguments from Conversion Operator");
10355     FunctionTemplateDecl *InvokeTemplate =
10356                           Invoker->getDescribedFunctionTemplate();
10357     void *InsertPos = 0;
10358     FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
10359                                                 DeducedTemplateArgs->data(),
10360                                                 DeducedTemplateArgs->size(),
10361                                                 InsertPos);
10362     assert(InvokeSpec &&
10363       "Must have a corresponding static invoker specialization");
10364     Invoker = cast<CXXMethodDecl>(InvokeSpec);
10365   }
10366   // Construct the body of the conversion function { return __invoke; }.
10367   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
10368                                         VK_LValue, Conv->getLocation()).take();
10369    assert(FunctionRef && "Can't refer to __invoke function?");
10370    Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
10371    Conv->setBody(new (Context) CompoundStmt(Context, Return,
10372                                             Conv->getLocation(),
10373                                             Conv->getLocation()));
10374 
10375   Conv->markUsed(Context);
10376   Conv->setReferenced();
10377 
10378   // Fill in the __invoke function with a dummy implementation. IR generation
10379   // will fill in the actual details.
10380   Invoker->markUsed(Context);
10381   Invoker->setReferenced();
10382   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10383 
10384   if (ASTMutationListener *L = getASTMutationListener()) {
10385     L->CompletedImplicitDefinition(Conv);
10386     L->CompletedImplicitDefinition(Invoker);
10387    }
10388 }
10389 
10390 
10391 
10392 void Sema::DefineImplicitLambdaToBlockPointerConversion(
10393        SourceLocation CurrentLocation,
10394        CXXConversionDecl *Conv)
10395 {
10396   assert(!Conv->getParent()->isGenericLambda());
10397 
10398   Conv->markUsed(Context);
10399 
10400   SynthesizedFunctionScope Scope(*this, Conv);
10401   DiagnosticErrorTrap Trap(Diags);
10402 
10403   // Copy-initialize the lambda object as needed to capture it.
10404   Expr *This = ActOnCXXThis(CurrentLocation).take();
10405   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
10406 
10407   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10408                                                         Conv->getLocation(),
10409                                                         Conv, DerefThis);
10410 
10411   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10412   // behavior.  Note that only the general conversion function does this
10413   // (since it's unusable otherwise); in the case where we inline the
10414   // block literal, it has block literal lifetime semantics.
10415   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
10416     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10417                                           CK_CopyAndAutoreleaseBlockObject,
10418                                           BuildBlock.get(), 0, VK_RValue);
10419 
10420   if (BuildBlock.isInvalid()) {
10421     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10422     Conv->setInvalidDecl();
10423     return;
10424   }
10425 
10426   // Create the return statement that returns the block from the conversion
10427   // function.
10428   StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
10429   if (Return.isInvalid()) {
10430     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10431     Conv->setInvalidDecl();
10432     return;
10433   }
10434 
10435   // Set the body of the conversion function.
10436   Stmt *ReturnS = Return.take();
10437   Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
10438                                            Conv->getLocation(),
10439                                            Conv->getLocation()));
10440 
10441   // We're done; notify the mutation listener, if any.
10442   if (ASTMutationListener *L = getASTMutationListener()) {
10443     L->CompletedImplicitDefinition(Conv);
10444   }
10445 }
10446 
10447 /// \brief Determine whether the given list arguments contains exactly one
10448 /// "real" (non-default) argument.
10449 static bool hasOneRealArgument(MultiExprArg Args) {
10450   switch (Args.size()) {
10451   case 0:
10452     return false;
10453 
10454   default:
10455     if (!Args[1]->isDefaultArgument())
10456       return false;
10457 
10458     // fall through
10459   case 1:
10460     return !Args[0]->isDefaultArgument();
10461   }
10462 
10463   return false;
10464 }
10465 
10466 ExprResult
10467 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10468                             CXXConstructorDecl *Constructor,
10469                             MultiExprArg ExprArgs,
10470                             bool HadMultipleCandidates,
10471                             bool IsListInitialization,
10472                             bool RequiresZeroInit,
10473                             unsigned ConstructKind,
10474                             SourceRange ParenRange) {
10475   bool Elidable = false;
10476 
10477   // C++0x [class.copy]p34:
10478   //   When certain criteria are met, an implementation is allowed to
10479   //   omit the copy/move construction of a class object, even if the
10480   //   copy/move constructor and/or destructor for the object have
10481   //   side effects. [...]
10482   //     - when a temporary class object that has not been bound to a
10483   //       reference (12.2) would be copied/moved to a class object
10484   //       with the same cv-unqualified type, the copy/move operation
10485   //       can be omitted by constructing the temporary object
10486   //       directly into the target of the omitted copy/move
10487   if (ConstructKind == CXXConstructExpr::CK_Complete &&
10488       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
10489     Expr *SubExpr = ExprArgs[0];
10490     Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
10491   }
10492 
10493   return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
10494                                Elidable, ExprArgs, HadMultipleCandidates,
10495                                IsListInitialization, RequiresZeroInit,
10496                                ConstructKind, ParenRange);
10497 }
10498 
10499 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
10500 /// including handling of its default argument expressions.
10501 ExprResult
10502 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10503                             CXXConstructorDecl *Constructor, bool Elidable,
10504                             MultiExprArg ExprArgs,
10505                             bool HadMultipleCandidates,
10506                             bool IsListInitialization,
10507                             bool RequiresZeroInit,
10508                             unsigned ConstructKind,
10509                             SourceRange ParenRange) {
10510   MarkFunctionReferenced(ConstructLoc, Constructor);
10511   return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
10512                                         Constructor, Elidable, ExprArgs,
10513                                         HadMultipleCandidates,
10514                                         IsListInitialization, RequiresZeroInit,
10515               static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10516                                         ParenRange));
10517 }
10518 
10519 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
10520   if (VD->isInvalidDecl()) return;
10521 
10522   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
10523   if (ClassDecl->isInvalidDecl()) return;
10524   if (ClassDecl->hasIrrelevantDestructor()) return;
10525   if (ClassDecl->isDependentContext()) return;
10526 
10527   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10528   MarkFunctionReferenced(VD->getLocation(), Destructor);
10529   CheckDestructorAccess(VD->getLocation(), Destructor,
10530                         PDiag(diag::err_access_dtor_var)
10531                         << VD->getDeclName()
10532                         << VD->getType());
10533   DiagnoseUseOfDecl(Destructor, VD->getLocation());
10534 
10535   if (Destructor->isTrivial()) return;
10536   if (!VD->hasGlobalStorage()) return;
10537 
10538   // Emit warning for non-trivial dtor in global scope (a real global,
10539   // class-static, function-static).
10540   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10541 
10542   // TODO: this should be re-enabled for static locals by !CXAAtExit
10543   if (!VD->isStaticLocal())
10544     Diag(VD->getLocation(), diag::warn_global_destructor);
10545 }
10546 
10547 /// \brief Given a constructor and the set of arguments provided for the
10548 /// constructor, convert the arguments and add any required default arguments
10549 /// to form a proper call to this constructor.
10550 ///
10551 /// \returns true if an error occurred, false otherwise.
10552 bool
10553 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10554                               MultiExprArg ArgsPtr,
10555                               SourceLocation Loc,
10556                               SmallVectorImpl<Expr*> &ConvertedArgs,
10557                               bool AllowExplicit,
10558                               bool IsListInitialization) {
10559   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10560   unsigned NumArgs = ArgsPtr.size();
10561   Expr **Args = ArgsPtr.data();
10562 
10563   const FunctionProtoType *Proto
10564     = Constructor->getType()->getAs<FunctionProtoType>();
10565   assert(Proto && "Constructor without a prototype?");
10566   unsigned NumParams = Proto->getNumParams();
10567 
10568   // If too few arguments are available, we'll fill in the rest with defaults.
10569   if (NumArgs < NumParams)
10570     ConvertedArgs.reserve(NumParams);
10571   else
10572     ConvertedArgs.reserve(NumArgs);
10573 
10574   VariadicCallType CallType =
10575     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
10576   SmallVector<Expr *, 8> AllArgs;
10577   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
10578                                         Proto, 0,
10579                                         llvm::makeArrayRef(Args, NumArgs),
10580                                         AllArgs,
10581                                         CallType, AllowExplicit,
10582                                         IsListInitialization);
10583   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
10584 
10585   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
10586 
10587   CheckConstructorCall(Constructor,
10588                        llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10589                                                         AllArgs.size()),
10590                        Proto, Loc);
10591 
10592   return Invalid;
10593 }
10594 
10595 static inline bool
10596 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10597                                        const FunctionDecl *FnDecl) {
10598   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
10599   if (isa<NamespaceDecl>(DC)) {
10600     return SemaRef.Diag(FnDecl->getLocation(),
10601                         diag::err_operator_new_delete_declared_in_namespace)
10602       << FnDecl->getDeclName();
10603   }
10604 
10605   if (isa<TranslationUnitDecl>(DC) &&
10606       FnDecl->getStorageClass() == SC_Static) {
10607     return SemaRef.Diag(FnDecl->getLocation(),
10608                         diag::err_operator_new_delete_declared_static)
10609       << FnDecl->getDeclName();
10610   }
10611 
10612   return false;
10613 }
10614 
10615 static inline bool
10616 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10617                             CanQualType ExpectedResultType,
10618                             CanQualType ExpectedFirstParamType,
10619                             unsigned DependentParamTypeDiag,
10620                             unsigned InvalidParamTypeDiag) {
10621   QualType ResultType =
10622       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
10623 
10624   // Check that the result type is not dependent.
10625   if (ResultType->isDependentType())
10626     return SemaRef.Diag(FnDecl->getLocation(),
10627                         diag::err_operator_new_delete_dependent_result_type)
10628     << FnDecl->getDeclName() << ExpectedResultType;
10629 
10630   // Check that the result type is what we expect.
10631   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10632     return SemaRef.Diag(FnDecl->getLocation(),
10633                         diag::err_operator_new_delete_invalid_result_type)
10634     << FnDecl->getDeclName() << ExpectedResultType;
10635 
10636   // A function template must have at least 2 parameters.
10637   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10638     return SemaRef.Diag(FnDecl->getLocation(),
10639                       diag::err_operator_new_delete_template_too_few_parameters)
10640         << FnDecl->getDeclName();
10641 
10642   // The function decl must have at least 1 parameter.
10643   if (FnDecl->getNumParams() == 0)
10644     return SemaRef.Diag(FnDecl->getLocation(),
10645                         diag::err_operator_new_delete_too_few_parameters)
10646       << FnDecl->getDeclName();
10647 
10648   // Check the first parameter type is not dependent.
10649   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10650   if (FirstParamType->isDependentType())
10651     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10652       << FnDecl->getDeclName() << ExpectedFirstParamType;
10653 
10654   // Check that the first parameter type is what we expect.
10655   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
10656       ExpectedFirstParamType)
10657     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10658     << FnDecl->getDeclName() << ExpectedFirstParamType;
10659 
10660   return false;
10661 }
10662 
10663 static bool
10664 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
10665   // C++ [basic.stc.dynamic.allocation]p1:
10666   //   A program is ill-formed if an allocation function is declared in a
10667   //   namespace scope other than global scope or declared static in global
10668   //   scope.
10669   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10670     return true;
10671 
10672   CanQualType SizeTy =
10673     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10674 
10675   // C++ [basic.stc.dynamic.allocation]p1:
10676   //  The return type shall be void*. The first parameter shall have type
10677   //  std::size_t.
10678   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10679                                   SizeTy,
10680                                   diag::err_operator_new_dependent_param_type,
10681                                   diag::err_operator_new_param_type))
10682     return true;
10683 
10684   // C++ [basic.stc.dynamic.allocation]p1:
10685   //  The first parameter shall not have an associated default argument.
10686   if (FnDecl->getParamDecl(0)->hasDefaultArg())
10687     return SemaRef.Diag(FnDecl->getLocation(),
10688                         diag::err_operator_new_default_arg)
10689       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10690 
10691   return false;
10692 }
10693 
10694 static bool
10695 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
10696   // C++ [basic.stc.dynamic.deallocation]p1:
10697   //   A program is ill-formed if deallocation functions are declared in a
10698   //   namespace scope other than global scope or declared static in global
10699   //   scope.
10700   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10701     return true;
10702 
10703   // C++ [basic.stc.dynamic.deallocation]p2:
10704   //   Each deallocation function shall return void and its first parameter
10705   //   shall be void*.
10706   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10707                                   SemaRef.Context.VoidPtrTy,
10708                                  diag::err_operator_delete_dependent_param_type,
10709                                  diag::err_operator_delete_param_type))
10710     return true;
10711 
10712   return false;
10713 }
10714 
10715 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
10716 /// of this overloaded operator is well-formed. If so, returns false;
10717 /// otherwise, emits appropriate diagnostics and returns true.
10718 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
10719   assert(FnDecl && FnDecl->isOverloadedOperator() &&
10720          "Expected an overloaded operator declaration");
10721 
10722   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10723 
10724   // C++ [over.oper]p5:
10725   //   The allocation and deallocation functions, operator new,
10726   //   operator new[], operator delete and operator delete[], are
10727   //   described completely in 3.7.3. The attributes and restrictions
10728   //   found in the rest of this subclause do not apply to them unless
10729   //   explicitly stated in 3.7.3.
10730   if (Op == OO_Delete || Op == OO_Array_Delete)
10731     return CheckOperatorDeleteDeclaration(*this, FnDecl);
10732 
10733   if (Op == OO_New || Op == OO_Array_New)
10734     return CheckOperatorNewDeclaration(*this, FnDecl);
10735 
10736   // C++ [over.oper]p6:
10737   //   An operator function shall either be a non-static member
10738   //   function or be a non-member function and have at least one
10739   //   parameter whose type is a class, a reference to a class, an
10740   //   enumeration, or a reference to an enumeration.
10741   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10742     if (MethodDecl->isStatic())
10743       return Diag(FnDecl->getLocation(),
10744                   diag::err_operator_overload_static) << FnDecl->getDeclName();
10745   } else {
10746     bool ClassOrEnumParam = false;
10747     for (auto Param : FnDecl->params()) {
10748       QualType ParamType = Param->getType().getNonReferenceType();
10749       if (ParamType->isDependentType() || ParamType->isRecordType() ||
10750           ParamType->isEnumeralType()) {
10751         ClassOrEnumParam = true;
10752         break;
10753       }
10754     }
10755 
10756     if (!ClassOrEnumParam)
10757       return Diag(FnDecl->getLocation(),
10758                   diag::err_operator_overload_needs_class_or_enum)
10759         << FnDecl->getDeclName();
10760   }
10761 
10762   // C++ [over.oper]p8:
10763   //   An operator function cannot have default arguments (8.3.6),
10764   //   except where explicitly stated below.
10765   //
10766   // Only the function-call operator allows default arguments
10767   // (C++ [over.call]p1).
10768   if (Op != OO_Call) {
10769     for (auto Param : FnDecl->params()) {
10770       if (Param->hasDefaultArg())
10771         return Diag(Param->getLocation(),
10772                     diag::err_operator_overload_default_arg)
10773           << FnDecl->getDeclName() << Param->getDefaultArgRange();
10774     }
10775   }
10776 
10777   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10778     { false, false, false }
10779 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10780     , { Unary, Binary, MemberOnly }
10781 #include "clang/Basic/OperatorKinds.def"
10782   };
10783 
10784   bool CanBeUnaryOperator = OperatorUses[Op][0];
10785   bool CanBeBinaryOperator = OperatorUses[Op][1];
10786   bool MustBeMemberOperator = OperatorUses[Op][2];
10787 
10788   // C++ [over.oper]p8:
10789   //   [...] Operator functions cannot have more or fewer parameters
10790   //   than the number required for the corresponding operator, as
10791   //   described in the rest of this subclause.
10792   unsigned NumParams = FnDecl->getNumParams()
10793                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
10794   if (Op != OO_Call &&
10795       ((NumParams == 1 && !CanBeUnaryOperator) ||
10796        (NumParams == 2 && !CanBeBinaryOperator) ||
10797        (NumParams < 1) || (NumParams > 2))) {
10798     // We have the wrong number of parameters.
10799     unsigned ErrorKind;
10800     if (CanBeUnaryOperator && CanBeBinaryOperator) {
10801       ErrorKind = 2;  // 2 -> unary or binary.
10802     } else if (CanBeUnaryOperator) {
10803       ErrorKind = 0;  // 0 -> unary
10804     } else {
10805       assert(CanBeBinaryOperator &&
10806              "All non-call overloaded operators are unary or binary!");
10807       ErrorKind = 1;  // 1 -> binary
10808     }
10809 
10810     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
10811       << FnDecl->getDeclName() << NumParams << ErrorKind;
10812   }
10813 
10814   // Overloaded operators other than operator() cannot be variadic.
10815   if (Op != OO_Call &&
10816       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
10817     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
10818       << FnDecl->getDeclName();
10819   }
10820 
10821   // Some operators must be non-static member functions.
10822   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10823     return Diag(FnDecl->getLocation(),
10824                 diag::err_operator_overload_must_be_member)
10825       << FnDecl->getDeclName();
10826   }
10827 
10828   // C++ [over.inc]p1:
10829   //   The user-defined function called operator++ implements the
10830   //   prefix and postfix ++ operator. If this function is a member
10831   //   function with no parameters, or a non-member function with one
10832   //   parameter of class or enumeration type, it defines the prefix
10833   //   increment operator ++ for objects of that type. If the function
10834   //   is a member function with one parameter (which shall be of type
10835   //   int) or a non-member function with two parameters (the second
10836   //   of which shall be of type int), it defines the postfix
10837   //   increment operator ++ for objects of that type.
10838   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10839     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10840     QualType ParamType = LastParam->getType();
10841 
10842     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
10843         !ParamType->isDependentType())
10844       return Diag(LastParam->getLocation(),
10845                   diag::err_operator_overload_post_incdec_must_be_int)
10846         << LastParam->getType() << (Op == OO_MinusMinus);
10847   }
10848 
10849   return false;
10850 }
10851 
10852 /// CheckLiteralOperatorDeclaration - Check whether the declaration
10853 /// of this literal operator function is well-formed. If so, returns
10854 /// false; otherwise, emits appropriate diagnostics and returns true.
10855 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
10856   if (isa<CXXMethodDecl>(FnDecl)) {
10857     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10858       << FnDecl->getDeclName();
10859     return true;
10860   }
10861 
10862   if (FnDecl->isExternC()) {
10863     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10864     return true;
10865   }
10866 
10867   bool Valid = false;
10868 
10869   // This might be the definition of a literal operator template.
10870   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10871   // This might be a specialization of a literal operator template.
10872   if (!TpDecl)
10873     TpDecl = FnDecl->getPrimaryTemplate();
10874 
10875   // template <char...> type operator "" name() and
10876   // template <class T, T...> type operator "" name() are the only valid
10877   // template signatures, and the only valid signatures with no parameters.
10878   if (TpDecl) {
10879     if (FnDecl->param_size() == 0) {
10880       // Must have one or two template parameters
10881       TemplateParameterList *Params = TpDecl->getTemplateParameters();
10882       if (Params->size() == 1) {
10883         NonTypeTemplateParmDecl *PmDecl =
10884           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
10885 
10886         // The template parameter must be a char parameter pack.
10887         if (PmDecl && PmDecl->isTemplateParameterPack() &&
10888             Context.hasSameType(PmDecl->getType(), Context.CharTy))
10889           Valid = true;
10890       } else if (Params->size() == 2) {
10891         TemplateTypeParmDecl *PmType =
10892           dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
10893         NonTypeTemplateParmDecl *PmArgs =
10894           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
10895 
10896         // The second template parameter must be a parameter pack with the
10897         // first template parameter as its type.
10898         if (PmType && PmArgs &&
10899             !PmType->isTemplateParameterPack() &&
10900             PmArgs->isTemplateParameterPack()) {
10901           const TemplateTypeParmType *TArgs =
10902             PmArgs->getType()->getAs<TemplateTypeParmType>();
10903           if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
10904               TArgs->getIndex() == PmType->getIndex()) {
10905             Valid = true;
10906             if (ActiveTemplateInstantiations.empty())
10907               Diag(FnDecl->getLocation(),
10908                    diag::ext_string_literal_operator_template);
10909           }
10910         }
10911       }
10912     }
10913   } else if (FnDecl->param_size()) {
10914     // Check the first parameter
10915     FunctionDecl::param_iterator Param = FnDecl->param_begin();
10916 
10917     QualType T = (*Param)->getType().getUnqualifiedType();
10918 
10919     // unsigned long long int, long double, and any character type are allowed
10920     // as the only parameters.
10921     if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10922         Context.hasSameType(T, Context.LongDoubleTy) ||
10923         Context.hasSameType(T, Context.CharTy) ||
10924         Context.hasSameType(T, Context.WideCharTy) ||
10925         Context.hasSameType(T, Context.Char16Ty) ||
10926         Context.hasSameType(T, Context.Char32Ty)) {
10927       if (++Param == FnDecl->param_end())
10928         Valid = true;
10929       goto FinishedParams;
10930     }
10931 
10932     // Otherwise it must be a pointer to const; let's strip those qualifiers.
10933     const PointerType *PT = T->getAs<PointerType>();
10934     if (!PT)
10935       goto FinishedParams;
10936     T = PT->getPointeeType();
10937     if (!T.isConstQualified() || T.isVolatileQualified())
10938       goto FinishedParams;
10939     T = T.getUnqualifiedType();
10940 
10941     // Move on to the second parameter;
10942     ++Param;
10943 
10944     // If there is no second parameter, the first must be a const char *
10945     if (Param == FnDecl->param_end()) {
10946       if (Context.hasSameType(T, Context.CharTy))
10947         Valid = true;
10948       goto FinishedParams;
10949     }
10950 
10951     // const char *, const wchar_t*, const char16_t*, and const char32_t*
10952     // are allowed as the first parameter to a two-parameter function
10953     if (!(Context.hasSameType(T, Context.CharTy) ||
10954           Context.hasSameType(T, Context.WideCharTy) ||
10955           Context.hasSameType(T, Context.Char16Ty) ||
10956           Context.hasSameType(T, Context.Char32Ty)))
10957       goto FinishedParams;
10958 
10959     // The second and final parameter must be an std::size_t
10960     T = (*Param)->getType().getUnqualifiedType();
10961     if (Context.hasSameType(T, Context.getSizeType()) &&
10962         ++Param == FnDecl->param_end())
10963       Valid = true;
10964   }
10965 
10966   // FIXME: This diagnostic is absolutely terrible.
10967 FinishedParams:
10968   if (!Valid) {
10969     Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10970       << FnDecl->getDeclName();
10971     return true;
10972   }
10973 
10974   // A parameter-declaration-clause containing a default argument is not
10975   // equivalent to any of the permitted forms.
10976   for (auto Param : FnDecl->params()) {
10977     if (Param->hasDefaultArg()) {
10978       Diag(Param->getDefaultArgRange().getBegin(),
10979            diag::err_literal_operator_default_argument)
10980         << Param->getDefaultArgRange();
10981       break;
10982     }
10983   }
10984 
10985   StringRef LiteralName
10986     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10987   if (LiteralName[0] != '_') {
10988     // C++11 [usrlit.suffix]p1:
10989     //   Literal suffix identifiers that do not start with an underscore
10990     //   are reserved for future standardization.
10991     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
10992       << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
10993   }
10994 
10995   return false;
10996 }
10997 
10998 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10999 /// linkage specification, including the language and (if present)
11000 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
11001 /// language string literal. LBraceLoc, if valid, provides the location of
11002 /// the '{' brace. Otherwise, this linkage specification does not
11003 /// have any braces.
11004 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
11005                                            Expr *LangStr,
11006                                            SourceLocation LBraceLoc) {
11007   StringLiteral *Lit = cast<StringLiteral>(LangStr);
11008   if (!Lit->isAscii()) {
11009     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11010       << LangStr->getSourceRange();
11011     return 0;
11012   }
11013 
11014   StringRef Lang = Lit->getString();
11015   LinkageSpecDecl::LanguageIDs Language;
11016   if (Lang == "C")
11017     Language = LinkageSpecDecl::lang_c;
11018   else if (Lang == "C++")
11019     Language = LinkageSpecDecl::lang_cxx;
11020   else {
11021     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11022       << LangStr->getSourceRange();
11023     return 0;
11024   }
11025 
11026   // FIXME: Add all the various semantics of linkage specifications
11027 
11028   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11029                                                LangStr->getExprLoc(), Language,
11030                                                LBraceLoc.isValid());
11031   CurContext->addDecl(D);
11032   PushDeclContext(S, D);
11033   return D;
11034 }
11035 
11036 /// ActOnFinishLinkageSpecification - Complete the definition of
11037 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
11038 /// valid, it's the position of the closing '}' brace in a linkage
11039 /// specification that uses braces.
11040 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
11041                                             Decl *LinkageSpec,
11042                                             SourceLocation RBraceLoc) {
11043   if (RBraceLoc.isValid()) {
11044     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11045     LSDecl->setRBraceLoc(RBraceLoc);
11046   }
11047   PopDeclContext();
11048   return LinkageSpec;
11049 }
11050 
11051 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11052                                   AttributeList *AttrList,
11053                                   SourceLocation SemiLoc) {
11054   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11055   // Attribute declarations appertain to empty declaration so we handle
11056   // them here.
11057   if (AttrList)
11058     ProcessDeclAttributeList(S, ED, AttrList);
11059 
11060   CurContext->addDecl(ED);
11061   return ED;
11062 }
11063 
11064 /// \brief Perform semantic analysis for the variable declaration that
11065 /// occurs within a C++ catch clause, returning the newly-created
11066 /// variable.
11067 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
11068                                          TypeSourceInfo *TInfo,
11069                                          SourceLocation StartLoc,
11070                                          SourceLocation Loc,
11071                                          IdentifierInfo *Name) {
11072   bool Invalid = false;
11073   QualType ExDeclType = TInfo->getType();
11074 
11075   // Arrays and functions decay.
11076   if (ExDeclType->isArrayType())
11077     ExDeclType = Context.getArrayDecayedType(ExDeclType);
11078   else if (ExDeclType->isFunctionType())
11079     ExDeclType = Context.getPointerType(ExDeclType);
11080 
11081   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11082   // The exception-declaration shall not denote a pointer or reference to an
11083   // incomplete type, other than [cv] void*.
11084   // N2844 forbids rvalue references.
11085   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
11086     Diag(Loc, diag::err_catch_rvalue_ref);
11087     Invalid = true;
11088   }
11089 
11090   QualType BaseType = ExDeclType;
11091   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
11092   unsigned DK = diag::err_catch_incomplete;
11093   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
11094     BaseType = Ptr->getPointeeType();
11095     Mode = 1;
11096     DK = diag::err_catch_incomplete_ptr;
11097   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
11098     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
11099     BaseType = Ref->getPointeeType();
11100     Mode = 2;
11101     DK = diag::err_catch_incomplete_ref;
11102   }
11103   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
11104       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
11105     Invalid = true;
11106 
11107   if (!Invalid && !ExDeclType->isDependentType() &&
11108       RequireNonAbstractType(Loc, ExDeclType,
11109                              diag::err_abstract_type_in_decl,
11110                              AbstractVariableType))
11111     Invalid = true;
11112 
11113   // Only the non-fragile NeXT runtime currently supports C++ catches
11114   // of ObjC types, and no runtime supports catching ObjC types by value.
11115   if (!Invalid && getLangOpts().ObjC1) {
11116     QualType T = ExDeclType;
11117     if (const ReferenceType *RT = T->getAs<ReferenceType>())
11118       T = RT->getPointeeType();
11119 
11120     if (T->isObjCObjectType()) {
11121       Diag(Loc, diag::err_objc_object_catch);
11122       Invalid = true;
11123     } else if (T->isObjCObjectPointerType()) {
11124       // FIXME: should this be a test for macosx-fragile specifically?
11125       if (getLangOpts().ObjCRuntime.isFragile())
11126         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
11127     }
11128   }
11129 
11130   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
11131                                     ExDeclType, TInfo, SC_None);
11132   ExDecl->setExceptionVariable(true);
11133 
11134   // In ARC, infer 'retaining' for variables of retainable type.
11135   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
11136     Invalid = true;
11137 
11138   if (!Invalid && !ExDeclType->isDependentType()) {
11139     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
11140       // Insulate this from anything else we might currently be parsing.
11141       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11142 
11143       // C++ [except.handle]p16:
11144       //   The object declared in an exception-declaration or, if the
11145       //   exception-declaration does not specify a name, a temporary (12.2) is
11146       //   copy-initialized (8.5) from the exception object. [...]
11147       //   The object is destroyed when the handler exits, after the destruction
11148       //   of any automatic objects initialized within the handler.
11149       //
11150       // We just pretend to initialize the object with itself, then make sure
11151       // it can be destroyed later.
11152       QualType initType = ExDeclType;
11153 
11154       InitializedEntity entity =
11155         InitializedEntity::InitializeVariable(ExDecl);
11156       InitializationKind initKind =
11157         InitializationKind::CreateCopy(Loc, SourceLocation());
11158 
11159       Expr *opaqueValue =
11160         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
11161       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11162       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
11163       if (result.isInvalid())
11164         Invalid = true;
11165       else {
11166         // If the constructor used was non-trivial, set this as the
11167         // "initializer".
11168         CXXConstructExpr *construct = result.takeAs<CXXConstructExpr>();
11169         if (!construct->getConstructor()->isTrivial()) {
11170           Expr *init = MaybeCreateExprWithCleanups(construct);
11171           ExDecl->setInit(init);
11172         }
11173 
11174         // And make sure it's destructable.
11175         FinalizeVarWithDestructor(ExDecl, recordType);
11176       }
11177     }
11178   }
11179 
11180   if (Invalid)
11181     ExDecl->setInvalidDecl();
11182 
11183   return ExDecl;
11184 }
11185 
11186 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11187 /// handler.
11188 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
11189   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11190   bool Invalid = D.isInvalidType();
11191 
11192   // Check for unexpanded parameter packs.
11193   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11194                                       UPPC_ExceptionType)) {
11195     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11196                                              D.getIdentifierLoc());
11197     Invalid = true;
11198   }
11199 
11200   IdentifierInfo *II = D.getIdentifier();
11201   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
11202                                              LookupOrdinaryName,
11203                                              ForRedeclaration)) {
11204     // The scope should be freshly made just for us. There is just no way
11205     // it contains any previous declaration.
11206     assert(!S->isDeclScope(PrevDecl));
11207     if (PrevDecl->isTemplateParameter()) {
11208       // Maybe we will complain about the shadowed template parameter.
11209       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11210       PrevDecl = 0;
11211     }
11212   }
11213 
11214   if (D.getCXXScopeSpec().isSet() && !Invalid) {
11215     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11216       << D.getCXXScopeSpec().getRange();
11217     Invalid = true;
11218   }
11219 
11220   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
11221                                               D.getLocStart(),
11222                                               D.getIdentifierLoc(),
11223                                               D.getIdentifier());
11224   if (Invalid)
11225     ExDecl->setInvalidDecl();
11226 
11227   // Add the exception declaration into this scope.
11228   if (II)
11229     PushOnScopeChains(ExDecl, S);
11230   else
11231     CurContext->addDecl(ExDecl);
11232 
11233   ProcessDeclAttributes(S, ExDecl, D);
11234   return ExDecl;
11235 }
11236 
11237 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11238                                          Expr *AssertExpr,
11239                                          Expr *AssertMessageExpr,
11240                                          SourceLocation RParenLoc) {
11241   StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
11242 
11243   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
11244     return 0;
11245 
11246   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11247                                       AssertMessage, RParenLoc, false);
11248 }
11249 
11250 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11251                                          Expr *AssertExpr,
11252                                          StringLiteral *AssertMessage,
11253                                          SourceLocation RParenLoc,
11254                                          bool Failed) {
11255   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11256       !Failed) {
11257     // In a static_assert-declaration, the constant-expression shall be a
11258     // constant expression that can be contextually converted to bool.
11259     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11260     if (Converted.isInvalid())
11261       Failed = true;
11262 
11263     llvm::APSInt Cond;
11264     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
11265           diag::err_static_assert_expression_is_not_constant,
11266           /*AllowFold=*/false).isInvalid())
11267       Failed = true;
11268 
11269     if (!Failed && !Cond) {
11270       SmallString<256> MsgBuffer;
11271       llvm::raw_svector_ostream Msg(MsgBuffer);
11272       AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
11273       Diag(StaticAssertLoc, diag::err_static_assert_failed)
11274         << Msg.str() << AssertExpr->getSourceRange();
11275       Failed = true;
11276     }
11277   }
11278 
11279   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
11280                                         AssertExpr, AssertMessage, RParenLoc,
11281                                         Failed);
11282 
11283   CurContext->addDecl(Decl);
11284   return Decl;
11285 }
11286 
11287 /// \brief Perform semantic analysis of the given friend type declaration.
11288 ///
11289 /// \returns A friend declaration that.
11290 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
11291                                       SourceLocation FriendLoc,
11292                                       TypeSourceInfo *TSInfo) {
11293   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11294 
11295   QualType T = TSInfo->getType();
11296   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
11297 
11298   // C++03 [class.friend]p2:
11299   //   An elaborated-type-specifier shall be used in a friend declaration
11300   //   for a class.*
11301   //
11302   //   * The class-key of the elaborated-type-specifier is required.
11303   if (!ActiveTemplateInstantiations.empty()) {
11304     // Do not complain about the form of friend template types during
11305     // template instantiation; we will already have complained when the
11306     // template was declared.
11307   } else {
11308     if (!T->isElaboratedTypeSpecifier()) {
11309       // If we evaluated the type to a record type, suggest putting
11310       // a tag in front.
11311       if (const RecordType *RT = T->getAs<RecordType>()) {
11312         RecordDecl *RD = RT->getDecl();
11313 
11314         std::string InsertionText = std::string(" ") + RD->getKindName();
11315 
11316         Diag(TypeRange.getBegin(),
11317              getLangOpts().CPlusPlus11 ?
11318                diag::warn_cxx98_compat_unelaborated_friend_type :
11319                diag::ext_unelaborated_friend_type)
11320           << (unsigned) RD->getTagKind()
11321           << T
11322           << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11323                                         InsertionText);
11324       } else {
11325         Diag(FriendLoc,
11326              getLangOpts().CPlusPlus11 ?
11327                diag::warn_cxx98_compat_nonclass_type_friend :
11328                diag::ext_nonclass_type_friend)
11329           << T
11330           << TypeRange;
11331       }
11332     } else if (T->getAs<EnumType>()) {
11333       Diag(FriendLoc,
11334            getLangOpts().CPlusPlus11 ?
11335              diag::warn_cxx98_compat_enum_friend :
11336              diag::ext_enum_friend)
11337         << T
11338         << TypeRange;
11339     }
11340 
11341     // C++11 [class.friend]p3:
11342     //   A friend declaration that does not declare a function shall have one
11343     //   of the following forms:
11344     //     friend elaborated-type-specifier ;
11345     //     friend simple-type-specifier ;
11346     //     friend typename-specifier ;
11347     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11348       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11349   }
11350 
11351   //   If the type specifier in a friend declaration designates a (possibly
11352   //   cv-qualified) class type, that class is declared as a friend; otherwise,
11353   //   the friend declaration is ignored.
11354   return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
11355 }
11356 
11357 /// Handle a friend tag declaration where the scope specifier was
11358 /// templated.
11359 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11360                                     unsigned TagSpec, SourceLocation TagLoc,
11361                                     CXXScopeSpec &SS,
11362                                     IdentifierInfo *Name,
11363                                     SourceLocation NameLoc,
11364                                     AttributeList *Attr,
11365                                     MultiTemplateParamsArg TempParamLists) {
11366   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11367 
11368   bool isExplicitSpecialization = false;
11369   bool Invalid = false;
11370 
11371   if (TemplateParameterList *TemplateParams =
11372           MatchTemplateParametersToScopeSpecifier(
11373               TagLoc, NameLoc, SS, TempParamLists, /*friend*/ true,
11374               isExplicitSpecialization, Invalid)) {
11375     if (TemplateParams->size() > 0) {
11376       // This is a declaration of a class template.
11377       if (Invalid)
11378         return 0;
11379 
11380       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
11381                                 SS, Name, NameLoc, Attr,
11382                                 TemplateParams, AS_public,
11383                                 /*ModulePrivateLoc=*/SourceLocation(),
11384                                 TempParamLists.size() - 1,
11385                                 TempParamLists.data()).take();
11386     } else {
11387       // The "template<>" header is extraneous.
11388       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11389         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11390       isExplicitSpecialization = true;
11391     }
11392   }
11393 
11394   if (Invalid) return 0;
11395 
11396   bool isAllExplicitSpecializations = true;
11397   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
11398     if (TempParamLists[I]->size()) {
11399       isAllExplicitSpecializations = false;
11400       break;
11401     }
11402   }
11403 
11404   // FIXME: don't ignore attributes.
11405 
11406   // If it's explicit specializations all the way down, just forget
11407   // about the template header and build an appropriate non-templated
11408   // friend.  TODO: for source fidelity, remember the headers.
11409   if (isAllExplicitSpecializations) {
11410     if (SS.isEmpty()) {
11411       bool Owned = false;
11412       bool IsDependent = false;
11413       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
11414                       Attr, AS_public,
11415                       /*ModulePrivateLoc=*/SourceLocation(),
11416                       MultiTemplateParamsArg(), Owned, IsDependent,
11417                       /*ScopedEnumKWLoc=*/SourceLocation(),
11418                       /*ScopedEnumUsesClassTag=*/false,
11419                       /*UnderlyingType=*/TypeResult(),
11420                       /*IsTypeSpecifier=*/false);
11421     }
11422 
11423     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11424     ElaboratedTypeKeyword Keyword
11425       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11426     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
11427                                    *Name, NameLoc);
11428     if (T.isNull())
11429       return 0;
11430 
11431     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11432     if (isa<DependentNameType>(T)) {
11433       DependentNameTypeLoc TL =
11434           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
11435       TL.setElaboratedKeywordLoc(TagLoc);
11436       TL.setQualifierLoc(QualifierLoc);
11437       TL.setNameLoc(NameLoc);
11438     } else {
11439       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
11440       TL.setElaboratedKeywordLoc(TagLoc);
11441       TL.setQualifierLoc(QualifierLoc);
11442       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
11443     }
11444 
11445     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
11446                                             TSI, FriendLoc, TempParamLists);
11447     Friend->setAccess(AS_public);
11448     CurContext->addDecl(Friend);
11449     return Friend;
11450   }
11451 
11452   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11453 
11454 
11455 
11456   // Handle the case of a templated-scope friend class.  e.g.
11457   //   template <class T> class A<T>::B;
11458   // FIXME: we don't support these right now.
11459   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
11460     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
11461   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11462   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11463   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11464   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
11465   TL.setElaboratedKeywordLoc(TagLoc);
11466   TL.setQualifierLoc(SS.getWithLocInContext(Context));
11467   TL.setNameLoc(NameLoc);
11468 
11469   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
11470                                           TSI, FriendLoc, TempParamLists);
11471   Friend->setAccess(AS_public);
11472   Friend->setUnsupportedFriend(true);
11473   CurContext->addDecl(Friend);
11474   return Friend;
11475 }
11476 
11477 
11478 /// Handle a friend type declaration.  This works in tandem with
11479 /// ActOnTag.
11480 ///
11481 /// Notes on friend class templates:
11482 ///
11483 /// We generally treat friend class declarations as if they were
11484 /// declaring a class.  So, for example, the elaborated type specifier
11485 /// in a friend declaration is required to obey the restrictions of a
11486 /// class-head (i.e. no typedefs in the scope chain), template
11487 /// parameters are required to match up with simple template-ids, &c.
11488 /// However, unlike when declaring a template specialization, it's
11489 /// okay to refer to a template specialization without an empty
11490 /// template parameter declaration, e.g.
11491 ///   friend class A<T>::B<unsigned>;
11492 /// We permit this as a special case; if there are any template
11493 /// parameters present at all, require proper matching, i.e.
11494 ///   template <> template \<class T> friend class A<int>::B;
11495 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
11496                                 MultiTemplateParamsArg TempParams) {
11497   SourceLocation Loc = DS.getLocStart();
11498 
11499   assert(DS.isFriendSpecified());
11500   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11501 
11502   // Try to convert the decl specifier to a type.  This works for
11503   // friend templates because ActOnTag never produces a ClassTemplateDecl
11504   // for a TUK_Friend.
11505   Declarator TheDeclarator(DS, Declarator::MemberContext);
11506   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11507   QualType T = TSI->getType();
11508   if (TheDeclarator.isInvalidType())
11509     return 0;
11510 
11511   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11512     return 0;
11513 
11514   // This is definitely an error in C++98.  It's probably meant to
11515   // be forbidden in C++0x, too, but the specification is just
11516   // poorly written.
11517   //
11518   // The problem is with declarations like the following:
11519   //   template <T> friend A<T>::foo;
11520   // where deciding whether a class C is a friend or not now hinges
11521   // on whether there exists an instantiation of A that causes
11522   // 'foo' to equal C.  There are restrictions on class-heads
11523   // (which we declare (by fiat) elaborated friend declarations to
11524   // be) that makes this tractable.
11525   //
11526   // FIXME: handle "template <> friend class A<T>;", which
11527   // is possibly well-formed?  Who even knows?
11528   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
11529     Diag(Loc, diag::err_tagless_friend_type_template)
11530       << DS.getSourceRange();
11531     return 0;
11532   }
11533 
11534   // C++98 [class.friend]p1: A friend of a class is a function
11535   //   or class that is not a member of the class . . .
11536   // This is fixed in DR77, which just barely didn't make the C++03
11537   // deadline.  It's also a very silly restriction that seriously
11538   // affects inner classes and which nobody else seems to implement;
11539   // thus we never diagnose it, not even in -pedantic.
11540   //
11541   // But note that we could warn about it: it's always useless to
11542   // friend one of your own members (it's not, however, worthless to
11543   // friend a member of an arbitrary specialization of your template).
11544 
11545   Decl *D;
11546   if (unsigned NumTempParamLists = TempParams.size())
11547     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
11548                                    NumTempParamLists,
11549                                    TempParams.data(),
11550                                    TSI,
11551                                    DS.getFriendSpecLoc());
11552   else
11553     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
11554 
11555   if (!D)
11556     return 0;
11557 
11558   D->setAccess(AS_public);
11559   CurContext->addDecl(D);
11560 
11561   return D;
11562 }
11563 
11564 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11565                                         MultiTemplateParamsArg TemplateParams) {
11566   const DeclSpec &DS = D.getDeclSpec();
11567 
11568   assert(DS.isFriendSpecified());
11569   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11570 
11571   SourceLocation Loc = D.getIdentifierLoc();
11572   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11573 
11574   // C++ [class.friend]p1
11575   //   A friend of a class is a function or class....
11576   // Note that this sees through typedefs, which is intended.
11577   // It *doesn't* see through dependent types, which is correct
11578   // according to [temp.arg.type]p3:
11579   //   If a declaration acquires a function type through a
11580   //   type dependent on a template-parameter and this causes
11581   //   a declaration that does not use the syntactic form of a
11582   //   function declarator to have a function type, the program
11583   //   is ill-formed.
11584   if (!TInfo->getType()->isFunctionType()) {
11585     Diag(Loc, diag::err_unexpected_friend);
11586 
11587     // It might be worthwhile to try to recover by creating an
11588     // appropriate declaration.
11589     return 0;
11590   }
11591 
11592   // C++ [namespace.memdef]p3
11593   //  - If a friend declaration in a non-local class first declares a
11594   //    class or function, the friend class or function is a member
11595   //    of the innermost enclosing namespace.
11596   //  - The name of the friend is not found by simple name lookup
11597   //    until a matching declaration is provided in that namespace
11598   //    scope (either before or after the class declaration granting
11599   //    friendship).
11600   //  - If a friend function is called, its name may be found by the
11601   //    name lookup that considers functions from namespaces and
11602   //    classes associated with the types of the function arguments.
11603   //  - When looking for a prior declaration of a class or a function
11604   //    declared as a friend, scopes outside the innermost enclosing
11605   //    namespace scope are not considered.
11606 
11607   CXXScopeSpec &SS = D.getCXXScopeSpec();
11608   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11609   DeclarationName Name = NameInfo.getName();
11610   assert(Name);
11611 
11612   // Check for unexpanded parameter packs.
11613   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11614       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11615       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11616     return 0;
11617 
11618   // The context we found the declaration in, or in which we should
11619   // create the declaration.
11620   DeclContext *DC;
11621   Scope *DCScope = S;
11622   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
11623                         ForRedeclaration);
11624 
11625   // There are five cases here.
11626   //   - There's no scope specifier and we're in a local class. Only look
11627   //     for functions declared in the immediately-enclosing block scope.
11628   // We recover from invalid scope qualifiers as if they just weren't there.
11629   FunctionDecl *FunctionContainingLocalClass = 0;
11630   if ((SS.isInvalid() || !SS.isSet()) &&
11631       (FunctionContainingLocalClass =
11632            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11633     // C++11 [class.friend]p11:
11634     //   If a friend declaration appears in a local class and the name
11635     //   specified is an unqualified name, a prior declaration is
11636     //   looked up without considering scopes that are outside the
11637     //   innermost enclosing non-class scope. For a friend function
11638     //   declaration, if there is no prior declaration, the program is
11639     //   ill-formed.
11640 
11641     // Find the innermost enclosing non-class scope. This is the block
11642     // scope containing the local class definition (or for a nested class,
11643     // the outer local class).
11644     DCScope = S->getFnParent();
11645 
11646     // Look up the function name in the scope.
11647     Previous.clear(LookupLocalFriendName);
11648     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11649 
11650     if (!Previous.empty()) {
11651       // All possible previous declarations must have the same context:
11652       // either they were declared at block scope or they are members of
11653       // one of the enclosing local classes.
11654       DC = Previous.getRepresentativeDecl()->getDeclContext();
11655     } else {
11656       // This is ill-formed, but provide the context that we would have
11657       // declared the function in, if we were permitted to, for error recovery.
11658       DC = FunctionContainingLocalClass;
11659     }
11660     adjustContextForLocalExternDecl(DC);
11661 
11662     // C++ [class.friend]p6:
11663     //   A function can be defined in a friend declaration of a class if and
11664     //   only if the class is a non-local class (9.8), the function name is
11665     //   unqualified, and the function has namespace scope.
11666     if (D.isFunctionDefinition()) {
11667       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11668     }
11669 
11670   //   - There's no scope specifier, in which case we just go to the
11671   //     appropriate scope and look for a function or function template
11672   //     there as appropriate.
11673   } else if (SS.isInvalid() || !SS.isSet()) {
11674     // C++11 [namespace.memdef]p3:
11675     //   If the name in a friend declaration is neither qualified nor
11676     //   a template-id and the declaration is a function or an
11677     //   elaborated-type-specifier, the lookup to determine whether
11678     //   the entity has been previously declared shall not consider
11679     //   any scopes outside the innermost enclosing namespace.
11680     bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
11681 
11682     // Find the appropriate context according to the above.
11683     DC = CurContext;
11684 
11685     // Skip class contexts.  If someone can cite chapter and verse
11686     // for this behavior, that would be nice --- it's what GCC and
11687     // EDG do, and it seems like a reasonable intent, but the spec
11688     // really only says that checks for unqualified existing
11689     // declarations should stop at the nearest enclosing namespace,
11690     // not that they should only consider the nearest enclosing
11691     // namespace.
11692     while (DC->isRecord())
11693       DC = DC->getParent();
11694 
11695     DeclContext *LookupDC = DC;
11696     while (LookupDC->isTransparentContext())
11697       LookupDC = LookupDC->getParent();
11698 
11699     while (true) {
11700       LookupQualifiedName(Previous, LookupDC);
11701 
11702       if (!Previous.empty()) {
11703         DC = LookupDC;
11704         break;
11705       }
11706 
11707       if (isTemplateId) {
11708         if (isa<TranslationUnitDecl>(LookupDC)) break;
11709       } else {
11710         if (LookupDC->isFileContext()) break;
11711       }
11712       LookupDC = LookupDC->getParent();
11713     }
11714 
11715     DCScope = getScopeForDeclContext(S, DC);
11716 
11717   //   - There's a non-dependent scope specifier, in which case we
11718   //     compute it and do a previous lookup there for a function
11719   //     or function template.
11720   } else if (!SS.getScopeRep()->isDependent()) {
11721     DC = computeDeclContext(SS);
11722     if (!DC) return 0;
11723 
11724     if (RequireCompleteDeclContext(SS, DC)) return 0;
11725 
11726     LookupQualifiedName(Previous, DC);
11727 
11728     // Ignore things found implicitly in the wrong scope.
11729     // TODO: better diagnostics for this case.  Suggesting the right
11730     // qualified scope would be nice...
11731     LookupResult::Filter F = Previous.makeFilter();
11732     while (F.hasNext()) {
11733       NamedDecl *D = F.next();
11734       if (!DC->InEnclosingNamespaceSetOf(
11735               D->getDeclContext()->getRedeclContext()))
11736         F.erase();
11737     }
11738     F.done();
11739 
11740     if (Previous.empty()) {
11741       D.setInvalidType();
11742       Diag(Loc, diag::err_qualified_friend_not_found)
11743           << Name << TInfo->getType();
11744       return 0;
11745     }
11746 
11747     // C++ [class.friend]p1: A friend of a class is a function or
11748     //   class that is not a member of the class . . .
11749     if (DC->Equals(CurContext))
11750       Diag(DS.getFriendSpecLoc(),
11751            getLangOpts().CPlusPlus11 ?
11752              diag::warn_cxx98_compat_friend_is_member :
11753              diag::err_friend_is_member);
11754 
11755     if (D.isFunctionDefinition()) {
11756       // C++ [class.friend]p6:
11757       //   A function can be defined in a friend declaration of a class if and
11758       //   only if the class is a non-local class (9.8), the function name is
11759       //   unqualified, and the function has namespace scope.
11760       SemaDiagnosticBuilder DB
11761         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11762 
11763       DB << SS.getScopeRep();
11764       if (DC->isFileContext())
11765         DB << FixItHint::CreateRemoval(SS.getRange());
11766       SS.clear();
11767     }
11768 
11769   //   - There's a scope specifier that does not match any template
11770   //     parameter lists, in which case we use some arbitrary context,
11771   //     create a method or method template, and wait for instantiation.
11772   //   - There's a scope specifier that does match some template
11773   //     parameter lists, which we don't handle right now.
11774   } else {
11775     if (D.isFunctionDefinition()) {
11776       // C++ [class.friend]p6:
11777       //   A function can be defined in a friend declaration of a class if and
11778       //   only if the class is a non-local class (9.8), the function name is
11779       //   unqualified, and the function has namespace scope.
11780       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11781         << SS.getScopeRep();
11782     }
11783 
11784     DC = CurContext;
11785     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
11786   }
11787 
11788   if (!DC->isRecord()) {
11789     // This implies that it has to be an operator or function.
11790     if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11791         D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11792         D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
11793       Diag(Loc, diag::err_introducing_special_friend) <<
11794         (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11795          D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
11796       return 0;
11797     }
11798   }
11799 
11800   // FIXME: This is an egregious hack to cope with cases where the scope stack
11801   // does not contain the declaration context, i.e., in an out-of-line
11802   // definition of a class.
11803   Scope FakeDCScope(S, Scope::DeclScope, Diags);
11804   if (!DCScope) {
11805     FakeDCScope.setEntity(DC);
11806     DCScope = &FakeDCScope;
11807   }
11808 
11809   bool AddToScope = true;
11810   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
11811                                           TemplateParams, AddToScope);
11812   if (!ND) return 0;
11813 
11814   assert(ND->getLexicalDeclContext() == CurContext);
11815 
11816   // If we performed typo correction, we might have added a scope specifier
11817   // and changed the decl context.
11818   DC = ND->getDeclContext();
11819 
11820   // Add the function declaration to the appropriate lookup tables,
11821   // adjusting the redeclarations list as necessary.  We don't
11822   // want to do this yet if the friending class is dependent.
11823   //
11824   // Also update the scope-based lookup if the target context's
11825   // lookup context is in lexical scope.
11826   if (!CurContext->isDependentContext()) {
11827     DC = DC->getRedeclContext();
11828     DC->makeDeclVisibleInContext(ND);
11829     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11830       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
11831   }
11832 
11833   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
11834                                        D.getIdentifierLoc(), ND,
11835                                        DS.getFriendSpecLoc());
11836   FrD->setAccess(AS_public);
11837   CurContext->addDecl(FrD);
11838 
11839   if (ND->isInvalidDecl()) {
11840     FrD->setInvalidDecl();
11841   } else {
11842     if (DC->isRecord()) CheckFriendAccess(ND);
11843 
11844     FunctionDecl *FD;
11845     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11846       FD = FTD->getTemplatedDecl();
11847     else
11848       FD = cast<FunctionDecl>(ND);
11849 
11850     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
11851     // default argument expression, that declaration shall be a definition
11852     // and shall be the only declaration of the function or function
11853     // template in the translation unit.
11854     if (functionDeclHasDefaultArgument(FD)) {
11855       if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
11856         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
11857         Diag(OldFD->getLocation(), diag::note_previous_declaration);
11858       } else if (!D.isFunctionDefinition())
11859         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
11860     }
11861 
11862     // Mark templated-scope function declarations as unsupported.
11863     if (FD->getNumTemplateParameterLists())
11864       FrD->setUnsupportedFriend(true);
11865   }
11866 
11867   return ND;
11868 }
11869 
11870 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11871   AdjustDeclIfTemplate(Dcl);
11872 
11873   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
11874   if (!Fn) {
11875     Diag(DelLoc, diag::err_deleted_non_function);
11876     return;
11877   }
11878 
11879   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
11880     // Don't consider the implicit declaration we generate for explicit
11881     // specializations. FIXME: Do not generate these implicit declarations.
11882     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
11883          Prev->getPreviousDecl()) &&
11884         !Prev->isDefined()) {
11885       Diag(DelLoc, diag::err_deleted_decl_not_first);
11886       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
11887            Prev->isImplicit() ? diag::note_previous_implicit_declaration
11888                               : diag::note_previous_declaration);
11889     }
11890     // If the declaration wasn't the first, we delete the function anyway for
11891     // recovery.
11892     Fn = Fn->getCanonicalDecl();
11893   }
11894 
11895   if (Fn->isDeleted())
11896     return;
11897 
11898   // See if we're deleting a function which is already known to override a
11899   // non-deleted virtual function.
11900   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11901     bool IssuedDiagnostic = false;
11902     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11903                                         E = MD->end_overridden_methods();
11904          I != E; ++I) {
11905       if (!(*MD->begin_overridden_methods())->isDeleted()) {
11906         if (!IssuedDiagnostic) {
11907           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11908           IssuedDiagnostic = true;
11909         }
11910         Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11911       }
11912     }
11913   }
11914 
11915   // C++11 [basic.start.main]p3:
11916   //   A program that defines main as deleted [...] is ill-formed.
11917   if (Fn->isMain())
11918     Diag(DelLoc, diag::err_deleted_main);
11919 
11920   Fn->setDeletedAsWritten();
11921 }
11922 
11923 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
11924   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
11925 
11926   if (MD) {
11927     if (MD->getParent()->isDependentType()) {
11928       MD->setDefaulted();
11929       MD->setExplicitlyDefaulted();
11930       return;
11931     }
11932 
11933     CXXSpecialMember Member = getSpecialMember(MD);
11934     if (Member == CXXInvalid) {
11935       if (!MD->isInvalidDecl())
11936         Diag(DefaultLoc, diag::err_default_special_members);
11937       return;
11938     }
11939 
11940     MD->setDefaulted();
11941     MD->setExplicitlyDefaulted();
11942 
11943     // If this definition appears within the record, do the checking when
11944     // the record is complete.
11945     const FunctionDecl *Primary = MD;
11946     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
11947       // Find the uninstantiated declaration that actually had the '= default'
11948       // on it.
11949       Pattern->isDefined(Primary);
11950 
11951     // If the method was defaulted on its first declaration, we will have
11952     // already performed the checking in CheckCompletedCXXClass. Such a
11953     // declaration doesn't trigger an implicit definition.
11954     if (Primary == Primary->getCanonicalDecl())
11955       return;
11956 
11957     CheckExplicitlyDefaultedSpecialMember(MD);
11958 
11959     // The exception specification is needed because we are defining the
11960     // function.
11961     ResolveExceptionSpec(DefaultLoc,
11962                          MD->getType()->castAs<FunctionProtoType>());
11963 
11964     if (MD->isInvalidDecl())
11965       return;
11966 
11967     switch (Member) {
11968     case CXXDefaultConstructor:
11969       DefineImplicitDefaultConstructor(DefaultLoc,
11970                                        cast<CXXConstructorDecl>(MD));
11971       break;
11972     case CXXCopyConstructor:
11973       DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
11974       break;
11975     case CXXCopyAssignment:
11976       DefineImplicitCopyAssignment(DefaultLoc, MD);
11977       break;
11978     case CXXDestructor:
11979       DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
11980       break;
11981     case CXXMoveConstructor:
11982       DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
11983       break;
11984     case CXXMoveAssignment:
11985       DefineImplicitMoveAssignment(DefaultLoc, MD);
11986       break;
11987     case CXXInvalid:
11988       llvm_unreachable("Invalid special member.");
11989     }
11990   } else {
11991     Diag(DefaultLoc, diag::err_default_special_members);
11992   }
11993 }
11994 
11995 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
11996   for (Stmt::child_range CI = S->children(); CI; ++CI) {
11997     Stmt *SubStmt = *CI;
11998     if (!SubStmt)
11999       continue;
12000     if (isa<ReturnStmt>(SubStmt))
12001       Self.Diag(SubStmt->getLocStart(),
12002            diag::err_return_in_constructor_handler);
12003     if (!isa<Expr>(SubStmt))
12004       SearchForReturnInStmt(Self, SubStmt);
12005   }
12006 }
12007 
12008 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12009   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12010     CXXCatchStmt *Handler = TryBlock->getHandler(I);
12011     SearchForReturnInStmt(*this, Handler);
12012   }
12013 }
12014 
12015 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
12016                                              const CXXMethodDecl *Old) {
12017   const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12018   const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12019 
12020   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12021 
12022   // If the calling conventions match, everything is fine
12023   if (NewCC == OldCC)
12024     return false;
12025 
12026   // If the calling conventions mismatch because the new function is static,
12027   // suppress the calling convention mismatch error; the error about static
12028   // function override (err_static_overrides_virtual from
12029   // Sema::CheckFunctionDeclaration) is more clear.
12030   if (New->getStorageClass() == SC_Static)
12031     return false;
12032 
12033   Diag(New->getLocation(),
12034        diag::err_conflicting_overriding_cc_attributes)
12035     << New->getDeclName() << New->getType() << Old->getType();
12036   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12037   return true;
12038 }
12039 
12040 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
12041                                              const CXXMethodDecl *Old) {
12042   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12043   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
12044 
12045   if (Context.hasSameType(NewTy, OldTy) ||
12046       NewTy->isDependentType() || OldTy->isDependentType())
12047     return false;
12048 
12049   // Check if the return types are covariant
12050   QualType NewClassTy, OldClassTy;
12051 
12052   /// Both types must be pointers or references to classes.
12053   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12054     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
12055       NewClassTy = NewPT->getPointeeType();
12056       OldClassTy = OldPT->getPointeeType();
12057     }
12058   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12059     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12060       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12061         NewClassTy = NewRT->getPointeeType();
12062         OldClassTy = OldRT->getPointeeType();
12063       }
12064     }
12065   }
12066 
12067   // The return types aren't either both pointers or references to a class type.
12068   if (NewClassTy.isNull()) {
12069     Diag(New->getLocation(),
12070          diag::err_different_return_type_for_overriding_virtual_function)
12071       << New->getDeclName() << NewTy << OldTy;
12072     Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12073 
12074     return true;
12075   }
12076 
12077   // C++ [class.virtual]p6:
12078   //   If the return type of D::f differs from the return type of B::f, the
12079   //   class type in the return type of D::f shall be complete at the point of
12080   //   declaration of D::f or shall be the class type D.
12081   if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12082     if (!RT->isBeingDefined() &&
12083         RequireCompleteType(New->getLocation(), NewClassTy,
12084                             diag::err_covariant_return_incomplete,
12085                             New->getDeclName()))
12086     return true;
12087   }
12088 
12089   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
12090     // Check if the new class derives from the old class.
12091     if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12092       Diag(New->getLocation(),
12093            diag::err_covariant_return_not_derived)
12094       << New->getDeclName() << NewTy << OldTy;
12095       Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12096       return true;
12097     }
12098 
12099     // Check if we the conversion from derived to base is valid.
12100     if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
12101                     diag::err_covariant_return_inaccessible_base,
12102                     diag::err_covariant_return_ambiguous_derived_to_base_conv,
12103                     // FIXME: Should this point to the return type?
12104                     New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
12105       // FIXME: this note won't trigger for delayed access control
12106       // diagnostics, and it's impossible to get an undelayed error
12107       // here from access control during the original parse because
12108       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
12109       Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12110       return true;
12111     }
12112   }
12113 
12114   // The qualifiers of the return types must be the same.
12115   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
12116     Diag(New->getLocation(),
12117          diag::err_covariant_return_type_different_qualifications)
12118     << New->getDeclName() << NewTy << OldTy;
12119     Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12120     return true;
12121   };
12122 
12123 
12124   // The new class type must have the same or less qualifiers as the old type.
12125   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12126     Diag(New->getLocation(),
12127          diag::err_covariant_return_type_class_type_more_qualified)
12128     << New->getDeclName() << NewTy << OldTy;
12129     Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12130     return true;
12131   };
12132 
12133   return false;
12134 }
12135 
12136 /// \brief Mark the given method pure.
12137 ///
12138 /// \param Method the method to be marked pure.
12139 ///
12140 /// \param InitRange the source range that covers the "0" initializer.
12141 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
12142   SourceLocation EndLoc = InitRange.getEnd();
12143   if (EndLoc.isValid())
12144     Method->setRangeEnd(EndLoc);
12145 
12146   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12147     Method->setPure();
12148     return false;
12149   }
12150 
12151   if (!Method->isInvalidDecl())
12152     Diag(Method->getLocation(), diag::err_non_virtual_pure)
12153       << Method->getDeclName() << InitRange;
12154   return true;
12155 }
12156 
12157 /// \brief Determine whether the given declaration is a static data member.
12158 static bool isStaticDataMember(const Decl *D) {
12159   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12160     return Var->isStaticDataMember();
12161 
12162   return false;
12163 }
12164 
12165 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12166 /// an initializer for the out-of-line declaration 'Dcl'.  The scope
12167 /// is a fresh scope pushed for just this purpose.
12168 ///
12169 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12170 /// static data member of class X, names should be looked up in the scope of
12171 /// class X.
12172 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
12173   // If there is no declaration, there was an error parsing it.
12174   if (D == 0 || D->isInvalidDecl()) return;
12175 
12176   // We will always have a nested name specifier here, but this declaration
12177   // might not be out of line if the specifier names the current namespace:
12178   //   extern int n;
12179   //   int ::n = 0;
12180   if (D->isOutOfLine())
12181     EnterDeclaratorContext(S, D->getDeclContext());
12182 
12183   // If we are parsing the initializer for a static data member, push a
12184   // new expression evaluation context that is associated with this static
12185   // data member.
12186   if (isStaticDataMember(D))
12187     PushExpressionEvaluationContext(PotentiallyEvaluated, D);
12188 }
12189 
12190 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
12191 /// initializer for the out-of-line declaration 'D'.
12192 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
12193   // If there is no declaration, there was an error parsing it.
12194   if (D == 0 || D->isInvalidDecl()) return;
12195 
12196   if (isStaticDataMember(D))
12197     PopExpressionEvaluationContext();
12198 
12199   if (D->isOutOfLine())
12200     ExitDeclaratorContext(S);
12201 }
12202 
12203 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12204 /// C++ if/switch/while/for statement.
12205 /// e.g: "if (int x = f()) {...}"
12206 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
12207   // C++ 6.4p2:
12208   // The declarator shall not specify a function or an array.
12209   // The type-specifier-seq shall not contain typedef and shall not declare a
12210   // new class or enumeration.
12211   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12212          "Parser allowed 'typedef' as storage class of condition decl.");
12213 
12214   Decl *Dcl = ActOnDeclarator(S, D);
12215   if (!Dcl)
12216     return true;
12217 
12218   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12219     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
12220       << D.getSourceRange();
12221     return true;
12222   }
12223 
12224   return Dcl;
12225 }
12226 
12227 void Sema::LoadExternalVTableUses() {
12228   if (!ExternalSource)
12229     return;
12230 
12231   SmallVector<ExternalVTableUse, 4> VTables;
12232   ExternalSource->ReadUsedVTables(VTables);
12233   SmallVector<VTableUse, 4> NewUses;
12234   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12235     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12236       = VTablesUsed.find(VTables[I].Record);
12237     // Even if a definition wasn't required before, it may be required now.
12238     if (Pos != VTablesUsed.end()) {
12239       if (!Pos->second && VTables[I].DefinitionRequired)
12240         Pos->second = true;
12241       continue;
12242     }
12243 
12244     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12245     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12246   }
12247 
12248   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12249 }
12250 
12251 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12252                           bool DefinitionRequired) {
12253   // Ignore any vtable uses in unevaluated operands or for classes that do
12254   // not have a vtable.
12255   if (!Class->isDynamicClass() || Class->isDependentContext() ||
12256       CurContext->isDependentContext() || isUnevaluatedContext())
12257     return;
12258 
12259   // Try to insert this class into the map.
12260   LoadExternalVTableUses();
12261   Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12262   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12263     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12264   if (!Pos.second) {
12265     // If we already had an entry, check to see if we are promoting this vtable
12266     // to required a definition. If so, we need to reappend to the VTableUses
12267     // list, since we may have already processed the first entry.
12268     if (DefinitionRequired && !Pos.first->second) {
12269       Pos.first->second = true;
12270     } else {
12271       // Otherwise, we can early exit.
12272       return;
12273     }
12274   } else {
12275     // The Microsoft ABI requires that we perform the destructor body
12276     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
12277     // the deleting destructor is emitted with the vtable, not with the
12278     // destructor definition as in the Itanium ABI.
12279     // If it has a definition, we do the check at that point instead.
12280     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12281         Class->hasUserDeclaredDestructor() &&
12282         !Class->getDestructor()->isDefined() &&
12283         !Class->getDestructor()->isDeleted()) {
12284       CheckDestructor(Class->getDestructor());
12285     }
12286   }
12287 
12288   // Local classes need to have their virtual members marked
12289   // immediately. For all other classes, we mark their virtual members
12290   // at the end of the translation unit.
12291   if (Class->isLocalClass())
12292     MarkVirtualMembersReferenced(Loc, Class);
12293   else
12294     VTableUses.push_back(std::make_pair(Class, Loc));
12295 }
12296 
12297 bool Sema::DefineUsedVTables() {
12298   LoadExternalVTableUses();
12299   if (VTableUses.empty())
12300     return false;
12301 
12302   // Note: The VTableUses vector could grow as a result of marking
12303   // the members of a class as "used", so we check the size each
12304   // time through the loop and prefer indices (which are stable) to
12305   // iterators (which are not).
12306   bool DefinedAnything = false;
12307   for (unsigned I = 0; I != VTableUses.size(); ++I) {
12308     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
12309     if (!Class)
12310       continue;
12311 
12312     SourceLocation Loc = VTableUses[I].second;
12313 
12314     bool DefineVTable = true;
12315 
12316     // If this class has a key function, but that key function is
12317     // defined in another translation unit, we don't need to emit the
12318     // vtable even though we're using it.
12319     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
12320     if (KeyFunction && !KeyFunction->hasBody()) {
12321       // The key function is in another translation unit.
12322       DefineVTable = false;
12323       TemplateSpecializationKind TSK =
12324           KeyFunction->getTemplateSpecializationKind();
12325       assert(TSK != TSK_ExplicitInstantiationDefinition &&
12326              TSK != TSK_ImplicitInstantiation &&
12327              "Instantiations don't have key functions");
12328       (void)TSK;
12329     } else if (!KeyFunction) {
12330       // If we have a class with no key function that is the subject
12331       // of an explicit instantiation declaration, suppress the
12332       // vtable; it will live with the explicit instantiation
12333       // definition.
12334       bool IsExplicitInstantiationDeclaration
12335         = Class->getTemplateSpecializationKind()
12336                                       == TSK_ExplicitInstantiationDeclaration;
12337       for (auto R : Class->redecls()) {
12338         TemplateSpecializationKind TSK
12339           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
12340         if (TSK == TSK_ExplicitInstantiationDeclaration)
12341           IsExplicitInstantiationDeclaration = true;
12342         else if (TSK == TSK_ExplicitInstantiationDefinition) {
12343           IsExplicitInstantiationDeclaration = false;
12344           break;
12345         }
12346       }
12347 
12348       if (IsExplicitInstantiationDeclaration)
12349         DefineVTable = false;
12350     }
12351 
12352     // The exception specifications for all virtual members may be needed even
12353     // if we are not providing an authoritative form of the vtable in this TU.
12354     // We may choose to emit it available_externally anyway.
12355     if (!DefineVTable) {
12356       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12357       continue;
12358     }
12359 
12360     // Mark all of the virtual members of this class as referenced, so
12361     // that we can build a vtable. Then, tell the AST consumer that a
12362     // vtable for this class is required.
12363     DefinedAnything = true;
12364     MarkVirtualMembersReferenced(Loc, Class);
12365     CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12366     Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12367 
12368     // Optionally warn if we're emitting a weak vtable.
12369     if (Class->isExternallyVisible() &&
12370         Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
12371       const FunctionDecl *KeyFunctionDef = 0;
12372       if (!KeyFunction ||
12373           (KeyFunction->hasBody(KeyFunctionDef) &&
12374            KeyFunctionDef->isInlined()))
12375         Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12376              TSK_ExplicitInstantiationDefinition
12377              ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12378           << Class;
12379     }
12380   }
12381   VTableUses.clear();
12382 
12383   return DefinedAnything;
12384 }
12385 
12386 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12387                                                  const CXXRecordDecl *RD) {
12388   for (const auto *I : RD->methods())
12389     if (I->isVirtual() && !I->isPure())
12390       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
12391 }
12392 
12393 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12394                                         const CXXRecordDecl *RD) {
12395   // Mark all functions which will appear in RD's vtable as used.
12396   CXXFinalOverriderMap FinalOverriders;
12397   RD->getFinalOverriders(FinalOverriders);
12398   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12399                                             E = FinalOverriders.end();
12400        I != E; ++I) {
12401     for (OverridingMethods::const_iterator OI = I->second.begin(),
12402                                            OE = I->second.end();
12403          OI != OE; ++OI) {
12404       assert(OI->second.size() > 0 && "no final overrider");
12405       CXXMethodDecl *Overrider = OI->second.front().Method;
12406 
12407       // C++ [basic.def.odr]p2:
12408       //   [...] A virtual member function is used if it is not pure. [...]
12409       if (!Overrider->isPure())
12410         MarkFunctionReferenced(Loc, Overrider);
12411     }
12412   }
12413 
12414   // Only classes that have virtual bases need a VTT.
12415   if (RD->getNumVBases() == 0)
12416     return;
12417 
12418   for (const auto &I : RD->bases()) {
12419     const CXXRecordDecl *Base =
12420         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
12421     if (Base->getNumVBases() == 0)
12422       continue;
12423     MarkVirtualMembersReferenced(Loc, Base);
12424   }
12425 }
12426 
12427 /// SetIvarInitializers - This routine builds initialization ASTs for the
12428 /// Objective-C implementation whose ivars need be initialized.
12429 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
12430   if (!getLangOpts().CPlusPlus)
12431     return;
12432   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
12433     SmallVector<ObjCIvarDecl*, 8> ivars;
12434     CollectIvarsToConstructOrDestruct(OID, ivars);
12435     if (ivars.empty())
12436       return;
12437     SmallVector<CXXCtorInitializer*, 32> AllToInit;
12438     for (unsigned i = 0; i < ivars.size(); i++) {
12439       FieldDecl *Field = ivars[i];
12440       if (Field->isInvalidDecl())
12441         continue;
12442 
12443       CXXCtorInitializer *Member;
12444       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12445       InitializationKind InitKind =
12446         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
12447 
12448       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12449       ExprResult MemberInit =
12450         InitSeq.Perform(*this, InitEntity, InitKind, None);
12451       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
12452       // Note, MemberInit could actually come back empty if no initialization
12453       // is required (e.g., because it would call a trivial default constructor)
12454       if (!MemberInit.get() || MemberInit.isInvalid())
12455         continue;
12456 
12457       Member =
12458         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12459                                          SourceLocation(),
12460                                          MemberInit.takeAs<Expr>(),
12461                                          SourceLocation());
12462       AllToInit.push_back(Member);
12463 
12464       // Be sure that the destructor is accessible and is marked as referenced.
12465       if (const RecordType *RecordTy
12466                   = Context.getBaseElementType(Field->getType())
12467                                                         ->getAs<RecordType>()) {
12468                     CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
12469         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
12470           MarkFunctionReferenced(Field->getLocation(), Destructor);
12471           CheckDestructorAccess(Field->getLocation(), Destructor,
12472                             PDiag(diag::err_access_dtor_ivar)
12473                               << Context.getBaseElementType(Field->getType()));
12474         }
12475       }
12476     }
12477     ObjCImplementation->setIvarInitializers(Context,
12478                                             AllToInit.data(), AllToInit.size());
12479   }
12480 }
12481 
12482 static
12483 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12484                            llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12485                            llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12486                            llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12487                            Sema &S) {
12488   if (Ctor->isInvalidDecl())
12489     return;
12490 
12491   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12492 
12493   // Target may not be determinable yet, for instance if this is a dependent
12494   // call in an uninstantiated template.
12495   if (Target) {
12496     const FunctionDecl *FNTarget = 0;
12497     (void)Target->hasBody(FNTarget);
12498     Target = const_cast<CXXConstructorDecl*>(
12499       cast_or_null<CXXConstructorDecl>(FNTarget));
12500   }
12501 
12502   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12503                      // Avoid dereferencing a null pointer here.
12504                      *TCanonical = Target ? Target->getCanonicalDecl() : 0;
12505 
12506   if (!Current.insert(Canonical))
12507     return;
12508 
12509   // We know that beyond here, we aren't chaining into a cycle.
12510   if (!Target || !Target->isDelegatingConstructor() ||
12511       Target->isInvalidDecl() || Valid.count(TCanonical)) {
12512     Valid.insert(Current.begin(), Current.end());
12513     Current.clear();
12514   // We've hit a cycle.
12515   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12516              Current.count(TCanonical)) {
12517     // If we haven't diagnosed this cycle yet, do so now.
12518     if (!Invalid.count(TCanonical)) {
12519       S.Diag((*Ctor->init_begin())->getSourceLocation(),
12520              diag::warn_delegating_ctor_cycle)
12521         << Ctor;
12522 
12523       // Don't add a note for a function delegating directly to itself.
12524       if (TCanonical != Canonical)
12525         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12526 
12527       CXXConstructorDecl *C = Target;
12528       while (C->getCanonicalDecl() != Canonical) {
12529         const FunctionDecl *FNTarget = 0;
12530         (void)C->getTargetConstructor()->hasBody(FNTarget);
12531         assert(FNTarget && "Ctor cycle through bodiless function");
12532 
12533         C = const_cast<CXXConstructorDecl*>(
12534           cast<CXXConstructorDecl>(FNTarget));
12535         S.Diag(C->getLocation(), diag::note_which_delegates_to);
12536       }
12537     }
12538 
12539     Invalid.insert(Current.begin(), Current.end());
12540     Current.clear();
12541   } else {
12542     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12543   }
12544 }
12545 
12546 
12547 void Sema::CheckDelegatingCtorCycles() {
12548   llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12549 
12550   for (DelegatingCtorDeclsType::iterator
12551          I = DelegatingCtorDecls.begin(ExternalSource),
12552          E = DelegatingCtorDecls.end();
12553        I != E; ++I)
12554     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
12555 
12556   for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12557                                                          CE = Invalid.end();
12558        CI != CE; ++CI)
12559     (*CI)->setInvalidDecl();
12560 }
12561 
12562 namespace {
12563   /// \brief AST visitor that finds references to the 'this' expression.
12564   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12565     Sema &S;
12566 
12567   public:
12568     explicit FindCXXThisExpr(Sema &S) : S(S) { }
12569 
12570     bool VisitCXXThisExpr(CXXThisExpr *E) {
12571       S.Diag(E->getLocation(), diag::err_this_static_member_func)
12572         << E->isImplicit();
12573       return false;
12574     }
12575   };
12576 }
12577 
12578 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12579   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12580   if (!TSInfo)
12581     return false;
12582 
12583   TypeLoc TL = TSInfo->getTypeLoc();
12584   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
12585   if (!ProtoTL)
12586     return false;
12587 
12588   // C++11 [expr.prim.general]p3:
12589   //   [The expression this] shall not appear before the optional
12590   //   cv-qualifier-seq and it shall not appear within the declaration of a
12591   //   static member function (although its type and value category are defined
12592   //   within a static member function as they are within a non-static member
12593   //   function). [ Note: this is because declaration matching does not occur
12594   //  until the complete declarator is known. - end note ]
12595   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
12596   FindCXXThisExpr Finder(*this);
12597 
12598   // If the return type came after the cv-qualifier-seq, check it now.
12599   if (Proto->hasTrailingReturn() &&
12600       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
12601     return true;
12602 
12603   // Check the exception specification.
12604   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12605     return true;
12606 
12607   return checkThisInStaticMemberFunctionAttributes(Method);
12608 }
12609 
12610 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12611   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12612   if (!TSInfo)
12613     return false;
12614 
12615   TypeLoc TL = TSInfo->getTypeLoc();
12616   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
12617   if (!ProtoTL)
12618     return false;
12619 
12620   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
12621   FindCXXThisExpr Finder(*this);
12622 
12623   switch (Proto->getExceptionSpecType()) {
12624   case EST_Uninstantiated:
12625   case EST_Unevaluated:
12626   case EST_BasicNoexcept:
12627   case EST_DynamicNone:
12628   case EST_MSAny:
12629   case EST_None:
12630     break;
12631 
12632   case EST_ComputedNoexcept:
12633     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12634       return true;
12635 
12636   case EST_Dynamic:
12637     for (const auto &E : Proto->exceptions()) {
12638       if (!Finder.TraverseType(E))
12639         return true;
12640     }
12641     break;
12642   }
12643 
12644   return false;
12645 }
12646 
12647 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12648   FindCXXThisExpr Finder(*this);
12649 
12650   // Check attributes.
12651   for (const auto *A : Method->attrs()) {
12652     // FIXME: This should be emitted by tblgen.
12653     Expr *Arg = 0;
12654     ArrayRef<Expr *> Args;
12655     if (const auto *G = dyn_cast<GuardedByAttr>(A))
12656       Arg = G->getArg();
12657     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
12658       Arg = G->getArg();
12659     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
12660       Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12661     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
12662       Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12663     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
12664       Arg = ETLF->getSuccessValue();
12665       Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12666     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
12667       Arg = STLF->getSuccessValue();
12668       Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12669     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
12670       Arg = LR->getArg();
12671     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
12672       Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12673     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
12674       Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
12675     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
12676       Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
12677     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
12678       Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
12679     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
12680       Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
12681 
12682     if (Arg && !Finder.TraverseStmt(Arg))
12683       return true;
12684 
12685     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12686       if (!Finder.TraverseStmt(Args[I]))
12687         return true;
12688     }
12689   }
12690 
12691   return false;
12692 }
12693 
12694 void
12695 Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12696                                   ArrayRef<ParsedType> DynamicExceptions,
12697                                   ArrayRef<SourceRange> DynamicExceptionRanges,
12698                                   Expr *NoexceptExpr,
12699                                   SmallVectorImpl<QualType> &Exceptions,
12700                                   FunctionProtoType::ExtProtoInfo &EPI) {
12701   Exceptions.clear();
12702   EPI.ExceptionSpecType = EST;
12703   if (EST == EST_Dynamic) {
12704     Exceptions.reserve(DynamicExceptions.size());
12705     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12706       // FIXME: Preserve type source info.
12707       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12708 
12709       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12710       collectUnexpandedParameterPacks(ET, Unexpanded);
12711       if (!Unexpanded.empty()) {
12712         DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12713                                          UPPC_ExceptionType,
12714                                          Unexpanded);
12715         continue;
12716       }
12717 
12718       // Check that the type is valid for an exception spec, and
12719       // drop it if not.
12720       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12721         Exceptions.push_back(ET);
12722     }
12723     EPI.NumExceptions = Exceptions.size();
12724     EPI.Exceptions = Exceptions.data();
12725     return;
12726   }
12727 
12728   if (EST == EST_ComputedNoexcept) {
12729     // If an error occurred, there's no expression here.
12730     if (NoexceptExpr) {
12731       assert((NoexceptExpr->isTypeDependent() ||
12732               NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12733               Context.BoolTy) &&
12734              "Parser should have made sure that the expression is boolean");
12735       if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12736         EPI.ExceptionSpecType = EST_BasicNoexcept;
12737         return;
12738       }
12739 
12740       if (!NoexceptExpr->isValueDependent())
12741         NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
12742                          diag::err_noexcept_needs_constant_expression,
12743                          /*AllowFold*/ false).take();
12744       EPI.NoexceptExpr = NoexceptExpr;
12745     }
12746     return;
12747   }
12748 }
12749 
12750 /// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12751 Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12752   // Implicitly declared functions (e.g. copy constructors) are
12753   // __host__ __device__
12754   if (D->isImplicit())
12755     return CFT_HostDevice;
12756 
12757   if (D->hasAttr<CUDAGlobalAttr>())
12758     return CFT_Global;
12759 
12760   if (D->hasAttr<CUDADeviceAttr>()) {
12761     if (D->hasAttr<CUDAHostAttr>())
12762       return CFT_HostDevice;
12763     return CFT_Device;
12764   }
12765 
12766   return CFT_Host;
12767 }
12768 
12769 bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12770                            CUDAFunctionTarget CalleeTarget) {
12771   // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12772   // Callable from the device only."
12773   if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12774     return true;
12775 
12776   // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12777   // Callable from the host only."
12778   // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12779   // Callable from the host only."
12780   if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12781       (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12782     return true;
12783 
12784   if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12785     return true;
12786 
12787   return false;
12788 }
12789 
12790 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12791 ///
12792 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12793                                        SourceLocation DeclStart,
12794                                        Declarator &D, Expr *BitWidth,
12795                                        InClassInitStyle InitStyle,
12796                                        AccessSpecifier AS,
12797                                        AttributeList *MSPropertyAttr) {
12798   IdentifierInfo *II = D.getIdentifier();
12799   if (!II) {
12800     Diag(DeclStart, diag::err_anonymous_property);
12801     return NULL;
12802   }
12803   SourceLocation Loc = D.getIdentifierLoc();
12804 
12805   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12806   QualType T = TInfo->getType();
12807   if (getLangOpts().CPlusPlus) {
12808     CheckExtraCXXDefaultArguments(D);
12809 
12810     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12811                                         UPPC_DataMemberType)) {
12812       D.setInvalidType();
12813       T = Context.IntTy;
12814       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12815     }
12816   }
12817 
12818   DiagnoseFunctionSpecifiers(D.getDeclSpec());
12819 
12820   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12821     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12822          diag::err_invalid_thread)
12823       << DeclSpec::getSpecifierName(TSCS);
12824 
12825   // Check to see if this name was declared as a member previously
12826   NamedDecl *PrevDecl = 0;
12827   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12828   LookupName(Previous, S);
12829   switch (Previous.getResultKind()) {
12830   case LookupResult::Found:
12831   case LookupResult::FoundUnresolvedValue:
12832     PrevDecl = Previous.getAsSingle<NamedDecl>();
12833     break;
12834 
12835   case LookupResult::FoundOverloaded:
12836     PrevDecl = Previous.getRepresentativeDecl();
12837     break;
12838 
12839   case LookupResult::NotFound:
12840   case LookupResult::NotFoundInCurrentInstantiation:
12841   case LookupResult::Ambiguous:
12842     break;
12843   }
12844 
12845   if (PrevDecl && PrevDecl->isTemplateParameter()) {
12846     // Maybe we will complain about the shadowed template parameter.
12847     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12848     // Just pretend that we didn't see the previous declaration.
12849     PrevDecl = 0;
12850   }
12851 
12852   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12853     PrevDecl = 0;
12854 
12855   SourceLocation TSSL = D.getLocStart();
12856   const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12857   MSPropertyDecl *NewPD = MSPropertyDecl::Create(
12858       Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
12859   ProcessDeclAttributes(TUScope, NewPD, D);
12860   NewPD->setAccess(AS);
12861 
12862   if (NewPD->isInvalidDecl())
12863     Record->setInvalidDecl();
12864 
12865   if (D.getDeclSpec().isModulePrivateSpecified())
12866     NewPD->setModulePrivate();
12867 
12868   if (NewPD->isInvalidDecl() && PrevDecl) {
12869     // Don't introduce NewFD into scope; there's already something
12870     // with the same name in the same scope.
12871   } else if (II) {
12872     PushOnScopeChains(NewPD, S);
12873   } else
12874     Record->addDecl(NewPD);
12875 
12876   return NewPD;
12877 }
12878