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   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
588   // template has a constexpr specifier then all its declarations shall
589   // contain the constexpr specifier.
590   if (New->isConstexpr() != Old->isConstexpr()) {
591     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
592       << New << New->isConstexpr();
593     Diag(Old->getLocation(), diag::note_previous_declaration);
594     Invalid = true;
595   }
596 
597   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
598   // argument expression, that declaration shall be a definition and shall be
599   // the only declaration of the function or function template in the
600   // translation unit.
601   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
602       functionDeclHasDefaultArgument(Old)) {
603     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
604     Diag(Old->getLocation(), diag::note_previous_declaration);
605     Invalid = true;
606   }
607 
608   if (CheckEquivalentExceptionSpec(Old, New))
609     Invalid = true;
610 
611   return Invalid;
612 }
613 
614 /// \brief Merge the exception specifications of two variable declarations.
615 ///
616 /// This is called when there's a redeclaration of a VarDecl. The function
617 /// checks if the redeclaration might have an exception specification and
618 /// validates compatibility and merges the specs if necessary.
619 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
620   // Shortcut if exceptions are disabled.
621   if (!getLangOpts().CXXExceptions)
622     return;
623 
624   assert(Context.hasSameType(New->getType(), Old->getType()) &&
625          "Should only be called if types are otherwise the same.");
626 
627   QualType NewType = New->getType();
628   QualType OldType = Old->getType();
629 
630   // We're only interested in pointers and references to functions, as well
631   // as pointers to member functions.
632   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
633     NewType = R->getPointeeType();
634     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
635   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
636     NewType = P->getPointeeType();
637     OldType = OldType->getAs<PointerType>()->getPointeeType();
638   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
639     NewType = M->getPointeeType();
640     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
641   }
642 
643   if (!NewType->isFunctionProtoType())
644     return;
645 
646   // There's lots of special cases for functions. For function pointers, system
647   // libraries are hopefully not as broken so that we don't need these
648   // workarounds.
649   if (CheckEquivalentExceptionSpec(
650         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
651         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
652     New->setInvalidDecl();
653   }
654 }
655 
656 /// CheckCXXDefaultArguments - Verify that the default arguments for a
657 /// function declaration are well-formed according to C++
658 /// [dcl.fct.default].
659 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
660   unsigned NumParams = FD->getNumParams();
661   unsigned p;
662 
663   // Find first parameter with a default argument
664   for (p = 0; p < NumParams; ++p) {
665     ParmVarDecl *Param = FD->getParamDecl(p);
666     if (Param->hasDefaultArg())
667       break;
668   }
669 
670   // C++ [dcl.fct.default]p4:
671   //   In a given function declaration, all parameters
672   //   subsequent to a parameter with a default argument shall
673   //   have default arguments supplied in this or previous
674   //   declarations. A default argument shall not be redefined
675   //   by a later declaration (not even to the same value).
676   unsigned LastMissingDefaultArg = 0;
677   for (; p < NumParams; ++p) {
678     ParmVarDecl *Param = FD->getParamDecl(p);
679     if (!Param->hasDefaultArg()) {
680       if (Param->isInvalidDecl())
681         /* We already complained about this parameter. */;
682       else if (Param->getIdentifier())
683         Diag(Param->getLocation(),
684              diag::err_param_default_argument_missing_name)
685           << Param->getIdentifier();
686       else
687         Diag(Param->getLocation(),
688              diag::err_param_default_argument_missing);
689 
690       LastMissingDefaultArg = p;
691     }
692   }
693 
694   if (LastMissingDefaultArg > 0) {
695     // Some default arguments were missing. Clear out all of the
696     // default arguments up to (and including) the last missing
697     // default argument, so that we leave the function parameters
698     // in a semantically valid state.
699     for (p = 0; p <= LastMissingDefaultArg; ++p) {
700       ParmVarDecl *Param = FD->getParamDecl(p);
701       if (Param->hasDefaultArg()) {
702         Param->setDefaultArg(0);
703       }
704     }
705   }
706 }
707 
708 // CheckConstexprParameterTypes - Check whether a function's parameter types
709 // are all literal types. If so, return true. If not, produce a suitable
710 // diagnostic and return false.
711 static bool CheckConstexprParameterTypes(Sema &SemaRef,
712                                          const FunctionDecl *FD) {
713   unsigned ArgIndex = 0;
714   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
715   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
716                                               e = FT->param_type_end();
717        i != e; ++i, ++ArgIndex) {
718     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
719     SourceLocation ParamLoc = PD->getLocation();
720     if (!(*i)->isDependentType() &&
721         SemaRef.RequireLiteralType(ParamLoc, *i,
722                                    diag::err_constexpr_non_literal_param,
723                                    ArgIndex+1, PD->getSourceRange(),
724                                    isa<CXXConstructorDecl>(FD)))
725       return false;
726   }
727   return true;
728 }
729 
730 /// \brief Get diagnostic %select index for tag kind for
731 /// record diagnostic message.
732 /// WARNING: Indexes apply to particular diagnostics only!
733 ///
734 /// \returns diagnostic %select index.
735 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
736   switch (Tag) {
737   case TTK_Struct: return 0;
738   case TTK_Interface: return 1;
739   case TTK_Class:  return 2;
740   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
741   }
742 }
743 
744 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
745 // the requirements of a constexpr function definition or a constexpr
746 // constructor definition. If so, return true. If not, produce appropriate
747 // diagnostics and return false.
748 //
749 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
750 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
751   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
752   if (MD && MD->isInstance()) {
753     // C++11 [dcl.constexpr]p4:
754     //  The definition of a constexpr constructor shall satisfy the following
755     //  constraints:
756     //  - the class shall not have any virtual base classes;
757     const CXXRecordDecl *RD = MD->getParent();
758     if (RD->getNumVBases()) {
759       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
760         << isa<CXXConstructorDecl>(NewFD)
761         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
762       for (const auto &I : RD->vbases())
763         Diag(I.getLocStart(),
764              diag::note_constexpr_virtual_base_here) << I.getSourceRange();
765       return false;
766     }
767   }
768 
769   if (!isa<CXXConstructorDecl>(NewFD)) {
770     // C++11 [dcl.constexpr]p3:
771     //  The definition of a constexpr function shall satisfy the following
772     //  constraints:
773     // - it shall not be virtual;
774     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
775     if (Method && Method->isVirtual()) {
776       Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
777 
778       // If it's not obvious why this function is virtual, find an overridden
779       // function which uses the 'virtual' keyword.
780       const CXXMethodDecl *WrittenVirtual = Method;
781       while (!WrittenVirtual->isVirtualAsWritten())
782         WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
783       if (WrittenVirtual != Method)
784         Diag(WrittenVirtual->getLocation(),
785              diag::note_overridden_virtual_function);
786       return false;
787     }
788 
789     // - its return type shall be a literal type;
790     QualType RT = NewFD->getReturnType();
791     if (!RT->isDependentType() &&
792         RequireLiteralType(NewFD->getLocation(), RT,
793                            diag::err_constexpr_non_literal_return))
794       return false;
795   }
796 
797   // - each of its parameter types shall be a literal type;
798   if (!CheckConstexprParameterTypes(*this, NewFD))
799     return false;
800 
801   return true;
802 }
803 
804 /// Check the given declaration statement is legal within a constexpr function
805 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
806 ///
807 /// \return true if the body is OK (maybe only as an extension), false if we
808 ///         have diagnosed a problem.
809 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
810                                    DeclStmt *DS, SourceLocation &Cxx1yLoc) {
811   // C++11 [dcl.constexpr]p3 and p4:
812   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
813   //  contain only
814   for (const auto *DclIt : DS->decls()) {
815     switch (DclIt->getKind()) {
816     case Decl::StaticAssert:
817     case Decl::Using:
818     case Decl::UsingShadow:
819     case Decl::UsingDirective:
820     case Decl::UnresolvedUsingTypename:
821     case Decl::UnresolvedUsingValue:
822       //   - static_assert-declarations
823       //   - using-declarations,
824       //   - using-directives,
825       continue;
826 
827     case Decl::Typedef:
828     case Decl::TypeAlias: {
829       //   - typedef declarations and alias-declarations that do not define
830       //     classes or enumerations,
831       const auto *TN = cast<TypedefNameDecl>(DclIt);
832       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
833         // Don't allow variably-modified types in constexpr functions.
834         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
835         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
836           << TL.getSourceRange() << TL.getType()
837           << isa<CXXConstructorDecl>(Dcl);
838         return false;
839       }
840       continue;
841     }
842 
843     case Decl::Enum:
844     case Decl::CXXRecord:
845       // C++1y allows types to be defined, not just declared.
846       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
847         SemaRef.Diag(DS->getLocStart(),
848                      SemaRef.getLangOpts().CPlusPlus1y
849                        ? diag::warn_cxx11_compat_constexpr_type_definition
850                        : diag::ext_constexpr_type_definition)
851           << isa<CXXConstructorDecl>(Dcl);
852       continue;
853 
854     case Decl::EnumConstant:
855     case Decl::IndirectField:
856     case Decl::ParmVar:
857       // These can only appear with other declarations which are banned in
858       // C++11 and permitted in C++1y, so ignore them.
859       continue;
860 
861     case Decl::Var: {
862       // C++1y [dcl.constexpr]p3 allows anything except:
863       //   a definition of a variable of non-literal type or of static or
864       //   thread storage duration or for which no initialization is performed.
865       const auto *VD = cast<VarDecl>(DclIt);
866       if (VD->isThisDeclarationADefinition()) {
867         if (VD->isStaticLocal()) {
868           SemaRef.Diag(VD->getLocation(),
869                        diag::err_constexpr_local_var_static)
870             << isa<CXXConstructorDecl>(Dcl)
871             << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
872           return false;
873         }
874         if (!VD->getType()->isDependentType() &&
875             SemaRef.RequireLiteralType(
876               VD->getLocation(), VD->getType(),
877               diag::err_constexpr_local_var_non_literal_type,
878               isa<CXXConstructorDecl>(Dcl)))
879           return false;
880         if (!VD->getType()->isDependentType() &&
881             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
882           SemaRef.Diag(VD->getLocation(),
883                        diag::err_constexpr_local_var_no_init)
884             << isa<CXXConstructorDecl>(Dcl);
885           return false;
886         }
887       }
888       SemaRef.Diag(VD->getLocation(),
889                    SemaRef.getLangOpts().CPlusPlus1y
890                     ? diag::warn_cxx11_compat_constexpr_local_var
891                     : diag::ext_constexpr_local_var)
892         << isa<CXXConstructorDecl>(Dcl);
893       continue;
894     }
895 
896     case Decl::NamespaceAlias:
897     case Decl::Function:
898       // These are disallowed in C++11 and permitted in C++1y. Allow them
899       // everywhere as an extension.
900       if (!Cxx1yLoc.isValid())
901         Cxx1yLoc = DS->getLocStart();
902       continue;
903 
904     default:
905       SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
906         << isa<CXXConstructorDecl>(Dcl);
907       return false;
908     }
909   }
910 
911   return true;
912 }
913 
914 /// Check that the given field is initialized within a constexpr constructor.
915 ///
916 /// \param Dcl The constexpr constructor being checked.
917 /// \param Field The field being checked. This may be a member of an anonymous
918 ///        struct or union nested within the class being checked.
919 /// \param Inits All declarations, including anonymous struct/union members and
920 ///        indirect members, for which any initialization was provided.
921 /// \param Diagnosed Set to true if an error is produced.
922 static void CheckConstexprCtorInitializer(Sema &SemaRef,
923                                           const FunctionDecl *Dcl,
924                                           FieldDecl *Field,
925                                           llvm::SmallSet<Decl*, 16> &Inits,
926                                           bool &Diagnosed) {
927   if (Field->isInvalidDecl())
928     return;
929 
930   if (Field->isUnnamedBitfield())
931     return;
932 
933   // Anonymous unions with no variant members and empty anonymous structs do not
934   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
935   // indirect fields don't need initializing.
936   if (Field->isAnonymousStructOrUnion() &&
937       (Field->getType()->isUnionType()
938            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
939            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
940     return;
941 
942   if (!Inits.count(Field)) {
943     if (!Diagnosed) {
944       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
945       Diagnosed = true;
946     }
947     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
948   } else if (Field->isAnonymousStructOrUnion()) {
949     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
950     for (auto *I : RD->fields())
951       // If an anonymous union contains an anonymous struct of which any member
952       // is initialized, all members must be initialized.
953       if (!RD->isUnion() || Inits.count(I))
954         CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
955   }
956 }
957 
958 /// Check the provided statement is allowed in a constexpr function
959 /// definition.
960 static bool
961 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
962                            SmallVectorImpl<SourceLocation> &ReturnStmts,
963                            SourceLocation &Cxx1yLoc) {
964   // - its function-body shall be [...] a compound-statement that contains only
965   switch (S->getStmtClass()) {
966   case Stmt::NullStmtClass:
967     //   - null statements,
968     return true;
969 
970   case Stmt::DeclStmtClass:
971     //   - static_assert-declarations
972     //   - using-declarations,
973     //   - using-directives,
974     //   - typedef declarations and alias-declarations that do not define
975     //     classes or enumerations,
976     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
977       return false;
978     return true;
979 
980   case Stmt::ReturnStmtClass:
981     //   - and exactly one return statement;
982     if (isa<CXXConstructorDecl>(Dcl)) {
983       // C++1y allows return statements in constexpr constructors.
984       if (!Cxx1yLoc.isValid())
985         Cxx1yLoc = S->getLocStart();
986       return true;
987     }
988 
989     ReturnStmts.push_back(S->getLocStart());
990     return true;
991 
992   case Stmt::CompoundStmtClass: {
993     // C++1y allows compound-statements.
994     if (!Cxx1yLoc.isValid())
995       Cxx1yLoc = S->getLocStart();
996 
997     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
998     for (auto *BodyIt : CompStmt->body()) {
999       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1000                                       Cxx1yLoc))
1001         return false;
1002     }
1003     return true;
1004   }
1005 
1006   case Stmt::AttributedStmtClass:
1007     if (!Cxx1yLoc.isValid())
1008       Cxx1yLoc = S->getLocStart();
1009     return true;
1010 
1011   case Stmt::IfStmtClass: {
1012     // C++1y allows if-statements.
1013     if (!Cxx1yLoc.isValid())
1014       Cxx1yLoc = S->getLocStart();
1015 
1016     IfStmt *If = cast<IfStmt>(S);
1017     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1018                                     Cxx1yLoc))
1019       return false;
1020     if (If->getElse() &&
1021         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1022                                     Cxx1yLoc))
1023       return false;
1024     return true;
1025   }
1026 
1027   case Stmt::WhileStmtClass:
1028   case Stmt::DoStmtClass:
1029   case Stmt::ForStmtClass:
1030   case Stmt::CXXForRangeStmtClass:
1031   case Stmt::ContinueStmtClass:
1032     // C++1y allows all of these. We don't allow them as extensions in C++11,
1033     // because they don't make sense without variable mutation.
1034     if (!SemaRef.getLangOpts().CPlusPlus1y)
1035       break;
1036     if (!Cxx1yLoc.isValid())
1037       Cxx1yLoc = S->getLocStart();
1038     for (Stmt::child_range Children = S->children(); Children; ++Children)
1039       if (*Children &&
1040           !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1041                                       Cxx1yLoc))
1042         return false;
1043     return true;
1044 
1045   case Stmt::SwitchStmtClass:
1046   case Stmt::CaseStmtClass:
1047   case Stmt::DefaultStmtClass:
1048   case Stmt::BreakStmtClass:
1049     // C++1y allows switch-statements, and since they don't need variable
1050     // mutation, we can reasonably allow them in C++11 as an extension.
1051     if (!Cxx1yLoc.isValid())
1052       Cxx1yLoc = S->getLocStart();
1053     for (Stmt::child_range Children = S->children(); Children; ++Children)
1054       if (*Children &&
1055           !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1056                                       Cxx1yLoc))
1057         return false;
1058     return true;
1059 
1060   default:
1061     if (!isa<Expr>(S))
1062       break;
1063 
1064     // C++1y allows expression-statements.
1065     if (!Cxx1yLoc.isValid())
1066       Cxx1yLoc = S->getLocStart();
1067     return true;
1068   }
1069 
1070   SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1071     << isa<CXXConstructorDecl>(Dcl);
1072   return false;
1073 }
1074 
1075 /// Check the body for the given constexpr function declaration only contains
1076 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1077 ///
1078 /// \return true if the body is OK, false if we have diagnosed a problem.
1079 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1080   if (isa<CXXTryStmt>(Body)) {
1081     // C++11 [dcl.constexpr]p3:
1082     //  The definition of a constexpr function shall satisfy the following
1083     //  constraints: [...]
1084     // - its function-body shall be = delete, = default, or a
1085     //   compound-statement
1086     //
1087     // C++11 [dcl.constexpr]p4:
1088     //  In the definition of a constexpr constructor, [...]
1089     // - its function-body shall not be a function-try-block;
1090     Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1091       << isa<CXXConstructorDecl>(Dcl);
1092     return false;
1093   }
1094 
1095   SmallVector<SourceLocation, 4> ReturnStmts;
1096 
1097   // - its function-body shall be [...] a compound-statement that contains only
1098   //   [... list of cases ...]
1099   CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1100   SourceLocation Cxx1yLoc;
1101   for (auto *BodyIt : CompBody->body()) {
1102     if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
1103       return false;
1104   }
1105 
1106   if (Cxx1yLoc.isValid())
1107     Diag(Cxx1yLoc,
1108          getLangOpts().CPlusPlus1y
1109            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1110            : diag::ext_constexpr_body_invalid_stmt)
1111       << isa<CXXConstructorDecl>(Dcl);
1112 
1113   if (const CXXConstructorDecl *Constructor
1114         = dyn_cast<CXXConstructorDecl>(Dcl)) {
1115     const CXXRecordDecl *RD = Constructor->getParent();
1116     // DR1359:
1117     // - every non-variant non-static data member and base class sub-object
1118     //   shall be initialized;
1119     // DR1460:
1120     // - if the class is a union having variant members, exactly one of them
1121     //   shall be initialized;
1122     if (RD->isUnion()) {
1123       if (Constructor->getNumCtorInitializers() == 0 &&
1124           RD->hasVariantMembers()) {
1125         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1126         return false;
1127       }
1128     } else if (!Constructor->isDependentContext() &&
1129                !Constructor->isDelegatingConstructor()) {
1130       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1131 
1132       // Skip detailed checking if we have enough initializers, and we would
1133       // allow at most one initializer per member.
1134       bool AnyAnonStructUnionMembers = false;
1135       unsigned Fields = 0;
1136       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1137            E = RD->field_end(); I != E; ++I, ++Fields) {
1138         if (I->isAnonymousStructOrUnion()) {
1139           AnyAnonStructUnionMembers = true;
1140           break;
1141         }
1142       }
1143       // DR1460:
1144       // - if the class is a union-like class, but is not a union, for each of
1145       //   its anonymous union members having variant members, exactly one of
1146       //   them shall be initialized;
1147       if (AnyAnonStructUnionMembers ||
1148           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1149         // Check initialization of non-static data members. Base classes are
1150         // always initialized so do not need to be checked. Dependent bases
1151         // might not have initializers in the member initializer list.
1152         llvm::SmallSet<Decl*, 16> Inits;
1153         for (const auto *I: Constructor->inits()) {
1154           if (FieldDecl *FD = I->getMember())
1155             Inits.insert(FD);
1156           else if (IndirectFieldDecl *ID = I->getIndirectMember())
1157             Inits.insert(ID->chain_begin(), ID->chain_end());
1158         }
1159 
1160         bool Diagnosed = false;
1161         for (auto *I : RD->fields())
1162           CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
1163         if (Diagnosed)
1164           return false;
1165       }
1166     }
1167   } else {
1168     if (ReturnStmts.empty()) {
1169       // C++1y doesn't require constexpr functions to contain a 'return'
1170       // statement. We still do, unless the return type is void, because
1171       // otherwise if there's no return statement, the function cannot
1172       // be used in a core constant expression.
1173       bool OK = getLangOpts().CPlusPlus1y && Dcl->getReturnType()->isVoidType();
1174       Diag(Dcl->getLocation(),
1175            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1176               : diag::err_constexpr_body_no_return);
1177       return OK;
1178     }
1179     if (ReturnStmts.size() > 1) {
1180       Diag(ReturnStmts.back(),
1181            getLangOpts().CPlusPlus1y
1182              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1183              : diag::ext_constexpr_body_multiple_return);
1184       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1185         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
1186     }
1187   }
1188 
1189   // C++11 [dcl.constexpr]p5:
1190   //   if no function argument values exist such that the function invocation
1191   //   substitution would produce a constant expression, the program is
1192   //   ill-formed; no diagnostic required.
1193   // C++11 [dcl.constexpr]p3:
1194   //   - every constructor call and implicit conversion used in initializing the
1195   //     return value shall be one of those allowed in a constant expression.
1196   // C++11 [dcl.constexpr]p4:
1197   //   - every constructor involved in initializing non-static data members and
1198   //     base class sub-objects shall be a constexpr constructor.
1199   SmallVector<PartialDiagnosticAt, 8> Diags;
1200   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
1201     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
1202       << isa<CXXConstructorDecl>(Dcl);
1203     for (size_t I = 0, N = Diags.size(); I != N; ++I)
1204       Diag(Diags[I].first, Diags[I].second);
1205     // Don't return false here: we allow this for compatibility in
1206     // system headers.
1207   }
1208 
1209   return true;
1210 }
1211 
1212 /// isCurrentClassName - Determine whether the identifier II is the
1213 /// name of the class type currently being defined. In the case of
1214 /// nested classes, this will only return true if II is the name of
1215 /// the innermost class.
1216 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1217                               const CXXScopeSpec *SS) {
1218   assert(getLangOpts().CPlusPlus && "No class names in C!");
1219 
1220   CXXRecordDecl *CurDecl;
1221   if (SS && SS->isSet() && !SS->isInvalid()) {
1222     DeclContext *DC = computeDeclContext(*SS, true);
1223     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1224   } else
1225     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1226 
1227   if (CurDecl && CurDecl->getIdentifier())
1228     return &II == CurDecl->getIdentifier();
1229   return false;
1230 }
1231 
1232 /// \brief Determine whether the identifier II is a typo for the name of
1233 /// the class type currently being defined. If so, update it to the identifier
1234 /// that should have been used.
1235 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1236   assert(getLangOpts().CPlusPlus && "No class names in C!");
1237 
1238   if (!getLangOpts().SpellChecking)
1239     return false;
1240 
1241   CXXRecordDecl *CurDecl;
1242   if (SS && SS->isSet() && !SS->isInvalid()) {
1243     DeclContext *DC = computeDeclContext(*SS, true);
1244     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1245   } else
1246     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1247 
1248   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1249       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1250           < II->getLength()) {
1251     II = CurDecl->getIdentifier();
1252     return true;
1253   }
1254 
1255   return false;
1256 }
1257 
1258 /// \brief Determine whether the given class is a base class of the given
1259 /// class, including looking at dependent bases.
1260 static bool findCircularInheritance(const CXXRecordDecl *Class,
1261                                     const CXXRecordDecl *Current) {
1262   SmallVector<const CXXRecordDecl*, 8> Queue;
1263 
1264   Class = Class->getCanonicalDecl();
1265   while (true) {
1266     for (const auto &I : Current->bases()) {
1267       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
1268       if (!Base)
1269         continue;
1270 
1271       Base = Base->getDefinition();
1272       if (!Base)
1273         continue;
1274 
1275       if (Base->getCanonicalDecl() == Class)
1276         return true;
1277 
1278       Queue.push_back(Base);
1279     }
1280 
1281     if (Queue.empty())
1282       return false;
1283 
1284     Current = Queue.pop_back_val();
1285   }
1286 
1287   return false;
1288 }
1289 
1290 /// \brief Check the validity of a C++ base class specifier.
1291 ///
1292 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1293 /// and returns NULL otherwise.
1294 CXXBaseSpecifier *
1295 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1296                          SourceRange SpecifierRange,
1297                          bool Virtual, AccessSpecifier Access,
1298                          TypeSourceInfo *TInfo,
1299                          SourceLocation EllipsisLoc) {
1300   QualType BaseType = TInfo->getType();
1301 
1302   // C++ [class.union]p1:
1303   //   A union shall not have base classes.
1304   if (Class->isUnion()) {
1305     Diag(Class->getLocation(), diag::err_base_clause_on_union)
1306       << SpecifierRange;
1307     return 0;
1308   }
1309 
1310   if (EllipsisLoc.isValid() &&
1311       !TInfo->getType()->containsUnexpandedParameterPack()) {
1312     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1313       << TInfo->getTypeLoc().getSourceRange();
1314     EllipsisLoc = SourceLocation();
1315   }
1316 
1317   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1318 
1319   if (BaseType->isDependentType()) {
1320     // Make sure that we don't have circular inheritance among our dependent
1321     // bases. For non-dependent bases, the check for completeness below handles
1322     // this.
1323     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1324       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1325           ((BaseDecl = BaseDecl->getDefinition()) &&
1326            findCircularInheritance(Class, BaseDecl))) {
1327         Diag(BaseLoc, diag::err_circular_inheritance)
1328           << BaseType << Context.getTypeDeclType(Class);
1329 
1330         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1331           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1332             << BaseType;
1333 
1334         return 0;
1335       }
1336     }
1337 
1338     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1339                                           Class->getTagKind() == TTK_Class,
1340                                           Access, TInfo, EllipsisLoc);
1341   }
1342 
1343   // Base specifiers must be record types.
1344   if (!BaseType->isRecordType()) {
1345     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1346     return 0;
1347   }
1348 
1349   // C++ [class.union]p1:
1350   //   A union shall not be used as a base class.
1351   if (BaseType->isUnionType()) {
1352     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1353     return 0;
1354   }
1355 
1356   // C++ [class.derived]p2:
1357   //   The class-name in a base-specifier shall not be an incompletely
1358   //   defined class.
1359   if (RequireCompleteType(BaseLoc, BaseType,
1360                           diag::err_incomplete_base_class, SpecifierRange)) {
1361     Class->setInvalidDecl();
1362     return 0;
1363   }
1364 
1365   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1366   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1367   assert(BaseDecl && "Record type has no declaration");
1368   BaseDecl = BaseDecl->getDefinition();
1369   assert(BaseDecl && "Base type is not incomplete, but has no definition");
1370   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1371   assert(CXXBaseDecl && "Base type is not a C++ type");
1372 
1373   // A class which contains a flexible array member is not suitable for use as a
1374   // base class:
1375   //   - If the layout determines that a base comes before another base,
1376   //     the flexible array member would index into the subsequent base.
1377   //   - If the layout determines that base comes before the derived class,
1378   //     the flexible array member would index into the derived class.
1379   if (CXXBaseDecl->hasFlexibleArrayMember()) {
1380     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1381       << CXXBaseDecl->getDeclName();
1382     return 0;
1383   }
1384 
1385   // C++ [class]p3:
1386   //   If a class is marked final and it appears as a base-type-specifier in
1387   //   base-clause, the program is ill-formed.
1388   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
1389     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1390       << CXXBaseDecl->getDeclName()
1391       << FA->isSpelledAsSealed();
1392     Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1393       << CXXBaseDecl->getDeclName();
1394     return 0;
1395   }
1396 
1397   if (BaseDecl->isInvalidDecl())
1398     Class->setInvalidDecl();
1399 
1400   // Create the base specifier.
1401   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1402                                         Class->getTagKind() == TTK_Class,
1403                                         Access, TInfo, EllipsisLoc);
1404 }
1405 
1406 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1407 /// one entry in the base class list of a class specifier, for
1408 /// example:
1409 ///    class foo : public bar, virtual private baz {
1410 /// 'public bar' and 'virtual private baz' are each base-specifiers.
1411 BaseResult
1412 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1413                          ParsedAttributes &Attributes,
1414                          bool Virtual, AccessSpecifier Access,
1415                          ParsedType basetype, SourceLocation BaseLoc,
1416                          SourceLocation EllipsisLoc) {
1417   if (!classdecl)
1418     return true;
1419 
1420   AdjustDeclIfTemplate(classdecl);
1421   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1422   if (!Class)
1423     return true;
1424 
1425   // We do not support any C++11 attributes on base-specifiers yet.
1426   // Diagnose any attributes we see.
1427   if (!Attributes.empty()) {
1428     for (AttributeList *Attr = Attributes.getList(); Attr;
1429          Attr = Attr->getNext()) {
1430       if (Attr->isInvalid() ||
1431           Attr->getKind() == AttributeList::IgnoredAttribute)
1432         continue;
1433       Diag(Attr->getLoc(),
1434            Attr->getKind() == AttributeList::UnknownAttribute
1435              ? diag::warn_unknown_attribute_ignored
1436              : diag::err_base_specifier_attribute)
1437         << Attr->getName();
1438     }
1439   }
1440 
1441   TypeSourceInfo *TInfo = 0;
1442   GetTypeFromParser(basetype, &TInfo);
1443 
1444   if (EllipsisLoc.isInvalid() &&
1445       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1446                                       UPPC_BaseType))
1447     return true;
1448 
1449   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1450                                                       Virtual, Access, TInfo,
1451                                                       EllipsisLoc))
1452     return BaseSpec;
1453   else
1454     Class->setInvalidDecl();
1455 
1456   return true;
1457 }
1458 
1459 /// \brief Performs the actual work of attaching the given base class
1460 /// specifiers to a C++ class.
1461 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1462                                 unsigned NumBases) {
1463  if (NumBases == 0)
1464     return false;
1465 
1466   // Used to keep track of which base types we have already seen, so
1467   // that we can properly diagnose redundant direct base types. Note
1468   // that the key is always the unqualified canonical type of the base
1469   // class.
1470   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1471 
1472   // Copy non-redundant base specifiers into permanent storage.
1473   unsigned NumGoodBases = 0;
1474   bool Invalid = false;
1475   for (unsigned idx = 0; idx < NumBases; ++idx) {
1476     QualType NewBaseType
1477       = Context.getCanonicalType(Bases[idx]->getType());
1478     NewBaseType = NewBaseType.getLocalUnqualifiedType();
1479 
1480     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1481     if (KnownBase) {
1482       // C++ [class.mi]p3:
1483       //   A class shall not be specified as a direct base class of a
1484       //   derived class more than once.
1485       Diag(Bases[idx]->getLocStart(),
1486            diag::err_duplicate_base_class)
1487         << KnownBase->getType()
1488         << Bases[idx]->getSourceRange();
1489 
1490       // Delete the duplicate base class specifier; we're going to
1491       // overwrite its pointer later.
1492       Context.Deallocate(Bases[idx]);
1493 
1494       Invalid = true;
1495     } else {
1496       // Okay, add this new base class.
1497       KnownBase = Bases[idx];
1498       Bases[NumGoodBases++] = Bases[idx];
1499       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1500         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1501         if (Class->isInterface() &&
1502               (!RD->isInterface() ||
1503                KnownBase->getAccessSpecifier() != AS_public)) {
1504           // The Microsoft extension __interface does not permit bases that
1505           // are not themselves public interfaces.
1506           Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1507             << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1508             << RD->getSourceRange();
1509           Invalid = true;
1510         }
1511         if (RD->hasAttr<WeakAttr>())
1512           Class->addAttr(WeakAttr::CreateImplicit(Context));
1513       }
1514     }
1515   }
1516 
1517   // Attach the remaining base class specifiers to the derived class.
1518   Class->setBases(Bases, NumGoodBases);
1519 
1520   // Delete the remaining (good) base class specifiers, since their
1521   // data has been copied into the CXXRecordDecl.
1522   for (unsigned idx = 0; idx < NumGoodBases; ++idx)
1523     Context.Deallocate(Bases[idx]);
1524 
1525   return Invalid;
1526 }
1527 
1528 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
1529 /// class, after checking whether there are any duplicate base
1530 /// classes.
1531 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
1532                                unsigned NumBases) {
1533   if (!ClassDecl || !Bases || !NumBases)
1534     return;
1535 
1536   AdjustDeclIfTemplate(ClassDecl);
1537   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
1538 }
1539 
1540 /// \brief Determine whether the type \p Derived is a C++ class that is
1541 /// derived from the type \p Base.
1542 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1543   if (!getLangOpts().CPlusPlus)
1544     return false;
1545 
1546   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1547   if (!DerivedRD)
1548     return false;
1549 
1550   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1551   if (!BaseRD)
1552     return false;
1553 
1554   // If either the base or the derived type is invalid, don't try to
1555   // check whether one is derived from the other.
1556   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1557     return false;
1558 
1559   // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
1560   return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
1561 }
1562 
1563 /// \brief Determine whether the type \p Derived is a C++ class that is
1564 /// derived from the type \p Base.
1565 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1566   if (!getLangOpts().CPlusPlus)
1567     return false;
1568 
1569   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1570   if (!DerivedRD)
1571     return false;
1572 
1573   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1574   if (!BaseRD)
1575     return false;
1576 
1577   return DerivedRD->isDerivedFrom(BaseRD, Paths);
1578 }
1579 
1580 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1581                               CXXCastPath &BasePathArray) {
1582   assert(BasePathArray.empty() && "Base path array must be empty!");
1583   assert(Paths.isRecordingPaths() && "Must record paths!");
1584 
1585   const CXXBasePath &Path = Paths.front();
1586 
1587   // We first go backward and check if we have a virtual base.
1588   // FIXME: It would be better if CXXBasePath had the base specifier for
1589   // the nearest virtual base.
1590   unsigned Start = 0;
1591   for (unsigned I = Path.size(); I != 0; --I) {
1592     if (Path[I - 1].Base->isVirtual()) {
1593       Start = I - 1;
1594       break;
1595     }
1596   }
1597 
1598   // Now add all bases.
1599   for (unsigned I = Start, E = Path.size(); I != E; ++I)
1600     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1601 }
1602 
1603 /// \brief Determine whether the given base path includes a virtual
1604 /// base class.
1605 bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1606   for (CXXCastPath::const_iterator B = BasePath.begin(),
1607                                 BEnd = BasePath.end();
1608        B != BEnd; ++B)
1609     if ((*B)->isVirtual())
1610       return true;
1611 
1612   return false;
1613 }
1614 
1615 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1616 /// conversion (where Derived and Base are class types) is
1617 /// well-formed, meaning that the conversion is unambiguous (and
1618 /// that all of the base classes are accessible). Returns true
1619 /// and emits a diagnostic if the code is ill-formed, returns false
1620 /// otherwise. Loc is the location where this routine should point to
1621 /// if there is an error, and Range is the source range to highlight
1622 /// if there is an error.
1623 bool
1624 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1625                                    unsigned InaccessibleBaseID,
1626                                    unsigned AmbigiousBaseConvID,
1627                                    SourceLocation Loc, SourceRange Range,
1628                                    DeclarationName Name,
1629                                    CXXCastPath *BasePath) {
1630   // First, determine whether the path from Derived to Base is
1631   // ambiguous. This is slightly more expensive than checking whether
1632   // the Derived to Base conversion exists, because here we need to
1633   // explore multiple paths to determine if there is an ambiguity.
1634   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1635                      /*DetectVirtual=*/false);
1636   bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1637   assert(DerivationOkay &&
1638          "Can only be used with a derived-to-base conversion");
1639   (void)DerivationOkay;
1640 
1641   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1642     if (InaccessibleBaseID) {
1643       // Check that the base class can be accessed.
1644       switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1645                                    InaccessibleBaseID)) {
1646         case AR_inaccessible:
1647           return true;
1648         case AR_accessible:
1649         case AR_dependent:
1650         case AR_delayed:
1651           break;
1652       }
1653     }
1654 
1655     // Build a base path if necessary.
1656     if (BasePath)
1657       BuildBasePathArray(Paths, *BasePath);
1658     return false;
1659   }
1660 
1661   if (AmbigiousBaseConvID) {
1662     // We know that the derived-to-base conversion is ambiguous, and
1663     // we're going to produce a diagnostic. Perform the derived-to-base
1664     // search just one more time to compute all of the possible paths so
1665     // that we can print them out. This is more expensive than any of
1666     // the previous derived-to-base checks we've done, but at this point
1667     // performance isn't as much of an issue.
1668     Paths.clear();
1669     Paths.setRecordingPaths(true);
1670     bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1671     assert(StillOkay && "Can only be used with a derived-to-base conversion");
1672     (void)StillOkay;
1673 
1674     // Build up a textual representation of the ambiguous paths, e.g.,
1675     // D -> B -> A, that will be used to illustrate the ambiguous
1676     // conversions in the diagnostic. We only print one of the paths
1677     // to each base class subobject.
1678     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1679 
1680     Diag(Loc, AmbigiousBaseConvID)
1681     << Derived << Base << PathDisplayStr << Range << Name;
1682   }
1683   return true;
1684 }
1685 
1686 bool
1687 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1688                                    SourceLocation Loc, SourceRange Range,
1689                                    CXXCastPath *BasePath,
1690                                    bool IgnoreAccess) {
1691   return CheckDerivedToBaseConversion(Derived, Base,
1692                                       IgnoreAccess ? 0
1693                                        : diag::err_upcast_to_inaccessible_base,
1694                                       diag::err_ambiguous_derived_to_base_conv,
1695                                       Loc, Range, DeclarationName(),
1696                                       BasePath);
1697 }
1698 
1699 
1700 /// @brief Builds a string representing ambiguous paths from a
1701 /// specific derived class to different subobjects of the same base
1702 /// class.
1703 ///
1704 /// This function builds a string that can be used in error messages
1705 /// to show the different paths that one can take through the
1706 /// inheritance hierarchy to go from the derived class to different
1707 /// subobjects of a base class. The result looks something like this:
1708 /// @code
1709 /// struct D -> struct B -> struct A
1710 /// struct D -> struct C -> struct A
1711 /// @endcode
1712 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1713   std::string PathDisplayStr;
1714   std::set<unsigned> DisplayedPaths;
1715   for (CXXBasePaths::paths_iterator Path = Paths.begin();
1716        Path != Paths.end(); ++Path) {
1717     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1718       // We haven't displayed a path to this particular base
1719       // class subobject yet.
1720       PathDisplayStr += "\n    ";
1721       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1722       for (CXXBasePath::const_iterator Element = Path->begin();
1723            Element != Path->end(); ++Element)
1724         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1725     }
1726   }
1727 
1728   return PathDisplayStr;
1729 }
1730 
1731 //===----------------------------------------------------------------------===//
1732 // C++ class member Handling
1733 //===----------------------------------------------------------------------===//
1734 
1735 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1736 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1737                                 SourceLocation ASLoc,
1738                                 SourceLocation ColonLoc,
1739                                 AttributeList *Attrs) {
1740   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1741   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1742                                                   ASLoc, ColonLoc);
1743   CurContext->addHiddenDecl(ASDecl);
1744   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1745 }
1746 
1747 /// CheckOverrideControl - Check C++11 override control semantics.
1748 void Sema::CheckOverrideControl(NamedDecl *D) {
1749   if (D->isInvalidDecl())
1750     return;
1751 
1752   // We only care about "override" and "final" declarations.
1753   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1754     return;
1755 
1756   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1757 
1758   // We can't check dependent instance methods.
1759   if (MD && MD->isInstance() &&
1760       (MD->getParent()->hasAnyDependentBases() ||
1761        MD->getType()->isDependentType()))
1762     return;
1763 
1764   if (MD && !MD->isVirtual()) {
1765     // If we have a non-virtual method, check if if hides a virtual method.
1766     // (In that case, it's most likely the method has the wrong type.)
1767     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1768     FindHiddenVirtualMethods(MD, OverloadedMethods);
1769 
1770     if (!OverloadedMethods.empty()) {
1771       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1772         Diag(OA->getLocation(),
1773              diag::override_keyword_hides_virtual_member_function)
1774           << "override" << (OverloadedMethods.size() > 1);
1775       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1776         Diag(FA->getLocation(),
1777              diag::override_keyword_hides_virtual_member_function)
1778           << (FA->isSpelledAsSealed() ? "sealed" : "final")
1779           << (OverloadedMethods.size() > 1);
1780       }
1781       NoteHiddenVirtualMethods(MD, OverloadedMethods);
1782       MD->setInvalidDecl();
1783       return;
1784     }
1785     // Fall through into the general case diagnostic.
1786     // FIXME: We might want to attempt typo correction here.
1787   }
1788 
1789   if (!MD || !MD->isVirtual()) {
1790     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1791       Diag(OA->getLocation(),
1792            diag::override_keyword_only_allowed_on_virtual_member_functions)
1793         << "override" << FixItHint::CreateRemoval(OA->getLocation());
1794       D->dropAttr<OverrideAttr>();
1795     }
1796     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1797       Diag(FA->getLocation(),
1798            diag::override_keyword_only_allowed_on_virtual_member_functions)
1799         << (FA->isSpelledAsSealed() ? "sealed" : "final")
1800         << FixItHint::CreateRemoval(FA->getLocation());
1801       D->dropAttr<FinalAttr>();
1802     }
1803     return;
1804   }
1805 
1806   // C++11 [class.virtual]p5:
1807   //   If a virtual function is marked with the virt-specifier override and
1808   //   does not override a member function of a base class, the program is
1809   //   ill-formed.
1810   bool HasOverriddenMethods =
1811     MD->begin_overridden_methods() != MD->end_overridden_methods();
1812   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1813     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1814       << MD->getDeclName();
1815 }
1816 
1817 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1818 /// function overrides a virtual member function marked 'final', according to
1819 /// C++11 [class.virtual]p4.
1820 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1821                                                   const CXXMethodDecl *Old) {
1822   FinalAttr *FA = Old->getAttr<FinalAttr>();
1823   if (!FA)
1824     return false;
1825 
1826   Diag(New->getLocation(), diag::err_final_function_overridden)
1827     << New->getDeclName()
1828     << FA->isSpelledAsSealed();
1829   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1830   return true;
1831 }
1832 
1833 static bool InitializationHasSideEffects(const FieldDecl &FD) {
1834   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1835   // FIXME: Destruction of ObjC lifetime types has side-effects.
1836   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1837     return !RD->isCompleteDefinition() ||
1838            !RD->hasTrivialDefaultConstructor() ||
1839            !RD->hasTrivialDestructor();
1840   return false;
1841 }
1842 
1843 static AttributeList *getMSPropertyAttr(AttributeList *list) {
1844   for (AttributeList* it = list; it != 0; it = it->getNext())
1845     if (it->isDeclspecPropertyAttribute())
1846       return it;
1847   return 0;
1848 }
1849 
1850 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1851 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1852 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
1853 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1854 /// present (but parsing it has been deferred).
1855 NamedDecl *
1856 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1857                                MultiTemplateParamsArg TemplateParameterLists,
1858                                Expr *BW, const VirtSpecifiers &VS,
1859                                InClassInitStyle InitStyle) {
1860   const DeclSpec &DS = D.getDeclSpec();
1861   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1862   DeclarationName Name = NameInfo.getName();
1863   SourceLocation Loc = NameInfo.getLoc();
1864 
1865   // For anonymous bitfields, the location should point to the type.
1866   if (Loc.isInvalid())
1867     Loc = D.getLocStart();
1868 
1869   Expr *BitWidth = static_cast<Expr*>(BW);
1870 
1871   assert(isa<CXXRecordDecl>(CurContext));
1872   assert(!DS.isFriendSpecified());
1873 
1874   bool isFunc = D.isDeclarationOfFunction();
1875 
1876   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1877     // The Microsoft extension __interface only permits public member functions
1878     // and prohibits constructors, destructors, operators, non-public member
1879     // functions, static methods and data members.
1880     unsigned InvalidDecl;
1881     bool ShowDeclName = true;
1882     if (!isFunc)
1883       InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1884     else if (AS != AS_public)
1885       InvalidDecl = 2;
1886     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1887       InvalidDecl = 3;
1888     else switch (Name.getNameKind()) {
1889       case DeclarationName::CXXConstructorName:
1890         InvalidDecl = 4;
1891         ShowDeclName = false;
1892         break;
1893 
1894       case DeclarationName::CXXDestructorName:
1895         InvalidDecl = 5;
1896         ShowDeclName = false;
1897         break;
1898 
1899       case DeclarationName::CXXOperatorName:
1900       case DeclarationName::CXXConversionFunctionName:
1901         InvalidDecl = 6;
1902         break;
1903 
1904       default:
1905         InvalidDecl = 0;
1906         break;
1907     }
1908 
1909     if (InvalidDecl) {
1910       if (ShowDeclName)
1911         Diag(Loc, diag::err_invalid_member_in_interface)
1912           << (InvalidDecl-1) << Name;
1913       else
1914         Diag(Loc, diag::err_invalid_member_in_interface)
1915           << (InvalidDecl-1) << "";
1916       return 0;
1917     }
1918   }
1919 
1920   // C++ 9.2p6: A member shall not be declared to have automatic storage
1921   // duration (auto, register) or with the extern storage-class-specifier.
1922   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1923   // data members and cannot be applied to names declared const or static,
1924   // and cannot be applied to reference members.
1925   switch (DS.getStorageClassSpec()) {
1926   case DeclSpec::SCS_unspecified:
1927   case DeclSpec::SCS_typedef:
1928   case DeclSpec::SCS_static:
1929     break;
1930   case DeclSpec::SCS_mutable:
1931     if (isFunc) {
1932       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
1933 
1934       // FIXME: It would be nicer if the keyword was ignored only for this
1935       // declarator. Otherwise we could get follow-up errors.
1936       D.getMutableDeclSpec().ClearStorageClassSpecs();
1937     }
1938     break;
1939   default:
1940     Diag(DS.getStorageClassSpecLoc(),
1941          diag::err_storageclass_invalid_for_member);
1942     D.getMutableDeclSpec().ClearStorageClassSpecs();
1943     break;
1944   }
1945 
1946   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1947                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
1948                       !isFunc);
1949 
1950   if (DS.isConstexprSpecified() && isInstField) {
1951     SemaDiagnosticBuilder B =
1952         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1953     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1954     if (InitStyle == ICIS_NoInit) {
1955       B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1956       D.getMutableDeclSpec().ClearConstexprSpec();
1957       const char *PrevSpec;
1958       unsigned DiagID;
1959       bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1960                                          PrevSpec, DiagID, getLangOpts());
1961       (void)Failed;
1962       assert(!Failed && "Making a constexpr member const shouldn't fail");
1963     } else {
1964       B << 1;
1965       const char *PrevSpec;
1966       unsigned DiagID;
1967       if (D.getMutableDeclSpec().SetStorageClassSpec(
1968           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
1969           Context.getPrintingPolicy())) {
1970         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
1971                "This is the only DeclSpec that should fail to be applied");
1972         B << 1;
1973       } else {
1974         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1975         isInstField = false;
1976       }
1977     }
1978   }
1979 
1980   NamedDecl *Member;
1981   if (isInstField) {
1982     CXXScopeSpec &SS = D.getCXXScopeSpec();
1983 
1984     // Data members must have identifiers for names.
1985     if (!Name.isIdentifier()) {
1986       Diag(Loc, diag::err_bad_variable_name)
1987         << Name;
1988       return 0;
1989     }
1990 
1991     IdentifierInfo *II = Name.getAsIdentifierInfo();
1992 
1993     // Member field could not be with "template" keyword.
1994     // So TemplateParameterLists should be empty in this case.
1995     if (TemplateParameterLists.size()) {
1996       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
1997       if (TemplateParams->size()) {
1998         // There is no such thing as a member field template.
1999         Diag(D.getIdentifierLoc(), diag::err_template_member)
2000             << II
2001             << SourceRange(TemplateParams->getTemplateLoc(),
2002                 TemplateParams->getRAngleLoc());
2003       } else {
2004         // There is an extraneous 'template<>' for this member.
2005         Diag(TemplateParams->getTemplateLoc(),
2006             diag::err_template_member_noparams)
2007             << II
2008             << SourceRange(TemplateParams->getTemplateLoc(),
2009                 TemplateParams->getRAngleLoc());
2010       }
2011       return 0;
2012     }
2013 
2014     if (SS.isSet() && !SS.isInvalid()) {
2015       // The user provided a superfluous scope specifier inside a class
2016       // definition:
2017       //
2018       // class X {
2019       //   int X::member;
2020       // };
2021       if (DeclContext *DC = computeDeclContext(SS, false))
2022         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
2023       else
2024         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2025           << Name << SS.getRange();
2026 
2027       SS.clear();
2028     }
2029 
2030     AttributeList *MSPropertyAttr =
2031       getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
2032     if (MSPropertyAttr) {
2033       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2034                                 BitWidth, InitStyle, AS, MSPropertyAttr);
2035       if (!Member)
2036         return 0;
2037       isInstField = false;
2038     } else {
2039       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2040                                 BitWidth, InitStyle, AS);
2041       assert(Member && "HandleField never returns null");
2042     }
2043   } else {
2044     assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2045 
2046     Member = HandleDeclarator(S, D, TemplateParameterLists);
2047     if (!Member)
2048       return 0;
2049 
2050     // Non-instance-fields can't have a bitfield.
2051     if (BitWidth) {
2052       if (Member->isInvalidDecl()) {
2053         // don't emit another diagnostic.
2054       } else if (isa<VarDecl>(Member)) {
2055         // C++ 9.6p3: A bit-field shall not be a static member.
2056         // "static member 'A' cannot be a bit-field"
2057         Diag(Loc, diag::err_static_not_bitfield)
2058           << Name << BitWidth->getSourceRange();
2059       } else if (isa<TypedefDecl>(Member)) {
2060         // "typedef member 'x' cannot be a bit-field"
2061         Diag(Loc, diag::err_typedef_not_bitfield)
2062           << Name << BitWidth->getSourceRange();
2063       } else {
2064         // A function typedef ("typedef int f(); f a;").
2065         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2066         Diag(Loc, diag::err_not_integral_type_bitfield)
2067           << Name << cast<ValueDecl>(Member)->getType()
2068           << BitWidth->getSourceRange();
2069       }
2070 
2071       BitWidth = 0;
2072       Member->setInvalidDecl();
2073     }
2074 
2075     Member->setAccess(AS);
2076 
2077     // If we have declared a member function template or static data member
2078     // template, set the access of the templated declaration as well.
2079     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2080       FunTmpl->getTemplatedDecl()->setAccess(AS);
2081     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2082       VarTmpl->getTemplatedDecl()->setAccess(AS);
2083   }
2084 
2085   if (VS.isOverrideSpecified())
2086     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
2087   if (VS.isFinalSpecified())
2088     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2089                                             VS.isFinalSpelledSealed()));
2090 
2091   if (VS.getLastLocation().isValid()) {
2092     // Update the end location of a method that has a virt-specifiers.
2093     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2094       MD->setRangeEnd(VS.getLastLocation());
2095   }
2096 
2097   CheckOverrideControl(Member);
2098 
2099   assert((Name || isInstField) && "No identifier for non-field ?");
2100 
2101   if (isInstField) {
2102     FieldDecl *FD = cast<FieldDecl>(Member);
2103     FieldCollector->Add(FD);
2104 
2105     if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2106                                  FD->getLocation())
2107           != DiagnosticsEngine::Ignored) {
2108       // Remember all explicit private FieldDecls that have a name, no side
2109       // effects and are not part of a dependent type declaration.
2110       if (!FD->isImplicit() && FD->getDeclName() &&
2111           FD->getAccess() == AS_private &&
2112           !FD->hasAttr<UnusedAttr>() &&
2113           !FD->getParent()->isDependentContext() &&
2114           !InitializationHasSideEffects(*FD))
2115         UnusedPrivateFields.insert(FD);
2116     }
2117   }
2118 
2119   return Member;
2120 }
2121 
2122 namespace {
2123   class UninitializedFieldVisitor
2124       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2125     Sema &S;
2126     // List of Decls to generate a warning on.  Also remove Decls that become
2127     // initialized.
2128     llvm::SmallPtrSet<ValueDecl*, 4> &Decls;
2129     // If non-null, add a note to the warning pointing back to the constructor.
2130     const CXXConstructorDecl *Constructor;
2131   public:
2132     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2133     UninitializedFieldVisitor(Sema &S,
2134                               llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
2135                               const CXXConstructorDecl *Constructor)
2136       : Inherited(S.Context), S(S), Decls(Decls),
2137         Constructor(Constructor) { }
2138 
2139     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) {
2140       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2141         return;
2142 
2143       // FieldME is the inner-most MemberExpr that is not an anonymous struct
2144       // or union.
2145       MemberExpr *FieldME = ME;
2146 
2147       Expr *Base = ME;
2148       while (isa<MemberExpr>(Base)) {
2149         ME = cast<MemberExpr>(Base);
2150 
2151         if (isa<VarDecl>(ME->getMemberDecl()))
2152           return;
2153 
2154         if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2155           if (!FD->isAnonymousStructOrUnion())
2156             FieldME = ME;
2157 
2158         Base = ME->getBase();
2159       }
2160 
2161       if (!isa<CXXThisExpr>(Base))
2162         return;
2163 
2164       ValueDecl* FoundVD = FieldME->getMemberDecl();
2165 
2166       if (!Decls.count(FoundVD))
2167         return;
2168 
2169       const bool IsReference = FoundVD->getType()->isReferenceType();
2170 
2171       // Prevent double warnings on use of unbounded references.
2172       if (IsReference != CheckReferenceOnly)
2173         return;
2174 
2175       unsigned diag = IsReference
2176           ? diag::warn_reference_field_is_uninit
2177           : diag::warn_field_is_uninit;
2178       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2179       if (Constructor)
2180         S.Diag(Constructor->getLocation(),
2181                diag::note_uninit_in_this_constructor)
2182           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2183 
2184     }
2185 
2186     void HandleValue(Expr *E) {
2187       E = E->IgnoreParens();
2188 
2189       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2190         HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
2191         return;
2192       }
2193 
2194       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2195         HandleValue(CO->getTrueExpr());
2196         HandleValue(CO->getFalseExpr());
2197         return;
2198       }
2199 
2200       if (BinaryConditionalOperator *BCO =
2201               dyn_cast<BinaryConditionalOperator>(E)) {
2202         HandleValue(BCO->getCommon());
2203         HandleValue(BCO->getFalseExpr());
2204         return;
2205       }
2206 
2207       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2208         switch (BO->getOpcode()) {
2209         default:
2210           return;
2211         case(BO_PtrMemD):
2212         case(BO_PtrMemI):
2213           HandleValue(BO->getLHS());
2214           return;
2215         case(BO_Comma):
2216           HandleValue(BO->getRHS());
2217           return;
2218         }
2219       }
2220     }
2221 
2222     void VisitMemberExpr(MemberExpr *ME) {
2223       // All uses of unbounded reference fields will warn.
2224       HandleMemberExpr(ME, true /*CheckReferenceOnly*/);
2225 
2226       Inherited::VisitMemberExpr(ME);
2227     }
2228 
2229     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2230       if (E->getCastKind() == CK_LValueToRValue)
2231         HandleValue(E->getSubExpr());
2232 
2233       Inherited::VisitImplicitCastExpr(E);
2234     }
2235 
2236     void VisitCXXConstructExpr(CXXConstructExpr *E) {
2237       if (E->getConstructor()->isCopyConstructor())
2238         if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0)))
2239           if (ICE->getCastKind() == CK_NoOp)
2240             if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr()))
2241               HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
2242 
2243       Inherited::VisitCXXConstructExpr(E);
2244     }
2245 
2246     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2247       Expr *Callee = E->getCallee();
2248       if (isa<MemberExpr>(Callee))
2249         HandleValue(Callee);
2250 
2251       Inherited::VisitCXXMemberCallExpr(E);
2252     }
2253 
2254     void VisitBinaryOperator(BinaryOperator *E) {
2255       // If a field assignment is detected, remove the field from the
2256       // uninitiailized field set.
2257       if (E->getOpcode() == BO_Assign)
2258         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2259           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2260             if (!FD->getType()->isReferenceType())
2261               Decls.erase(FD);
2262 
2263       Inherited::VisitBinaryOperator(E);
2264     }
2265   };
2266   static void CheckInitExprContainsUninitializedFields(
2267       Sema &S, Expr *E, llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
2268       const CXXConstructorDecl *Constructor) {
2269     if (Decls.size() == 0)
2270       return;
2271 
2272     if (!E)
2273       return;
2274 
2275     if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(E)) {
2276       E = Default->getExpr();
2277       if (!E)
2278         return;
2279       // In class initializers will point to the constructor.
2280       UninitializedFieldVisitor(S, Decls, Constructor).Visit(E);
2281     } else {
2282       UninitializedFieldVisitor(S, Decls, 0).Visit(E);
2283     }
2284   }
2285 
2286   // Diagnose value-uses of fields to initialize themselves, e.g.
2287   //   foo(foo)
2288   // where foo is not also a parameter to the constructor.
2289   // Also diagnose across field uninitialized use such as
2290   //   x(y), y(x)
2291   // TODO: implement -Wuninitialized and fold this into that framework.
2292   static void DiagnoseUninitializedFields(
2293       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2294 
2295     if (SemaRef.getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit,
2296                                                     Constructor->getLocation())
2297         == DiagnosticsEngine::Ignored) {
2298       return;
2299     }
2300 
2301     if (Constructor->isInvalidDecl())
2302       return;
2303 
2304     const CXXRecordDecl *RD = Constructor->getParent();
2305 
2306     // Holds fields that are uninitialized.
2307     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2308 
2309     // At the beginning, all fields are uninitialized.
2310     for (auto *I : RD->decls()) {
2311       if (auto *FD = dyn_cast<FieldDecl>(I)) {
2312         UninitializedFields.insert(FD);
2313       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
2314         UninitializedFields.insert(IFD->getAnonField());
2315       }
2316     }
2317 
2318     for (const auto *FieldInit : Constructor->inits()) {
2319       Expr *InitExpr = FieldInit->getInit();
2320 
2321       CheckInitExprContainsUninitializedFields(
2322           SemaRef, InitExpr, UninitializedFields, Constructor);
2323 
2324       if (FieldDecl *Field = FieldInit->getAnyMember())
2325         UninitializedFields.erase(Field);
2326     }
2327   }
2328 } // namespace
2329 
2330 /// \brief Enter a new C++ default initializer scope. After calling this, the
2331 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2332 /// parsing or instantiating the initializer failed.
2333 void Sema::ActOnStartCXXInClassMemberInitializer() {
2334   // Create a synthetic function scope to represent the call to the constructor
2335   // that notionally surrounds a use of this initializer.
2336   PushFunctionScope();
2337 }
2338 
2339 /// \brief This is invoked after parsing an in-class initializer for a
2340 /// non-static C++ class member, and after instantiating an in-class initializer
2341 /// in a class template. Such actions are deferred until the class is complete.
2342 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2343                                                   SourceLocation InitLoc,
2344                                                   Expr *InitExpr) {
2345   // Pop the notional constructor scope we created earlier.
2346   PopFunctionScopeInfo(0, D);
2347 
2348   FieldDecl *FD = cast<FieldDecl>(D);
2349   assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2350          "must set init style when field is created");
2351 
2352   if (!InitExpr) {
2353     FD->setInvalidDecl();
2354     FD->removeInClassInitializer();
2355     return;
2356   }
2357 
2358   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2359     FD->setInvalidDecl();
2360     FD->removeInClassInitializer();
2361     return;
2362   }
2363 
2364   ExprResult Init = InitExpr;
2365   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
2366     InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
2367     InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
2368         ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
2369         : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
2370     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2371     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
2372     if (Init.isInvalid()) {
2373       FD->setInvalidDecl();
2374       return;
2375     }
2376   }
2377 
2378   // C++11 [class.base.init]p7:
2379   //   The initialization of each base and member constitutes a
2380   //   full-expression.
2381   Init = ActOnFinishFullExpr(Init.take(), InitLoc);
2382   if (Init.isInvalid()) {
2383     FD->setInvalidDecl();
2384     return;
2385   }
2386 
2387   InitExpr = Init.release();
2388 
2389   FD->setInClassInitializer(InitExpr);
2390 }
2391 
2392 /// \brief Find the direct and/or virtual base specifiers that
2393 /// correspond to the given base type, for use in base initialization
2394 /// within a constructor.
2395 static bool FindBaseInitializer(Sema &SemaRef,
2396                                 CXXRecordDecl *ClassDecl,
2397                                 QualType BaseType,
2398                                 const CXXBaseSpecifier *&DirectBaseSpec,
2399                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
2400   // First, check for a direct base class.
2401   DirectBaseSpec = 0;
2402   for (const auto &Base : ClassDecl->bases()) {
2403     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
2404       // We found a direct base of this type. That's what we're
2405       // initializing.
2406       DirectBaseSpec = &Base;
2407       break;
2408     }
2409   }
2410 
2411   // Check for a virtual base class.
2412   // FIXME: We might be able to short-circuit this if we know in advance that
2413   // there are no virtual bases.
2414   VirtualBaseSpec = 0;
2415   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2416     // We haven't found a base yet; search the class hierarchy for a
2417     // virtual base class.
2418     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2419                        /*DetectVirtual=*/false);
2420     if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2421                               BaseType, Paths)) {
2422       for (CXXBasePaths::paths_iterator Path = Paths.begin();
2423            Path != Paths.end(); ++Path) {
2424         if (Path->back().Base->isVirtual()) {
2425           VirtualBaseSpec = Path->back().Base;
2426           break;
2427         }
2428       }
2429     }
2430   }
2431 
2432   return DirectBaseSpec || VirtualBaseSpec;
2433 }
2434 
2435 /// \brief Handle a C++ member initializer using braced-init-list syntax.
2436 MemInitResult
2437 Sema::ActOnMemInitializer(Decl *ConstructorD,
2438                           Scope *S,
2439                           CXXScopeSpec &SS,
2440                           IdentifierInfo *MemberOrBase,
2441                           ParsedType TemplateTypeTy,
2442                           const DeclSpec &DS,
2443                           SourceLocation IdLoc,
2444                           Expr *InitList,
2445                           SourceLocation EllipsisLoc) {
2446   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2447                              DS, IdLoc, InitList,
2448                              EllipsisLoc);
2449 }
2450 
2451 /// \brief Handle a C++ member initializer using parentheses syntax.
2452 MemInitResult
2453 Sema::ActOnMemInitializer(Decl *ConstructorD,
2454                           Scope *S,
2455                           CXXScopeSpec &SS,
2456                           IdentifierInfo *MemberOrBase,
2457                           ParsedType TemplateTypeTy,
2458                           const DeclSpec &DS,
2459                           SourceLocation IdLoc,
2460                           SourceLocation LParenLoc,
2461                           ArrayRef<Expr *> Args,
2462                           SourceLocation RParenLoc,
2463                           SourceLocation EllipsisLoc) {
2464   Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2465                                            Args, RParenLoc);
2466   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2467                              DS, IdLoc, List, EllipsisLoc);
2468 }
2469 
2470 namespace {
2471 
2472 // Callback to only accept typo corrections that can be a valid C++ member
2473 // intializer: either a non-static field member or a base class.
2474 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2475 public:
2476   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2477       : ClassDecl(ClassDecl) {}
2478 
2479   bool ValidateCandidate(const TypoCorrection &candidate) override {
2480     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2481       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2482         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2483       return isa<TypeDecl>(ND);
2484     }
2485     return false;
2486   }
2487 
2488 private:
2489   CXXRecordDecl *ClassDecl;
2490 };
2491 
2492 }
2493 
2494 /// \brief Handle a C++ member initializer.
2495 MemInitResult
2496 Sema::BuildMemInitializer(Decl *ConstructorD,
2497                           Scope *S,
2498                           CXXScopeSpec &SS,
2499                           IdentifierInfo *MemberOrBase,
2500                           ParsedType TemplateTypeTy,
2501                           const DeclSpec &DS,
2502                           SourceLocation IdLoc,
2503                           Expr *Init,
2504                           SourceLocation EllipsisLoc) {
2505   if (!ConstructorD)
2506     return true;
2507 
2508   AdjustDeclIfTemplate(ConstructorD);
2509 
2510   CXXConstructorDecl *Constructor
2511     = dyn_cast<CXXConstructorDecl>(ConstructorD);
2512   if (!Constructor) {
2513     // The user wrote a constructor initializer on a function that is
2514     // not a C++ constructor. Ignore the error for now, because we may
2515     // have more member initializers coming; we'll diagnose it just
2516     // once in ActOnMemInitializers.
2517     return true;
2518   }
2519 
2520   CXXRecordDecl *ClassDecl = Constructor->getParent();
2521 
2522   // C++ [class.base.init]p2:
2523   //   Names in a mem-initializer-id are looked up in the scope of the
2524   //   constructor's class and, if not found in that scope, are looked
2525   //   up in the scope containing the constructor's definition.
2526   //   [Note: if the constructor's class contains a member with the
2527   //   same name as a direct or virtual base class of the class, a
2528   //   mem-initializer-id naming the member or base class and composed
2529   //   of a single identifier refers to the class member. A
2530   //   mem-initializer-id for the hidden base class may be specified
2531   //   using a qualified name. ]
2532   if (!SS.getScopeRep() && !TemplateTypeTy) {
2533     // Look for a member, first.
2534     DeclContext::lookup_result Result
2535       = ClassDecl->lookup(MemberOrBase);
2536     if (!Result.empty()) {
2537       ValueDecl *Member;
2538       if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2539           (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
2540         if (EllipsisLoc.isValid())
2541           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
2542             << MemberOrBase
2543             << SourceRange(IdLoc, Init->getSourceRange().getEnd());
2544 
2545         return BuildMemberInitializer(Member, Init, IdLoc);
2546       }
2547     }
2548   }
2549   // It didn't name a member, so see if it names a class.
2550   QualType BaseType;
2551   TypeSourceInfo *TInfo = 0;
2552 
2553   if (TemplateTypeTy) {
2554     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
2555   } else if (DS.getTypeSpecType() == TST_decltype) {
2556     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
2557   } else {
2558     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2559     LookupParsedName(R, S, &SS);
2560 
2561     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2562     if (!TyD) {
2563       if (R.isAmbiguous()) return true;
2564 
2565       // We don't want access-control diagnostics here.
2566       R.suppressDiagnostics();
2567 
2568       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2569         bool NotUnknownSpecialization = false;
2570         DeclContext *DC = computeDeclContext(SS, false);
2571         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2572           NotUnknownSpecialization = !Record->hasAnyDependentBases();
2573 
2574         if (!NotUnknownSpecialization) {
2575           // When the scope specifier can refer to a member of an unknown
2576           // specialization, we take it as a type name.
2577           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2578                                        SS.getWithLocInContext(Context),
2579                                        *MemberOrBase, IdLoc);
2580           if (BaseType.isNull())
2581             return true;
2582 
2583           R.clear();
2584           R.setLookupName(MemberOrBase);
2585         }
2586       }
2587 
2588       // If no results were found, try to correct typos.
2589       TypoCorrection Corr;
2590       MemInitializerValidatorCCC Validator(ClassDecl);
2591       if (R.empty() && BaseType.isNull() &&
2592           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2593                               Validator, ClassDecl))) {
2594         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
2595           // We have found a non-static data member with a similar
2596           // name to what was typed; complain and initialize that
2597           // member.
2598           diagnoseTypo(Corr,
2599                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
2600                          << MemberOrBase << true);
2601           return BuildMemberInitializer(Member, Init, IdLoc);
2602         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
2603           const CXXBaseSpecifier *DirectBaseSpec;
2604           const CXXBaseSpecifier *VirtualBaseSpec;
2605           if (FindBaseInitializer(*this, ClassDecl,
2606                                   Context.getTypeDeclType(Type),
2607                                   DirectBaseSpec, VirtualBaseSpec)) {
2608             // We have found a direct or virtual base class with a
2609             // similar name to what was typed; complain and initialize
2610             // that base class.
2611             diagnoseTypo(Corr,
2612                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
2613                            << MemberOrBase << false,
2614                          PDiag() /*Suppress note, we provide our own.*/);
2615 
2616             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2617                                                               : VirtualBaseSpec;
2618             Diag(BaseSpec->getLocStart(),
2619                  diag::note_base_class_specified_here)
2620               << BaseSpec->getType()
2621               << BaseSpec->getSourceRange();
2622 
2623             TyD = Type;
2624           }
2625         }
2626       }
2627 
2628       if (!TyD && BaseType.isNull()) {
2629         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
2630           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
2631         return true;
2632       }
2633     }
2634 
2635     if (BaseType.isNull()) {
2636       BaseType = Context.getTypeDeclType(TyD);
2637       if (SS.isSet())
2638         // FIXME: preserve source range information
2639         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2640                                              BaseType);
2641     }
2642   }
2643 
2644   if (!TInfo)
2645     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
2646 
2647   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
2648 }
2649 
2650 /// Checks a member initializer expression for cases where reference (or
2651 /// pointer) members are bound to by-value parameters (or their addresses).
2652 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2653                                                Expr *Init,
2654                                                SourceLocation IdLoc) {
2655   QualType MemberTy = Member->getType();
2656 
2657   // We only handle pointers and references currently.
2658   // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2659   if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2660     return;
2661 
2662   const bool IsPointer = MemberTy->isPointerType();
2663   if (IsPointer) {
2664     if (const UnaryOperator *Op
2665           = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2666       // The only case we're worried about with pointers requires taking the
2667       // address.
2668       if (Op->getOpcode() != UO_AddrOf)
2669         return;
2670 
2671       Init = Op->getSubExpr();
2672     } else {
2673       // We only handle address-of expression initializers for pointers.
2674       return;
2675     }
2676   }
2677 
2678   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2679     // We only warn when referring to a non-reference parameter declaration.
2680     const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2681     if (!Parameter || Parameter->getType()->isReferenceType())
2682       return;
2683 
2684     S.Diag(Init->getExprLoc(),
2685            IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2686                      : diag::warn_bind_ref_member_to_parameter)
2687       << Member << Parameter << Init->getSourceRange();
2688   } else {
2689     // Other initializers are fine.
2690     return;
2691   }
2692 
2693   S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2694     << (unsigned)IsPointer;
2695 }
2696 
2697 MemInitResult
2698 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
2699                              SourceLocation IdLoc) {
2700   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2701   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2702   assert((DirectMember || IndirectMember) &&
2703          "Member must be a FieldDecl or IndirectFieldDecl");
2704 
2705   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2706     return true;
2707 
2708   if (Member->isInvalidDecl())
2709     return true;
2710 
2711   MultiExprArg Args;
2712   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2713     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2714   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2715     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
2716   } else {
2717     // Template instantiation doesn't reconstruct ParenListExprs for us.
2718     Args = Init;
2719   }
2720 
2721   SourceRange InitRange = Init->getSourceRange();
2722 
2723   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
2724     // Can't check initialization for a member of dependent type or when
2725     // any of the arguments are type-dependent expressions.
2726     DiscardCleanupsInEvaluationContext();
2727   } else {
2728     bool InitList = false;
2729     if (isa<InitListExpr>(Init)) {
2730       InitList = true;
2731       Args = Init;
2732     }
2733 
2734     // Initialize the member.
2735     InitializedEntity MemberEntity =
2736       DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2737                    : InitializedEntity::InitializeMember(IndirectMember, 0);
2738     InitializationKind Kind =
2739       InitList ? InitializationKind::CreateDirectList(IdLoc)
2740                : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2741                                                   InitRange.getEnd());
2742 
2743     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2744     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
2745     if (MemberInit.isInvalid())
2746       return true;
2747 
2748     CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2749 
2750     // C++11 [class.base.init]p7:
2751     //   The initialization of each base and member constitutes a
2752     //   full-expression.
2753     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
2754     if (MemberInit.isInvalid())
2755       return true;
2756 
2757     Init = MemberInit.get();
2758   }
2759 
2760   if (DirectMember) {
2761     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2762                                             InitRange.getBegin(), Init,
2763                                             InitRange.getEnd());
2764   } else {
2765     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2766                                             InitRange.getBegin(), Init,
2767                                             InitRange.getEnd());
2768   }
2769 }
2770 
2771 MemInitResult
2772 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
2773                                  CXXRecordDecl *ClassDecl) {
2774   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
2775   if (!LangOpts.CPlusPlus11)
2776     return Diag(NameLoc, diag::err_delegating_ctor)
2777       << TInfo->getTypeLoc().getLocalSourceRange();
2778   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
2779 
2780   bool InitList = true;
2781   MultiExprArg Args = Init;
2782   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2783     InitList = false;
2784     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2785   }
2786 
2787   SourceRange InitRange = Init->getSourceRange();
2788   // Initialize the object.
2789   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2790                                      QualType(ClassDecl->getTypeForDecl(), 0));
2791   InitializationKind Kind =
2792     InitList ? InitializationKind::CreateDirectList(NameLoc)
2793              : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2794                                                 InitRange.getEnd());
2795   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
2796   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2797                                               Args, 0);
2798   if (DelegationInit.isInvalid())
2799     return true;
2800 
2801   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2802          "Delegating constructor with no target?");
2803 
2804   // C++11 [class.base.init]p7:
2805   //   The initialization of each base and member constitutes a
2806   //   full-expression.
2807   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2808                                        InitRange.getBegin());
2809   if (DelegationInit.isInvalid())
2810     return true;
2811 
2812   // If we are in a dependent context, template instantiation will
2813   // perform this type-checking again. Just save the arguments that we
2814   // received in a ParenListExpr.
2815   // FIXME: This isn't quite ideal, since our ASTs don't capture all
2816   // of the information that we have about the base
2817   // initializer. However, deconstructing the ASTs is a dicey process,
2818   // and this approach is far more likely to get the corner cases right.
2819   if (CurContext->isDependentContext())
2820     DelegationInit = Owned(Init);
2821 
2822   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
2823                                           DelegationInit.takeAs<Expr>(),
2824                                           InitRange.getEnd());
2825 }
2826 
2827 MemInitResult
2828 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
2829                            Expr *Init, CXXRecordDecl *ClassDecl,
2830                            SourceLocation EllipsisLoc) {
2831   SourceLocation BaseLoc
2832     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
2833 
2834   if (!BaseType->isDependentType() && !BaseType->isRecordType())
2835     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2836              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2837 
2838   // C++ [class.base.init]p2:
2839   //   [...] Unless the mem-initializer-id names a nonstatic data
2840   //   member of the constructor's class or a direct or virtual base
2841   //   of that class, the mem-initializer is ill-formed. A
2842   //   mem-initializer-list can initialize a base class using any
2843   //   name that denotes that base class type.
2844   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
2845 
2846   SourceRange InitRange = Init->getSourceRange();
2847   if (EllipsisLoc.isValid()) {
2848     // This is a pack expansion.
2849     if (!BaseType->containsUnexpandedParameterPack())  {
2850       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2851         << SourceRange(BaseLoc, InitRange.getEnd());
2852 
2853       EllipsisLoc = SourceLocation();
2854     }
2855   } else {
2856     // Check for any unexpanded parameter packs.
2857     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2858       return true;
2859 
2860     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2861       return true;
2862   }
2863 
2864   // Check for direct and virtual base classes.
2865   const CXXBaseSpecifier *DirectBaseSpec = 0;
2866   const CXXBaseSpecifier *VirtualBaseSpec = 0;
2867   if (!Dependent) {
2868     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2869                                        BaseType))
2870       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
2871 
2872     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2873                         VirtualBaseSpec);
2874 
2875     // C++ [base.class.init]p2:
2876     // Unless the mem-initializer-id names a nonstatic data member of the
2877     // constructor's class or a direct or virtual base of that class, the
2878     // mem-initializer is ill-formed.
2879     if (!DirectBaseSpec && !VirtualBaseSpec) {
2880       // If the class has any dependent bases, then it's possible that
2881       // one of those types will resolve to the same type as
2882       // BaseType. Therefore, just treat this as a dependent base
2883       // class initialization.  FIXME: Should we try to check the
2884       // initialization anyway? It seems odd.
2885       if (ClassDecl->hasAnyDependentBases())
2886         Dependent = true;
2887       else
2888         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2889           << BaseType << Context.getTypeDeclType(ClassDecl)
2890           << BaseTInfo->getTypeLoc().getLocalSourceRange();
2891     }
2892   }
2893 
2894   if (Dependent) {
2895     DiscardCleanupsInEvaluationContext();
2896 
2897     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2898                                             /*IsVirtual=*/false,
2899                                             InitRange.getBegin(), Init,
2900                                             InitRange.getEnd(), EllipsisLoc);
2901   }
2902 
2903   // C++ [base.class.init]p2:
2904   //   If a mem-initializer-id is ambiguous because it designates both
2905   //   a direct non-virtual base class and an inherited virtual base
2906   //   class, the mem-initializer is ill-formed.
2907   if (DirectBaseSpec && VirtualBaseSpec)
2908     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
2909       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2910 
2911   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
2912   if (!BaseSpec)
2913     BaseSpec = VirtualBaseSpec;
2914 
2915   // Initialize the base.
2916   bool InitList = true;
2917   MultiExprArg Args = Init;
2918   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2919     InitList = false;
2920     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2921   }
2922 
2923   InitializedEntity BaseEntity =
2924     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2925   InitializationKind Kind =
2926     InitList ? InitializationKind::CreateDirectList(BaseLoc)
2927              : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2928                                                 InitRange.getEnd());
2929   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2930   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
2931   if (BaseInit.isInvalid())
2932     return true;
2933 
2934   // C++11 [class.base.init]p7:
2935   //   The initialization of each base and member constitutes a
2936   //   full-expression.
2937   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
2938   if (BaseInit.isInvalid())
2939     return true;
2940 
2941   // If we are in a dependent context, template instantiation will
2942   // perform this type-checking again. Just save the arguments that we
2943   // received in a ParenListExpr.
2944   // FIXME: This isn't quite ideal, since our ASTs don't capture all
2945   // of the information that we have about the base
2946   // initializer. However, deconstructing the ASTs is a dicey process,
2947   // and this approach is far more likely to get the corner cases right.
2948   if (CurContext->isDependentContext())
2949     BaseInit = Owned(Init);
2950 
2951   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2952                                           BaseSpec->isVirtual(),
2953                                           InitRange.getBegin(),
2954                                           BaseInit.takeAs<Expr>(),
2955                                           InitRange.getEnd(), EllipsisLoc);
2956 }
2957 
2958 // Create a static_cast\<T&&>(expr).
2959 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2960   if (T.isNull()) T = E->getType();
2961   QualType TargetType = SemaRef.BuildReferenceType(
2962       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
2963   SourceLocation ExprLoc = E->getLocStart();
2964   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2965       TargetType, ExprLoc);
2966 
2967   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2968                                    SourceRange(ExprLoc, ExprLoc),
2969                                    E->getSourceRange()).take();
2970 }
2971 
2972 /// ImplicitInitializerKind - How an implicit base or member initializer should
2973 /// initialize its base or member.
2974 enum ImplicitInitializerKind {
2975   IIK_Default,
2976   IIK_Copy,
2977   IIK_Move,
2978   IIK_Inherit
2979 };
2980 
2981 static bool
2982 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2983                              ImplicitInitializerKind ImplicitInitKind,
2984                              CXXBaseSpecifier *BaseSpec,
2985                              bool IsInheritedVirtualBase,
2986                              CXXCtorInitializer *&CXXBaseInit) {
2987   InitializedEntity InitEntity
2988     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2989                                         IsInheritedVirtualBase);
2990 
2991   ExprResult BaseInit;
2992 
2993   switch (ImplicitInitKind) {
2994   case IIK_Inherit: {
2995     const CXXRecordDecl *Inherited =
2996         Constructor->getInheritedConstructor()->getParent();
2997     const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2998     if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2999       // C++11 [class.inhctor]p8:
3000       //   Each expression in the expression-list is of the form
3001       //   static_cast<T&&>(p), where p is the name of the corresponding
3002       //   constructor parameter and T is the declared type of p.
3003       SmallVector<Expr*, 16> Args;
3004       for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3005         ParmVarDecl *PD = Constructor->getParamDecl(I);
3006         ExprResult ArgExpr =
3007             SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3008                                      VK_LValue, SourceLocation());
3009         if (ArgExpr.isInvalid())
3010           return true;
3011         Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
3012       }
3013 
3014       InitializationKind InitKind = InitializationKind::CreateDirect(
3015           Constructor->getLocation(), SourceLocation(), SourceLocation());
3016       InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
3017       BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3018       break;
3019     }
3020   }
3021   // Fall through.
3022   case IIK_Default: {
3023     InitializationKind InitKind
3024       = InitializationKind::CreateDefault(Constructor->getLocation());
3025     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3026     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3027     break;
3028   }
3029 
3030   case IIK_Move:
3031   case IIK_Copy: {
3032     bool Moving = ImplicitInitKind == IIK_Move;
3033     ParmVarDecl *Param = Constructor->getParamDecl(0);
3034     QualType ParamType = Param->getType().getNonReferenceType();
3035 
3036     Expr *CopyCtorArg =
3037       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3038                           SourceLocation(), Param, false,
3039                           Constructor->getLocation(), ParamType,
3040                           VK_LValue, 0);
3041 
3042     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3043 
3044     // Cast to the base class to avoid ambiguities.
3045     QualType ArgTy =
3046       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3047                                        ParamType.getQualifiers());
3048 
3049     if (Moving) {
3050       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3051     }
3052 
3053     CXXCastPath BasePath;
3054     BasePath.push_back(BaseSpec);
3055     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3056                                             CK_UncheckedDerivedToBase,
3057                                             Moving ? VK_XValue : VK_LValue,
3058                                             &BasePath).take();
3059 
3060     InitializationKind InitKind
3061       = InitializationKind::CreateDirect(Constructor->getLocation(),
3062                                          SourceLocation(), SourceLocation());
3063     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3064     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
3065     break;
3066   }
3067   }
3068 
3069   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
3070   if (BaseInit.isInvalid())
3071     return true;
3072 
3073   CXXBaseInit =
3074     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3075                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3076                                                         SourceLocation()),
3077                                              BaseSpec->isVirtual(),
3078                                              SourceLocation(),
3079                                              BaseInit.takeAs<Expr>(),
3080                                              SourceLocation(),
3081                                              SourceLocation());
3082 
3083   return false;
3084 }
3085 
3086 static bool RefersToRValueRef(Expr *MemRef) {
3087   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3088   return Referenced->getType()->isRValueReferenceType();
3089 }
3090 
3091 static bool
3092 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3093                                ImplicitInitializerKind ImplicitInitKind,
3094                                FieldDecl *Field, IndirectFieldDecl *Indirect,
3095                                CXXCtorInitializer *&CXXMemberInit) {
3096   if (Field->isInvalidDecl())
3097     return true;
3098 
3099   SourceLocation Loc = Constructor->getLocation();
3100 
3101   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3102     bool Moving = ImplicitInitKind == IIK_Move;
3103     ParmVarDecl *Param = Constructor->getParamDecl(0);
3104     QualType ParamType = Param->getType().getNonReferenceType();
3105 
3106     // Suppress copying zero-width bitfields.
3107     if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3108       return false;
3109 
3110     Expr *MemberExprBase =
3111       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3112                           SourceLocation(), Param, false,
3113                           Loc, ParamType, VK_LValue, 0);
3114 
3115     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3116 
3117     if (Moving) {
3118       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3119     }
3120 
3121     // Build a reference to this field within the parameter.
3122     CXXScopeSpec SS;
3123     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3124                               Sema::LookupMemberName);
3125     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3126                                   : cast<ValueDecl>(Field), AS_public);
3127     MemberLookup.resolveKind();
3128     ExprResult CtorArg
3129       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
3130                                          ParamType, Loc,
3131                                          /*IsArrow=*/false,
3132                                          SS,
3133                                          /*TemplateKWLoc=*/SourceLocation(),
3134                                          /*FirstQualifierInScope=*/0,
3135                                          MemberLookup,
3136                                          /*TemplateArgs=*/0);
3137     if (CtorArg.isInvalid())
3138       return true;
3139 
3140     // C++11 [class.copy]p15:
3141     //   - if a member m has rvalue reference type T&&, it is direct-initialized
3142     //     with static_cast<T&&>(x.m);
3143     if (RefersToRValueRef(CtorArg.get())) {
3144       CtorArg = CastForMoving(SemaRef, CtorArg.take());
3145     }
3146 
3147     // When the field we are copying is an array, create index variables for
3148     // each dimension of the array. We use these index variables to subscript
3149     // the source array, and other clients (e.g., CodeGen) will perform the
3150     // necessary iteration with these index variables.
3151     SmallVector<VarDecl *, 4> IndexVariables;
3152     QualType BaseType = Field->getType();
3153     QualType SizeType = SemaRef.Context.getSizeType();
3154     bool InitializingArray = false;
3155     while (const ConstantArrayType *Array
3156                           = SemaRef.Context.getAsConstantArrayType(BaseType)) {
3157       InitializingArray = true;
3158       // Create the iteration variable for this array index.
3159       IdentifierInfo *IterationVarName = 0;
3160       {
3161         SmallString<8> Str;
3162         llvm::raw_svector_ostream OS(Str);
3163         OS << "__i" << IndexVariables.size();
3164         IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3165       }
3166       VarDecl *IterationVar
3167         = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
3168                           IterationVarName, SizeType,
3169                         SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
3170                           SC_None);
3171       IndexVariables.push_back(IterationVar);
3172 
3173       // Create a reference to the iteration variable.
3174       ExprResult IterationVarRef
3175         = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
3176       assert(!IterationVarRef.isInvalid() &&
3177              "Reference to invented variable cannot fail!");
3178       IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3179       assert(!IterationVarRef.isInvalid() &&
3180              "Conversion of invented variable cannot fail!");
3181 
3182       // Subscript the array with this iteration variable.
3183       CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
3184                                                         IterationVarRef.take(),
3185                                                         Loc);
3186       if (CtorArg.isInvalid())
3187         return true;
3188 
3189       BaseType = Array->getElementType();
3190     }
3191 
3192     // The array subscript expression is an lvalue, which is wrong for moving.
3193     if (Moving && InitializingArray)
3194       CtorArg = CastForMoving(SemaRef, CtorArg.take());
3195 
3196     // Construct the entity that we will be initializing. For an array, this
3197     // will be first element in the array, which may require several levels
3198     // of array-subscript entities.
3199     SmallVector<InitializedEntity, 4> Entities;
3200     Entities.reserve(1 + IndexVariables.size());
3201     if (Indirect)
3202       Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3203     else
3204       Entities.push_back(InitializedEntity::InitializeMember(Field));
3205     for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3206       Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3207                                                               0,
3208                                                               Entities.back()));
3209 
3210     // Direct-initialize to use the copy constructor.
3211     InitializationKind InitKind =
3212       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3213 
3214     Expr *CtorArgE = CtorArg.takeAs<Expr>();
3215     InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
3216 
3217     ExprResult MemberInit
3218       = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
3219                         MultiExprArg(&CtorArgE, 1));
3220     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3221     if (MemberInit.isInvalid())
3222       return true;
3223 
3224     if (Indirect) {
3225       assert(IndexVariables.size() == 0 &&
3226              "Indirect field improperly initialized");
3227       CXXMemberInit
3228         = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3229                                                    Loc, Loc,
3230                                                    MemberInit.takeAs<Expr>(),
3231                                                    Loc);
3232     } else
3233       CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3234                                                  Loc, MemberInit.takeAs<Expr>(),
3235                                                  Loc,
3236                                                  IndexVariables.data(),
3237                                                  IndexVariables.size());
3238     return false;
3239   }
3240 
3241   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3242          "Unhandled implicit init kind!");
3243 
3244   QualType FieldBaseElementType =
3245     SemaRef.Context.getBaseElementType(Field->getType());
3246 
3247   if (FieldBaseElementType->isRecordType()) {
3248     InitializedEntity InitEntity
3249       = Indirect? InitializedEntity::InitializeMember(Indirect)
3250                 : InitializedEntity::InitializeMember(Field);
3251     InitializationKind InitKind =
3252       InitializationKind::CreateDefault(Loc);
3253 
3254     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3255     ExprResult MemberInit =
3256       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3257 
3258     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3259     if (MemberInit.isInvalid())
3260       return true;
3261 
3262     if (Indirect)
3263       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3264                                                                Indirect, Loc,
3265                                                                Loc,
3266                                                                MemberInit.get(),
3267                                                                Loc);
3268     else
3269       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3270                                                                Field, Loc, Loc,
3271                                                                MemberInit.get(),
3272                                                                Loc);
3273     return false;
3274   }
3275 
3276   if (!Field->getParent()->isUnion()) {
3277     if (FieldBaseElementType->isReferenceType()) {
3278       SemaRef.Diag(Constructor->getLocation(),
3279                    diag::err_uninitialized_member_in_ctor)
3280       << (int)Constructor->isImplicit()
3281       << SemaRef.Context.getTagDeclType(Constructor->getParent())
3282       << 0 << Field->getDeclName();
3283       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3284       return true;
3285     }
3286 
3287     if (FieldBaseElementType.isConstQualified()) {
3288       SemaRef.Diag(Constructor->getLocation(),
3289                    diag::err_uninitialized_member_in_ctor)
3290       << (int)Constructor->isImplicit()
3291       << SemaRef.Context.getTagDeclType(Constructor->getParent())
3292       << 1 << Field->getDeclName();
3293       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3294       return true;
3295     }
3296   }
3297 
3298   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
3299       FieldBaseElementType->isObjCRetainableType() &&
3300       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3301       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
3302     // ARC:
3303     //   Default-initialize Objective-C pointers to NULL.
3304     CXXMemberInit
3305       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3306                                                  Loc, Loc,
3307                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3308                                                  Loc);
3309     return false;
3310   }
3311 
3312   // Nothing to initialize.
3313   CXXMemberInit = 0;
3314   return false;
3315 }
3316 
3317 namespace {
3318 struct BaseAndFieldInfo {
3319   Sema &S;
3320   CXXConstructorDecl *Ctor;
3321   bool AnyErrorsInInits;
3322   ImplicitInitializerKind IIK;
3323   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
3324   SmallVector<CXXCtorInitializer*, 8> AllToInit;
3325   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
3326 
3327   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3328     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
3329     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3330     if (Generated && Ctor->isCopyConstructor())
3331       IIK = IIK_Copy;
3332     else if (Generated && Ctor->isMoveConstructor())
3333       IIK = IIK_Move;
3334     else if (Ctor->getInheritedConstructor())
3335       IIK = IIK_Inherit;
3336     else
3337       IIK = IIK_Default;
3338   }
3339 
3340   bool isImplicitCopyOrMove() const {
3341     switch (IIK) {
3342     case IIK_Copy:
3343     case IIK_Move:
3344       return true;
3345 
3346     case IIK_Default:
3347     case IIK_Inherit:
3348       return false;
3349     }
3350 
3351     llvm_unreachable("Invalid ImplicitInitializerKind!");
3352   }
3353 
3354   bool addFieldInitializer(CXXCtorInitializer *Init) {
3355     AllToInit.push_back(Init);
3356 
3357     // Check whether this initializer makes the field "used".
3358     if (Init->getInit()->HasSideEffects(S.Context))
3359       S.UnusedPrivateFields.remove(Init->getAnyMember());
3360 
3361     return false;
3362   }
3363 
3364   bool isInactiveUnionMember(FieldDecl *Field) {
3365     RecordDecl *Record = Field->getParent();
3366     if (!Record->isUnion())
3367       return false;
3368 
3369     if (FieldDecl *Active =
3370             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
3371       return Active != Field->getCanonicalDecl();
3372 
3373     // In an implicit copy or move constructor, ignore any in-class initializer.
3374     if (isImplicitCopyOrMove())
3375       return true;
3376 
3377     // If there's no explicit initialization, the field is active only if it
3378     // has an in-class initializer...
3379     if (Field->hasInClassInitializer())
3380       return false;
3381     // ... or it's an anonymous struct or union whose class has an in-class
3382     // initializer.
3383     if (!Field->isAnonymousStructOrUnion())
3384       return true;
3385     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3386     return !FieldRD->hasInClassInitializer();
3387   }
3388 
3389   /// \brief Determine whether the given field is, or is within, a union member
3390   /// that is inactive (because there was an initializer given for a different
3391   /// member of the union, or because the union was not initialized at all).
3392   bool isWithinInactiveUnionMember(FieldDecl *Field,
3393                                    IndirectFieldDecl *Indirect) {
3394     if (!Indirect)
3395       return isInactiveUnionMember(Field);
3396 
3397     for (auto *C : Indirect->chain()) {
3398       FieldDecl *Field = dyn_cast<FieldDecl>(C);
3399       if (Field && isInactiveUnionMember(Field))
3400         return true;
3401     }
3402     return false;
3403   }
3404 };
3405 }
3406 
3407 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
3408 /// array type.
3409 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3410   if (T->isIncompleteArrayType())
3411     return true;
3412 
3413   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3414     if (!ArrayT->getSize())
3415       return true;
3416 
3417     T = ArrayT->getElementType();
3418   }
3419 
3420   return false;
3421 }
3422 
3423 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
3424                                     FieldDecl *Field,
3425                                     IndirectFieldDecl *Indirect = 0) {
3426   if (Field->isInvalidDecl())
3427     return false;
3428 
3429   // Overwhelmingly common case: we have a direct initializer for this field.
3430   if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3431     return Info.addFieldInitializer(Init);
3432 
3433   // C++11 [class.base.init]p8:
3434   //   if the entity is a non-static data member that has a
3435   //   brace-or-equal-initializer and either
3436   //   -- the constructor's class is a union and no other variant member of that
3437   //      union is designated by a mem-initializer-id or
3438   //   -- the constructor's class is not a union, and, if the entity is a member
3439   //      of an anonymous union, no other member of that union is designated by
3440   //      a mem-initializer-id,
3441   //   the entity is initialized as specified in [dcl.init].
3442   //
3443   // We also apply the same rules to handle anonymous structs within anonymous
3444   // unions.
3445   if (Info.isWithinInactiveUnionMember(Field, Indirect))
3446     return false;
3447 
3448   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
3449     Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3450                                            Info.Ctor->getLocation(), Field);
3451     CXXCtorInitializer *Init;
3452     if (Indirect)
3453       Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3454                                                       SourceLocation(),
3455                                                       SourceLocation(), DIE,
3456                                                       SourceLocation());
3457     else
3458       Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3459                                                       SourceLocation(),
3460                                                       SourceLocation(), DIE,
3461                                                       SourceLocation());
3462     return Info.addFieldInitializer(Init);
3463   }
3464 
3465   // Don't initialize incomplete or zero-length arrays.
3466   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3467     return false;
3468 
3469   // Don't try to build an implicit initializer if there were semantic
3470   // errors in any of the initializers (and therefore we might be
3471   // missing some that the user actually wrote).
3472   if (Info.AnyErrorsInInits)
3473     return false;
3474 
3475   CXXCtorInitializer *Init = 0;
3476   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3477                                      Indirect, Init))
3478     return true;
3479 
3480   if (!Init)
3481     return false;
3482 
3483   return Info.addFieldInitializer(Init);
3484 }
3485 
3486 bool
3487 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3488                                CXXCtorInitializer *Initializer) {
3489   assert(Initializer->isDelegatingInitializer());
3490   Constructor->setNumCtorInitializers(1);
3491   CXXCtorInitializer **initializer =
3492     new (Context) CXXCtorInitializer*[1];
3493   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3494   Constructor->setCtorInitializers(initializer);
3495 
3496   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
3497     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
3498     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3499   }
3500 
3501   DelegatingCtorDecls.push_back(Constructor);
3502 
3503   return false;
3504 }
3505 
3506 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3507                                ArrayRef<CXXCtorInitializer *> Initializers) {
3508   if (Constructor->isDependentContext()) {
3509     // Just store the initializers as written, they will be checked during
3510     // instantiation.
3511     if (!Initializers.empty()) {
3512       Constructor->setNumCtorInitializers(Initializers.size());
3513       CXXCtorInitializer **baseOrMemberInitializers =
3514         new (Context) CXXCtorInitializer*[Initializers.size()];
3515       memcpy(baseOrMemberInitializers, Initializers.data(),
3516              Initializers.size() * sizeof(CXXCtorInitializer*));
3517       Constructor->setCtorInitializers(baseOrMemberInitializers);
3518     }
3519 
3520     // Let template instantiation know whether we had errors.
3521     if (AnyErrors)
3522       Constructor->setInvalidDecl();
3523 
3524     return false;
3525   }
3526 
3527   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
3528 
3529   // We need to build the initializer AST according to order of construction
3530   // and not what user specified in the Initializers list.
3531   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
3532   if (!ClassDecl)
3533     return true;
3534 
3535   bool HadError = false;
3536 
3537   for (unsigned i = 0; i < Initializers.size(); i++) {
3538     CXXCtorInitializer *Member = Initializers[i];
3539 
3540     if (Member->isBaseInitializer())
3541       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
3542     else {
3543       Info.AllBaseFields[Member->getAnyMember()] = Member;
3544 
3545       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
3546         for (auto *C : F->chain()) {
3547           FieldDecl *FD = dyn_cast<FieldDecl>(C);
3548           if (FD && FD->getParent()->isUnion())
3549             Info.ActiveUnionMember.insert(std::make_pair(
3550                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3551         }
3552       } else if (FieldDecl *FD = Member->getMember()) {
3553         if (FD->getParent()->isUnion())
3554           Info.ActiveUnionMember.insert(std::make_pair(
3555               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3556       }
3557     }
3558   }
3559 
3560   // Keep track of the direct virtual bases.
3561   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3562   for (auto &I : ClassDecl->bases()) {
3563     if (I.isVirtual())
3564       DirectVBases.insert(&I);
3565   }
3566 
3567   // Push virtual bases before others.
3568   for (auto &VBase : ClassDecl->vbases()) {
3569     if (CXXCtorInitializer *Value
3570         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
3571       // [class.base.init]p7, per DR257:
3572       //   A mem-initializer where the mem-initializer-id names a virtual base
3573       //   class is ignored during execution of a constructor of any class that
3574       //   is not the most derived class.
3575       if (ClassDecl->isAbstract()) {
3576         // FIXME: Provide a fixit to remove the base specifier. This requires
3577         // tracking the location of the associated comma for a base specifier.
3578         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3579           << VBase.getType() << ClassDecl;
3580         DiagnoseAbstractType(ClassDecl);
3581       }
3582 
3583       Info.AllToInit.push_back(Value);
3584     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3585       // [class.base.init]p8, per DR257:
3586       //   If a given [...] base class is not named by a mem-initializer-id
3587       //   [...] and the entity is not a virtual base class of an abstract
3588       //   class, then [...] the entity is default-initialized.
3589       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
3590       CXXCtorInitializer *CXXBaseInit;
3591       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3592                                        &VBase, IsInheritedVirtualBase,
3593                                        CXXBaseInit)) {
3594         HadError = true;
3595         continue;
3596       }
3597 
3598       Info.AllToInit.push_back(CXXBaseInit);
3599     }
3600   }
3601 
3602   // Non-virtual bases.
3603   for (auto &Base : ClassDecl->bases()) {
3604     // Virtuals are in the virtual base list and already constructed.
3605     if (Base.isVirtual())
3606       continue;
3607 
3608     if (CXXCtorInitializer *Value
3609           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
3610       Info.AllToInit.push_back(Value);
3611     } else if (!AnyErrors) {
3612       CXXCtorInitializer *CXXBaseInit;
3613       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3614                                        &Base, /*IsInheritedVirtualBase=*/false,
3615                                        CXXBaseInit)) {
3616         HadError = true;
3617         continue;
3618       }
3619 
3620       Info.AllToInit.push_back(CXXBaseInit);
3621     }
3622   }
3623 
3624   // Fields.
3625   for (auto *Mem : ClassDecl->decls()) {
3626     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
3627       // C++ [class.bit]p2:
3628       //   A declaration for a bit-field that omits the identifier declares an
3629       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
3630       //   initialized.
3631       if (F->isUnnamedBitfield())
3632         continue;
3633 
3634       // If we're not generating the implicit copy/move constructor, then we'll
3635       // handle anonymous struct/union fields based on their individual
3636       // indirect fields.
3637       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
3638         continue;
3639 
3640       if (CollectFieldInitializer(*this, Info, F))
3641         HadError = true;
3642       continue;
3643     }
3644 
3645     // Beyond this point, we only consider default initialization.
3646     if (Info.isImplicitCopyOrMove())
3647       continue;
3648 
3649     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
3650       if (F->getType()->isIncompleteArrayType()) {
3651         assert(ClassDecl->hasFlexibleArrayMember() &&
3652                "Incomplete array type is not valid");
3653         continue;
3654       }
3655 
3656       // Initialize each field of an anonymous struct individually.
3657       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3658         HadError = true;
3659 
3660       continue;
3661     }
3662   }
3663 
3664   unsigned NumInitializers = Info.AllToInit.size();
3665   if (NumInitializers > 0) {
3666     Constructor->setNumCtorInitializers(NumInitializers);
3667     CXXCtorInitializer **baseOrMemberInitializers =
3668       new (Context) CXXCtorInitializer*[NumInitializers];
3669     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
3670            NumInitializers * sizeof(CXXCtorInitializer*));
3671     Constructor->setCtorInitializers(baseOrMemberInitializers);
3672 
3673     // Constructors implicitly reference the base and member
3674     // destructors.
3675     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3676                                            Constructor->getParent());
3677   }
3678 
3679   return HadError;
3680 }
3681 
3682 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
3683   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
3684     const RecordDecl *RD = RT->getDecl();
3685     if (RD->isAnonymousStructOrUnion()) {
3686       for (auto *Field : RD->fields())
3687         PopulateKeysForFields(Field, IdealInits);
3688       return;
3689     }
3690   }
3691   IdealInits.push_back(Field);
3692 }
3693 
3694 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3695   return Context.getCanonicalType(BaseType).getTypePtr();
3696 }
3697 
3698 static const void *GetKeyForMember(ASTContext &Context,
3699                                    CXXCtorInitializer *Member) {
3700   if (!Member->isAnyMemberInitializer())
3701     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
3702 
3703   return Member->getAnyMember();
3704 }
3705 
3706 static void DiagnoseBaseOrMemInitializerOrder(
3707     Sema &SemaRef, const CXXConstructorDecl *Constructor,
3708     ArrayRef<CXXCtorInitializer *> Inits) {
3709   if (Constructor->getDeclContext()->isDependentContext())
3710     return;
3711 
3712   // Don't check initializers order unless the warning is enabled at the
3713   // location of at least one initializer.
3714   bool ShouldCheckOrder = false;
3715   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3716     CXXCtorInitializer *Init = Inits[InitIndex];
3717     if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3718                                          Init->getSourceLocation())
3719           != DiagnosticsEngine::Ignored) {
3720       ShouldCheckOrder = true;
3721       break;
3722     }
3723   }
3724   if (!ShouldCheckOrder)
3725     return;
3726 
3727   // Build the list of bases and members in the order that they'll
3728   // actually be initialized.  The explicit initializers should be in
3729   // this same order but may be missing things.
3730   SmallVector<const void*, 32> IdealInitKeys;
3731 
3732   const CXXRecordDecl *ClassDecl = Constructor->getParent();
3733 
3734   // 1. Virtual bases.
3735   for (const auto &VBase : ClassDecl->vbases())
3736     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
3737 
3738   // 2. Non-virtual bases.
3739   for (const auto &Base : ClassDecl->bases()) {
3740     if (Base.isVirtual())
3741       continue;
3742     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
3743   }
3744 
3745   // 3. Direct fields.
3746   for (auto *Field : ClassDecl->fields()) {
3747     if (Field->isUnnamedBitfield())
3748       continue;
3749 
3750     PopulateKeysForFields(Field, IdealInitKeys);
3751   }
3752 
3753   unsigned NumIdealInits = IdealInitKeys.size();
3754   unsigned IdealIndex = 0;
3755 
3756   CXXCtorInitializer *PrevInit = 0;
3757   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3758     CXXCtorInitializer *Init = Inits[InitIndex];
3759     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
3760 
3761     // Scan forward to try to find this initializer in the idealized
3762     // initializers list.
3763     for (; IdealIndex != NumIdealInits; ++IdealIndex)
3764       if (InitKey == IdealInitKeys[IdealIndex])
3765         break;
3766 
3767     // If we didn't find this initializer, it must be because we
3768     // scanned past it on a previous iteration.  That can only
3769     // happen if we're out of order;  emit a warning.
3770     if (IdealIndex == NumIdealInits && PrevInit) {
3771       Sema::SemaDiagnosticBuilder D =
3772         SemaRef.Diag(PrevInit->getSourceLocation(),
3773                      diag::warn_initializer_out_of_order);
3774 
3775       if (PrevInit->isAnyMemberInitializer())
3776         D << 0 << PrevInit->getAnyMember()->getDeclName();
3777       else
3778         D << 1 << PrevInit->getTypeSourceInfo()->getType();
3779 
3780       if (Init->isAnyMemberInitializer())
3781         D << 0 << Init->getAnyMember()->getDeclName();
3782       else
3783         D << 1 << Init->getTypeSourceInfo()->getType();
3784 
3785       // Move back to the initializer's location in the ideal list.
3786       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3787         if (InitKey == IdealInitKeys[IdealIndex])
3788           break;
3789 
3790       assert(IdealIndex != NumIdealInits &&
3791              "initializer not found in initializer list");
3792     }
3793 
3794     PrevInit = Init;
3795   }
3796 }
3797 
3798 namespace {
3799 bool CheckRedundantInit(Sema &S,
3800                         CXXCtorInitializer *Init,
3801                         CXXCtorInitializer *&PrevInit) {
3802   if (!PrevInit) {
3803     PrevInit = Init;
3804     return false;
3805   }
3806 
3807   if (FieldDecl *Field = Init->getAnyMember())
3808     S.Diag(Init->getSourceLocation(),
3809            diag::err_multiple_mem_initialization)
3810       << Field->getDeclName()
3811       << Init->getSourceRange();
3812   else {
3813     const Type *BaseClass = Init->getBaseClass();
3814     assert(BaseClass && "neither field nor base");
3815     S.Diag(Init->getSourceLocation(),
3816            diag::err_multiple_base_initialization)
3817       << QualType(BaseClass, 0)
3818       << Init->getSourceRange();
3819   }
3820   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3821     << 0 << PrevInit->getSourceRange();
3822 
3823   return true;
3824 }
3825 
3826 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
3827 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3828 
3829 bool CheckRedundantUnionInit(Sema &S,
3830                              CXXCtorInitializer *Init,
3831                              RedundantUnionMap &Unions) {
3832   FieldDecl *Field = Init->getAnyMember();
3833   RecordDecl *Parent = Field->getParent();
3834   NamedDecl *Child = Field;
3835 
3836   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
3837     if (Parent->isUnion()) {
3838       UnionEntry &En = Unions[Parent];
3839       if (En.first && En.first != Child) {
3840         S.Diag(Init->getSourceLocation(),
3841                diag::err_multiple_mem_union_initialization)
3842           << Field->getDeclName()
3843           << Init->getSourceRange();
3844         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3845           << 0 << En.second->getSourceRange();
3846         return true;
3847       }
3848       if (!En.first) {
3849         En.first = Child;
3850         En.second = Init;
3851       }
3852       if (!Parent->isAnonymousStructOrUnion())
3853         return false;
3854     }
3855 
3856     Child = Parent;
3857     Parent = cast<RecordDecl>(Parent->getDeclContext());
3858   }
3859 
3860   return false;
3861 }
3862 }
3863 
3864 /// ActOnMemInitializers - Handle the member initializers for a constructor.
3865 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
3866                                 SourceLocation ColonLoc,
3867                                 ArrayRef<CXXCtorInitializer*> MemInits,
3868                                 bool AnyErrors) {
3869   if (!ConstructorDecl)
3870     return;
3871 
3872   AdjustDeclIfTemplate(ConstructorDecl);
3873 
3874   CXXConstructorDecl *Constructor
3875     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
3876 
3877   if (!Constructor) {
3878     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3879     return;
3880   }
3881 
3882   // Mapping for the duplicate initializers check.
3883   // For member initializers, this is keyed with a FieldDecl*.
3884   // For base initializers, this is keyed with a Type*.
3885   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
3886 
3887   // Mapping for the inconsistent anonymous-union initializers check.
3888   RedundantUnionMap MemberUnions;
3889 
3890   bool HadError = false;
3891   for (unsigned i = 0; i < MemInits.size(); i++) {
3892     CXXCtorInitializer *Init = MemInits[i];
3893 
3894     // Set the source order index.
3895     Init->setSourceOrder(i);
3896 
3897     if (Init->isAnyMemberInitializer()) {
3898       FieldDecl *Field = Init->getAnyMember();
3899       if (CheckRedundantInit(*this, Init, Members[Field]) ||
3900           CheckRedundantUnionInit(*this, Init, MemberUnions))
3901         HadError = true;
3902     } else if (Init->isBaseInitializer()) {
3903       const void *Key =
3904           GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3905       if (CheckRedundantInit(*this, Init, Members[Key]))
3906         HadError = true;
3907     } else {
3908       assert(Init->isDelegatingInitializer());
3909       // This must be the only initializer
3910       if (MemInits.size() != 1) {
3911         Diag(Init->getSourceLocation(),
3912              diag::err_delegating_initializer_alone)
3913           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
3914         // We will treat this as being the only initializer.
3915       }
3916       SetDelegatingInitializer(Constructor, MemInits[i]);
3917       // Return immediately as the initializer is set.
3918       return;
3919     }
3920   }
3921 
3922   if (HadError)
3923     return;
3924 
3925   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
3926 
3927   SetCtorInitializers(Constructor, AnyErrors, MemInits);
3928 
3929   DiagnoseUninitializedFields(*this, Constructor);
3930 }
3931 
3932 void
3933 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3934                                              CXXRecordDecl *ClassDecl) {
3935   // Ignore dependent contexts. Also ignore unions, since their members never
3936   // have destructors implicitly called.
3937   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
3938     return;
3939 
3940   // FIXME: all the access-control diagnostics are positioned on the
3941   // field/base declaration.  That's probably good; that said, the
3942   // user might reasonably want to know why the destructor is being
3943   // emitted, and we currently don't say.
3944 
3945   // Non-static data members.
3946   for (auto *Field : ClassDecl->fields()) {
3947     if (Field->isInvalidDecl())
3948       continue;
3949 
3950     // Don't destroy incomplete or zero-length arrays.
3951     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3952       continue;
3953 
3954     QualType FieldType = Context.getBaseElementType(Field->getType());
3955 
3956     const RecordType* RT = FieldType->getAs<RecordType>();
3957     if (!RT)
3958       continue;
3959 
3960     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3961     if (FieldClassDecl->isInvalidDecl())
3962       continue;
3963     if (FieldClassDecl->hasIrrelevantDestructor())
3964       continue;
3965     // The destructor for an implicit anonymous union member is never invoked.
3966     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3967       continue;
3968 
3969     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
3970     assert(Dtor && "No dtor found for FieldClassDecl!");
3971     CheckDestructorAccess(Field->getLocation(), Dtor,
3972                           PDiag(diag::err_access_dtor_field)
3973                             << Field->getDeclName()
3974                             << FieldType);
3975 
3976     MarkFunctionReferenced(Location, Dtor);
3977     DiagnoseUseOfDecl(Dtor, Location);
3978   }
3979 
3980   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3981 
3982   // Bases.
3983   for (const auto &Base : ClassDecl->bases()) {
3984     // Bases are always records in a well-formed non-dependent class.
3985     const RecordType *RT = Base.getType()->getAs<RecordType>();
3986 
3987     // Remember direct virtual bases.
3988     if (Base.isVirtual())
3989       DirectVirtualBases.insert(RT);
3990 
3991     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3992     // If our base class is invalid, we probably can't get its dtor anyway.
3993     if (BaseClassDecl->isInvalidDecl())
3994       continue;
3995     if (BaseClassDecl->hasIrrelevantDestructor())
3996       continue;
3997 
3998     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3999     assert(Dtor && "No dtor found for BaseClassDecl!");
4000 
4001     // FIXME: caret should be on the start of the class name
4002     CheckDestructorAccess(Base.getLocStart(), Dtor,
4003                           PDiag(diag::err_access_dtor_base)
4004                             << Base.getType()
4005                             << Base.getSourceRange(),
4006                           Context.getTypeDeclType(ClassDecl));
4007 
4008     MarkFunctionReferenced(Location, Dtor);
4009     DiagnoseUseOfDecl(Dtor, Location);
4010   }
4011 
4012   // Virtual bases.
4013   for (const auto &VBase : ClassDecl->vbases()) {
4014     // Bases are always records in a well-formed non-dependent class.
4015     const RecordType *RT = VBase.getType()->castAs<RecordType>();
4016 
4017     // Ignore direct virtual bases.
4018     if (DirectVirtualBases.count(RT))
4019       continue;
4020 
4021     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4022     // If our base class is invalid, we probably can't get its dtor anyway.
4023     if (BaseClassDecl->isInvalidDecl())
4024       continue;
4025     if (BaseClassDecl->hasIrrelevantDestructor())
4026       continue;
4027 
4028     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4029     assert(Dtor && "No dtor found for BaseClassDecl!");
4030     if (CheckDestructorAccess(
4031             ClassDecl->getLocation(), Dtor,
4032             PDiag(diag::err_access_dtor_vbase)
4033                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
4034             Context.getTypeDeclType(ClassDecl)) ==
4035         AR_accessible) {
4036       CheckDerivedToBaseConversion(
4037           Context.getTypeDeclType(ClassDecl), VBase.getType(),
4038           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4039           SourceRange(), DeclarationName(), 0);
4040     }
4041 
4042     MarkFunctionReferenced(Location, Dtor);
4043     DiagnoseUseOfDecl(Dtor, Location);
4044   }
4045 }
4046 
4047 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
4048   if (!CDtorDecl)
4049     return;
4050 
4051   if (CXXConstructorDecl *Constructor
4052       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
4053     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
4054     DiagnoseUninitializedFields(*this, Constructor);
4055   }
4056 }
4057 
4058 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4059                                   unsigned DiagID, AbstractDiagSelID SelID) {
4060   class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4061     unsigned DiagID;
4062     AbstractDiagSelID SelID;
4063 
4064   public:
4065     NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4066       : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
4067 
4068     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
4069       if (Suppressed) return;
4070       if (SelID == -1)
4071         S.Diag(Loc, DiagID) << T;
4072       else
4073         S.Diag(Loc, DiagID) << SelID << T;
4074     }
4075   } Diagnoser(DiagID, SelID);
4076 
4077   return RequireNonAbstractType(Loc, T, Diagnoser);
4078 }
4079 
4080 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4081                                   TypeDiagnoser &Diagnoser) {
4082   if (!getLangOpts().CPlusPlus)
4083     return false;
4084 
4085   if (const ArrayType *AT = Context.getAsArrayType(T))
4086     return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4087 
4088   if (const PointerType *PT = T->getAs<PointerType>()) {
4089     // Find the innermost pointer type.
4090     while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
4091       PT = T;
4092 
4093     if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
4094       return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4095   }
4096 
4097   const RecordType *RT = T->getAs<RecordType>();
4098   if (!RT)
4099     return false;
4100 
4101   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4102 
4103   // We can't answer whether something is abstract until it has a
4104   // definition.  If it's currently being defined, we'll walk back
4105   // over all the declarations when we have a full definition.
4106   const CXXRecordDecl *Def = RD->getDefinition();
4107   if (!Def || Def->isBeingDefined())
4108     return false;
4109 
4110   if (!RD->isAbstract())
4111     return false;
4112 
4113   Diagnoser.diagnose(*this, Loc, T);
4114   DiagnoseAbstractType(RD);
4115 
4116   return true;
4117 }
4118 
4119 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4120   // Check if we've already emitted the list of pure virtual functions
4121   // for this class.
4122   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
4123     return;
4124 
4125   // If the diagnostic is suppressed, don't emit the notes. We're only
4126   // going to emit them once, so try to attach them to a diagnostic we're
4127   // actually going to show.
4128   if (Diags.isLastDiagnosticIgnored())
4129     return;
4130 
4131   CXXFinalOverriderMap FinalOverriders;
4132   RD->getFinalOverriders(FinalOverriders);
4133 
4134   // Keep a set of seen pure methods so we won't diagnose the same method
4135   // more than once.
4136   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4137 
4138   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4139                                    MEnd = FinalOverriders.end();
4140        M != MEnd;
4141        ++M) {
4142     for (OverridingMethods::iterator SO = M->second.begin(),
4143                                   SOEnd = M->second.end();
4144          SO != SOEnd; ++SO) {
4145       // C++ [class.abstract]p4:
4146       //   A class is abstract if it contains or inherits at least one
4147       //   pure virtual function for which the final overrider is pure
4148       //   virtual.
4149 
4150       //
4151       if (SO->second.size() != 1)
4152         continue;
4153 
4154       if (!SO->second.front().Method->isPure())
4155         continue;
4156 
4157       if (!SeenPureMethods.insert(SO->second.front().Method))
4158         continue;
4159 
4160       Diag(SO->second.front().Method->getLocation(),
4161            diag::note_pure_virtual_function)
4162         << SO->second.front().Method->getDeclName() << RD->getDeclName();
4163     }
4164   }
4165 
4166   if (!PureVirtualClassDiagSet)
4167     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4168   PureVirtualClassDiagSet->insert(RD);
4169 }
4170 
4171 namespace {
4172 struct AbstractUsageInfo {
4173   Sema &S;
4174   CXXRecordDecl *Record;
4175   CanQualType AbstractType;
4176   bool Invalid;
4177 
4178   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4179     : S(S), Record(Record),
4180       AbstractType(S.Context.getCanonicalType(
4181                    S.Context.getTypeDeclType(Record))),
4182       Invalid(false) {}
4183 
4184   void DiagnoseAbstractType() {
4185     if (Invalid) return;
4186     S.DiagnoseAbstractType(Record);
4187     Invalid = true;
4188   }
4189 
4190   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4191 };
4192 
4193 struct CheckAbstractUsage {
4194   AbstractUsageInfo &Info;
4195   const NamedDecl *Ctx;
4196 
4197   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4198     : Info(Info), Ctx(Ctx) {}
4199 
4200   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4201     switch (TL.getTypeLocClass()) {
4202 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4203 #define TYPELOC(CLASS, PARENT) \
4204     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
4205 #include "clang/AST/TypeLocNodes.def"
4206     }
4207   }
4208 
4209   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4210     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
4211     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4212       if (!TL.getParam(I))
4213         continue;
4214 
4215       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
4216       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
4217     }
4218   }
4219 
4220   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4221     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4222   }
4223 
4224   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4225     // Visit the type parameters from a permissive context.
4226     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4227       TemplateArgumentLoc TAL = TL.getArgLoc(I);
4228       if (TAL.getArgument().getKind() == TemplateArgument::Type)
4229         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4230           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4231       // TODO: other template argument types?
4232     }
4233   }
4234 
4235   // Visit pointee types from a permissive context.
4236 #define CheckPolymorphic(Type) \
4237   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4238     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4239   }
4240   CheckPolymorphic(PointerTypeLoc)
4241   CheckPolymorphic(ReferenceTypeLoc)
4242   CheckPolymorphic(MemberPointerTypeLoc)
4243   CheckPolymorphic(BlockPointerTypeLoc)
4244   CheckPolymorphic(AtomicTypeLoc)
4245 
4246   /// Handle all the types we haven't given a more specific
4247   /// implementation for above.
4248   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4249     // Every other kind of type that we haven't called out already
4250     // that has an inner type is either (1) sugar or (2) contains that
4251     // inner type in some way as a subobject.
4252     if (TypeLoc Next = TL.getNextTypeLoc())
4253       return Visit(Next, Sel);
4254 
4255     // If there's no inner type and we're in a permissive context,
4256     // don't diagnose.
4257     if (Sel == Sema::AbstractNone) return;
4258 
4259     // Check whether the type matches the abstract type.
4260     QualType T = TL.getType();
4261     if (T->isArrayType()) {
4262       Sel = Sema::AbstractArrayType;
4263       T = Info.S.Context.getBaseElementType(T);
4264     }
4265     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4266     if (CT != Info.AbstractType) return;
4267 
4268     // It matched; do some magic.
4269     if (Sel == Sema::AbstractArrayType) {
4270       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4271         << T << TL.getSourceRange();
4272     } else {
4273       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4274         << Sel << T << TL.getSourceRange();
4275     }
4276     Info.DiagnoseAbstractType();
4277   }
4278 };
4279 
4280 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4281                                   Sema::AbstractDiagSelID Sel) {
4282   CheckAbstractUsage(*this, D).Visit(TL, Sel);
4283 }
4284 
4285 }
4286 
4287 /// Check for invalid uses of an abstract type in a method declaration.
4288 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4289                                     CXXMethodDecl *MD) {
4290   // No need to do the check on definitions, which require that
4291   // the return/param types be complete.
4292   if (MD->doesThisDeclarationHaveABody())
4293     return;
4294 
4295   // For safety's sake, just ignore it if we don't have type source
4296   // information.  This should never happen for non-implicit methods,
4297   // but...
4298   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4299     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4300 }
4301 
4302 /// Check for invalid uses of an abstract type within a class definition.
4303 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4304                                     CXXRecordDecl *RD) {
4305   for (auto *D : RD->decls()) {
4306     if (D->isImplicit()) continue;
4307 
4308     // Methods and method templates.
4309     if (isa<CXXMethodDecl>(D)) {
4310       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4311     } else if (isa<FunctionTemplateDecl>(D)) {
4312       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4313       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4314 
4315     // Fields and static variables.
4316     } else if (isa<FieldDecl>(D)) {
4317       FieldDecl *FD = cast<FieldDecl>(D);
4318       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4319         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4320     } else if (isa<VarDecl>(D)) {
4321       VarDecl *VD = cast<VarDecl>(D);
4322       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4323         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4324 
4325     // Nested classes and class templates.
4326     } else if (isa<CXXRecordDecl>(D)) {
4327       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4328     } else if (isa<ClassTemplateDecl>(D)) {
4329       CheckAbstractClassUsage(Info,
4330                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4331     }
4332   }
4333 }
4334 
4335 /// \brief Perform semantic checks on a class definition that has been
4336 /// completing, introducing implicitly-declared members, checking for
4337 /// abstract types, etc.
4338 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
4339   if (!Record)
4340     return;
4341 
4342   if (Record->isAbstract() && !Record->isInvalidDecl()) {
4343     AbstractUsageInfo Info(*this, Record);
4344     CheckAbstractClassUsage(Info, Record);
4345   }
4346 
4347   // If this is not an aggregate type and has no user-declared constructor,
4348   // complain about any non-static data members of reference or const scalar
4349   // type, since they will never get initializers.
4350   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
4351       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4352       !Record->isLambda()) {
4353     bool Complained = false;
4354     for (const auto *F : Record->fields()) {
4355       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
4356         continue;
4357 
4358       if (F->getType()->isReferenceType() ||
4359           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
4360         if (!Complained) {
4361           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4362             << Record->getTagKind() << Record;
4363           Complained = true;
4364         }
4365 
4366         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4367           << F->getType()->isReferenceType()
4368           << F->getDeclName();
4369       }
4370     }
4371   }
4372 
4373   if (Record->isDynamicClass() && !Record->isDependentType())
4374     DynamicClasses.push_back(Record);
4375 
4376   if (Record->getIdentifier()) {
4377     // C++ [class.mem]p13:
4378     //   If T is the name of a class, then each of the following shall have a
4379     //   name different from T:
4380     //     - every member of every anonymous union that is a member of class T.
4381     //
4382     // C++ [class.mem]p14:
4383     //   In addition, if class T has a user-declared constructor (12.1), every
4384     //   non-static data member of class T shall have a name different from T.
4385     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4386     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4387          ++I) {
4388       NamedDecl *D = *I;
4389       if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4390           isa<IndirectFieldDecl>(D)) {
4391         Diag(D->getLocation(), diag::err_member_name_of_class)
4392           << D->getDeclName();
4393         break;
4394       }
4395     }
4396   }
4397 
4398   // Warn if the class has virtual methods but non-virtual public destructor.
4399   if (Record->isPolymorphic() && !Record->isDependentType()) {
4400     CXXDestructorDecl *dtor = Record->getDestructor();
4401     if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
4402       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4403            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4404   }
4405 
4406   if (Record->isAbstract()) {
4407     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4408       Diag(Record->getLocation(), diag::warn_abstract_final_class)
4409         << FA->isSpelledAsSealed();
4410       DiagnoseAbstractType(Record);
4411     }
4412   }
4413 
4414   if (!Record->isDependentType()) {
4415     for (auto *M : Record->methods()) {
4416       // See if a method overloads virtual methods in a base
4417       // class without overriding any.
4418       if (!M->isStatic())
4419         DiagnoseHiddenVirtualMethods(M);
4420 
4421       // Check whether the explicitly-defaulted special members are valid.
4422       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4423         CheckExplicitlyDefaultedSpecialMember(M);
4424 
4425       // For an explicitly defaulted or deleted special member, we defer
4426       // determining triviality until the class is complete. That time is now!
4427       if (!M->isImplicit() && !M->isUserProvided()) {
4428         CXXSpecialMember CSM = getSpecialMember(M);
4429         if (CSM != CXXInvalid) {
4430           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
4431 
4432           // Inform the class that we've finished declaring this member.
4433           Record->finishedDefaultedOrDeletedMember(M);
4434         }
4435       }
4436     }
4437   }
4438 
4439   // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4440   // function that is not a constructor declares that member function to be
4441   // const. [...] The class of which that function is a member shall be
4442   // a literal type.
4443   //
4444   // If the class has virtual bases, any constexpr members will already have
4445   // been diagnosed by the checks performed on the member declaration, so
4446   // suppress this (less useful) diagnostic.
4447   //
4448   // We delay this until we know whether an explicitly-defaulted (or deleted)
4449   // destructor for the class is trivial.
4450   if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
4451       !Record->isLiteral() && !Record->getNumVBases()) {
4452     for (const auto *M : Record->methods()) {
4453       if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) {
4454         switch (Record->getTemplateSpecializationKind()) {
4455         case TSK_ImplicitInstantiation:
4456         case TSK_ExplicitInstantiationDeclaration:
4457         case TSK_ExplicitInstantiationDefinition:
4458           // If a template instantiates to a non-literal type, but its members
4459           // instantiate to constexpr functions, the template is technically
4460           // ill-formed, but we allow it for sanity.
4461           continue;
4462 
4463         case TSK_Undeclared:
4464         case TSK_ExplicitSpecialization:
4465           RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4466                              diag::err_constexpr_method_non_literal);
4467           break;
4468         }
4469 
4470         // Only produce one error per class.
4471         break;
4472       }
4473     }
4474   }
4475 
4476   // ms_struct is a request to use the same ABI rules as MSVC.  Check
4477   // whether this class uses any C++ features that are implemented
4478   // completely differently in MSVC, and if so, emit a diagnostic.
4479   // That diagnostic defaults to an error, but we allow projects to
4480   // map it down to a warning (or ignore it).  It's a fairly common
4481   // practice among users of the ms_struct pragma to mass-annotate
4482   // headers, sweeping up a bunch of types that the project doesn't
4483   // really rely on MSVC-compatible layout for.  We must therefore
4484   // support "ms_struct except for C++ stuff" as a secondary ABI.
4485   if (Record->isMsStruct(Context) &&
4486       (Record->isPolymorphic() || Record->getNumBases())) {
4487     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
4488   }
4489 
4490   // Declare inheriting constructors. We do this eagerly here because:
4491   // - The standard requires an eager diagnostic for conflicting inheriting
4492   //   constructors from different classes.
4493   // - The lazy declaration of the other implicit constructors is so as to not
4494   //   waste space and performance on classes that are not meant to be
4495   //   instantiated (e.g. meta-functions). This doesn't apply to classes that
4496   //   have inheriting constructors.
4497   DeclareInheritingConstructors(Record);
4498 }
4499 
4500 /// Look up the special member function that would be called by a special
4501 /// member function for a subobject of class type.
4502 ///
4503 /// \param Class The class type of the subobject.
4504 /// \param CSM The kind of special member function.
4505 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4506 /// \param ConstRHS True if this is a copy operation with a const object
4507 ///        on its RHS, that is, if the argument to the outer special member
4508 ///        function is 'const' and this is not a field marked 'mutable'.
4509 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
4510     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
4511     unsigned FieldQuals, bool ConstRHS) {
4512   unsigned LHSQuals = 0;
4513   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
4514     LHSQuals = FieldQuals;
4515 
4516   unsigned RHSQuals = FieldQuals;
4517   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4518     RHSQuals = 0;
4519   else if (ConstRHS)
4520     RHSQuals |= Qualifiers::Const;
4521 
4522   return S.LookupSpecialMember(Class, CSM,
4523                                RHSQuals & Qualifiers::Const,
4524                                RHSQuals & Qualifiers::Volatile,
4525                                false,
4526                                LHSQuals & Qualifiers::Const,
4527                                LHSQuals & Qualifiers::Volatile);
4528 }
4529 
4530 /// Is the special member function which would be selected to perform the
4531 /// specified operation on the specified class type a constexpr constructor?
4532 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4533                                      Sema::CXXSpecialMember CSM,
4534                                      unsigned Quals, bool ConstRHS) {
4535   Sema::SpecialMemberOverloadResult *SMOR =
4536       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
4537   if (!SMOR || !SMOR->getMethod())
4538     // A constructor we wouldn't select can't be "involved in initializing"
4539     // anything.
4540     return true;
4541   return SMOR->getMethod()->isConstexpr();
4542 }
4543 
4544 /// Determine whether the specified special member function would be constexpr
4545 /// if it were implicitly defined.
4546 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4547                                               Sema::CXXSpecialMember CSM,
4548                                               bool ConstArg) {
4549   if (!S.getLangOpts().CPlusPlus11)
4550     return false;
4551 
4552   // C++11 [dcl.constexpr]p4:
4553   // In the definition of a constexpr constructor [...]
4554   bool Ctor = true;
4555   switch (CSM) {
4556   case Sema::CXXDefaultConstructor:
4557     // Since default constructor lookup is essentially trivial (and cannot
4558     // involve, for instance, template instantiation), we compute whether a
4559     // defaulted default constructor is constexpr directly within CXXRecordDecl.
4560     //
4561     // This is important for performance; we need to know whether the default
4562     // constructor is constexpr to determine whether the type is a literal type.
4563     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4564 
4565   case Sema::CXXCopyConstructor:
4566   case Sema::CXXMoveConstructor:
4567     // For copy or move constructors, we need to perform overload resolution.
4568     break;
4569 
4570   case Sema::CXXCopyAssignment:
4571   case Sema::CXXMoveAssignment:
4572     if (!S.getLangOpts().CPlusPlus1y)
4573       return false;
4574     // In C++1y, we need to perform overload resolution.
4575     Ctor = false;
4576     break;
4577 
4578   case Sema::CXXDestructor:
4579   case Sema::CXXInvalid:
4580     return false;
4581   }
4582 
4583   //   -- if the class is a non-empty union, or for each non-empty anonymous
4584   //      union member of a non-union class, exactly one non-static data member
4585   //      shall be initialized; [DR1359]
4586   //
4587   // If we squint, this is guaranteed, since exactly one non-static data member
4588   // will be initialized (if the constructor isn't deleted), we just don't know
4589   // which one.
4590   if (Ctor && ClassDecl->isUnion())
4591     return true;
4592 
4593   //   -- the class shall not have any virtual base classes;
4594   if (Ctor && ClassDecl->getNumVBases())
4595     return false;
4596 
4597   // C++1y [class.copy]p26:
4598   //   -- [the class] is a literal type, and
4599   if (!Ctor && !ClassDecl->isLiteral())
4600     return false;
4601 
4602   //   -- every constructor involved in initializing [...] base class
4603   //      sub-objects shall be a constexpr constructor;
4604   //   -- the assignment operator selected to copy/move each direct base
4605   //      class is a constexpr function, and
4606   for (const auto &B : ClassDecl->bases()) {
4607     const RecordType *BaseType = B.getType()->getAs<RecordType>();
4608     if (!BaseType) continue;
4609 
4610     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4611     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
4612       return false;
4613   }
4614 
4615   //   -- every constructor involved in initializing non-static data members
4616   //      [...] shall be a constexpr constructor;
4617   //   -- every non-static data member and base class sub-object shall be
4618   //      initialized
4619   //   -- for each non-static data member of X that is of class type (or array
4620   //      thereof), the assignment operator selected to copy/move that member is
4621   //      a constexpr function
4622   for (const auto *F : ClassDecl->fields()) {
4623     if (F->isInvalidDecl())
4624       continue;
4625     QualType BaseType = S.Context.getBaseElementType(F->getType());
4626     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
4627       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4628       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
4629                                     BaseType.getCVRQualifiers(),
4630                                     ConstArg && !F->isMutable()))
4631         return false;
4632     }
4633   }
4634 
4635   // All OK, it's constexpr!
4636   return true;
4637 }
4638 
4639 static Sema::ImplicitExceptionSpecification
4640 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4641   switch (S.getSpecialMember(MD)) {
4642   case Sema::CXXDefaultConstructor:
4643     return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4644   case Sema::CXXCopyConstructor:
4645     return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4646   case Sema::CXXCopyAssignment:
4647     return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4648   case Sema::CXXMoveConstructor:
4649     return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4650   case Sema::CXXMoveAssignment:
4651     return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4652   case Sema::CXXDestructor:
4653     return S.ComputeDefaultedDtorExceptionSpec(MD);
4654   case Sema::CXXInvalid:
4655     break;
4656   }
4657   assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4658          "only special members have implicit exception specs");
4659   return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
4660 }
4661 
4662 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4663                                                             CXXMethodDecl *MD) {
4664   FunctionProtoType::ExtProtoInfo EPI;
4665 
4666   // Build an exception specification pointing back at this member.
4667   EPI.ExceptionSpecType = EST_Unevaluated;
4668   EPI.ExceptionSpecDecl = MD;
4669 
4670   // Set the calling convention to the default for C++ instance methods.
4671   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4672       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4673                                             /*IsCXXMethod=*/true));
4674   return EPI;
4675 }
4676 
4677 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4678   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4679   if (FPT->getExceptionSpecType() != EST_Unevaluated)
4680     return;
4681 
4682   // Evaluate the exception specification.
4683   ImplicitExceptionSpecification ExceptSpec =
4684       computeImplicitExceptionSpec(*this, Loc, MD);
4685 
4686   FunctionProtoType::ExtProtoInfo EPI;
4687   ExceptSpec.getEPI(EPI);
4688 
4689   // Update the type of the special member to use it.
4690   UpdateExceptionSpec(MD, EPI);
4691 
4692   // A user-provided destructor can be defined outside the class. When that
4693   // happens, be sure to update the exception specification on both
4694   // declarations.
4695   const FunctionProtoType *CanonicalFPT =
4696     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4697   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4698     UpdateExceptionSpec(MD->getCanonicalDecl(), EPI);
4699 }
4700 
4701 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4702   CXXRecordDecl *RD = MD->getParent();
4703   CXXSpecialMember CSM = getSpecialMember(MD);
4704 
4705   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4706          "not an explicitly-defaulted special member");
4707 
4708   // Whether this was the first-declared instance of the constructor.
4709   // This affects whether we implicitly add an exception spec and constexpr.
4710   bool First = MD == MD->getCanonicalDecl();
4711 
4712   bool HadError = false;
4713 
4714   // C++11 [dcl.fct.def.default]p1:
4715   //   A function that is explicitly defaulted shall
4716   //     -- be a special member function (checked elsewhere),
4717   //     -- have the same type (except for ref-qualifiers, and except that a
4718   //        copy operation can take a non-const reference) as an implicit
4719   //        declaration, and
4720   //     -- not have default arguments.
4721   unsigned ExpectedParams = 1;
4722   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4723     ExpectedParams = 0;
4724   if (MD->getNumParams() != ExpectedParams) {
4725     // This also checks for default arguments: a copy or move constructor with a
4726     // default argument is classified as a default constructor, and assignment
4727     // operations and destructors can't have default arguments.
4728     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4729       << CSM << MD->getSourceRange();
4730     HadError = true;
4731   } else if (MD->isVariadic()) {
4732     Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4733       << CSM << MD->getSourceRange();
4734     HadError = true;
4735   }
4736 
4737   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
4738 
4739   bool CanHaveConstParam = false;
4740   if (CSM == CXXCopyConstructor)
4741     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
4742   else if (CSM == CXXCopyAssignment)
4743     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
4744 
4745   QualType ReturnType = Context.VoidTy;
4746   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4747     // Check for return type matching.
4748     ReturnType = Type->getReturnType();
4749     QualType ExpectedReturnType =
4750         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4751     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4752       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4753         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4754       HadError = true;
4755     }
4756 
4757     // A defaulted special member cannot have cv-qualifiers.
4758     if (Type->getTypeQuals()) {
4759       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4760         << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
4761       HadError = true;
4762     }
4763   }
4764 
4765   // Check for parameter type matching.
4766   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
4767   bool HasConstParam = false;
4768   if (ExpectedParams && ArgType->isReferenceType()) {
4769     // Argument must be reference to possibly-const T.
4770     QualType ReferentType = ArgType->getPointeeType();
4771     HasConstParam = ReferentType.isConstQualified();
4772 
4773     if (ReferentType.isVolatileQualified()) {
4774       Diag(MD->getLocation(),
4775            diag::err_defaulted_special_member_volatile_param) << CSM;
4776       HadError = true;
4777     }
4778 
4779     if (HasConstParam && !CanHaveConstParam) {
4780       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4781         Diag(MD->getLocation(),
4782              diag::err_defaulted_special_member_copy_const_param)
4783           << (CSM == CXXCopyAssignment);
4784         // FIXME: Explain why this special member can't be const.
4785       } else {
4786         Diag(MD->getLocation(),
4787              diag::err_defaulted_special_member_move_const_param)
4788           << (CSM == CXXMoveAssignment);
4789       }
4790       HadError = true;
4791     }
4792   } else if (ExpectedParams) {
4793     // A copy assignment operator can take its argument by value, but a
4794     // defaulted one cannot.
4795     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
4796     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
4797     HadError = true;
4798   }
4799 
4800   // C++11 [dcl.fct.def.default]p2:
4801   //   An explicitly-defaulted function may be declared constexpr only if it
4802   //   would have been implicitly declared as constexpr,
4803   // Do not apply this rule to members of class templates, since core issue 1358
4804   // makes such functions always instantiate to constexpr functions. For
4805   // functions which cannot be constexpr (for non-constructors in C++11 and for
4806   // destructors in C++1y), this is checked elsewhere.
4807   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4808                                                      HasConstParam);
4809   if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4810                                  : isa<CXXConstructorDecl>(MD)) &&
4811       MD->isConstexpr() && !Constexpr &&
4812       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4813     Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
4814     // FIXME: Explain why the special member can't be constexpr.
4815     HadError = true;
4816   }
4817 
4818   //   and may have an explicit exception-specification only if it is compatible
4819   //   with the exception-specification on the implicit declaration.
4820   if (Type->hasExceptionSpec()) {
4821     // Delay the check if this is the first declaration of the special member,
4822     // since we may not have parsed some necessary in-class initializers yet.
4823     if (First) {
4824       // If the exception specification needs to be instantiated, do so now,
4825       // before we clobber it with an EST_Unevaluated specification below.
4826       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4827         InstantiateExceptionSpec(MD->getLocStart(), MD);
4828         Type = MD->getType()->getAs<FunctionProtoType>();
4829       }
4830       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
4831     } else
4832       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4833   }
4834 
4835   //   If a function is explicitly defaulted on its first declaration,
4836   if (First) {
4837     //  -- it is implicitly considered to be constexpr if the implicit
4838     //     definition would be,
4839     MD->setConstexpr(Constexpr);
4840 
4841     //  -- it is implicitly considered to have the same exception-specification
4842     //     as if it had been implicitly declared,
4843     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4844     EPI.ExceptionSpecType = EST_Unevaluated;
4845     EPI.ExceptionSpecDecl = MD;
4846     MD->setType(Context.getFunctionType(ReturnType,
4847                                         ArrayRef<QualType>(&ArgType,
4848                                                            ExpectedParams),
4849                                         EPI));
4850   }
4851 
4852   if (ShouldDeleteSpecialMember(MD, CSM)) {
4853     if (First) {
4854       SetDeclDeleted(MD, MD->getLocation());
4855     } else {
4856       // C++11 [dcl.fct.def.default]p4:
4857       //   [For a] user-provided explicitly-defaulted function [...] if such a
4858       //   function is implicitly defined as deleted, the program is ill-formed.
4859       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4860       ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
4861       HadError = true;
4862     }
4863   }
4864 
4865   if (HadError)
4866     MD->setInvalidDecl();
4867 }
4868 
4869 /// Check whether the exception specification provided for an
4870 /// explicitly-defaulted special member matches the exception specification
4871 /// that would have been generated for an implicit special member, per
4872 /// C++11 [dcl.fct.def.default]p2.
4873 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4874     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4875   // Compute the implicit exception specification.
4876   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4877                                                        /*IsCXXMethod=*/true);
4878   FunctionProtoType::ExtProtoInfo EPI(CC);
4879   computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4880   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
4881     Context.getFunctionType(Context.VoidTy, None, EPI));
4882 
4883   // Ensure that it matches.
4884   CheckEquivalentExceptionSpec(
4885     PDiag(diag::err_incorrect_defaulted_exception_spec)
4886       << getSpecialMember(MD), PDiag(),
4887     ImplicitType, SourceLocation(),
4888     SpecifiedType, MD->getLocation());
4889 }
4890 
4891 void Sema::CheckDelayedMemberExceptionSpecs() {
4892   SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
4893               2> Checks;
4894   SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
4895 
4896   std::swap(Checks, DelayedDestructorExceptionSpecChecks);
4897   std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
4898 
4899   // Perform any deferred checking of exception specifications for virtual
4900   // destructors.
4901   for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
4902     const CXXDestructorDecl *Dtor = Checks[i].first;
4903     assert(!Dtor->getParent()->isDependentType() &&
4904            "Should not ever add destructors of templates into the list.");
4905     CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
4906   }
4907 
4908   // Check that any explicitly-defaulted methods have exception specifications
4909   // compatible with their implicit exception specifications.
4910   for (unsigned I = 0, N = Specs.size(); I != N; ++I)
4911     CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
4912                                                 Specs[I].second);
4913 }
4914 
4915 namespace {
4916 struct SpecialMemberDeletionInfo {
4917   Sema &S;
4918   CXXMethodDecl *MD;
4919   Sema::CXXSpecialMember CSM;
4920   bool Diagnose;
4921 
4922   // Properties of the special member, computed for convenience.
4923   bool IsConstructor, IsAssignment, IsMove, ConstArg;
4924   SourceLocation Loc;
4925 
4926   bool AllFieldsAreConst;
4927 
4928   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
4929                             Sema::CXXSpecialMember CSM, bool Diagnose)
4930     : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
4931       IsConstructor(false), IsAssignment(false), IsMove(false),
4932       ConstArg(false), Loc(MD->getLocation()),
4933       AllFieldsAreConst(true) {
4934     switch (CSM) {
4935       case Sema::CXXDefaultConstructor:
4936       case Sema::CXXCopyConstructor:
4937         IsConstructor = true;
4938         break;
4939       case Sema::CXXMoveConstructor:
4940         IsConstructor = true;
4941         IsMove = true;
4942         break;
4943       case Sema::CXXCopyAssignment:
4944         IsAssignment = true;
4945         break;
4946       case Sema::CXXMoveAssignment:
4947         IsAssignment = true;
4948         IsMove = true;
4949         break;
4950       case Sema::CXXDestructor:
4951         break;
4952       case Sema::CXXInvalid:
4953         llvm_unreachable("invalid special member kind");
4954     }
4955 
4956     if (MD->getNumParams()) {
4957       if (const ReferenceType *RT =
4958               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
4959         ConstArg = RT->getPointeeType().isConstQualified();
4960     }
4961   }
4962 
4963   bool inUnion() const { return MD->getParent()->isUnion(); }
4964 
4965   /// Look up the corresponding special member in the given class.
4966   Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4967                                               unsigned Quals, bool IsMutable) {
4968     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
4969                                        ConstArg && !IsMutable);
4970   }
4971 
4972   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
4973 
4974   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
4975   bool shouldDeleteForField(FieldDecl *FD);
4976   bool shouldDeleteForAllConstMembers();
4977 
4978   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4979                                      unsigned Quals);
4980   bool shouldDeleteForSubobjectCall(Subobject Subobj,
4981                                     Sema::SpecialMemberOverloadResult *SMOR,
4982                                     bool IsDtorCallInCtor);
4983 
4984   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
4985 };
4986 }
4987 
4988 /// Is the given special member inaccessible when used on the given
4989 /// sub-object.
4990 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4991                                              CXXMethodDecl *target) {
4992   /// If we're operating on a base class, the object type is the
4993   /// type of this special member.
4994   QualType objectTy;
4995   AccessSpecifier access = target->getAccess();
4996   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4997     objectTy = S.Context.getTypeDeclType(MD->getParent());
4998     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4999 
5000   // If we're operating on a field, the object type is the type of the field.
5001   } else {
5002     objectTy = S.Context.getTypeDeclType(target->getParent());
5003   }
5004 
5005   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5006 }
5007 
5008 /// Check whether we should delete a special member due to the implicit
5009 /// definition containing a call to a special member of a subobject.
5010 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5011     Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5012     bool IsDtorCallInCtor) {
5013   CXXMethodDecl *Decl = SMOR->getMethod();
5014   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5015 
5016   int DiagKind = -1;
5017 
5018   if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5019     DiagKind = !Decl ? 0 : 1;
5020   else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5021     DiagKind = 2;
5022   else if (!isAccessible(Subobj, Decl))
5023     DiagKind = 3;
5024   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5025            !Decl->isTrivial()) {
5026     // A member of a union must have a trivial corresponding special member.
5027     // As a weird special case, a destructor call from a union's constructor
5028     // must be accessible and non-deleted, but need not be trivial. Such a
5029     // destructor is never actually called, but is semantically checked as
5030     // if it were.
5031     DiagKind = 4;
5032   }
5033 
5034   if (DiagKind == -1)
5035     return false;
5036 
5037   if (Diagnose) {
5038     if (Field) {
5039       S.Diag(Field->getLocation(),
5040              diag::note_deleted_special_member_class_subobject)
5041         << CSM << MD->getParent() << /*IsField*/true
5042         << Field << DiagKind << IsDtorCallInCtor;
5043     } else {
5044       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5045       S.Diag(Base->getLocStart(),
5046              diag::note_deleted_special_member_class_subobject)
5047         << CSM << MD->getParent() << /*IsField*/false
5048         << Base->getType() << DiagKind << IsDtorCallInCtor;
5049     }
5050 
5051     if (DiagKind == 1)
5052       S.NoteDeletedFunction(Decl);
5053     // FIXME: Explain inaccessibility if DiagKind == 3.
5054   }
5055 
5056   return true;
5057 }
5058 
5059 /// Check whether we should delete a special member function due to having a
5060 /// direct or virtual base class or non-static data member of class type M.
5061 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
5062     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
5063   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5064   bool IsMutable = Field && Field->isMutable();
5065 
5066   // C++11 [class.ctor]p5:
5067   // -- any direct or virtual base class, or non-static data member with no
5068   //    brace-or-equal-initializer, has class type M (or array thereof) and
5069   //    either M has no default constructor or overload resolution as applied
5070   //    to M's default constructor results in an ambiguity or in a function
5071   //    that is deleted or inaccessible
5072   // C++11 [class.copy]p11, C++11 [class.copy]p23:
5073   // -- a direct or virtual base class B that cannot be copied/moved because
5074   //    overload resolution, as applied to B's corresponding special member,
5075   //    results in an ambiguity or a function that is deleted or inaccessible
5076   //    from the defaulted special member
5077   // C++11 [class.dtor]p5:
5078   // -- any direct or virtual base class [...] has a type with a destructor
5079   //    that is deleted or inaccessible
5080   if (!(CSM == Sema::CXXDefaultConstructor &&
5081         Field && Field->hasInClassInitializer()) &&
5082       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5083                                    false))
5084     return true;
5085 
5086   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5087   // -- any direct or virtual base class or non-static data member has a
5088   //    type with a destructor that is deleted or inaccessible
5089   if (IsConstructor) {
5090     Sema::SpecialMemberOverloadResult *SMOR =
5091         S.LookupSpecialMember(Class, Sema::CXXDestructor,
5092                               false, false, false, false, false);
5093     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5094       return true;
5095   }
5096 
5097   return false;
5098 }
5099 
5100 /// Check whether we should delete a special member function due to the class
5101 /// having a particular direct or virtual base class.
5102 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
5103   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
5104   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
5105 }
5106 
5107 /// Check whether we should delete a special member function due to the class
5108 /// having a particular non-static data member.
5109 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5110   QualType FieldType = S.Context.getBaseElementType(FD->getType());
5111   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5112 
5113   if (CSM == Sema::CXXDefaultConstructor) {
5114     // For a default constructor, all references must be initialized in-class
5115     // and, if a union, it must have a non-const member.
5116     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5117       if (Diagnose)
5118         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5119           << MD->getParent() << FD << FieldType << /*Reference*/0;
5120       return true;
5121     }
5122     // C++11 [class.ctor]p5: any non-variant non-static data member of
5123     // const-qualified type (or array thereof) with no
5124     // brace-or-equal-initializer does not have a user-provided default
5125     // constructor.
5126     if (!inUnion() && FieldType.isConstQualified() &&
5127         !FD->hasInClassInitializer() &&
5128         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5129       if (Diagnose)
5130         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5131           << MD->getParent() << FD << FD->getType() << /*Const*/1;
5132       return true;
5133     }
5134 
5135     if (inUnion() && !FieldType.isConstQualified())
5136       AllFieldsAreConst = false;
5137   } else if (CSM == Sema::CXXCopyConstructor) {
5138     // For a copy constructor, data members must not be of rvalue reference
5139     // type.
5140     if (FieldType->isRValueReferenceType()) {
5141       if (Diagnose)
5142         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5143           << MD->getParent() << FD << FieldType;
5144       return true;
5145     }
5146   } else if (IsAssignment) {
5147     // For an assignment operator, data members must not be of reference type.
5148     if (FieldType->isReferenceType()) {
5149       if (Diagnose)
5150         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5151           << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
5152       return true;
5153     }
5154     if (!FieldRecord && FieldType.isConstQualified()) {
5155       // C++11 [class.copy]p23:
5156       // -- a non-static data member of const non-class type (or array thereof)
5157       if (Diagnose)
5158         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5159           << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
5160       return true;
5161     }
5162   }
5163 
5164   if (FieldRecord) {
5165     // Some additional restrictions exist on the variant members.
5166     if (!inUnion() && FieldRecord->isUnion() &&
5167         FieldRecord->isAnonymousStructOrUnion()) {
5168       bool AllVariantFieldsAreConst = true;
5169 
5170       // FIXME: Handle anonymous unions declared within anonymous unions.
5171       for (auto *UI : FieldRecord->fields()) {
5172         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
5173 
5174         if (!UnionFieldType.isConstQualified())
5175           AllVariantFieldsAreConst = false;
5176 
5177         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5178         if (UnionFieldRecord &&
5179             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
5180                                           UnionFieldType.getCVRQualifiers()))
5181           return true;
5182       }
5183 
5184       // At least one member in each anonymous union must be non-const
5185       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
5186           !FieldRecord->field_empty()) {
5187         if (Diagnose)
5188           S.Diag(FieldRecord->getLocation(),
5189                  diag::note_deleted_default_ctor_all_const)
5190             << MD->getParent() << /*anonymous union*/1;
5191         return true;
5192       }
5193 
5194       // Don't check the implicit member of the anonymous union type.
5195       // This is technically non-conformant, but sanity demands it.
5196       return false;
5197     }
5198 
5199     if (shouldDeleteForClassSubobject(FieldRecord, FD,
5200                                       FieldType.getCVRQualifiers()))
5201       return true;
5202   }
5203 
5204   return false;
5205 }
5206 
5207 /// C++11 [class.ctor] p5:
5208 ///   A defaulted default constructor for a class X is defined as deleted if
5209 /// X is a union and all of its variant members are of const-qualified type.
5210 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
5211   // This is a silly definition, because it gives an empty union a deleted
5212   // default constructor. Don't do that.
5213   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5214       !MD->getParent()->field_empty()) {
5215     if (Diagnose)
5216       S.Diag(MD->getParent()->getLocation(),
5217              diag::note_deleted_default_ctor_all_const)
5218         << MD->getParent() << /*not anonymous union*/0;
5219     return true;
5220   }
5221   return false;
5222 }
5223 
5224 /// Determine whether a defaulted special member function should be defined as
5225 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5226 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
5227 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5228                                      bool Diagnose) {
5229   if (MD->isInvalidDecl())
5230     return false;
5231   CXXRecordDecl *RD = MD->getParent();
5232   assert(!RD->isDependentType() && "do deletion after instantiation");
5233   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
5234     return false;
5235 
5236   // C++11 [expr.lambda.prim]p19:
5237   //   The closure type associated with a lambda-expression has a
5238   //   deleted (8.4.3) default constructor and a deleted copy
5239   //   assignment operator.
5240   if (RD->isLambda() &&
5241       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5242     if (Diagnose)
5243       Diag(RD->getLocation(), diag::note_lambda_decl);
5244     return true;
5245   }
5246 
5247   // For an anonymous struct or union, the copy and assignment special members
5248   // will never be used, so skip the check. For an anonymous union declared at
5249   // namespace scope, the constructor and destructor are used.
5250   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5251       RD->isAnonymousStructOrUnion())
5252     return false;
5253 
5254   // C++11 [class.copy]p7, p18:
5255   //   If the class definition declares a move constructor or move assignment
5256   //   operator, an implicitly declared copy constructor or copy assignment
5257   //   operator is defined as deleted.
5258   if (MD->isImplicit() &&
5259       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5260     CXXMethodDecl *UserDeclaredMove = 0;
5261 
5262     // In Microsoft mode, a user-declared move only causes the deletion of the
5263     // corresponding copy operation, not both copy operations.
5264     if (RD->hasUserDeclaredMoveConstructor() &&
5265         (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
5266       if (!Diagnose) return true;
5267 
5268       // Find any user-declared move constructor.
5269       for (auto *I : RD->ctors()) {
5270         if (I->isMoveConstructor()) {
5271           UserDeclaredMove = I;
5272           break;
5273         }
5274       }
5275       assert(UserDeclaredMove);
5276     } else if (RD->hasUserDeclaredMoveAssignment() &&
5277                (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
5278       if (!Diagnose) return true;
5279 
5280       // Find any user-declared move assignment operator.
5281       for (auto *I : RD->methods()) {
5282         if (I->isMoveAssignmentOperator()) {
5283           UserDeclaredMove = I;
5284           break;
5285         }
5286       }
5287       assert(UserDeclaredMove);
5288     }
5289 
5290     if (UserDeclaredMove) {
5291       Diag(UserDeclaredMove->getLocation(),
5292            diag::note_deleted_copy_user_declared_move)
5293         << (CSM == CXXCopyAssignment) << RD
5294         << UserDeclaredMove->isMoveAssignmentOperator();
5295       return true;
5296     }
5297   }
5298 
5299   // Do access control from the special member function
5300   ContextRAII MethodContext(*this, MD);
5301 
5302   // C++11 [class.dtor]p5:
5303   // -- for a virtual destructor, lookup of the non-array deallocation function
5304   //    results in an ambiguity or in a function that is deleted or inaccessible
5305   if (CSM == CXXDestructor && MD->isVirtual()) {
5306     FunctionDecl *OperatorDelete = 0;
5307     DeclarationName Name =
5308       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5309     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
5310                                  OperatorDelete, false)) {
5311       if (Diagnose)
5312         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
5313       return true;
5314     }
5315   }
5316 
5317   SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
5318 
5319   for (auto &BI : RD->bases())
5320     if (!BI.isVirtual() &&
5321         SMI.shouldDeleteForBase(&BI))
5322       return true;
5323 
5324   // Per DR1611, do not consider virtual bases of constructors of abstract
5325   // classes, since we are not going to construct them.
5326   if (!RD->isAbstract() || !SMI.IsConstructor) {
5327     for (auto &BI : RD->vbases())
5328       if (SMI.shouldDeleteForBase(&BI))
5329         return true;
5330   }
5331 
5332   for (auto *FI : RD->fields())
5333     if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
5334         SMI.shouldDeleteForField(FI))
5335       return true;
5336 
5337   if (SMI.shouldDeleteForAllConstMembers())
5338     return true;
5339 
5340   return false;
5341 }
5342 
5343 /// Perform lookup for a special member of the specified kind, and determine
5344 /// whether it is trivial. If the triviality can be determined without the
5345 /// lookup, skip it. This is intended for use when determining whether a
5346 /// special member of a containing object is trivial, and thus does not ever
5347 /// perform overload resolution for default constructors.
5348 ///
5349 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5350 /// member that was most likely to be intended to be trivial, if any.
5351 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5352                                      Sema::CXXSpecialMember CSM, unsigned Quals,
5353                                      bool ConstRHS, CXXMethodDecl **Selected) {
5354   if (Selected)
5355     *Selected = 0;
5356 
5357   switch (CSM) {
5358   case Sema::CXXInvalid:
5359     llvm_unreachable("not a special member");
5360 
5361   case Sema::CXXDefaultConstructor:
5362     // C++11 [class.ctor]p5:
5363     //   A default constructor is trivial if:
5364     //    - all the [direct subobjects] have trivial default constructors
5365     //
5366     // Note, no overload resolution is performed in this case.
5367     if (RD->hasTrivialDefaultConstructor())
5368       return true;
5369 
5370     if (Selected) {
5371       // If there's a default constructor which could have been trivial, dig it
5372       // out. Otherwise, if there's any user-provided default constructor, point
5373       // to that as an example of why there's not a trivial one.
5374       CXXConstructorDecl *DefCtor = 0;
5375       if (RD->needsImplicitDefaultConstructor())
5376         S.DeclareImplicitDefaultConstructor(RD);
5377       for (auto *CI : RD->ctors()) {
5378         if (!CI->isDefaultConstructor())
5379           continue;
5380         DefCtor = CI;
5381         if (!DefCtor->isUserProvided())
5382           break;
5383       }
5384 
5385       *Selected = DefCtor;
5386     }
5387 
5388     return false;
5389 
5390   case Sema::CXXDestructor:
5391     // C++11 [class.dtor]p5:
5392     //   A destructor is trivial if:
5393     //    - all the direct [subobjects] have trivial destructors
5394     if (RD->hasTrivialDestructor())
5395       return true;
5396 
5397     if (Selected) {
5398       if (RD->needsImplicitDestructor())
5399         S.DeclareImplicitDestructor(RD);
5400       *Selected = RD->getDestructor();
5401     }
5402 
5403     return false;
5404 
5405   case Sema::CXXCopyConstructor:
5406     // C++11 [class.copy]p12:
5407     //   A copy constructor is trivial if:
5408     //    - the constructor selected to copy each direct [subobject] is trivial
5409     if (RD->hasTrivialCopyConstructor()) {
5410       if (Quals == Qualifiers::Const)
5411         // We must either select the trivial copy constructor or reach an
5412         // ambiguity; no need to actually perform overload resolution.
5413         return true;
5414     } else if (!Selected) {
5415       return false;
5416     }
5417     // In C++98, we are not supposed to perform overload resolution here, but we
5418     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5419     // cases like B as having a non-trivial copy constructor:
5420     //   struct A { template<typename T> A(T&); };
5421     //   struct B { mutable A a; };
5422     goto NeedOverloadResolution;
5423 
5424   case Sema::CXXCopyAssignment:
5425     // C++11 [class.copy]p25:
5426     //   A copy assignment operator is trivial if:
5427     //    - the assignment operator selected to copy each direct [subobject] is
5428     //      trivial
5429     if (RD->hasTrivialCopyAssignment()) {
5430       if (Quals == Qualifiers::Const)
5431         return true;
5432     } else if (!Selected) {
5433       return false;
5434     }
5435     // In C++98, we are not supposed to perform overload resolution here, but we
5436     // treat that as a language defect.
5437     goto NeedOverloadResolution;
5438 
5439   case Sema::CXXMoveConstructor:
5440   case Sema::CXXMoveAssignment:
5441   NeedOverloadResolution:
5442     Sema::SpecialMemberOverloadResult *SMOR =
5443         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
5444 
5445     // The standard doesn't describe how to behave if the lookup is ambiguous.
5446     // We treat it as not making the member non-trivial, just like the standard
5447     // mandates for the default constructor. This should rarely matter, because
5448     // the member will also be deleted.
5449     if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5450       return true;
5451 
5452     if (!SMOR->getMethod()) {
5453       assert(SMOR->getKind() ==
5454              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5455       return false;
5456     }
5457 
5458     // We deliberately don't check if we found a deleted special member. We're
5459     // not supposed to!
5460     if (Selected)
5461       *Selected = SMOR->getMethod();
5462     return SMOR->getMethod()->isTrivial();
5463   }
5464 
5465   llvm_unreachable("unknown special method kind");
5466 }
5467 
5468 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
5469   for (auto *CI : RD->ctors())
5470     if (!CI->isImplicit())
5471       return CI;
5472 
5473   // Look for constructor templates.
5474   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5475   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5476     if (CXXConstructorDecl *CD =
5477           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5478       return CD;
5479   }
5480 
5481   return 0;
5482 }
5483 
5484 /// The kind of subobject we are checking for triviality. The values of this
5485 /// enumeration are used in diagnostics.
5486 enum TrivialSubobjectKind {
5487   /// The subobject is a base class.
5488   TSK_BaseClass,
5489   /// The subobject is a non-static data member.
5490   TSK_Field,
5491   /// The object is actually the complete object.
5492   TSK_CompleteObject
5493 };
5494 
5495 /// Check whether the special member selected for a given type would be trivial.
5496 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5497                                       QualType SubType, bool ConstRHS,
5498                                       Sema::CXXSpecialMember CSM,
5499                                       TrivialSubobjectKind Kind,
5500                                       bool Diagnose) {
5501   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5502   if (!SubRD)
5503     return true;
5504 
5505   CXXMethodDecl *Selected;
5506   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5507                                ConstRHS, Diagnose ? &Selected : 0))
5508     return true;
5509 
5510   if (Diagnose) {
5511     if (ConstRHS)
5512       SubType.addConst();
5513 
5514     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5515       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5516         << Kind << SubType.getUnqualifiedType();
5517       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5518         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5519     } else if (!Selected)
5520       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5521         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5522     else if (Selected->isUserProvided()) {
5523       if (Kind == TSK_CompleteObject)
5524         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5525           << Kind << SubType.getUnqualifiedType() << CSM;
5526       else {
5527         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5528           << Kind << SubType.getUnqualifiedType() << CSM;
5529         S.Diag(Selected->getLocation(), diag::note_declared_at);
5530       }
5531     } else {
5532       if (Kind != TSK_CompleteObject)
5533         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5534           << Kind << SubType.getUnqualifiedType() << CSM;
5535 
5536       // Explain why the defaulted or deleted special member isn't trivial.
5537       S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5538     }
5539   }
5540 
5541   return false;
5542 }
5543 
5544 /// Check whether the members of a class type allow a special member to be
5545 /// trivial.
5546 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5547                                      Sema::CXXSpecialMember CSM,
5548                                      bool ConstArg, bool Diagnose) {
5549   for (const auto *FI : RD->fields()) {
5550     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5551       continue;
5552 
5553     QualType FieldType = S.Context.getBaseElementType(FI->getType());
5554 
5555     // Pretend anonymous struct or union members are members of this class.
5556     if (FI->isAnonymousStructOrUnion()) {
5557       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5558                                     CSM, ConstArg, Diagnose))
5559         return false;
5560       continue;
5561     }
5562 
5563     // C++11 [class.ctor]p5:
5564     //   A default constructor is trivial if [...]
5565     //    -- no non-static data member of its class has a
5566     //       brace-or-equal-initializer
5567     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5568       if (Diagnose)
5569         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
5570       return false;
5571     }
5572 
5573     // Objective C ARC 4.3.5:
5574     //   [...] nontrivally ownership-qualified types are [...] not trivially
5575     //   default constructible, copy constructible, move constructible, copy
5576     //   assignable, move assignable, or destructible [...]
5577     if (S.getLangOpts().ObjCAutoRefCount &&
5578         FieldType.hasNonTrivialObjCLifetime()) {
5579       if (Diagnose)
5580         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5581           << RD << FieldType.getObjCLifetime();
5582       return false;
5583     }
5584 
5585     bool ConstRHS = ConstArg && !FI->isMutable();
5586     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
5587                                    CSM, TSK_Field, Diagnose))
5588       return false;
5589   }
5590 
5591   return true;
5592 }
5593 
5594 /// Diagnose why the specified class does not have a trivial special member of
5595 /// the given kind.
5596 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5597   QualType Ty = Context.getRecordType(RD);
5598 
5599   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
5600   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
5601                             TSK_CompleteObject, /*Diagnose*/true);
5602 }
5603 
5604 /// Determine whether a defaulted or deleted special member function is trivial,
5605 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5606 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5607 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5608                                   bool Diagnose) {
5609   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5610 
5611   CXXRecordDecl *RD = MD->getParent();
5612 
5613   bool ConstArg = false;
5614 
5615   // C++11 [class.copy]p12, p25: [DR1593]
5616   //   A [special member] is trivial if [...] its parameter-type-list is
5617   //   equivalent to the parameter-type-list of an implicit declaration [...]
5618   switch (CSM) {
5619   case CXXDefaultConstructor:
5620   case CXXDestructor:
5621     // Trivial default constructors and destructors cannot have parameters.
5622     break;
5623 
5624   case CXXCopyConstructor:
5625   case CXXCopyAssignment: {
5626     // Trivial copy operations always have const, non-volatile parameter types.
5627     ConstArg = true;
5628     const ParmVarDecl *Param0 = MD->getParamDecl(0);
5629     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5630     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5631       if (Diagnose)
5632         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5633           << Param0->getSourceRange() << Param0->getType()
5634           << Context.getLValueReferenceType(
5635                Context.getRecordType(RD).withConst());
5636       return false;
5637     }
5638     break;
5639   }
5640 
5641   case CXXMoveConstructor:
5642   case CXXMoveAssignment: {
5643     // Trivial move operations always have non-cv-qualified parameters.
5644     const ParmVarDecl *Param0 = MD->getParamDecl(0);
5645     const RValueReferenceType *RT =
5646       Param0->getType()->getAs<RValueReferenceType>();
5647     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5648       if (Diagnose)
5649         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5650           << Param0->getSourceRange() << Param0->getType()
5651           << Context.getRValueReferenceType(Context.getRecordType(RD));
5652       return false;
5653     }
5654     break;
5655   }
5656 
5657   case CXXInvalid:
5658     llvm_unreachable("not a special member");
5659   }
5660 
5661   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5662     if (Diagnose)
5663       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5664            diag::note_nontrivial_default_arg)
5665         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5666     return false;
5667   }
5668   if (MD->isVariadic()) {
5669     if (Diagnose)
5670       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5671     return false;
5672   }
5673 
5674   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5675   //   A copy/move [constructor or assignment operator] is trivial if
5676   //    -- the [member] selected to copy/move each direct base class subobject
5677   //       is trivial
5678   //
5679   // C++11 [class.copy]p12, C++11 [class.copy]p25:
5680   //   A [default constructor or destructor] is trivial if
5681   //    -- all the direct base classes have trivial [default constructors or
5682   //       destructors]
5683   for (const auto &BI : RD->bases())
5684     if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
5685                                    ConstArg, CSM, TSK_BaseClass, Diagnose))
5686       return false;
5687 
5688   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5689   //   A copy/move [constructor or assignment operator] for a class X is
5690   //   trivial if
5691   //    -- for each non-static data member of X that is of class type (or array
5692   //       thereof), the constructor selected to copy/move that member is
5693   //       trivial
5694   //
5695   // C++11 [class.copy]p12, C++11 [class.copy]p25:
5696   //   A [default constructor or destructor] is trivial if
5697   //    -- for all of the non-static data members of its class that are of class
5698   //       type (or array thereof), each such class has a trivial [default
5699   //       constructor or destructor]
5700   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5701     return false;
5702 
5703   // C++11 [class.dtor]p5:
5704   //   A destructor is trivial if [...]
5705   //    -- the destructor is not virtual
5706   if (CSM == CXXDestructor && MD->isVirtual()) {
5707     if (Diagnose)
5708       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5709     return false;
5710   }
5711 
5712   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5713   //   A [special member] for class X is trivial if [...]
5714   //    -- class X has no virtual functions and no virtual base classes
5715   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5716     if (!Diagnose)
5717       return false;
5718 
5719     if (RD->getNumVBases()) {
5720       // Check for virtual bases. We already know that the corresponding
5721       // member in all bases is trivial, so vbases must all be direct.
5722       CXXBaseSpecifier &BS = *RD->vbases_begin();
5723       assert(BS.isVirtual());
5724       Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5725       return false;
5726     }
5727 
5728     // Must have a virtual method.
5729     for (const auto *MI : RD->methods()) {
5730       if (MI->isVirtual()) {
5731         SourceLocation MLoc = MI->getLocStart();
5732         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5733         return false;
5734       }
5735     }
5736 
5737     llvm_unreachable("dynamic class with no vbases and no virtual functions");
5738   }
5739 
5740   // Looks like it's trivial!
5741   return true;
5742 }
5743 
5744 /// \brief Data used with FindHiddenVirtualMethod
5745 namespace {
5746   struct FindHiddenVirtualMethodData {
5747     Sema *S;
5748     CXXMethodDecl *Method;
5749     llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
5750     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5751   };
5752 }
5753 
5754 /// \brief Check whether any most overriden method from MD in Methods
5755 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5756                    const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5757   if (MD->size_overridden_methods() == 0)
5758     return Methods.count(MD->getCanonicalDecl());
5759   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5760                                       E = MD->end_overridden_methods();
5761        I != E; ++I)
5762     if (CheckMostOverridenMethods(*I, Methods))
5763       return true;
5764   return false;
5765 }
5766 
5767 /// \brief Member lookup function that determines whether a given C++
5768 /// method overloads virtual methods in a base class without overriding any,
5769 /// to be used with CXXRecordDecl::lookupInBases().
5770 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5771                                     CXXBasePath &Path,
5772                                     void *UserData) {
5773   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5774 
5775   FindHiddenVirtualMethodData &Data
5776     = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5777 
5778   DeclarationName Name = Data.Method->getDeclName();
5779   assert(Name.getNameKind() == DeclarationName::Identifier);
5780 
5781   bool foundSameNameMethod = false;
5782   SmallVector<CXXMethodDecl *, 8> overloadedMethods;
5783   for (Path.Decls = BaseRecord->lookup(Name);
5784        !Path.Decls.empty();
5785        Path.Decls = Path.Decls.slice(1)) {
5786     NamedDecl *D = Path.Decls.front();
5787     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5788       MD = MD->getCanonicalDecl();
5789       foundSameNameMethod = true;
5790       // Interested only in hidden virtual methods.
5791       if (!MD->isVirtual())
5792         continue;
5793       // If the method we are checking overrides a method from its base
5794       // don't warn about the other overloaded methods.
5795       if (!Data.S->IsOverload(Data.Method, MD, false))
5796         return true;
5797       // Collect the overload only if its hidden.
5798       if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
5799         overloadedMethods.push_back(MD);
5800     }
5801   }
5802 
5803   if (foundSameNameMethod)
5804     Data.OverloadedMethods.append(overloadedMethods.begin(),
5805                                    overloadedMethods.end());
5806   return foundSameNameMethod;
5807 }
5808 
5809 /// \brief Add the most overriden methods from MD to Methods
5810 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5811                          llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5812   if (MD->size_overridden_methods() == 0)
5813     Methods.insert(MD->getCanonicalDecl());
5814   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5815                                       E = MD->end_overridden_methods();
5816        I != E; ++I)
5817     AddMostOverridenMethods(*I, Methods);
5818 }
5819 
5820 /// \brief Check if a method overloads virtual methods in a base class without
5821 /// overriding any.
5822 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
5823                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
5824   if (!MD->getDeclName().isIdentifier())
5825     return;
5826 
5827   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5828                      /*bool RecordPaths=*/false,
5829                      /*bool DetectVirtual=*/false);
5830   FindHiddenVirtualMethodData Data;
5831   Data.Method = MD;
5832   Data.S = this;
5833 
5834   // Keep the base methods that were overriden or introduced in the subclass
5835   // by 'using' in a set. A base method not in this set is hidden.
5836   CXXRecordDecl *DC = MD->getParent();
5837   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5838   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5839     NamedDecl *ND = *I;
5840     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
5841       ND = shad->getTargetDecl();
5842     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5843       AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
5844   }
5845 
5846   if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
5847     OverloadedMethods = Data.OverloadedMethods;
5848 }
5849 
5850 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
5851                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
5852   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
5853     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
5854     PartialDiagnostic PD = PDiag(
5855          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5856     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5857     Diag(overloadedMD->getLocation(), PD);
5858   }
5859 }
5860 
5861 /// \brief Diagnose methods which overload virtual methods in a base class
5862 /// without overriding any.
5863 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
5864   if (MD->isInvalidDecl())
5865     return;
5866 
5867   if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
5868                                MD->getLocation()) == DiagnosticsEngine::Ignored)
5869     return;
5870 
5871   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5872   FindHiddenVirtualMethods(MD, OverloadedMethods);
5873   if (!OverloadedMethods.empty()) {
5874     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5875       << MD << (OverloadedMethods.size() > 1);
5876 
5877     NoteHiddenVirtualMethods(MD, OverloadedMethods);
5878   }
5879 }
5880 
5881 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5882                                              Decl *TagDecl,
5883                                              SourceLocation LBrac,
5884                                              SourceLocation RBrac,
5885                                              AttributeList *AttrList) {
5886   if (!TagDecl)
5887     return;
5888 
5889   AdjustDeclIfTemplate(TagDecl);
5890 
5891   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5892     if (l->getKind() != AttributeList::AT_Visibility)
5893       continue;
5894     l->setInvalid();
5895     Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5896       l->getName();
5897   }
5898 
5899   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
5900               // strict aliasing violation!
5901               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
5902               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
5903 
5904   CheckCompletedCXXClass(
5905                         dyn_cast_or_null<CXXRecordDecl>(TagDecl));
5906 }
5907 
5908 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5909 /// special functions, such as the default constructor, copy
5910 /// constructor, or destructor, to the given C++ class (C++
5911 /// [special]p1).  This routine can only be executed just before the
5912 /// definition of the class is complete.
5913 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
5914   if (!ClassDecl->hasUserDeclaredConstructor())
5915     ++ASTContext::NumImplicitDefaultConstructors;
5916 
5917   if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
5918     ++ASTContext::NumImplicitCopyConstructors;
5919 
5920     // If the properties or semantics of the copy constructor couldn't be
5921     // determined while the class was being declared, force a declaration
5922     // of it now.
5923     if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5924       DeclareImplicitCopyConstructor(ClassDecl);
5925   }
5926 
5927   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
5928     ++ASTContext::NumImplicitMoveConstructors;
5929 
5930     if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5931       DeclareImplicitMoveConstructor(ClassDecl);
5932   }
5933 
5934   if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5935     ++ASTContext::NumImplicitCopyAssignmentOperators;
5936 
5937     // If we have a dynamic class, then the copy assignment operator may be
5938     // virtual, so we have to declare it immediately. This ensures that, e.g.,
5939     // it shows up in the right place in the vtable and that we diagnose
5940     // problems with the implicit exception specification.
5941     if (ClassDecl->isDynamicClass() ||
5942         ClassDecl->needsOverloadResolutionForCopyAssignment())
5943       DeclareImplicitCopyAssignment(ClassDecl);
5944   }
5945 
5946   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
5947     ++ASTContext::NumImplicitMoveAssignmentOperators;
5948 
5949     // Likewise for the move assignment operator.
5950     if (ClassDecl->isDynamicClass() ||
5951         ClassDecl->needsOverloadResolutionForMoveAssignment())
5952       DeclareImplicitMoveAssignment(ClassDecl);
5953   }
5954 
5955   if (!ClassDecl->hasUserDeclaredDestructor()) {
5956     ++ASTContext::NumImplicitDestructors;
5957 
5958     // If we have a dynamic class, then the destructor may be virtual, so we
5959     // have to declare the destructor immediately. This ensures that, e.g., it
5960     // shows up in the right place in the vtable and that we diagnose problems
5961     // with the implicit exception specification.
5962     if (ClassDecl->isDynamicClass() ||
5963         ClassDecl->needsOverloadResolutionForDestructor())
5964       DeclareImplicitDestructor(ClassDecl);
5965   }
5966 }
5967 
5968 void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5969   if (!D)
5970     return;
5971 
5972   int NumParamList = D->getNumTemplateParameterLists();
5973   for (int i = 0; i < NumParamList; i++) {
5974     TemplateParameterList* Params = D->getTemplateParameterList(i);
5975     for (TemplateParameterList::iterator Param = Params->begin(),
5976                                       ParamEnd = Params->end();
5977           Param != ParamEnd; ++Param) {
5978       NamedDecl *Named = cast<NamedDecl>(*Param);
5979       if (Named->getDeclName()) {
5980         S->AddDecl(Named);
5981         IdResolver.AddDecl(Named);
5982       }
5983     }
5984   }
5985 }
5986 
5987 void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
5988   if (!D)
5989     return;
5990 
5991   TemplateParameterList *Params = 0;
5992   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5993     Params = Template->getTemplateParameters();
5994   else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5995            = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5996     Params = PartialSpec->getTemplateParameters();
5997   else
5998     return;
5999 
6000   for (TemplateParameterList::iterator Param = Params->begin(),
6001                                     ParamEnd = Params->end();
6002        Param != ParamEnd; ++Param) {
6003     NamedDecl *Named = cast<NamedDecl>(*Param);
6004     if (Named->getDeclName()) {
6005       S->AddDecl(Named);
6006       IdResolver.AddDecl(Named);
6007     }
6008   }
6009 }
6010 
6011 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6012   if (!RecordD) return;
6013   AdjustDeclIfTemplate(RecordD);
6014   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
6015   PushDeclContext(S, Record);
6016 }
6017 
6018 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6019   if (!RecordD) return;
6020   PopDeclContext();
6021 }
6022 
6023 /// This is used to implement the constant expression evaluation part of the
6024 /// attribute enable_if extension. There is nothing in standard C++ which would
6025 /// require reentering parameters.
6026 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6027   if (!Param)
6028     return;
6029 
6030   S->AddDecl(Param);
6031   if (Param->getDeclName())
6032     IdResolver.AddDecl(Param);
6033 }
6034 
6035 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
6036 /// parsing a top-level (non-nested) C++ class, and we are now
6037 /// parsing those parts of the given Method declaration that could
6038 /// not be parsed earlier (C++ [class.mem]p2), such as default
6039 /// arguments. This action should enter the scope of the given
6040 /// Method declaration as if we had just parsed the qualified method
6041 /// name. However, it should not bring the parameters into scope;
6042 /// that will be performed by ActOnDelayedCXXMethodParameter.
6043 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6044 }
6045 
6046 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
6047 /// C++ method declaration. We're (re-)introducing the given
6048 /// function parameter into scope for use in parsing later parts of
6049 /// the method declaration. For example, we could see an
6050 /// ActOnParamDefaultArgument event for this parameter.
6051 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
6052   if (!ParamD)
6053     return;
6054 
6055   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
6056 
6057   // If this parameter has an unparsed default argument, clear it out
6058   // to make way for the parsed default argument.
6059   if (Param->hasUnparsedDefaultArg())
6060     Param->setDefaultArg(0);
6061 
6062   S->AddDecl(Param);
6063   if (Param->getDeclName())
6064     IdResolver.AddDecl(Param);
6065 }
6066 
6067 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6068 /// processing the delayed method declaration for Method. The method
6069 /// declaration is now considered finished. There may be a separate
6070 /// ActOnStartOfFunctionDef action later (not necessarily
6071 /// immediately!) for this method, if it was also defined inside the
6072 /// class body.
6073 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6074   if (!MethodD)
6075     return;
6076 
6077   AdjustDeclIfTemplate(MethodD);
6078 
6079   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
6080 
6081   // Now that we have our default arguments, check the constructor
6082   // again. It could produce additional diagnostics or affect whether
6083   // the class has implicitly-declared destructors, among other
6084   // things.
6085   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6086     CheckConstructor(Constructor);
6087 
6088   // Check the default arguments, which we may have added.
6089   if (!Method->isInvalidDecl())
6090     CheckCXXDefaultArguments(Method);
6091 }
6092 
6093 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
6094 /// the well-formedness of the constructor declarator @p D with type @p
6095 /// R. If there are any errors in the declarator, this routine will
6096 /// emit diagnostics and set the invalid bit to true.  In any case, the type
6097 /// will be updated to reflect a well-formed type for the constructor and
6098 /// returned.
6099 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
6100                                           StorageClass &SC) {
6101   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6102 
6103   // C++ [class.ctor]p3:
6104   //   A constructor shall not be virtual (10.3) or static (9.4). A
6105   //   constructor can be invoked for a const, volatile or const
6106   //   volatile object. A constructor shall not be declared const,
6107   //   volatile, or const volatile (9.3.2).
6108   if (isVirtual) {
6109     if (!D.isInvalidType())
6110       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6111         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6112         << SourceRange(D.getIdentifierLoc());
6113     D.setInvalidType();
6114   }
6115   if (SC == SC_Static) {
6116     if (!D.isInvalidType())
6117       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6118         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6119         << SourceRange(D.getIdentifierLoc());
6120     D.setInvalidType();
6121     SC = SC_None;
6122   }
6123 
6124   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6125   if (FTI.TypeQuals != 0) {
6126     if (FTI.TypeQuals & Qualifiers::Const)
6127       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6128         << "const" << SourceRange(D.getIdentifierLoc());
6129     if (FTI.TypeQuals & Qualifiers::Volatile)
6130       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6131         << "volatile" << SourceRange(D.getIdentifierLoc());
6132     if (FTI.TypeQuals & Qualifiers::Restrict)
6133       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6134         << "restrict" << SourceRange(D.getIdentifierLoc());
6135     D.setInvalidType();
6136   }
6137 
6138   // C++0x [class.ctor]p4:
6139   //   A constructor shall not be declared with a ref-qualifier.
6140   if (FTI.hasRefQualifier()) {
6141     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6142       << FTI.RefQualifierIsLValueRef
6143       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6144     D.setInvalidType();
6145   }
6146 
6147   // Rebuild the function type "R" without any type qualifiers (in
6148   // case any of the errors above fired) and with "void" as the
6149   // return type, since constructors don't have return types.
6150   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6151   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
6152     return R;
6153 
6154   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6155   EPI.TypeQuals = 0;
6156   EPI.RefQualifier = RQ_None;
6157 
6158   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
6159 }
6160 
6161 /// CheckConstructor - Checks a fully-formed constructor for
6162 /// well-formedness, issuing any diagnostics required. Returns true if
6163 /// the constructor declarator is invalid.
6164 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
6165   CXXRecordDecl *ClassDecl
6166     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6167   if (!ClassDecl)
6168     return Constructor->setInvalidDecl();
6169 
6170   // C++ [class.copy]p3:
6171   //   A declaration of a constructor for a class X is ill-formed if
6172   //   its first parameter is of type (optionally cv-qualified) X and
6173   //   either there are no other parameters or else all other
6174   //   parameters have default arguments.
6175   if (!Constructor->isInvalidDecl() &&
6176       ((Constructor->getNumParams() == 1) ||
6177        (Constructor->getNumParams() > 1 &&
6178         Constructor->getParamDecl(1)->hasDefaultArg())) &&
6179       Constructor->getTemplateSpecializationKind()
6180                                               != TSK_ImplicitInstantiation) {
6181     QualType ParamType = Constructor->getParamDecl(0)->getType();
6182     QualType ClassTy = Context.getTagDeclType(ClassDecl);
6183     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
6184       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
6185       const char *ConstRef
6186         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6187                                                         : " const &";
6188       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
6189         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
6190 
6191       // FIXME: Rather that making the constructor invalid, we should endeavor
6192       // to fix the type.
6193       Constructor->setInvalidDecl();
6194     }
6195   }
6196 }
6197 
6198 /// CheckDestructor - Checks a fully-formed destructor definition for
6199 /// well-formedness, issuing any diagnostics required.  Returns true
6200 /// on error.
6201 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
6202   CXXRecordDecl *RD = Destructor->getParent();
6203 
6204   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
6205     SourceLocation Loc;
6206 
6207     if (!Destructor->isImplicit())
6208       Loc = Destructor->getLocation();
6209     else
6210       Loc = RD->getLocation();
6211 
6212     // If we have a virtual destructor, look up the deallocation function
6213     FunctionDecl *OperatorDelete = 0;
6214     DeclarationName Name =
6215     Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6216     if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
6217       return true;
6218     // If there's no class-specific operator delete, look up the global
6219     // non-array delete.
6220     if (!OperatorDelete)
6221       OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
6222 
6223     MarkFunctionReferenced(Loc, OperatorDelete);
6224 
6225     Destructor->setOperatorDelete(OperatorDelete);
6226   }
6227 
6228   return false;
6229 }
6230 
6231 static inline bool
6232 FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
6233   return (FTI.NumParams == 1 && !FTI.isVariadic && FTI.Params[0].Ident == 0 &&
6234           FTI.Params[0].Param &&
6235           cast<ParmVarDecl>(FTI.Params[0].Param)->getType()->isVoidType());
6236 }
6237 
6238 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6239 /// the well-formednes of the destructor declarator @p D with type @p
6240 /// R. If there are any errors in the declarator, this routine will
6241 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
6242 /// will be updated to reflect a well-formed type for the destructor and
6243 /// returned.
6244 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
6245                                          StorageClass& SC) {
6246   // C++ [class.dtor]p1:
6247   //   [...] A typedef-name that names a class is a class-name
6248   //   (7.1.3); however, a typedef-name that names a class shall not
6249   //   be used as the identifier in the declarator for a destructor
6250   //   declaration.
6251   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
6252   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
6253     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6254       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
6255   else if (const TemplateSpecializationType *TST =
6256              DeclaratorType->getAs<TemplateSpecializationType>())
6257     if (TST->isTypeAlias())
6258       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6259         << DeclaratorType << 1;
6260 
6261   // C++ [class.dtor]p2:
6262   //   A destructor is used to destroy objects of its class type. A
6263   //   destructor takes no parameters, and no return type can be
6264   //   specified for it (not even void). The address of a destructor
6265   //   shall not be taken. A destructor shall not be static. A
6266   //   destructor can be invoked for a const, volatile or const
6267   //   volatile object. A destructor shall not be declared const,
6268   //   volatile or const volatile (9.3.2).
6269   if (SC == SC_Static) {
6270     if (!D.isInvalidType())
6271       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6272         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6273         << SourceRange(D.getIdentifierLoc())
6274         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6275 
6276     SC = SC_None;
6277   }
6278   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
6279     // Destructors don't have return types, but the parser will
6280     // happily parse something like:
6281     //
6282     //   class X {
6283     //     float ~X();
6284     //   };
6285     //
6286     // The return type will be eliminated later.
6287     Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6288       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6289       << SourceRange(D.getIdentifierLoc());
6290   }
6291 
6292   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6293   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
6294     if (FTI.TypeQuals & Qualifiers::Const)
6295       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6296         << "const" << SourceRange(D.getIdentifierLoc());
6297     if (FTI.TypeQuals & Qualifiers::Volatile)
6298       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6299         << "volatile" << SourceRange(D.getIdentifierLoc());
6300     if (FTI.TypeQuals & Qualifiers::Restrict)
6301       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6302         << "restrict" << SourceRange(D.getIdentifierLoc());
6303     D.setInvalidType();
6304   }
6305 
6306   // C++0x [class.dtor]p2:
6307   //   A destructor shall not be declared with a ref-qualifier.
6308   if (FTI.hasRefQualifier()) {
6309     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6310       << FTI.RefQualifierIsLValueRef
6311       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6312     D.setInvalidType();
6313   }
6314 
6315   // Make sure we don't have any parameters.
6316   if (FTI.NumParams > 0 && !FTIHasSingleVoidArgument(FTI)) {
6317     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6318 
6319     // Delete the parameters.
6320     FTI.freeParams();
6321     D.setInvalidType();
6322   }
6323 
6324   // Make sure the destructor isn't variadic.
6325   if (FTI.isVariadic) {
6326     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
6327     D.setInvalidType();
6328   }
6329 
6330   // Rebuild the function type "R" without any type qualifiers or
6331   // parameters (in case any of the errors above fired) and with
6332   // "void" as the return type, since destructors don't have return
6333   // types.
6334   if (!D.isInvalidType())
6335     return R;
6336 
6337   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6338   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6339   EPI.Variadic = false;
6340   EPI.TypeQuals = 0;
6341   EPI.RefQualifier = RQ_None;
6342   return Context.getFunctionType(Context.VoidTy, None, EPI);
6343 }
6344 
6345 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6346 /// well-formednes of the conversion function declarator @p D with
6347 /// type @p R. If there are any errors in the declarator, this routine
6348 /// will emit diagnostics and return true. Otherwise, it will return
6349 /// false. Either way, the type @p R will be updated to reflect a
6350 /// well-formed type for the conversion operator.
6351 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
6352                                      StorageClass& SC) {
6353   // C++ [class.conv.fct]p1:
6354   //   Neither parameter types nor return type can be specified. The
6355   //   type of a conversion function (8.3.5) is "function taking no
6356   //   parameter returning conversion-type-id."
6357   if (SC == SC_Static) {
6358     if (!D.isInvalidType())
6359       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
6360         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6361         << D.getName().getSourceRange();
6362     D.setInvalidType();
6363     SC = SC_None;
6364   }
6365 
6366   QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6367 
6368   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
6369     // Conversion functions don't have return types, but the parser will
6370     // happily parse something like:
6371     //
6372     //   class X {
6373     //     float operator bool();
6374     //   };
6375     //
6376     // The return type will be changed later anyway.
6377     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6378       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6379       << SourceRange(D.getIdentifierLoc());
6380     D.setInvalidType();
6381   }
6382 
6383   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6384 
6385   // Make sure we don't have any parameters.
6386   if (Proto->getNumParams() > 0) {
6387     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6388 
6389     // Delete the parameters.
6390     D.getFunctionTypeInfo().freeParams();
6391     D.setInvalidType();
6392   } else if (Proto->isVariadic()) {
6393     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
6394     D.setInvalidType();
6395   }
6396 
6397   // Diagnose "&operator bool()" and other such nonsense.  This
6398   // is actually a gcc extension which we don't support.
6399   if (Proto->getReturnType() != ConvType) {
6400     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6401         << Proto->getReturnType();
6402     D.setInvalidType();
6403     ConvType = Proto->getReturnType();
6404   }
6405 
6406   // C++ [class.conv.fct]p4:
6407   //   The conversion-type-id shall not represent a function type nor
6408   //   an array type.
6409   if (ConvType->isArrayType()) {
6410     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6411     ConvType = Context.getPointerType(ConvType);
6412     D.setInvalidType();
6413   } else if (ConvType->isFunctionType()) {
6414     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6415     ConvType = Context.getPointerType(ConvType);
6416     D.setInvalidType();
6417   }
6418 
6419   // Rebuild the function type "R" without any parameters (in case any
6420   // of the errors above fired) and with the conversion type as the
6421   // return type.
6422   if (D.isInvalidType())
6423     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
6424 
6425   // C++0x explicit conversion operators.
6426   if (D.getDeclSpec().isExplicitSpecified())
6427     Diag(D.getDeclSpec().getExplicitSpecLoc(),
6428          getLangOpts().CPlusPlus11 ?
6429            diag::warn_cxx98_compat_explicit_conversion_functions :
6430            diag::ext_explicit_conversion_functions)
6431       << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
6432 }
6433 
6434 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6435 /// the declaration of the given C++ conversion function. This routine
6436 /// is responsible for recording the conversion function in the C++
6437 /// class, if possible.
6438 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
6439   assert(Conversion && "Expected to receive a conversion function declaration");
6440 
6441   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
6442 
6443   // Make sure we aren't redeclaring the conversion function.
6444   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
6445 
6446   // C++ [class.conv.fct]p1:
6447   //   [...] A conversion function is never used to convert a
6448   //   (possibly cv-qualified) object to the (possibly cv-qualified)
6449   //   same object type (or a reference to it), to a (possibly
6450   //   cv-qualified) base class of that type (or a reference to it),
6451   //   or to (possibly cv-qualified) void.
6452   // FIXME: Suppress this warning if the conversion function ends up being a
6453   // virtual function that overrides a virtual function in a base class.
6454   QualType ClassType
6455     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6456   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
6457     ConvType = ConvTypeRef->getPointeeType();
6458   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6459       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
6460     /* Suppress diagnostics for instantiations. */;
6461   else if (ConvType->isRecordType()) {
6462     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6463     if (ConvType == ClassType)
6464       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
6465         << ClassType;
6466     else if (IsDerivedFrom(ClassType, ConvType))
6467       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
6468         <<  ClassType << ConvType;
6469   } else if (ConvType->isVoidType()) {
6470     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
6471       << ClassType << ConvType;
6472   }
6473 
6474   if (FunctionTemplateDecl *ConversionTemplate
6475                                 = Conversion->getDescribedFunctionTemplate())
6476     return ConversionTemplate;
6477 
6478   return Conversion;
6479 }
6480 
6481 //===----------------------------------------------------------------------===//
6482 // Namespace Handling
6483 //===----------------------------------------------------------------------===//
6484 
6485 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6486 /// reopened.
6487 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6488                                             SourceLocation Loc,
6489                                             IdentifierInfo *II, bool *IsInline,
6490                                             NamespaceDecl *PrevNS) {
6491   assert(*IsInline != PrevNS->isInline());
6492 
6493   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6494   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6495   // inline namespaces, with the intention of bringing names into namespace std.
6496   //
6497   // We support this just well enough to get that case working; this is not
6498   // sufficient to support reopening namespaces as inline in general.
6499   if (*IsInline && II && II->getName().startswith("__atomic") &&
6500       S.getSourceManager().isInSystemHeader(Loc)) {
6501     // Mark all prior declarations of the namespace as inline.
6502     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6503          NS = NS->getPreviousDecl())
6504       NS->setInline(*IsInline);
6505     // Patch up the lookup table for the containing namespace. This isn't really
6506     // correct, but it's good enough for this particular case.
6507     for (auto *I : PrevNS->decls())
6508       if (auto *ND = dyn_cast<NamedDecl>(I))
6509         PrevNS->getParent()->makeDeclVisibleInContext(ND);
6510     return;
6511   }
6512 
6513   if (PrevNS->isInline())
6514     // The user probably just forgot the 'inline', so suggest that it
6515     // be added back.
6516     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6517       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6518   else
6519     S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
6520 
6521   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6522   *IsInline = PrevNS->isInline();
6523 }
6524 
6525 /// ActOnStartNamespaceDef - This is called at the start of a namespace
6526 /// definition.
6527 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
6528                                    SourceLocation InlineLoc,
6529                                    SourceLocation NamespaceLoc,
6530                                    SourceLocation IdentLoc,
6531                                    IdentifierInfo *II,
6532                                    SourceLocation LBrace,
6533                                    AttributeList *AttrList) {
6534   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6535   // For anonymous namespace, take the location of the left brace.
6536   SourceLocation Loc = II ? IdentLoc : LBrace;
6537   bool IsInline = InlineLoc.isValid();
6538   bool IsInvalid = false;
6539   bool IsStd = false;
6540   bool AddToKnown = false;
6541   Scope *DeclRegionScope = NamespcScope->getParent();
6542 
6543   NamespaceDecl *PrevNS = 0;
6544   if (II) {
6545     // C++ [namespace.def]p2:
6546     //   The identifier in an original-namespace-definition shall not
6547     //   have been previously defined in the declarative region in
6548     //   which the original-namespace-definition appears. The
6549     //   identifier in an original-namespace-definition is the name of
6550     //   the namespace. Subsequently in that declarative region, it is
6551     //   treated as an original-namespace-name.
6552     //
6553     // Since namespace names are unique in their scope, and we don't
6554     // look through using directives, just look for any ordinary names.
6555 
6556     const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
6557     Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6558     Decl::IDNS_Namespace;
6559     NamedDecl *PrevDecl = 0;
6560     DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6561     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6562          ++I) {
6563       if ((*I)->getIdentifierNamespace() & IDNS) {
6564         PrevDecl = *I;
6565         break;
6566       }
6567     }
6568 
6569     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6570 
6571     if (PrevNS) {
6572       // This is an extended namespace definition.
6573       if (IsInline != PrevNS->isInline())
6574         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6575                                         &IsInline, PrevNS);
6576     } else if (PrevDecl) {
6577       // This is an invalid name redefinition.
6578       Diag(Loc, diag::err_redefinition_different_kind)
6579         << II;
6580       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6581       IsInvalid = true;
6582       // Continue on to push Namespc as current DeclContext and return it.
6583     } else if (II->isStr("std") &&
6584                CurContext->getRedeclContext()->isTranslationUnit()) {
6585       // This is the first "real" definition of the namespace "std", so update
6586       // our cache of the "std" namespace to point at this definition.
6587       PrevNS = getStdNamespace();
6588       IsStd = true;
6589       AddToKnown = !IsInline;
6590     } else {
6591       // We've seen this namespace for the first time.
6592       AddToKnown = !IsInline;
6593     }
6594   } else {
6595     // Anonymous namespaces.
6596 
6597     // Determine whether the parent already has an anonymous namespace.
6598     DeclContext *Parent = CurContext->getRedeclContext();
6599     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6600       PrevNS = TU->getAnonymousNamespace();
6601     } else {
6602       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
6603       PrevNS = ND->getAnonymousNamespace();
6604     }
6605 
6606     if (PrevNS && IsInline != PrevNS->isInline())
6607       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6608                                       &IsInline, PrevNS);
6609   }
6610 
6611   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6612                                                  StartLoc, Loc, II, PrevNS);
6613   if (IsInvalid)
6614     Namespc->setInvalidDecl();
6615 
6616   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
6617 
6618   // FIXME: Should we be merging attributes?
6619   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
6620     PushNamespaceVisibilityAttr(Attr, Loc);
6621 
6622   if (IsStd)
6623     StdNamespace = Namespc;
6624   if (AddToKnown)
6625     KnownNamespaces[Namespc] = false;
6626 
6627   if (II) {
6628     PushOnScopeChains(Namespc, DeclRegionScope);
6629   } else {
6630     // Link the anonymous namespace into its parent.
6631     DeclContext *Parent = CurContext->getRedeclContext();
6632     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6633       TU->setAnonymousNamespace(Namespc);
6634     } else {
6635       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
6636     }
6637 
6638     CurContext->addDecl(Namespc);
6639 
6640     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
6641     //   behaves as if it were replaced by
6642     //     namespace unique { /* empty body */ }
6643     //     using namespace unique;
6644     //     namespace unique { namespace-body }
6645     //   where all occurrences of 'unique' in a translation unit are
6646     //   replaced by the same identifier and this identifier differs
6647     //   from all other identifiers in the entire program.
6648 
6649     // We just create the namespace with an empty name and then add an
6650     // implicit using declaration, just like the standard suggests.
6651     //
6652     // CodeGen enforces the "universally unique" aspect by giving all
6653     // declarations semantically contained within an anonymous
6654     // namespace internal linkage.
6655 
6656     if (!PrevNS) {
6657       UsingDirectiveDecl* UD
6658         = UsingDirectiveDecl::Create(Context, Parent,
6659                                      /* 'using' */ LBrace,
6660                                      /* 'namespace' */ SourceLocation(),
6661                                      /* qualifier */ NestedNameSpecifierLoc(),
6662                                      /* identifier */ SourceLocation(),
6663                                      Namespc,
6664                                      /* Ancestor */ Parent);
6665       UD->setImplicit();
6666       Parent->addDecl(UD);
6667     }
6668   }
6669 
6670   ActOnDocumentableDecl(Namespc);
6671 
6672   // Although we could have an invalid decl (i.e. the namespace name is a
6673   // redefinition), push it as current DeclContext and try to continue parsing.
6674   // FIXME: We should be able to push Namespc here, so that the each DeclContext
6675   // for the namespace has the declarations that showed up in that particular
6676   // namespace definition.
6677   PushDeclContext(NamespcScope, Namespc);
6678   return Namespc;
6679 }
6680 
6681 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6682 /// is a namespace alias, returns the namespace it points to.
6683 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6684   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6685     return AD->getNamespace();
6686   return dyn_cast_or_null<NamespaceDecl>(D);
6687 }
6688 
6689 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
6690 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
6691 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
6692   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6693   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
6694   Namespc->setRBraceLoc(RBrace);
6695   PopDeclContext();
6696   if (Namespc->hasAttr<VisibilityAttr>())
6697     PopPragmaVisibility(true, RBrace);
6698 }
6699 
6700 CXXRecordDecl *Sema::getStdBadAlloc() const {
6701   return cast_or_null<CXXRecordDecl>(
6702                                   StdBadAlloc.get(Context.getExternalSource()));
6703 }
6704 
6705 NamespaceDecl *Sema::getStdNamespace() const {
6706   return cast_or_null<NamespaceDecl>(
6707                                  StdNamespace.get(Context.getExternalSource()));
6708 }
6709 
6710 /// \brief Retrieve the special "std" namespace, which may require us to
6711 /// implicitly define the namespace.
6712 NamespaceDecl *Sema::getOrCreateStdNamespace() {
6713   if (!StdNamespace) {
6714     // The "std" namespace has not yet been defined, so build one implicitly.
6715     StdNamespace = NamespaceDecl::Create(Context,
6716                                          Context.getTranslationUnitDecl(),
6717                                          /*Inline=*/false,
6718                                          SourceLocation(), SourceLocation(),
6719                                          &PP.getIdentifierTable().get("std"),
6720                                          /*PrevDecl=*/0);
6721     getStdNamespace()->setImplicit(true);
6722   }
6723 
6724   return getStdNamespace();
6725 }
6726 
6727 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
6728   assert(getLangOpts().CPlusPlus &&
6729          "Looking for std::initializer_list outside of C++.");
6730 
6731   // We're looking for implicit instantiations of
6732   // template <typename E> class std::initializer_list.
6733 
6734   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6735     return false;
6736 
6737   ClassTemplateDecl *Template = 0;
6738   const TemplateArgument *Arguments = 0;
6739 
6740   if (const RecordType *RT = Ty->getAs<RecordType>()) {
6741 
6742     ClassTemplateSpecializationDecl *Specialization =
6743         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6744     if (!Specialization)
6745       return false;
6746 
6747     Template = Specialization->getSpecializedTemplate();
6748     Arguments = Specialization->getTemplateArgs().data();
6749   } else if (const TemplateSpecializationType *TST =
6750                  Ty->getAs<TemplateSpecializationType>()) {
6751     Template = dyn_cast_or_null<ClassTemplateDecl>(
6752         TST->getTemplateName().getAsTemplateDecl());
6753     Arguments = TST->getArgs();
6754   }
6755   if (!Template)
6756     return false;
6757 
6758   if (!StdInitializerList) {
6759     // Haven't recognized std::initializer_list yet, maybe this is it.
6760     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6761     if (TemplateClass->getIdentifier() !=
6762             &PP.getIdentifierTable().get("initializer_list") ||
6763         !getStdNamespace()->InEnclosingNamespaceSetOf(
6764             TemplateClass->getDeclContext()))
6765       return false;
6766     // This is a template called std::initializer_list, but is it the right
6767     // template?
6768     TemplateParameterList *Params = Template->getTemplateParameters();
6769     if (Params->getMinRequiredArguments() != 1)
6770       return false;
6771     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6772       return false;
6773 
6774     // It's the right template.
6775     StdInitializerList = Template;
6776   }
6777 
6778   if (Template != StdInitializerList)
6779     return false;
6780 
6781   // This is an instance of std::initializer_list. Find the argument type.
6782   if (Element)
6783     *Element = Arguments[0].getAsType();
6784   return true;
6785 }
6786 
6787 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6788   NamespaceDecl *Std = S.getStdNamespace();
6789   if (!Std) {
6790     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6791     return 0;
6792   }
6793 
6794   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6795                       Loc, Sema::LookupOrdinaryName);
6796   if (!S.LookupQualifiedName(Result, Std)) {
6797     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6798     return 0;
6799   }
6800   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6801   if (!Template) {
6802     Result.suppressDiagnostics();
6803     // We found something weird. Complain about the first thing we found.
6804     NamedDecl *Found = *Result.begin();
6805     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6806     return 0;
6807   }
6808 
6809   // We found some template called std::initializer_list. Now verify that it's
6810   // correct.
6811   TemplateParameterList *Params = Template->getTemplateParameters();
6812   if (Params->getMinRequiredArguments() != 1 ||
6813       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6814     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6815     return 0;
6816   }
6817 
6818   return Template;
6819 }
6820 
6821 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6822   if (!StdInitializerList) {
6823     StdInitializerList = LookupStdInitializerList(*this, Loc);
6824     if (!StdInitializerList)
6825       return QualType();
6826   }
6827 
6828   TemplateArgumentListInfo Args(Loc, Loc);
6829   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6830                                        Context.getTrivialTypeSourceInfo(Element,
6831                                                                         Loc)));
6832   return Context.getCanonicalType(
6833       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6834 }
6835 
6836 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6837   // C++ [dcl.init.list]p2:
6838   //   A constructor is an initializer-list constructor if its first parameter
6839   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
6840   //   std::initializer_list<E> for some type E, and either there are no other
6841   //   parameters or else all other parameters have default arguments.
6842   if (Ctor->getNumParams() < 1 ||
6843       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6844     return false;
6845 
6846   QualType ArgType = Ctor->getParamDecl(0)->getType();
6847   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6848     ArgType = RT->getPointeeType().getUnqualifiedType();
6849 
6850   return isStdInitializerList(ArgType, 0);
6851 }
6852 
6853 /// \brief Determine whether a using statement is in a context where it will be
6854 /// apply in all contexts.
6855 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6856   switch (CurContext->getDeclKind()) {
6857     case Decl::TranslationUnit:
6858       return true;
6859     case Decl::LinkageSpec:
6860       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6861     default:
6862       return false;
6863   }
6864 }
6865 
6866 namespace {
6867 
6868 // Callback to only accept typo corrections that are namespaces.
6869 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6870 public:
6871   bool ValidateCandidate(const TypoCorrection &candidate) override {
6872     if (NamedDecl *ND = candidate.getCorrectionDecl())
6873       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6874     return false;
6875   }
6876 };
6877 
6878 }
6879 
6880 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6881                                        CXXScopeSpec &SS,
6882                                        SourceLocation IdentLoc,
6883                                        IdentifierInfo *Ident) {
6884   NamespaceValidatorCCC Validator;
6885   R.clear();
6886   if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
6887                                                R.getLookupKind(), Sc, &SS,
6888                                                Validator)) {
6889     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
6890       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6891       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
6892                               Ident->getName().equals(CorrectedStr);
6893       S.diagnoseTypo(Corrected,
6894                      S.PDiag(diag::err_using_directive_member_suggest)
6895                        << Ident << DC << DroppedSpecifier << SS.getRange(),
6896                      S.PDiag(diag::note_namespace_defined_here));
6897     } else {
6898       S.diagnoseTypo(Corrected,
6899                      S.PDiag(diag::err_using_directive_suggest) << Ident,
6900                      S.PDiag(diag::note_namespace_defined_here));
6901     }
6902     R.addDecl(Corrected.getCorrectionDecl());
6903     return true;
6904   }
6905   return false;
6906 }
6907 
6908 Decl *Sema::ActOnUsingDirective(Scope *S,
6909                                           SourceLocation UsingLoc,
6910                                           SourceLocation NamespcLoc,
6911                                           CXXScopeSpec &SS,
6912                                           SourceLocation IdentLoc,
6913                                           IdentifierInfo *NamespcName,
6914                                           AttributeList *AttrList) {
6915   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6916   assert(NamespcName && "Invalid NamespcName.");
6917   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
6918 
6919   // This can only happen along a recovery path.
6920   while (S->getFlags() & Scope::TemplateParamScope)
6921     S = S->getParent();
6922   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
6923 
6924   UsingDirectiveDecl *UDir = 0;
6925   NestedNameSpecifier *Qualifier = 0;
6926   if (SS.isSet())
6927     Qualifier = SS.getScopeRep();
6928 
6929   // Lookup namespace name.
6930   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6931   LookupParsedName(R, S, &SS);
6932   if (R.isAmbiguous())
6933     return 0;
6934 
6935   if (R.empty()) {
6936     R.clear();
6937     // Allow "using namespace std;" or "using namespace ::std;" even if
6938     // "std" hasn't been defined yet, for GCC compatibility.
6939     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6940         NamespcName->isStr("std")) {
6941       Diag(IdentLoc, diag::ext_using_undefined_std);
6942       R.addDecl(getOrCreateStdNamespace());
6943       R.resolveKind();
6944     }
6945     // Otherwise, attempt typo correction.
6946     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
6947   }
6948 
6949   if (!R.empty()) {
6950     NamedDecl *Named = R.getFoundDecl();
6951     assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6952         && "expected namespace decl");
6953     // C++ [namespace.udir]p1:
6954     //   A using-directive specifies that the names in the nominated
6955     //   namespace can be used in the scope in which the
6956     //   using-directive appears after the using-directive. During
6957     //   unqualified name lookup (3.4.1), the names appear as if they
6958     //   were declared in the nearest enclosing namespace which
6959     //   contains both the using-directive and the nominated
6960     //   namespace. [Note: in this context, "contains" means "contains
6961     //   directly or indirectly". ]
6962 
6963     // Find enclosing context containing both using-directive and
6964     // nominated namespace.
6965     NamespaceDecl *NS = getNamespaceDecl(Named);
6966     DeclContext *CommonAncestor = cast<DeclContext>(NS);
6967     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6968       CommonAncestor = CommonAncestor->getParent();
6969 
6970     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
6971                                       SS.getWithLocInContext(Context),
6972                                       IdentLoc, Named, CommonAncestor);
6973 
6974     if (IsUsingDirectiveInToplevelContext(CurContext) &&
6975         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
6976       Diag(IdentLoc, diag::warn_using_directive_in_header);
6977     }
6978 
6979     PushUsingDirective(S, UDir);
6980   } else {
6981     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
6982   }
6983 
6984   if (UDir)
6985     ProcessDeclAttributeList(S, UDir, AttrList);
6986 
6987   return UDir;
6988 }
6989 
6990 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
6991   // If the scope has an associated entity and the using directive is at
6992   // namespace or translation unit scope, add the UsingDirectiveDecl into
6993   // its lookup structure so qualified name lookup can find it.
6994   DeclContext *Ctx = S->getEntity();
6995   if (Ctx && !Ctx->isFunctionOrMethod())
6996     Ctx->addDecl(UDir);
6997   else
6998     // Otherwise, it is at block sope. The using-directives will affect lookup
6999     // only to the end of the scope.
7000     S->PushUsingDirective(UDir);
7001 }
7002 
7003 
7004 Decl *Sema::ActOnUsingDeclaration(Scope *S,
7005                                   AccessSpecifier AS,
7006                                   bool HasUsingKeyword,
7007                                   SourceLocation UsingLoc,
7008                                   CXXScopeSpec &SS,
7009                                   UnqualifiedId &Name,
7010                                   AttributeList *AttrList,
7011                                   bool HasTypenameKeyword,
7012                                   SourceLocation TypenameLoc) {
7013   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7014 
7015   switch (Name.getKind()) {
7016   case UnqualifiedId::IK_ImplicitSelfParam:
7017   case UnqualifiedId::IK_Identifier:
7018   case UnqualifiedId::IK_OperatorFunctionId:
7019   case UnqualifiedId::IK_LiteralOperatorId:
7020   case UnqualifiedId::IK_ConversionFunctionId:
7021     break;
7022 
7023   case UnqualifiedId::IK_ConstructorName:
7024   case UnqualifiedId::IK_ConstructorTemplateId:
7025     // C++11 inheriting constructors.
7026     Diag(Name.getLocStart(),
7027          getLangOpts().CPlusPlus11 ?
7028            diag::warn_cxx98_compat_using_decl_constructor :
7029            diag::err_using_decl_constructor)
7030       << SS.getRange();
7031 
7032     if (getLangOpts().CPlusPlus11) break;
7033 
7034     return 0;
7035 
7036   case UnqualifiedId::IK_DestructorName:
7037     Diag(Name.getLocStart(), diag::err_using_decl_destructor)
7038       << SS.getRange();
7039     return 0;
7040 
7041   case UnqualifiedId::IK_TemplateId:
7042     Diag(Name.getLocStart(), diag::err_using_decl_template_id)
7043       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
7044     return 0;
7045   }
7046 
7047   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7048   DeclarationName TargetName = TargetNameInfo.getName();
7049   if (!TargetName)
7050     return 0;
7051 
7052   // Warn about access declarations.
7053   if (!HasUsingKeyword) {
7054     Diag(Name.getLocStart(),
7055          getLangOpts().CPlusPlus11 ? diag::err_access_decl
7056                                    : diag::warn_access_decl_deprecated)
7057       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
7058   }
7059 
7060   if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7061       DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7062     return 0;
7063 
7064   NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
7065                                         TargetNameInfo, AttrList,
7066                                         /* IsInstantiation */ false,
7067                                         HasTypenameKeyword, TypenameLoc);
7068   if (UD)
7069     PushOnScopeChains(UD, S, /*AddToContext*/ false);
7070 
7071   return UD;
7072 }
7073 
7074 /// \brief Determine whether a using declaration considers the given
7075 /// declarations as "equivalent", e.g., if they are redeclarations of
7076 /// the same entity or are both typedefs of the same type.
7077 static bool
7078 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7079   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
7080     return true;
7081 
7082   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
7083     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
7084       return Context.hasSameType(TD1->getUnderlyingType(),
7085                                  TD2->getUnderlyingType());
7086 
7087   return false;
7088 }
7089 
7090 
7091 /// Determines whether to create a using shadow decl for a particular
7092 /// decl, given the set of decls existing prior to this using lookup.
7093 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
7094                                 const LookupResult &Previous,
7095                                 UsingShadowDecl *&PrevShadow) {
7096   // Diagnose finding a decl which is not from a base class of the
7097   // current class.  We do this now because there are cases where this
7098   // function will silently decide not to build a shadow decl, which
7099   // will pre-empt further diagnostics.
7100   //
7101   // We don't need to do this in C++0x because we do the check once on
7102   // the qualifier.
7103   //
7104   // FIXME: diagnose the following if we care enough:
7105   //   struct A { int foo; };
7106   //   struct B : A { using A::foo; };
7107   //   template <class T> struct C : A {};
7108   //   template <class T> struct D : C<T> { using B::foo; } // <---
7109   // This is invalid (during instantiation) in C++03 because B::foo
7110   // resolves to the using decl in B, which is not a base class of D<T>.
7111   // We can't diagnose it immediately because C<T> is an unknown
7112   // specialization.  The UsingShadowDecl in D<T> then points directly
7113   // to A::foo, which will look well-formed when we instantiate.
7114   // The right solution is to not collapse the shadow-decl chain.
7115   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
7116     DeclContext *OrigDC = Orig->getDeclContext();
7117 
7118     // Handle enums and anonymous structs.
7119     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7120     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7121     while (OrigRec->isAnonymousStructOrUnion())
7122       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7123 
7124     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7125       if (OrigDC == CurContext) {
7126         Diag(Using->getLocation(),
7127              diag::err_using_decl_nested_name_specifier_is_current_class)
7128           << Using->getQualifierLoc().getSourceRange();
7129         Diag(Orig->getLocation(), diag::note_using_decl_target);
7130         return true;
7131       }
7132 
7133       Diag(Using->getQualifierLoc().getBeginLoc(),
7134            diag::err_using_decl_nested_name_specifier_is_not_base_class)
7135         << Using->getQualifier()
7136         << cast<CXXRecordDecl>(CurContext)
7137         << Using->getQualifierLoc().getSourceRange();
7138       Diag(Orig->getLocation(), diag::note_using_decl_target);
7139       return true;
7140     }
7141   }
7142 
7143   if (Previous.empty()) return false;
7144 
7145   NamedDecl *Target = Orig;
7146   if (isa<UsingShadowDecl>(Target))
7147     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7148 
7149   // If the target happens to be one of the previous declarations, we
7150   // don't have a conflict.
7151   //
7152   // FIXME: but we might be increasing its access, in which case we
7153   // should redeclare it.
7154   NamedDecl *NonTag = 0, *Tag = 0;
7155   bool FoundEquivalentDecl = false;
7156   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7157          I != E; ++I) {
7158     NamedDecl *D = (*I)->getUnderlyingDecl();
7159     if (IsEquivalentForUsingDecl(Context, D, Target)) {
7160       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7161         PrevShadow = Shadow;
7162       FoundEquivalentDecl = true;
7163     }
7164 
7165     (isa<TagDecl>(D) ? Tag : NonTag) = D;
7166   }
7167 
7168   if (FoundEquivalentDecl)
7169     return false;
7170 
7171   if (FunctionDecl *FD = Target->getAsFunction()) {
7172     NamedDecl *OldDecl = 0;
7173     switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
7174     case Ovl_Overload:
7175       return false;
7176 
7177     case Ovl_NonFunction:
7178       Diag(Using->getLocation(), diag::err_using_decl_conflict);
7179       break;
7180 
7181     // We found a decl with the exact signature.
7182     case Ovl_Match:
7183       // If we're in a record, we want to hide the target, so we
7184       // return true (without a diagnostic) to tell the caller not to
7185       // build a shadow decl.
7186       if (CurContext->isRecord())
7187         return true;
7188 
7189       // If we're not in a record, this is an error.
7190       Diag(Using->getLocation(), diag::err_using_decl_conflict);
7191       break;
7192     }
7193 
7194     Diag(Target->getLocation(), diag::note_using_decl_target);
7195     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7196     return true;
7197   }
7198 
7199   // Target is not a function.
7200 
7201   if (isa<TagDecl>(Target)) {
7202     // No conflict between a tag and a non-tag.
7203     if (!Tag) return false;
7204 
7205     Diag(Using->getLocation(), diag::err_using_decl_conflict);
7206     Diag(Target->getLocation(), diag::note_using_decl_target);
7207     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7208     return true;
7209   }
7210 
7211   // No conflict between a tag and a non-tag.
7212   if (!NonTag) return false;
7213 
7214   Diag(Using->getLocation(), diag::err_using_decl_conflict);
7215   Diag(Target->getLocation(), diag::note_using_decl_target);
7216   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7217   return true;
7218 }
7219 
7220 /// Builds a shadow declaration corresponding to a 'using' declaration.
7221 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
7222                                             UsingDecl *UD,
7223                                             NamedDecl *Orig,
7224                                             UsingShadowDecl *PrevDecl) {
7225 
7226   // If we resolved to another shadow declaration, just coalesce them.
7227   NamedDecl *Target = Orig;
7228   if (isa<UsingShadowDecl>(Target)) {
7229     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7230     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
7231   }
7232 
7233   UsingShadowDecl *Shadow
7234     = UsingShadowDecl::Create(Context, CurContext,
7235                               UD->getLocation(), UD, Target);
7236   UD->addShadowDecl(Shadow);
7237 
7238   Shadow->setAccess(UD->getAccess());
7239   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7240     Shadow->setInvalidDecl();
7241 
7242   Shadow->setPreviousDecl(PrevDecl);
7243 
7244   if (S)
7245     PushOnScopeChains(Shadow, S);
7246   else
7247     CurContext->addDecl(Shadow);
7248 
7249 
7250   return Shadow;
7251 }
7252 
7253 /// Hides a using shadow declaration.  This is required by the current
7254 /// using-decl implementation when a resolvable using declaration in a
7255 /// class is followed by a declaration which would hide or override
7256 /// one or more of the using decl's targets; for example:
7257 ///
7258 ///   struct Base { void foo(int); };
7259 ///   struct Derived : Base {
7260 ///     using Base::foo;
7261 ///     void foo(int);
7262 ///   };
7263 ///
7264 /// The governing language is C++03 [namespace.udecl]p12:
7265 ///
7266 ///   When a using-declaration brings names from a base class into a
7267 ///   derived class scope, member functions in the derived class
7268 ///   override and/or hide member functions with the same name and
7269 ///   parameter types in a base class (rather than conflicting).
7270 ///
7271 /// There are two ways to implement this:
7272 ///   (1) optimistically create shadow decls when they're not hidden
7273 ///       by existing declarations, or
7274 ///   (2) don't create any shadow decls (or at least don't make them
7275 ///       visible) until we've fully parsed/instantiated the class.
7276 /// The problem with (1) is that we might have to retroactively remove
7277 /// a shadow decl, which requires several O(n) operations because the
7278 /// decl structures are (very reasonably) not designed for removal.
7279 /// (2) avoids this but is very fiddly and phase-dependent.
7280 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
7281   if (Shadow->getDeclName().getNameKind() ==
7282         DeclarationName::CXXConversionFunctionName)
7283     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7284 
7285   // Remove it from the DeclContext...
7286   Shadow->getDeclContext()->removeDecl(Shadow);
7287 
7288   // ...and the scope, if applicable...
7289   if (S) {
7290     S->RemoveDecl(Shadow);
7291     IdResolver.RemoveDecl(Shadow);
7292   }
7293 
7294   // ...and the using decl.
7295   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7296 
7297   // TODO: complain somehow if Shadow was used.  It shouldn't
7298   // be possible for this to happen, because...?
7299 }
7300 
7301 namespace {
7302 class UsingValidatorCCC : public CorrectionCandidateCallback {
7303 public:
7304   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
7305                     bool RequireMember)
7306       : HasTypenameKeyword(HasTypenameKeyword),
7307         IsInstantiation(IsInstantiation), RequireMember(RequireMember) {}
7308 
7309   bool ValidateCandidate(const TypoCorrection &Candidate) override {
7310     NamedDecl *ND = Candidate.getCorrectionDecl();
7311 
7312     // Keywords are not valid here.
7313     if (!ND || isa<NamespaceDecl>(ND))
7314       return false;
7315 
7316     if (RequireMember && !isa<FieldDecl>(ND) && !isa<CXXMethodDecl>(ND) &&
7317         !isa<TypeDecl>(ND))
7318       return false;
7319 
7320     // Completely unqualified names are invalid for a 'using' declaration.
7321     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7322       return false;
7323 
7324     if (isa<TypeDecl>(ND))
7325       return HasTypenameKeyword || !IsInstantiation;
7326 
7327     return !HasTypenameKeyword;
7328   }
7329 
7330 private:
7331   bool HasTypenameKeyword;
7332   bool IsInstantiation;
7333   bool RequireMember;
7334 };
7335 } // end anonymous namespace
7336 
7337 /// Builds a using declaration.
7338 ///
7339 /// \param IsInstantiation - Whether this call arises from an
7340 ///   instantiation of an unresolved using declaration.  We treat
7341 ///   the lookup differently for these declarations.
7342 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7343                                        SourceLocation UsingLoc,
7344                                        CXXScopeSpec &SS,
7345                                        const DeclarationNameInfo &NameInfo,
7346                                        AttributeList *AttrList,
7347                                        bool IsInstantiation,
7348                                        bool HasTypenameKeyword,
7349                                        SourceLocation TypenameLoc) {
7350   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7351   SourceLocation IdentLoc = NameInfo.getLoc();
7352   assert(IdentLoc.isValid() && "Invalid TargetName location.");
7353 
7354   // FIXME: We ignore attributes for now.
7355 
7356   if (SS.isEmpty()) {
7357     Diag(IdentLoc, diag::err_using_requires_qualname);
7358     return 0;
7359   }
7360 
7361   // Do the redeclaration lookup in the current scope.
7362   LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
7363                         ForRedeclaration);
7364   Previous.setHideTags(false);
7365   if (S) {
7366     LookupName(Previous, S);
7367 
7368     // It is really dumb that we have to do this.
7369     LookupResult::Filter F = Previous.makeFilter();
7370     while (F.hasNext()) {
7371       NamedDecl *D = F.next();
7372       if (!isDeclInScope(D, CurContext, S))
7373         F.erase();
7374     }
7375     F.done();
7376   } else {
7377     assert(IsInstantiation && "no scope in non-instantiation");
7378     assert(CurContext->isRecord() && "scope not record in instantiation");
7379     LookupQualifiedName(Previous, CurContext);
7380   }
7381 
7382   // Check for invalid redeclarations.
7383   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7384                                   SS, IdentLoc, Previous))
7385     return 0;
7386 
7387   // Check for bad qualifiers.
7388   if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7389     return 0;
7390 
7391   DeclContext *LookupContext = computeDeclContext(SS);
7392   NamedDecl *D;
7393   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
7394   if (!LookupContext) {
7395     if (HasTypenameKeyword) {
7396       // FIXME: not all declaration name kinds are legal here
7397       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7398                                               UsingLoc, TypenameLoc,
7399                                               QualifierLoc,
7400                                               IdentLoc, NameInfo.getName());
7401     } else {
7402       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7403                                            QualifierLoc, NameInfo);
7404     }
7405   } else {
7406     D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
7407                           NameInfo, HasTypenameKeyword);
7408   }
7409   D->setAccess(AS);
7410   CurContext->addDecl(D);
7411 
7412   if (!LookupContext) return D;
7413   UsingDecl *UD = cast<UsingDecl>(D);
7414 
7415   if (RequireCompleteDeclContext(SS, LookupContext)) {
7416     UD->setInvalidDecl();
7417     return UD;
7418   }
7419 
7420   // The normal rules do not apply to inheriting constructor declarations.
7421   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
7422     if (CheckInheritingConstructorUsingDecl(UD))
7423       UD->setInvalidDecl();
7424     return UD;
7425   }
7426 
7427   // Otherwise, look up the target name.
7428 
7429   LookupResult R(*this, NameInfo, LookupOrdinaryName);
7430 
7431   // Unlike most lookups, we don't always want to hide tag
7432   // declarations: tag names are visible through the using declaration
7433   // even if hidden by ordinary names, *except* in a dependent context
7434   // where it's important for the sanity of two-phase lookup.
7435   if (!IsInstantiation)
7436     R.setHideTags(false);
7437 
7438   // For the purposes of this lookup, we have a base object type
7439   // equal to that of the current context.
7440   if (CurContext->isRecord()) {
7441     R.setBaseObjectType(
7442                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7443   }
7444 
7445   LookupQualifiedName(R, LookupContext);
7446 
7447   // Try to correct typos if possible.
7448   if (R.empty()) {
7449     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation,
7450                           CurContext->isRecord());
7451     if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
7452                                                R.getLookupKind(), S, &SS, CCC)){
7453       // We reject any correction for which ND would be NULL.
7454       NamedDecl *ND = Corrected.getCorrectionDecl();
7455       R.setLookupName(Corrected.getCorrection());
7456       R.addDecl(ND);
7457       // We reject candidates where DroppedSpecifier == true, hence the
7458       // literal '0' below.
7459       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7460                                 << NameInfo.getName() << LookupContext << 0
7461                                 << SS.getRange());
7462     } else {
7463       Diag(IdentLoc, diag::err_no_member)
7464         << NameInfo.getName() << LookupContext << SS.getRange();
7465       UD->setInvalidDecl();
7466       return UD;
7467     }
7468   }
7469 
7470   if (R.isAmbiguous()) {
7471     UD->setInvalidDecl();
7472     return UD;
7473   }
7474 
7475   if (HasTypenameKeyword) {
7476     // If we asked for a typename and got a non-type decl, error out.
7477     if (!R.getAsSingle<TypeDecl>()) {
7478       Diag(IdentLoc, diag::err_using_typename_non_type);
7479       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7480         Diag((*I)->getUnderlyingDecl()->getLocation(),
7481              diag::note_using_decl_target);
7482       UD->setInvalidDecl();
7483       return UD;
7484     }
7485   } else {
7486     // If we asked for a non-typename and we got a type, error out,
7487     // but only if this is an instantiation of an unresolved using
7488     // decl.  Otherwise just silently find the type name.
7489     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
7490       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7491       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
7492       UD->setInvalidDecl();
7493       return UD;
7494     }
7495   }
7496 
7497   // C++0x N2914 [namespace.udecl]p6:
7498   // A using-declaration shall not name a namespace.
7499   if (R.getAsSingle<NamespaceDecl>()) {
7500     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7501       << SS.getRange();
7502     UD->setInvalidDecl();
7503     return UD;
7504   }
7505 
7506   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7507     UsingShadowDecl *PrevDecl = 0;
7508     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
7509       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
7510   }
7511 
7512   return UD;
7513 }
7514 
7515 /// Additional checks for a using declaration referring to a constructor name.
7516 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
7517   assert(!UD->hasTypename() && "expecting a constructor name");
7518 
7519   const Type *SourceType = UD->getQualifier()->getAsType();
7520   assert(SourceType &&
7521          "Using decl naming constructor doesn't have type in scope spec.");
7522   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7523 
7524   // Check whether the named type is a direct base class.
7525   CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7526   CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7527   for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7528        BaseIt != BaseE; ++BaseIt) {
7529     CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7530     if (CanonicalSourceType == BaseType)
7531       break;
7532     if (BaseIt->getType()->isDependentType())
7533       break;
7534   }
7535 
7536   if (BaseIt == BaseE) {
7537     // Did not find SourceType in the bases.
7538     Diag(UD->getUsingLoc(),
7539          diag::err_using_decl_constructor_not_in_direct_base)
7540       << UD->getNameInfo().getSourceRange()
7541       << QualType(SourceType, 0) << TargetClass;
7542     return true;
7543   }
7544 
7545   if (!CurContext->isDependentContext())
7546     BaseIt->setInheritConstructors();
7547 
7548   return false;
7549 }
7550 
7551 /// Checks that the given using declaration is not an invalid
7552 /// redeclaration.  Note that this is checking only for the using decl
7553 /// itself, not for any ill-formedness among the UsingShadowDecls.
7554 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7555                                        bool HasTypenameKeyword,
7556                                        const CXXScopeSpec &SS,
7557                                        SourceLocation NameLoc,
7558                                        const LookupResult &Prev) {
7559   // C++03 [namespace.udecl]p8:
7560   // C++0x [namespace.udecl]p10:
7561   //   A using-declaration is a declaration and can therefore be used
7562   //   repeatedly where (and only where) multiple declarations are
7563   //   allowed.
7564   //
7565   // That's in non-member contexts.
7566   if (!CurContext->getRedeclContext()->isRecord())
7567     return false;
7568 
7569   NestedNameSpecifier *Qual = SS.getScopeRep();
7570 
7571   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7572     NamedDecl *D = *I;
7573 
7574     bool DTypename;
7575     NestedNameSpecifier *DQual;
7576     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7577       DTypename = UD->hasTypename();
7578       DQual = UD->getQualifier();
7579     } else if (UnresolvedUsingValueDecl *UD
7580                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7581       DTypename = false;
7582       DQual = UD->getQualifier();
7583     } else if (UnresolvedUsingTypenameDecl *UD
7584                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7585       DTypename = true;
7586       DQual = UD->getQualifier();
7587     } else continue;
7588 
7589     // using decls differ if one says 'typename' and the other doesn't.
7590     // FIXME: non-dependent using decls?
7591     if (HasTypenameKeyword != DTypename) continue;
7592 
7593     // using decls differ if they name different scopes (but note that
7594     // template instantiation can cause this check to trigger when it
7595     // didn't before instantiation).
7596     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7597         Context.getCanonicalNestedNameSpecifier(DQual))
7598       continue;
7599 
7600     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
7601     Diag(D->getLocation(), diag::note_using_decl) << 1;
7602     return true;
7603   }
7604 
7605   return false;
7606 }
7607 
7608 
7609 /// Checks that the given nested-name qualifier used in a using decl
7610 /// in the current context is appropriately related to the current
7611 /// scope.  If an error is found, diagnoses it and returns true.
7612 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7613                                    const CXXScopeSpec &SS,
7614                                    SourceLocation NameLoc) {
7615   DeclContext *NamedContext = computeDeclContext(SS);
7616 
7617   if (!CurContext->isRecord()) {
7618     // C++03 [namespace.udecl]p3:
7619     // C++0x [namespace.udecl]p8:
7620     //   A using-declaration for a class member shall be a member-declaration.
7621 
7622     // If we weren't able to compute a valid scope, it must be a
7623     // dependent class scope.
7624     if (!NamedContext || NamedContext->isRecord()) {
7625       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7626         << SS.getRange();
7627       return true;
7628     }
7629 
7630     // Otherwise, everything is known to be fine.
7631     return false;
7632   }
7633 
7634   // The current scope is a record.
7635 
7636   // If the named context is dependent, we can't decide much.
7637   if (!NamedContext) {
7638     // FIXME: in C++0x, we can diagnose if we can prove that the
7639     // nested-name-specifier does not refer to a base class, which is
7640     // still possible in some cases.
7641 
7642     // Otherwise we have to conservatively report that things might be
7643     // okay.
7644     return false;
7645   }
7646 
7647   if (!NamedContext->isRecord()) {
7648     // Ideally this would point at the last name in the specifier,
7649     // but we don't have that level of source info.
7650     Diag(SS.getRange().getBegin(),
7651          diag::err_using_decl_nested_name_specifier_is_not_class)
7652       << SS.getScopeRep() << SS.getRange();
7653     return true;
7654   }
7655 
7656   if (!NamedContext->isDependentContext() &&
7657       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7658     return true;
7659 
7660   if (getLangOpts().CPlusPlus11) {
7661     // C++0x [namespace.udecl]p3:
7662     //   In a using-declaration used as a member-declaration, the
7663     //   nested-name-specifier shall name a base class of the class
7664     //   being defined.
7665 
7666     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7667                                  cast<CXXRecordDecl>(NamedContext))) {
7668       if (CurContext == NamedContext) {
7669         Diag(NameLoc,
7670              diag::err_using_decl_nested_name_specifier_is_current_class)
7671           << SS.getRange();
7672         return true;
7673       }
7674 
7675       Diag(SS.getRange().getBegin(),
7676            diag::err_using_decl_nested_name_specifier_is_not_base_class)
7677         << SS.getScopeRep()
7678         << cast<CXXRecordDecl>(CurContext)
7679         << SS.getRange();
7680       return true;
7681     }
7682 
7683     return false;
7684   }
7685 
7686   // C++03 [namespace.udecl]p4:
7687   //   A using-declaration used as a member-declaration shall refer
7688   //   to a member of a base class of the class being defined [etc.].
7689 
7690   // Salient point: SS doesn't have to name a base class as long as
7691   // lookup only finds members from base classes.  Therefore we can
7692   // diagnose here only if we can prove that that can't happen,
7693   // i.e. if the class hierarchies provably don't intersect.
7694 
7695   // TODO: it would be nice if "definitely valid" results were cached
7696   // in the UsingDecl and UsingShadowDecl so that these checks didn't
7697   // need to be repeated.
7698 
7699   struct UserData {
7700     llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
7701 
7702     static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7703       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7704       Data->Bases.insert(Base);
7705       return true;
7706     }
7707 
7708     bool hasDependentBases(const CXXRecordDecl *Class) {
7709       return !Class->forallBases(collect, this);
7710     }
7711 
7712     /// Returns true if the base is dependent or is one of the
7713     /// accumulated base classes.
7714     static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7715       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7716       return !Data->Bases.count(Base);
7717     }
7718 
7719     bool mightShareBases(const CXXRecordDecl *Class) {
7720       return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7721     }
7722   };
7723 
7724   UserData Data;
7725 
7726   // Returns false if we find a dependent base.
7727   if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7728     return false;
7729 
7730   // Returns false if the class has a dependent base or if it or one
7731   // of its bases is present in the base set of the current context.
7732   if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7733     return false;
7734 
7735   Diag(SS.getRange().getBegin(),
7736        diag::err_using_decl_nested_name_specifier_is_not_base_class)
7737     << SS.getScopeRep()
7738     << cast<CXXRecordDecl>(CurContext)
7739     << SS.getRange();
7740 
7741   return true;
7742 }
7743 
7744 Decl *Sema::ActOnAliasDeclaration(Scope *S,
7745                                   AccessSpecifier AS,
7746                                   MultiTemplateParamsArg TemplateParamLists,
7747                                   SourceLocation UsingLoc,
7748                                   UnqualifiedId &Name,
7749                                   AttributeList *AttrList,
7750                                   TypeResult Type) {
7751   // Skip up to the relevant declaration scope.
7752   while (S->getFlags() & Scope::TemplateParamScope)
7753     S = S->getParent();
7754   assert((S->getFlags() & Scope::DeclScope) &&
7755          "got alias-declaration outside of declaration scope");
7756 
7757   if (Type.isInvalid())
7758     return 0;
7759 
7760   bool Invalid = false;
7761   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7762   TypeSourceInfo *TInfo = 0;
7763   GetTypeFromParser(Type.get(), &TInfo);
7764 
7765   if (DiagnoseClassNameShadow(CurContext, NameInfo))
7766     return 0;
7767 
7768   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
7769                                       UPPC_DeclarationType)) {
7770     Invalid = true;
7771     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7772                                              TInfo->getTypeLoc().getBeginLoc());
7773   }
7774 
7775   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7776   LookupName(Previous, S);
7777 
7778   // Warn about shadowing the name of a template parameter.
7779   if (Previous.isSingleResult() &&
7780       Previous.getFoundDecl()->isTemplateParameter()) {
7781     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
7782     Previous.clear();
7783   }
7784 
7785   assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7786          "name in alias declaration must be an identifier");
7787   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7788                                                Name.StartLocation,
7789                                                Name.Identifier, TInfo);
7790 
7791   NewTD->setAccess(AS);
7792 
7793   if (Invalid)
7794     NewTD->setInvalidDecl();
7795 
7796   ProcessDeclAttributeList(S, NewTD, AttrList);
7797 
7798   CheckTypedefForVariablyModifiedType(S, NewTD);
7799   Invalid |= NewTD->isInvalidDecl();
7800 
7801   bool Redeclaration = false;
7802 
7803   NamedDecl *NewND;
7804   if (TemplateParamLists.size()) {
7805     TypeAliasTemplateDecl *OldDecl = 0;
7806     TemplateParameterList *OldTemplateParams = 0;
7807 
7808     if (TemplateParamLists.size() != 1) {
7809       Diag(UsingLoc, diag::err_alias_template_extra_headers)
7810         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7811          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
7812     }
7813     TemplateParameterList *TemplateParams = TemplateParamLists[0];
7814 
7815     // Only consider previous declarations in the same scope.
7816     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7817                          /*ExplicitInstantiationOrSpecialization*/false);
7818     if (!Previous.empty()) {
7819       Redeclaration = true;
7820 
7821       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7822       if (!OldDecl && !Invalid) {
7823         Diag(UsingLoc, diag::err_redefinition_different_kind)
7824           << Name.Identifier;
7825 
7826         NamedDecl *OldD = Previous.getRepresentativeDecl();
7827         if (OldD->getLocation().isValid())
7828           Diag(OldD->getLocation(), diag::note_previous_definition);
7829 
7830         Invalid = true;
7831       }
7832 
7833       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7834         if (TemplateParameterListsAreEqual(TemplateParams,
7835                                            OldDecl->getTemplateParameters(),
7836                                            /*Complain=*/true,
7837                                            TPL_TemplateMatch))
7838           OldTemplateParams = OldDecl->getTemplateParameters();
7839         else
7840           Invalid = true;
7841 
7842         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7843         if (!Invalid &&
7844             !Context.hasSameType(OldTD->getUnderlyingType(),
7845                                  NewTD->getUnderlyingType())) {
7846           // FIXME: The C++0x standard does not clearly say this is ill-formed,
7847           // but we can't reasonably accept it.
7848           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7849             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7850           if (OldTD->getLocation().isValid())
7851             Diag(OldTD->getLocation(), diag::note_previous_definition);
7852           Invalid = true;
7853         }
7854       }
7855     }
7856 
7857     // Merge any previous default template arguments into our parameters,
7858     // and check the parameter list.
7859     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7860                                    TPC_TypeAliasTemplate))
7861       return 0;
7862 
7863     TypeAliasTemplateDecl *NewDecl =
7864       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7865                                     Name.Identifier, TemplateParams,
7866                                     NewTD);
7867 
7868     NewDecl->setAccess(AS);
7869 
7870     if (Invalid)
7871       NewDecl->setInvalidDecl();
7872     else if (OldDecl)
7873       NewDecl->setPreviousDecl(OldDecl);
7874 
7875     NewND = NewDecl;
7876   } else {
7877     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7878     NewND = NewTD;
7879   }
7880 
7881   if (!Redeclaration)
7882     PushOnScopeChains(NewND, S);
7883 
7884   ActOnDocumentableDecl(NewND);
7885   return NewND;
7886 }
7887 
7888 Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
7889                                              SourceLocation NamespaceLoc,
7890                                              SourceLocation AliasLoc,
7891                                              IdentifierInfo *Alias,
7892                                              CXXScopeSpec &SS,
7893                                              SourceLocation IdentLoc,
7894                                              IdentifierInfo *Ident) {
7895 
7896   // Lookup the namespace name.
7897   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7898   LookupParsedName(R, S, &SS);
7899 
7900   // Check if we have a previous declaration with the same name.
7901   NamedDecl *PrevDecl
7902     = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7903                        ForRedeclaration);
7904   if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7905     PrevDecl = 0;
7906 
7907   if (PrevDecl) {
7908     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
7909       // We already have an alias with the same name that points to the same
7910       // namespace, so don't create a new one.
7911       // FIXME: At some point, we'll want to create the (redundant)
7912       // declaration to maintain better source information.
7913       if (!R.isAmbiguous() && !R.empty() &&
7914           AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
7915         return 0;
7916     }
7917 
7918     unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7919       diag::err_redefinition_different_kind;
7920     Diag(AliasLoc, DiagID) << Alias;
7921     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
7922     return 0;
7923   }
7924 
7925   if (R.isAmbiguous())
7926     return 0;
7927 
7928   if (R.empty()) {
7929     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
7930       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
7931       return 0;
7932     }
7933   }
7934 
7935   NamespaceAliasDecl *AliasDecl =
7936     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
7937                                Alias, SS.getWithLocInContext(Context),
7938                                IdentLoc, R.getFoundDecl());
7939 
7940   PushOnScopeChains(AliasDecl, S);
7941   return AliasDecl;
7942 }
7943 
7944 Sema::ImplicitExceptionSpecification
7945 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7946                                                CXXMethodDecl *MD) {
7947   CXXRecordDecl *ClassDecl = MD->getParent();
7948 
7949   // C++ [except.spec]p14:
7950   //   An implicitly declared special member function (Clause 12) shall have an
7951   //   exception-specification. [...]
7952   ImplicitExceptionSpecification ExceptSpec(*this);
7953   if (ClassDecl->isInvalidDecl())
7954     return ExceptSpec;
7955 
7956   // Direct base-class constructors.
7957   for (const auto &B : ClassDecl->bases()) {
7958     if (B.isVirtual()) // Handled below.
7959       continue;
7960 
7961     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
7962       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7963       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7964       // If this is a deleted function, add it anyway. This might be conformant
7965       // with the standard. This might not. I'm not sure. It might not matter.
7966       if (Constructor)
7967         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
7968     }
7969   }
7970 
7971   // Virtual base-class constructors.
7972   for (const auto &B : ClassDecl->vbases()) {
7973     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
7974       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7975       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7976       // If this is a deleted function, add it anyway. This might be conformant
7977       // with the standard. This might not. I'm not sure. It might not matter.
7978       if (Constructor)
7979         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
7980     }
7981   }
7982 
7983   // Field constructors.
7984   for (const auto *F : ClassDecl->fields()) {
7985     if (F->hasInClassInitializer()) {
7986       if (Expr *E = F->getInClassInitializer())
7987         ExceptSpec.CalledExpr(E);
7988       else if (!F->isInvalidDecl())
7989         // DR1351:
7990         //   If the brace-or-equal-initializer of a non-static data member
7991         //   invokes a defaulted default constructor of its class or of an
7992         //   enclosing class in a potentially evaluated subexpression, the
7993         //   program is ill-formed.
7994         //
7995         // This resolution is unworkable: the exception specification of the
7996         // default constructor can be needed in an unevaluated context, in
7997         // particular, in the operand of a noexcept-expression, and we can be
7998         // unable to compute an exception specification for an enclosed class.
7999         //
8000         // We do not allow an in-class initializer to require the evaluation
8001         // of the exception specification for any in-class initializer whose
8002         // definition is not lexically complete.
8003         Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
8004     } else if (const RecordType *RecordTy
8005               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8006       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8007       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8008       // If this is a deleted function, add it anyway. This might be conformant
8009       // with the standard. This might not. I'm not sure. It might not matter.
8010       // In particular, the problem is that this function never gets called. It
8011       // might just be ill-formed because this function attempts to refer to
8012       // a deleted function here.
8013       if (Constructor)
8014         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8015     }
8016   }
8017 
8018   return ExceptSpec;
8019 }
8020 
8021 Sema::ImplicitExceptionSpecification
8022 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8023   CXXRecordDecl *ClassDecl = CD->getParent();
8024 
8025   // C++ [except.spec]p14:
8026   //   An inheriting constructor [...] shall have an exception-specification. [...]
8027   ImplicitExceptionSpecification ExceptSpec(*this);
8028   if (ClassDecl->isInvalidDecl())
8029     return ExceptSpec;
8030 
8031   // Inherited constructor.
8032   const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8033   const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8034   // FIXME: Copying or moving the parameters could add extra exceptions to the
8035   // set, as could the default arguments for the inherited constructor. This
8036   // will be addressed when we implement the resolution of core issue 1351.
8037   ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8038 
8039   // Direct base-class constructors.
8040   for (const auto &B : ClassDecl->bases()) {
8041     if (B.isVirtual()) // Handled below.
8042       continue;
8043 
8044     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8045       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8046       if (BaseClassDecl == InheritedDecl)
8047         continue;
8048       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8049       if (Constructor)
8050         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8051     }
8052   }
8053 
8054   // Virtual base-class constructors.
8055   for (const auto &B : ClassDecl->vbases()) {
8056     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8057       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8058       if (BaseClassDecl == InheritedDecl)
8059         continue;
8060       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8061       if (Constructor)
8062         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8063     }
8064   }
8065 
8066   // Field constructors.
8067   for (const auto *F : ClassDecl->fields()) {
8068     if (F->hasInClassInitializer()) {
8069       if (Expr *E = F->getInClassInitializer())
8070         ExceptSpec.CalledExpr(E);
8071       else if (!F->isInvalidDecl())
8072         Diag(CD->getLocation(),
8073              diag::err_in_class_initializer_references_def_ctor) << CD;
8074     } else if (const RecordType *RecordTy
8075               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8076       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8077       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8078       if (Constructor)
8079         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8080     }
8081   }
8082 
8083   return ExceptSpec;
8084 }
8085 
8086 namespace {
8087 /// RAII object to register a special member as being currently declared.
8088 struct DeclaringSpecialMember {
8089   Sema &S;
8090   Sema::SpecialMemberDecl D;
8091   bool WasAlreadyBeingDeclared;
8092 
8093   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8094     : S(S), D(RD, CSM) {
8095     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8096     if (WasAlreadyBeingDeclared)
8097       // This almost never happens, but if it does, ensure that our cache
8098       // doesn't contain a stale result.
8099       S.SpecialMemberCache.clear();
8100 
8101     // FIXME: Register a note to be produced if we encounter an error while
8102     // declaring the special member.
8103   }
8104   ~DeclaringSpecialMember() {
8105     if (!WasAlreadyBeingDeclared)
8106       S.SpecialMembersBeingDeclared.erase(D);
8107   }
8108 
8109   /// \brief Are we already trying to declare this special member?
8110   bool isAlreadyBeingDeclared() const {
8111     return WasAlreadyBeingDeclared;
8112   }
8113 };
8114 }
8115 
8116 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8117                                                      CXXRecordDecl *ClassDecl) {
8118   // C++ [class.ctor]p5:
8119   //   A default constructor for a class X is a constructor of class X
8120   //   that can be called without an argument. If there is no
8121   //   user-declared constructor for class X, a default constructor is
8122   //   implicitly declared. An implicitly-declared default constructor
8123   //   is an inline public member of its class.
8124   assert(ClassDecl->needsImplicitDefaultConstructor() &&
8125          "Should not build implicit default constructor!");
8126 
8127   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8128   if (DSM.isAlreadyBeingDeclared())
8129     return 0;
8130 
8131   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8132                                                      CXXDefaultConstructor,
8133                                                      false);
8134 
8135   // Create the actual constructor declaration.
8136   CanQualType ClassType
8137     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8138   SourceLocation ClassLoc = ClassDecl->getLocation();
8139   DeclarationName Name
8140     = Context.DeclarationNames.getCXXConstructorName(ClassType);
8141   DeclarationNameInfo NameInfo(Name, ClassLoc);
8142   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
8143       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
8144       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8145       Constexpr);
8146   DefaultCon->setAccess(AS_public);
8147   DefaultCon->setDefaulted();
8148   DefaultCon->setImplicit();
8149 
8150   // Build an exception specification pointing back at this constructor.
8151   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
8152   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8153 
8154   // We don't need to use SpecialMemberIsTrivial here; triviality for default
8155   // constructors is easy to compute.
8156   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8157 
8158   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
8159     SetDeclDeleted(DefaultCon, ClassLoc);
8160 
8161   // Note that we have declared this constructor.
8162   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
8163 
8164   if (Scope *S = getScopeForContext(ClassDecl))
8165     PushOnScopeChains(DefaultCon, S, false);
8166   ClassDecl->addDecl(DefaultCon);
8167 
8168   return DefaultCon;
8169 }
8170 
8171 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8172                                             CXXConstructorDecl *Constructor) {
8173   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
8174           !Constructor->doesThisDeclarationHaveABody() &&
8175           !Constructor->isDeleted()) &&
8176     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
8177 
8178   CXXRecordDecl *ClassDecl = Constructor->getParent();
8179   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
8180 
8181   SynthesizedFunctionScope Scope(*this, Constructor);
8182   DiagnosticErrorTrap Trap(Diags);
8183   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8184       Trap.hasErrorOccurred()) {
8185     Diag(CurrentLocation, diag::note_member_synthesized_at)
8186       << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
8187     Constructor->setInvalidDecl();
8188     return;
8189   }
8190 
8191   SourceLocation Loc = Constructor->getLocation();
8192   Constructor->setBody(new (Context) CompoundStmt(Loc));
8193 
8194   Constructor->markUsed(Context);
8195   MarkVTableUsed(CurrentLocation, ClassDecl);
8196 
8197   if (ASTMutationListener *L = getASTMutationListener()) {
8198     L->CompletedImplicitDefinition(Constructor);
8199   }
8200 
8201   DiagnoseUninitializedFields(*this, Constructor);
8202 }
8203 
8204 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
8205   // Perform any delayed checks on exception specifications.
8206   CheckDelayedMemberExceptionSpecs();
8207 }
8208 
8209 namespace {
8210 /// Information on inheriting constructors to declare.
8211 class InheritingConstructorInfo {
8212 public:
8213   InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8214       : SemaRef(SemaRef), Derived(Derived) {
8215     // Mark the constructors that we already have in the derived class.
8216     //
8217     // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8218     //   unless there is a user-declared constructor with the same signature in
8219     //   the class where the using-declaration appears.
8220     visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8221   }
8222 
8223   void inheritAll(CXXRecordDecl *RD) {
8224     visitAll(RD, &InheritingConstructorInfo::inherit);
8225   }
8226 
8227 private:
8228   /// Information about an inheriting constructor.
8229   struct InheritingConstructor {
8230     InheritingConstructor()
8231       : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
8232 
8233     /// If \c true, a constructor with this signature is already declared
8234     /// in the derived class.
8235     bool DeclaredInDerived;
8236 
8237     /// The constructor which is inherited.
8238     const CXXConstructorDecl *BaseCtor;
8239 
8240     /// The derived constructor we declared.
8241     CXXConstructorDecl *DerivedCtor;
8242   };
8243 
8244   /// Inheriting constructors with a given canonical type. There can be at
8245   /// most one such non-template constructor, and any number of templated
8246   /// constructors.
8247   struct InheritingConstructorsForType {
8248     InheritingConstructor NonTemplate;
8249     SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8250         Templates;
8251 
8252     InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8253       if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8254         TemplateParameterList *ParamList = FTD->getTemplateParameters();
8255         for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8256           if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8257                                                false, S.TPL_TemplateMatch))
8258             return Templates[I].second;
8259         Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8260         return Templates.back().second;
8261       }
8262 
8263       return NonTemplate;
8264     }
8265   };
8266 
8267   /// Get or create the inheriting constructor record for a constructor.
8268   InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8269                                   QualType CtorType) {
8270     return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8271         .getEntry(SemaRef, Ctor);
8272   }
8273 
8274   typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8275 
8276   /// Process all constructors for a class.
8277   void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
8278     for (const auto *Ctor : RD->ctors())
8279       (this->*Callback)(Ctor);
8280     for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8281              I(RD->decls_begin()), E(RD->decls_end());
8282          I != E; ++I) {
8283       const FunctionDecl *FD = (*I)->getTemplatedDecl();
8284       if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8285         (this->*Callback)(CD);
8286     }
8287   }
8288 
8289   /// Note that a constructor (or constructor template) was declared in Derived.
8290   void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8291     getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8292   }
8293 
8294   /// Inherit a single constructor.
8295   void inherit(const CXXConstructorDecl *Ctor) {
8296     const FunctionProtoType *CtorType =
8297         Ctor->getType()->castAs<FunctionProtoType>();
8298     ArrayRef<QualType> ArgTypes(CtorType->getParamTypes());
8299     FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8300 
8301     SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8302 
8303     // Core issue (no number yet): the ellipsis is always discarded.
8304     if (EPI.Variadic) {
8305       SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8306       SemaRef.Diag(Ctor->getLocation(),
8307                    diag::note_using_decl_constructor_ellipsis);
8308       EPI.Variadic = false;
8309     }
8310 
8311     // Declare a constructor for each number of parameters.
8312     //
8313     // C++11 [class.inhctor]p1:
8314     //   The candidate set of inherited constructors from the class X named in
8315     //   the using-declaration consists of [... modulo defects ...] for each
8316     //   constructor or constructor template of X, the set of constructors or
8317     //   constructor templates that results from omitting any ellipsis parameter
8318     //   specification and successively omitting parameters with a default
8319     //   argument from the end of the parameter-type-list
8320     unsigned MinParams = minParamsToInherit(Ctor);
8321     unsigned Params = Ctor->getNumParams();
8322     if (Params >= MinParams) {
8323       do
8324         declareCtor(UsingLoc, Ctor,
8325                     SemaRef.Context.getFunctionType(
8326                         Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
8327       while (Params > MinParams &&
8328              Ctor->getParamDecl(--Params)->hasDefaultArg());
8329     }
8330   }
8331 
8332   /// Find the using-declaration which specified that we should inherit the
8333   /// constructors of \p Base.
8334   SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8335     // No fancy lookup required; just look for the base constructor name
8336     // directly within the derived class.
8337     ASTContext &Context = SemaRef.Context;
8338     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8339         Context.getCanonicalType(Context.getRecordType(Base)));
8340     DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8341     return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8342   }
8343 
8344   unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8345     // C++11 [class.inhctor]p3:
8346     //   [F]or each constructor template in the candidate set of inherited
8347     //   constructors, a constructor template is implicitly declared
8348     if (Ctor->getDescribedFunctionTemplate())
8349       return 0;
8350 
8351     //   For each non-template constructor in the candidate set of inherited
8352     //   constructors other than a constructor having no parameters or a
8353     //   copy/move constructor having a single parameter, a constructor is
8354     //   implicitly declared [...]
8355     if (Ctor->getNumParams() == 0)
8356       return 1;
8357     if (Ctor->isCopyOrMoveConstructor())
8358       return 2;
8359 
8360     // Per discussion on core reflector, never inherit a constructor which
8361     // would become a default, copy, or move constructor of Derived either.
8362     const ParmVarDecl *PD = Ctor->getParamDecl(0);
8363     const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8364     return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8365   }
8366 
8367   /// Declare a single inheriting constructor, inheriting the specified
8368   /// constructor, with the given type.
8369   void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8370                    QualType DerivedType) {
8371     InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8372 
8373     // C++11 [class.inhctor]p3:
8374     //   ... a constructor is implicitly declared with the same constructor
8375     //   characteristics unless there is a user-declared constructor with
8376     //   the same signature in the class where the using-declaration appears
8377     if (Entry.DeclaredInDerived)
8378       return;
8379 
8380     // C++11 [class.inhctor]p7:
8381     //   If two using-declarations declare inheriting constructors with the
8382     //   same signature, the program is ill-formed
8383     if (Entry.DerivedCtor) {
8384       if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8385         // Only diagnose this once per constructor.
8386         if (Entry.DerivedCtor->isInvalidDecl())
8387           return;
8388         Entry.DerivedCtor->setInvalidDecl();
8389 
8390         SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8391         SemaRef.Diag(BaseCtor->getLocation(),
8392                      diag::note_using_decl_constructor_conflict_current_ctor);
8393         SemaRef.Diag(Entry.BaseCtor->getLocation(),
8394                      diag::note_using_decl_constructor_conflict_previous_ctor);
8395         SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8396                      diag::note_using_decl_constructor_conflict_previous_using);
8397       } else {
8398         // Core issue (no number): if the same inheriting constructor is
8399         // produced by multiple base class constructors from the same base
8400         // class, the inheriting constructor is defined as deleted.
8401         SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8402       }
8403 
8404       return;
8405     }
8406 
8407     ASTContext &Context = SemaRef.Context;
8408     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8409         Context.getCanonicalType(Context.getRecordType(Derived)));
8410     DeclarationNameInfo NameInfo(Name, UsingLoc);
8411 
8412     TemplateParameterList *TemplateParams = 0;
8413     if (const FunctionTemplateDecl *FTD =
8414             BaseCtor->getDescribedFunctionTemplate()) {
8415       TemplateParams = FTD->getTemplateParameters();
8416       // We're reusing template parameters from a different DeclContext. This
8417       // is questionable at best, but works out because the template depth in
8418       // both places is guaranteed to be 0.
8419       // FIXME: Rebuild the template parameters in the new context, and
8420       // transform the function type to refer to them.
8421     }
8422 
8423     // Build type source info pointing at the using-declaration. This is
8424     // required by template instantiation.
8425     TypeSourceInfo *TInfo =
8426         Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8427     FunctionProtoTypeLoc ProtoLoc =
8428         TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8429 
8430     CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8431         Context, Derived, UsingLoc, NameInfo, DerivedType,
8432         TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8433         /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8434 
8435     // Build an unevaluated exception specification for this constructor.
8436     const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8437     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8438     EPI.ExceptionSpecType = EST_Unevaluated;
8439     EPI.ExceptionSpecDecl = DerivedCtor;
8440     DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
8441                                                  FPT->getParamTypes(), EPI));
8442 
8443     // Build the parameter declarations.
8444     SmallVector<ParmVarDecl *, 16> ParamDecls;
8445     for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
8446       TypeSourceInfo *TInfo =
8447           Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
8448       ParmVarDecl *PD = ParmVarDecl::Create(
8449           Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
8450           FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/0);
8451       PD->setScopeInfo(0, I);
8452       PD->setImplicit();
8453       ParamDecls.push_back(PD);
8454       ProtoLoc.setParam(I, PD);
8455     }
8456 
8457     // Set up the new constructor.
8458     DerivedCtor->setAccess(BaseCtor->getAccess());
8459     DerivedCtor->setParams(ParamDecls);
8460     DerivedCtor->setInheritedConstructor(BaseCtor);
8461     if (BaseCtor->isDeleted())
8462       SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8463 
8464     // If this is a constructor template, build the template declaration.
8465     if (TemplateParams) {
8466       FunctionTemplateDecl *DerivedTemplate =
8467           FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8468                                        TemplateParams, DerivedCtor);
8469       DerivedTemplate->setAccess(BaseCtor->getAccess());
8470       DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8471       Derived->addDecl(DerivedTemplate);
8472     } else {
8473       Derived->addDecl(DerivedCtor);
8474     }
8475 
8476     Entry.BaseCtor = BaseCtor;
8477     Entry.DerivedCtor = DerivedCtor;
8478   }
8479 
8480   Sema &SemaRef;
8481   CXXRecordDecl *Derived;
8482   typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8483   MapType Map;
8484 };
8485 }
8486 
8487 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8488   // Defer declaring the inheriting constructors until the class is
8489   // instantiated.
8490   if (ClassDecl->isDependentContext())
8491     return;
8492 
8493   // Find base classes from which we might inherit constructors.
8494   SmallVector<CXXRecordDecl*, 4> InheritedBases;
8495   for (const auto &BaseIt : ClassDecl->bases())
8496     if (BaseIt.getInheritConstructors())
8497       InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
8498 
8499   // Go no further if we're not inheriting any constructors.
8500   if (InheritedBases.empty())
8501     return;
8502 
8503   // Declare the inherited constructors.
8504   InheritingConstructorInfo ICI(*this, ClassDecl);
8505   for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8506     ICI.inheritAll(InheritedBases[I]);
8507 }
8508 
8509 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8510                                        CXXConstructorDecl *Constructor) {
8511   CXXRecordDecl *ClassDecl = Constructor->getParent();
8512   assert(Constructor->getInheritedConstructor() &&
8513          !Constructor->doesThisDeclarationHaveABody() &&
8514          !Constructor->isDeleted());
8515 
8516   SynthesizedFunctionScope Scope(*this, Constructor);
8517   DiagnosticErrorTrap Trap(Diags);
8518   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8519       Trap.hasErrorOccurred()) {
8520     Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8521       << Context.getTagDeclType(ClassDecl);
8522     Constructor->setInvalidDecl();
8523     return;
8524   }
8525 
8526   SourceLocation Loc = Constructor->getLocation();
8527   Constructor->setBody(new (Context) CompoundStmt(Loc));
8528 
8529   Constructor->markUsed(Context);
8530   MarkVTableUsed(CurrentLocation, ClassDecl);
8531 
8532   if (ASTMutationListener *L = getASTMutationListener()) {
8533     L->CompletedImplicitDefinition(Constructor);
8534   }
8535 }
8536 
8537 
8538 Sema::ImplicitExceptionSpecification
8539 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8540   CXXRecordDecl *ClassDecl = MD->getParent();
8541 
8542   // C++ [except.spec]p14:
8543   //   An implicitly declared special member function (Clause 12) shall have
8544   //   an exception-specification.
8545   ImplicitExceptionSpecification ExceptSpec(*this);
8546   if (ClassDecl->isInvalidDecl())
8547     return ExceptSpec;
8548 
8549   // Direct base-class destructors.
8550   for (const auto &B : ClassDecl->bases()) {
8551     if (B.isVirtual()) // Handled below.
8552       continue;
8553 
8554     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8555       ExceptSpec.CalledDecl(B.getLocStart(),
8556                    LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
8557   }
8558 
8559   // Virtual base-class destructors.
8560   for (const auto &B : ClassDecl->vbases()) {
8561     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8562       ExceptSpec.CalledDecl(B.getLocStart(),
8563                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
8564   }
8565 
8566   // Field destructors.
8567   for (const auto *F : ClassDecl->fields()) {
8568     if (const RecordType *RecordTy
8569         = Context.getBaseElementType(F->getType())->getAs<RecordType>())
8570       ExceptSpec.CalledDecl(F->getLocation(),
8571                   LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
8572   }
8573 
8574   return ExceptSpec;
8575 }
8576 
8577 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8578   // C++ [class.dtor]p2:
8579   //   If a class has no user-declared destructor, a destructor is
8580   //   declared implicitly. An implicitly-declared destructor is an
8581   //   inline public member of its class.
8582   assert(ClassDecl->needsImplicitDestructor());
8583 
8584   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8585   if (DSM.isAlreadyBeingDeclared())
8586     return 0;
8587 
8588   // Create the actual destructor declaration.
8589   CanQualType ClassType
8590     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8591   SourceLocation ClassLoc = ClassDecl->getLocation();
8592   DeclarationName Name
8593     = Context.DeclarationNames.getCXXDestructorName(ClassType);
8594   DeclarationNameInfo NameInfo(Name, ClassLoc);
8595   CXXDestructorDecl *Destructor
8596       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8597                                   QualType(), 0, /*isInline=*/true,
8598                                   /*isImplicitlyDeclared=*/true);
8599   Destructor->setAccess(AS_public);
8600   Destructor->setDefaulted();
8601   Destructor->setImplicit();
8602 
8603   // Build an exception specification pointing back at this destructor.
8604   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
8605   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8606 
8607   AddOverriddenMethods(ClassDecl, Destructor);
8608 
8609   // We don't need to use SpecialMemberIsTrivial here; triviality for
8610   // destructors is easy to compute.
8611   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8612 
8613   if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
8614     SetDeclDeleted(Destructor, ClassLoc);
8615 
8616   // Note that we have declared this destructor.
8617   ++ASTContext::NumImplicitDestructorsDeclared;
8618 
8619   // Introduce this destructor into its scope.
8620   if (Scope *S = getScopeForContext(ClassDecl))
8621     PushOnScopeChains(Destructor, S, false);
8622   ClassDecl->addDecl(Destructor);
8623 
8624   return Destructor;
8625 }
8626 
8627 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
8628                                     CXXDestructorDecl *Destructor) {
8629   assert((Destructor->isDefaulted() &&
8630           !Destructor->doesThisDeclarationHaveABody() &&
8631           !Destructor->isDeleted()) &&
8632          "DefineImplicitDestructor - call it for implicit default dtor");
8633   CXXRecordDecl *ClassDecl = Destructor->getParent();
8634   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
8635 
8636   if (Destructor->isInvalidDecl())
8637     return;
8638 
8639   SynthesizedFunctionScope Scope(*this, Destructor);
8640 
8641   DiagnosticErrorTrap Trap(Diags);
8642   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8643                                          Destructor->getParent());
8644 
8645   if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
8646     Diag(CurrentLocation, diag::note_member_synthesized_at)
8647       << CXXDestructor << Context.getTagDeclType(ClassDecl);
8648 
8649     Destructor->setInvalidDecl();
8650     return;
8651   }
8652 
8653   SourceLocation Loc = Destructor->getLocation();
8654   Destructor->setBody(new (Context) CompoundStmt(Loc));
8655   Destructor->markUsed(Context);
8656   MarkVTableUsed(CurrentLocation, ClassDecl);
8657 
8658   if (ASTMutationListener *L = getASTMutationListener()) {
8659     L->CompletedImplicitDefinition(Destructor);
8660   }
8661 }
8662 
8663 /// \brief Perform any semantic analysis which needs to be delayed until all
8664 /// pending class member declarations have been parsed.
8665 void Sema::ActOnFinishCXXMemberDecls() {
8666   // If the context is an invalid C++ class, just suppress these checks.
8667   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8668     if (Record->isInvalidDecl()) {
8669       DelayedDefaultedMemberExceptionSpecs.clear();
8670       DelayedDestructorExceptionSpecChecks.clear();
8671       return;
8672     }
8673   }
8674 }
8675 
8676 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8677                                          CXXDestructorDecl *Destructor) {
8678   assert(getLangOpts().CPlusPlus11 &&
8679          "adjusting dtor exception specs was introduced in c++11");
8680 
8681   // C++11 [class.dtor]p3:
8682   //   A declaration of a destructor that does not have an exception-
8683   //   specification is implicitly considered to have the same exception-
8684   //   specification as an implicit declaration.
8685   const FunctionProtoType *DtorType = Destructor->getType()->
8686                                         getAs<FunctionProtoType>();
8687   if (DtorType->hasExceptionSpec())
8688     return;
8689 
8690   // Replace the destructor's type, building off the existing one. Fortunately,
8691   // the only thing of interest in the destructor type is its extended info.
8692   // The return and arguments are fixed.
8693   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8694   EPI.ExceptionSpecType = EST_Unevaluated;
8695   EPI.ExceptionSpecDecl = Destructor;
8696   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8697 
8698   // FIXME: If the destructor has a body that could throw, and the newly created
8699   // spec doesn't allow exceptions, we should emit a warning, because this
8700   // change in behavior can break conforming C++03 programs at runtime.
8701   // However, we don't have a body or an exception specification yet, so it
8702   // needs to be done somewhere else.
8703 }
8704 
8705 namespace {
8706 /// \brief An abstract base class for all helper classes used in building the
8707 //  copy/move operators. These classes serve as factory functions and help us
8708 //  avoid using the same Expr* in the AST twice.
8709 class ExprBuilder {
8710   ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8711   ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8712 
8713 protected:
8714   static Expr *assertNotNull(Expr *E) {
8715     assert(E && "Expression construction must not fail.");
8716     return E;
8717   }
8718 
8719 public:
8720   ExprBuilder() {}
8721   virtual ~ExprBuilder() {}
8722 
8723   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
8724 };
8725 
8726 class RefBuilder: public ExprBuilder {
8727   VarDecl *Var;
8728   QualType VarType;
8729 
8730 public:
8731   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
8732     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).take());
8733   }
8734 
8735   RefBuilder(VarDecl *Var, QualType VarType)
8736       : Var(Var), VarType(VarType) {}
8737 };
8738 
8739 class ThisBuilder: public ExprBuilder {
8740 public:
8741   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
8742     return assertNotNull(S.ActOnCXXThis(Loc).takeAs<Expr>());
8743   }
8744 };
8745 
8746 class CastBuilder: public ExprBuilder {
8747   const ExprBuilder &Builder;
8748   QualType Type;
8749   ExprValueKind Kind;
8750   const CXXCastPath &Path;
8751 
8752 public:
8753   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
8754     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
8755                                              CK_UncheckedDerivedToBase, Kind,
8756                                              &Path).take());
8757   }
8758 
8759   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
8760               const CXXCastPath &Path)
8761       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
8762 };
8763 
8764 class DerefBuilder: public ExprBuilder {
8765   const ExprBuilder &Builder;
8766 
8767 public:
8768   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
8769     return assertNotNull(
8770         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).take());
8771   }
8772 
8773   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8774 };
8775 
8776 class MemberBuilder: public ExprBuilder {
8777   const ExprBuilder &Builder;
8778   QualType Type;
8779   CXXScopeSpec SS;
8780   bool IsArrow;
8781   LookupResult &MemberLookup;
8782 
8783 public:
8784   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
8785     return assertNotNull(S.BuildMemberReferenceExpr(
8786         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 0,
8787         MemberLookup, 0).take());
8788   }
8789 
8790   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
8791                 LookupResult &MemberLookup)
8792       : Builder(Builder), Type(Type), IsArrow(IsArrow),
8793         MemberLookup(MemberLookup) {}
8794 };
8795 
8796 class MoveCastBuilder: public ExprBuilder {
8797   const ExprBuilder &Builder;
8798 
8799 public:
8800   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
8801     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
8802   }
8803 
8804   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8805 };
8806 
8807 class LvalueConvBuilder: public ExprBuilder {
8808   const ExprBuilder &Builder;
8809 
8810 public:
8811   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
8812     return assertNotNull(
8813         S.DefaultLvalueConversion(Builder.build(S, Loc)).take());
8814   }
8815 
8816   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8817 };
8818 
8819 class SubscriptBuilder: public ExprBuilder {
8820   const ExprBuilder &Base;
8821   const ExprBuilder &Index;
8822 
8823 public:
8824   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
8825     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
8826         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).take());
8827   }
8828 
8829   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
8830       : Base(Base), Index(Index) {}
8831 };
8832 
8833 } // end anonymous namespace
8834 
8835 /// When generating a defaulted copy or move assignment operator, if a field
8836 /// should be copied with __builtin_memcpy rather than via explicit assignments,
8837 /// do so. This optimization only applies for arrays of scalars, and for arrays
8838 /// of class type where the selected copy/move-assignment operator is trivial.
8839 static StmtResult
8840 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
8841                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
8842   // Compute the size of the memory buffer to be copied.
8843   QualType SizeType = S.Context.getSizeType();
8844   llvm::APInt Size(S.Context.getTypeSize(SizeType),
8845                    S.Context.getTypeSizeInChars(T).getQuantity());
8846 
8847   // Take the address of the field references for "from" and "to". We
8848   // directly construct UnaryOperators here because semantic analysis
8849   // does not permit us to take the address of an xvalue.
8850   Expr *From = FromB.build(S, Loc);
8851   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8852                          S.Context.getPointerType(From->getType()),
8853                          VK_RValue, OK_Ordinary, Loc);
8854   Expr *To = ToB.build(S, Loc);
8855   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8856                        S.Context.getPointerType(To->getType()),
8857                        VK_RValue, OK_Ordinary, Loc);
8858 
8859   const Type *E = T->getBaseElementTypeUnsafe();
8860   bool NeedsCollectableMemCpy =
8861     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8862 
8863   // Create a reference to the __builtin_objc_memmove_collectable function
8864   StringRef MemCpyName = NeedsCollectableMemCpy ?
8865     "__builtin_objc_memmove_collectable" :
8866     "__builtin_memcpy";
8867   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8868                  Sema::LookupOrdinaryName);
8869   S.LookupName(R, S.TUScope, true);
8870 
8871   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8872   if (!MemCpy)
8873     // Something went horribly wrong earlier, and we will have complained
8874     // about it.
8875     return StmtError();
8876 
8877   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8878                                             VK_RValue, Loc, 0);
8879   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8880 
8881   Expr *CallArgs[] = {
8882     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8883   };
8884   ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8885                                     Loc, CallArgs, Loc);
8886 
8887   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8888   return S.Owned(Call.takeAs<Stmt>());
8889 }
8890 
8891 /// \brief Builds a statement that copies/moves the given entity from \p From to
8892 /// \c To.
8893 ///
8894 /// This routine is used to copy/move the members of a class with an
8895 /// implicitly-declared copy/move assignment operator. When the entities being
8896 /// copied are arrays, this routine builds for loops to copy them.
8897 ///
8898 /// \param S The Sema object used for type-checking.
8899 ///
8900 /// \param Loc The location where the implicit copy/move is being generated.
8901 ///
8902 /// \param T The type of the expressions being copied/moved. Both expressions
8903 /// must have this type.
8904 ///
8905 /// \param To The expression we are copying/moving to.
8906 ///
8907 /// \param From The expression we are copying/moving from.
8908 ///
8909 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
8910 /// Otherwise, it's a non-static member subobject.
8911 ///
8912 /// \param Copying Whether we're copying or moving.
8913 ///
8914 /// \param Depth Internal parameter recording the depth of the recursion.
8915 ///
8916 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8917 /// if a memcpy should be used instead.
8918 static StmtResult
8919 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8920                                  const ExprBuilder &To, const ExprBuilder &From,
8921                                  bool CopyingBaseSubobject, bool Copying,
8922                                  unsigned Depth = 0) {
8923   // C++11 [class.copy]p28:
8924   //   Each subobject is assigned in the manner appropriate to its type:
8925   //
8926   //     - if the subobject is of class type, as if by a call to operator= with
8927   //       the subobject as the object expression and the corresponding
8928   //       subobject of x as a single function argument (as if by explicit
8929   //       qualification; that is, ignoring any possible virtual overriding
8930   //       functions in more derived classes);
8931   //
8932   // C++03 [class.copy]p13:
8933   //     - if the subobject is of class type, the copy assignment operator for
8934   //       the class is used (as if by explicit qualification; that is,
8935   //       ignoring any possible virtual overriding functions in more derived
8936   //       classes);
8937   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8938     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8939 
8940     // Look for operator=.
8941     DeclarationName Name
8942       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8943     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8944     S.LookupQualifiedName(OpLookup, ClassDecl, false);
8945 
8946     // Prior to C++11, filter out any result that isn't a copy/move-assignment
8947     // operator.
8948     if (!S.getLangOpts().CPlusPlus11) {
8949       LookupResult::Filter F = OpLookup.makeFilter();
8950       while (F.hasNext()) {
8951         NamedDecl *D = F.next();
8952         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8953           if (Method->isCopyAssignmentOperator() ||
8954               (!Copying && Method->isMoveAssignmentOperator()))
8955             continue;
8956 
8957         F.erase();
8958       }
8959       F.done();
8960     }
8961 
8962     // Suppress the protected check (C++ [class.protected]) for each of the
8963     // assignment operators we found. This strange dance is required when
8964     // we're assigning via a base classes's copy-assignment operator. To
8965     // ensure that we're getting the right base class subobject (without
8966     // ambiguities), we need to cast "this" to that subobject type; to
8967     // ensure that we don't go through the virtual call mechanism, we need
8968     // to qualify the operator= name with the base class (see below). However,
8969     // this means that if the base class has a protected copy assignment
8970     // operator, the protected member access check will fail. So, we
8971     // rewrite "protected" access to "public" access in this case, since we
8972     // know by construction that we're calling from a derived class.
8973     if (CopyingBaseSubobject) {
8974       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8975            L != LEnd; ++L) {
8976         if (L.getAccess() == AS_protected)
8977           L.setAccess(AS_public);
8978       }
8979     }
8980 
8981     // Create the nested-name-specifier that will be used to qualify the
8982     // reference to operator=; this is required to suppress the virtual
8983     // call mechanism.
8984     CXXScopeSpec SS;
8985     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
8986     SS.MakeTrivial(S.Context,
8987                    NestedNameSpecifier::Create(S.Context, 0, false,
8988                                                CanonicalT),
8989                    Loc);
8990 
8991     // Create the reference to operator=.
8992     ExprResult OpEqualRef
8993       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
8994                                    SS, /*TemplateKWLoc=*/SourceLocation(),
8995                                    /*FirstQualifierInScope=*/0,
8996                                    OpLookup,
8997                                    /*TemplateArgs=*/0,
8998                                    /*SuppressQualifierCheck=*/true);
8999     if (OpEqualRef.isInvalid())
9000       return StmtError();
9001 
9002     // Build the call to the assignment operator.
9003 
9004     Expr *FromInst = From.build(S, Loc);
9005     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
9006                                                   OpEqualRef.takeAs<Expr>(),
9007                                                   Loc, FromInst, Loc);
9008     if (Call.isInvalid())
9009       return StmtError();
9010 
9011     // If we built a call to a trivial 'operator=' while copying an array,
9012     // bail out. We'll replace the whole shebang with a memcpy.
9013     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9014     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9015       return StmtResult((Stmt*)0);
9016 
9017     // Convert to an expression-statement, and clean up any produced
9018     // temporaries.
9019     return S.ActOnExprStmt(Call);
9020   }
9021 
9022   //     - if the subobject is of scalar type, the built-in assignment
9023   //       operator is used.
9024   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
9025   if (!ArrayTy) {
9026     ExprResult Assignment = S.CreateBuiltinBinOp(
9027         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
9028     if (Assignment.isInvalid())
9029       return StmtError();
9030     return S.ActOnExprStmt(Assignment);
9031   }
9032 
9033   //     - if the subobject is an array, each element is assigned, in the
9034   //       manner appropriate to the element type;
9035 
9036   // Construct a loop over the array bounds, e.g.,
9037   //
9038   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9039   //
9040   // that will copy each of the array elements.
9041   QualType SizeType = S.Context.getSizeType();
9042 
9043   // Create the iteration variable.
9044   IdentifierInfo *IterationVarName = 0;
9045   {
9046     SmallString<8> Str;
9047     llvm::raw_svector_ostream OS(Str);
9048     OS << "__i" << Depth;
9049     IterationVarName = &S.Context.Idents.get(OS.str());
9050   }
9051   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
9052                                           IterationVarName, SizeType,
9053                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
9054                                           SC_None);
9055 
9056   // Initialize the iteration variable to zero.
9057   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
9058   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
9059 
9060   // Creates a reference to the iteration variable.
9061   RefBuilder IterationVarRef(IterationVar, SizeType);
9062   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
9063 
9064   // Create the DeclStmt that holds the iteration variable.
9065   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
9066 
9067   // Subscript the "from" and "to" expressions with the iteration variable.
9068   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9069   MoveCastBuilder FromIndexMove(FromIndexCopy);
9070   const ExprBuilder *FromIndex;
9071   if (Copying)
9072     FromIndex = &FromIndexCopy;
9073   else
9074     FromIndex = &FromIndexMove;
9075 
9076   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
9077 
9078   // Build the copy/move for an individual element of the array.
9079   StmtResult Copy =
9080     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
9081                                      ToIndex, *FromIndex, CopyingBaseSubobject,
9082                                      Copying, Depth + 1);
9083   // Bail out if copying fails or if we determined that we should use memcpy.
9084   if (Copy.isInvalid() || !Copy.get())
9085     return Copy;
9086 
9087   // Create the comparison against the array bound.
9088   llvm::APInt Upper
9089     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9090   Expr *Comparison
9091     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
9092                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9093                                      BO_NE, S.Context.BoolTy,
9094                                      VK_RValue, OK_Ordinary, Loc, false);
9095 
9096   // Create the pre-increment of the iteration variable.
9097   Expr *Increment
9098     = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9099                                     SizeType, VK_LValue, OK_Ordinary, Loc);
9100 
9101   // Construct the loop that copies all elements of this array.
9102   return S.ActOnForStmt(Loc, Loc, InitStmt,
9103                         S.MakeFullExpr(Comparison),
9104                         0, S.MakeFullDiscardedValueExpr(Increment),
9105                         Loc, Copy.take());
9106 }
9107 
9108 static StmtResult
9109 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
9110                       const ExprBuilder &To, const ExprBuilder &From,
9111                       bool CopyingBaseSubobject, bool Copying) {
9112   // Maybe we should use a memcpy?
9113   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9114       T.isTriviallyCopyableType(S.Context))
9115     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9116 
9117   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9118                                                      CopyingBaseSubobject,
9119                                                      Copying, 0));
9120 
9121   // If we ended up picking a trivial assignment operator for an array of a
9122   // non-trivially-copyable class type, just emit a memcpy.
9123   if (!Result.isInvalid() && !Result.get())
9124     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9125 
9126   return Result;
9127 }
9128 
9129 Sema::ImplicitExceptionSpecification
9130 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9131   CXXRecordDecl *ClassDecl = MD->getParent();
9132 
9133   ImplicitExceptionSpecification ExceptSpec(*this);
9134   if (ClassDecl->isInvalidDecl())
9135     return ExceptSpec;
9136 
9137   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9138   assert(T->getNumParams() == 1 && "not a copy assignment op");
9139   unsigned ArgQuals =
9140       T->getParamType(0).getNonReferenceType().getCVRQualifiers();
9141 
9142   // C++ [except.spec]p14:
9143   //   An implicitly declared special member function (Clause 12) shall have an
9144   //   exception-specification. [...]
9145 
9146   // It is unspecified whether or not an implicit copy assignment operator
9147   // attempts to deduplicate calls to assignment operators of virtual bases are
9148   // made. As such, this exception specification is effectively unspecified.
9149   // Based on a similar decision made for constness in C++0x, we're erring on
9150   // the side of assuming such calls to be made regardless of whether they
9151   // actually happen.
9152   for (const auto &Base : ClassDecl->bases()) {
9153     if (Base.isVirtual())
9154       continue;
9155 
9156     CXXRecordDecl *BaseClassDecl
9157       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9158     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9159                                                             ArgQuals, false, 0))
9160       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
9161   }
9162 
9163   for (const auto &Base : ClassDecl->vbases()) {
9164     CXXRecordDecl *BaseClassDecl
9165       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9166     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9167                                                             ArgQuals, false, 0))
9168       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
9169   }
9170 
9171   for (const auto *Field : ClassDecl->fields()) {
9172     QualType FieldType = Context.getBaseElementType(Field->getType());
9173     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9174       if (CXXMethodDecl *CopyAssign =
9175           LookupCopyingAssignment(FieldClassDecl,
9176                                   ArgQuals | FieldType.getCVRQualifiers(),
9177                                   false, 0))
9178         ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
9179     }
9180   }
9181 
9182   return ExceptSpec;
9183 }
9184 
9185 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9186   // Note: The following rules are largely analoguous to the copy
9187   // constructor rules. Note that virtual bases are not taken into account
9188   // for determining the argument type of the operator. Note also that
9189   // operators taking an object instead of a reference are allowed.
9190   assert(ClassDecl->needsImplicitCopyAssignment());
9191 
9192   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9193   if (DSM.isAlreadyBeingDeclared())
9194     return 0;
9195 
9196   QualType ArgType = Context.getTypeDeclType(ClassDecl);
9197   QualType RetType = Context.getLValueReferenceType(ArgType);
9198   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9199   if (Const)
9200     ArgType = ArgType.withConst();
9201   ArgType = Context.getLValueReferenceType(ArgType);
9202 
9203   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9204                                                      CXXCopyAssignment,
9205                                                      Const);
9206 
9207   //   An implicitly-declared copy assignment operator is an inline public
9208   //   member of its class.
9209   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9210   SourceLocation ClassLoc = ClassDecl->getLocation();
9211   DeclarationNameInfo NameInfo(Name, ClassLoc);
9212   CXXMethodDecl *CopyAssignment =
9213       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9214                             /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
9215                             /*isInline=*/ true, Constexpr, SourceLocation());
9216   CopyAssignment->setAccess(AS_public);
9217   CopyAssignment->setDefaulted();
9218   CopyAssignment->setImplicit();
9219 
9220   // Build an exception specification pointing back at this member.
9221   FunctionProtoType::ExtProtoInfo EPI =
9222       getImplicitMethodEPI(*this, CopyAssignment);
9223   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
9224 
9225   // Add the parameter to the operator.
9226   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
9227                                                ClassLoc, ClassLoc, /*Id=*/0,
9228                                                ArgType, /*TInfo=*/0,
9229                                                SC_None, 0);
9230   CopyAssignment->setParams(FromParam);
9231 
9232   AddOverriddenMethods(ClassDecl, CopyAssignment);
9233 
9234   CopyAssignment->setTrivial(
9235     ClassDecl->needsOverloadResolutionForCopyAssignment()
9236       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9237       : ClassDecl->hasTrivialCopyAssignment());
9238 
9239   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
9240     SetDeclDeleted(CopyAssignment, ClassLoc);
9241 
9242   // Note that we have added this copy-assignment operator.
9243   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9244 
9245   if (Scope *S = getScopeForContext(ClassDecl))
9246     PushOnScopeChains(CopyAssignment, S, false);
9247   ClassDecl->addDecl(CopyAssignment);
9248 
9249   return CopyAssignment;
9250 }
9251 
9252 /// Diagnose an implicit copy operation for a class which is odr-used, but
9253 /// which is deprecated because the class has a user-declared copy constructor,
9254 /// copy assignment operator, or destructor.
9255 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9256                                             SourceLocation UseLoc) {
9257   assert(CopyOp->isImplicit());
9258 
9259   CXXRecordDecl *RD = CopyOp->getParent();
9260   CXXMethodDecl *UserDeclaredOperation = 0;
9261 
9262   // In Microsoft mode, assignment operations don't affect constructors and
9263   // vice versa.
9264   if (RD->hasUserDeclaredDestructor()) {
9265     UserDeclaredOperation = RD->getDestructor();
9266   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9267              RD->hasUserDeclaredCopyConstructor() &&
9268              !S.getLangOpts().MSVCCompat) {
9269     // Find any user-declared copy constructor.
9270     for (auto *I : RD->ctors()) {
9271       if (I->isCopyConstructor()) {
9272         UserDeclaredOperation = I;
9273         break;
9274       }
9275     }
9276     assert(UserDeclaredOperation);
9277   } else if (isa<CXXConstructorDecl>(CopyOp) &&
9278              RD->hasUserDeclaredCopyAssignment() &&
9279              !S.getLangOpts().MSVCCompat) {
9280     // Find any user-declared move assignment operator.
9281     for (auto *I : RD->methods()) {
9282       if (I->isCopyAssignmentOperator()) {
9283         UserDeclaredOperation = I;
9284         break;
9285       }
9286     }
9287     assert(UserDeclaredOperation);
9288   }
9289 
9290   if (UserDeclaredOperation) {
9291     S.Diag(UserDeclaredOperation->getLocation(),
9292          diag::warn_deprecated_copy_operation)
9293       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9294       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9295     S.Diag(UseLoc, diag::note_member_synthesized_at)
9296       << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9297                                           : Sema::CXXCopyAssignment)
9298       << RD;
9299   }
9300 }
9301 
9302 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9303                                         CXXMethodDecl *CopyAssignOperator) {
9304   assert((CopyAssignOperator->isDefaulted() &&
9305           CopyAssignOperator->isOverloadedOperator() &&
9306           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
9307           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9308           !CopyAssignOperator->isDeleted()) &&
9309          "DefineImplicitCopyAssignment called for wrong function");
9310 
9311   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9312 
9313   if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9314     CopyAssignOperator->setInvalidDecl();
9315     return;
9316   }
9317 
9318   // C++11 [class.copy]p18:
9319   //   The [definition of an implicitly declared copy assignment operator] is
9320   //   deprecated if the class has a user-declared copy constructor or a
9321   //   user-declared destructor.
9322   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9323     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9324 
9325   CopyAssignOperator->markUsed(Context);
9326 
9327   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
9328   DiagnosticErrorTrap Trap(Diags);
9329 
9330   // C++0x [class.copy]p30:
9331   //   The implicitly-defined or explicitly-defaulted copy assignment operator
9332   //   for a non-union class X performs memberwise copy assignment of its
9333   //   subobjects. The direct base classes of X are assigned first, in the
9334   //   order of their declaration in the base-specifier-list, and then the
9335   //   immediate non-static data members of X are assigned, in the order in
9336   //   which they were declared in the class definition.
9337 
9338   // The statements that form the synthesized function body.
9339   SmallVector<Stmt*, 8> Statements;
9340 
9341   // The parameter for the "other" object, which we are copying from.
9342   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9343   Qualifiers OtherQuals = Other->getType().getQualifiers();
9344   QualType OtherRefType = Other->getType();
9345   if (const LValueReferenceType *OtherRef
9346                                 = OtherRefType->getAs<LValueReferenceType>()) {
9347     OtherRefType = OtherRef->getPointeeType();
9348     OtherQuals = OtherRefType.getQualifiers();
9349   }
9350 
9351   // Our location for everything implicitly-generated.
9352   SourceLocation Loc = CopyAssignOperator->getLocation();
9353 
9354   // Builds a DeclRefExpr for the "other" object.
9355   RefBuilder OtherRef(Other, OtherRefType);
9356 
9357   // Builds the "this" pointer.
9358   ThisBuilder This;
9359 
9360   // Assign base classes.
9361   bool Invalid = false;
9362   for (auto &Base : ClassDecl->bases()) {
9363     // Form the assignment:
9364     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
9365     QualType BaseType = Base.getType().getUnqualifiedType();
9366     if (!BaseType->isRecordType()) {
9367       Invalid = true;
9368       continue;
9369     }
9370 
9371     CXXCastPath BasePath;
9372     BasePath.push_back(&Base);
9373 
9374     // Construct the "from" expression, which is an implicit cast to the
9375     // appropriately-qualified base type.
9376     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9377                      VK_LValue, BasePath);
9378 
9379     // Dereference "this".
9380     DerefBuilder DerefThis(This);
9381     CastBuilder To(DerefThis,
9382                    Context.getCVRQualifiedType(
9383                        BaseType, CopyAssignOperator->getTypeQualifiers()),
9384                    VK_LValue, BasePath);
9385 
9386     // Build the copy.
9387     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
9388                                             To, From,
9389                                             /*CopyingBaseSubobject=*/true,
9390                                             /*Copying=*/true);
9391     if (Copy.isInvalid()) {
9392       Diag(CurrentLocation, diag::note_member_synthesized_at)
9393         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9394       CopyAssignOperator->setInvalidDecl();
9395       return;
9396     }
9397 
9398     // Success! Record the copy.
9399     Statements.push_back(Copy.takeAs<Expr>());
9400   }
9401 
9402   // Assign non-static members.
9403   for (auto *Field : ClassDecl->fields()) {
9404     if (Field->isUnnamedBitfield())
9405       continue;
9406 
9407     if (Field->isInvalidDecl()) {
9408       Invalid = true;
9409       continue;
9410     }
9411 
9412     // Check for members of reference type; we can't copy those.
9413     if (Field->getType()->isReferenceType()) {
9414       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9415         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9416       Diag(Field->getLocation(), diag::note_declared_at);
9417       Diag(CurrentLocation, diag::note_member_synthesized_at)
9418         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9419       Invalid = true;
9420       continue;
9421     }
9422 
9423     // Check for members of const-qualified, non-class type.
9424     QualType BaseType = Context.getBaseElementType(Field->getType());
9425     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9426       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9427         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9428       Diag(Field->getLocation(), diag::note_declared_at);
9429       Diag(CurrentLocation, diag::note_member_synthesized_at)
9430         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9431       Invalid = true;
9432       continue;
9433     }
9434 
9435     // Suppress assigning zero-width bitfields.
9436     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9437       continue;
9438 
9439     QualType FieldType = Field->getType().getNonReferenceType();
9440     if (FieldType->isIncompleteArrayType()) {
9441       assert(ClassDecl->hasFlexibleArrayMember() &&
9442              "Incomplete array type is not valid");
9443       continue;
9444     }
9445 
9446     // Build references to the field in the object we're copying from and to.
9447     CXXScopeSpec SS; // Intentionally empty
9448     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9449                               LookupMemberName);
9450     MemberLookup.addDecl(Field);
9451     MemberLookup.resolveKind();
9452 
9453     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9454 
9455     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
9456 
9457     // Build the copy of this field.
9458     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
9459                                             To, From,
9460                                             /*CopyingBaseSubobject=*/false,
9461                                             /*Copying=*/true);
9462     if (Copy.isInvalid()) {
9463       Diag(CurrentLocation, diag::note_member_synthesized_at)
9464         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9465       CopyAssignOperator->setInvalidDecl();
9466       return;
9467     }
9468 
9469     // Success! Record the copy.
9470     Statements.push_back(Copy.takeAs<Stmt>());
9471   }
9472 
9473   if (!Invalid) {
9474     // Add a "return *this;"
9475     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
9476 
9477     StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9478     if (Return.isInvalid())
9479       Invalid = true;
9480     else {
9481       Statements.push_back(Return.takeAs<Stmt>());
9482 
9483       if (Trap.hasErrorOccurred()) {
9484         Diag(CurrentLocation, diag::note_member_synthesized_at)
9485           << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9486         Invalid = true;
9487       }
9488     }
9489   }
9490 
9491   if (Invalid) {
9492     CopyAssignOperator->setInvalidDecl();
9493     return;
9494   }
9495 
9496   StmtResult Body;
9497   {
9498     CompoundScopeRAII CompoundScope(*this);
9499     Body = ActOnCompoundStmt(Loc, Loc, Statements,
9500                              /*isStmtExpr=*/false);
9501     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9502   }
9503   CopyAssignOperator->setBody(Body.takeAs<Stmt>());
9504 
9505   if (ASTMutationListener *L = getASTMutationListener()) {
9506     L->CompletedImplicitDefinition(CopyAssignOperator);
9507   }
9508 }
9509 
9510 Sema::ImplicitExceptionSpecification
9511 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9512   CXXRecordDecl *ClassDecl = MD->getParent();
9513 
9514   ImplicitExceptionSpecification ExceptSpec(*this);
9515   if (ClassDecl->isInvalidDecl())
9516     return ExceptSpec;
9517 
9518   // C++0x [except.spec]p14:
9519   //   An implicitly declared special member function (Clause 12) shall have an
9520   //   exception-specification. [...]
9521 
9522   // It is unspecified whether or not an implicit move assignment operator
9523   // attempts to deduplicate calls to assignment operators of virtual bases are
9524   // made. As such, this exception specification is effectively unspecified.
9525   // Based on a similar decision made for constness in C++0x, we're erring on
9526   // the side of assuming such calls to be made regardless of whether they
9527   // actually happen.
9528   // Note that a move constructor is not implicitly declared when there are
9529   // virtual bases, but it can still be user-declared and explicitly defaulted.
9530   for (const auto &Base : ClassDecl->bases()) {
9531     if (Base.isVirtual())
9532       continue;
9533 
9534     CXXRecordDecl *BaseClassDecl
9535       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9536     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
9537                                                            0, false, 0))
9538       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
9539   }
9540 
9541   for (const auto &Base : ClassDecl->vbases()) {
9542     CXXRecordDecl *BaseClassDecl
9543       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9544     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
9545                                                            0, false, 0))
9546       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
9547   }
9548 
9549   for (const auto *Field : ClassDecl->fields()) {
9550     QualType FieldType = Context.getBaseElementType(Field->getType());
9551     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9552       if (CXXMethodDecl *MoveAssign =
9553               LookupMovingAssignment(FieldClassDecl,
9554                                      FieldType.getCVRQualifiers(),
9555                                      false, 0))
9556         ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
9557     }
9558   }
9559 
9560   return ExceptSpec;
9561 }
9562 
9563 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
9564   assert(ClassDecl->needsImplicitMoveAssignment());
9565 
9566   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9567   if (DSM.isAlreadyBeingDeclared())
9568     return 0;
9569 
9570   // Note: The following rules are largely analoguous to the move
9571   // constructor rules.
9572 
9573   QualType ArgType = Context.getTypeDeclType(ClassDecl);
9574   QualType RetType = Context.getLValueReferenceType(ArgType);
9575   ArgType = Context.getRValueReferenceType(ArgType);
9576 
9577   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9578                                                      CXXMoveAssignment,
9579                                                      false);
9580 
9581   //   An implicitly-declared move assignment operator is an inline public
9582   //   member of its class.
9583   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9584   SourceLocation ClassLoc = ClassDecl->getLocation();
9585   DeclarationNameInfo NameInfo(Name, ClassLoc);
9586   CXXMethodDecl *MoveAssignment =
9587       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9588                             /*TInfo=*/0, /*StorageClass=*/SC_None,
9589                             /*isInline=*/true, Constexpr, SourceLocation());
9590   MoveAssignment->setAccess(AS_public);
9591   MoveAssignment->setDefaulted();
9592   MoveAssignment->setImplicit();
9593 
9594   // Build an exception specification pointing back at this member.
9595   FunctionProtoType::ExtProtoInfo EPI =
9596       getImplicitMethodEPI(*this, MoveAssignment);
9597   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
9598 
9599   // Add the parameter to the operator.
9600   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9601                                                ClassLoc, ClassLoc, /*Id=*/0,
9602                                                ArgType, /*TInfo=*/0,
9603                                                SC_None, 0);
9604   MoveAssignment->setParams(FromParam);
9605 
9606   AddOverriddenMethods(ClassDecl, MoveAssignment);
9607 
9608   MoveAssignment->setTrivial(
9609     ClassDecl->needsOverloadResolutionForMoveAssignment()
9610       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9611       : ClassDecl->hasTrivialMoveAssignment());
9612 
9613   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
9614     ClassDecl->setImplicitMoveAssignmentIsDeleted();
9615     SetDeclDeleted(MoveAssignment, ClassLoc);
9616   }
9617 
9618   // Note that we have added this copy-assignment operator.
9619   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9620 
9621   if (Scope *S = getScopeForContext(ClassDecl))
9622     PushOnScopeChains(MoveAssignment, S, false);
9623   ClassDecl->addDecl(MoveAssignment);
9624 
9625   return MoveAssignment;
9626 }
9627 
9628 /// Check if we're implicitly defining a move assignment operator for a class
9629 /// with virtual bases. Such a move assignment might move-assign the virtual
9630 /// base multiple times.
9631 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
9632                                                SourceLocation CurrentLocation) {
9633   assert(!Class->isDependentContext() && "should not define dependent move");
9634 
9635   // Only a virtual base could get implicitly move-assigned multiple times.
9636   // Only a non-trivial move assignment can observe this. We only want to
9637   // diagnose if we implicitly define an assignment operator that assigns
9638   // two base classes, both of which move-assign the same virtual base.
9639   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
9640       Class->getNumBases() < 2)
9641     return;
9642 
9643   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
9644   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
9645   VBaseMap VBases;
9646 
9647   for (auto &BI : Class->bases()) {
9648     Worklist.push_back(&BI);
9649     while (!Worklist.empty()) {
9650       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
9651       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
9652 
9653       // If the base has no non-trivial move assignment operators,
9654       // we don't care about moves from it.
9655       if (!Base->hasNonTrivialMoveAssignment())
9656         continue;
9657 
9658       // If there's nothing virtual here, skip it.
9659       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
9660         continue;
9661 
9662       // If we're not actually going to call a move assignment for this base,
9663       // or the selected move assignment is trivial, skip it.
9664       Sema::SpecialMemberOverloadResult *SMOR =
9665         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
9666                               /*ConstArg*/false, /*VolatileArg*/false,
9667                               /*RValueThis*/true, /*ConstThis*/false,
9668                               /*VolatileThis*/false);
9669       if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
9670           !SMOR->getMethod()->isMoveAssignmentOperator())
9671         continue;
9672 
9673       if (BaseSpec->isVirtual()) {
9674         // We're going to move-assign this virtual base, and its move
9675         // assignment operator is not trivial. If this can happen for
9676         // multiple distinct direct bases of Class, diagnose it. (If it
9677         // only happens in one base, we'll diagnose it when synthesizing
9678         // that base class's move assignment operator.)
9679         CXXBaseSpecifier *&Existing =
9680             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
9681                 .first->second;
9682         if (Existing && Existing != &BI) {
9683           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
9684             << Class << Base;
9685           S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
9686             << (Base->getCanonicalDecl() ==
9687                 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9688             << Base << Existing->getType() << Existing->getSourceRange();
9689           S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
9690             << (Base->getCanonicalDecl() ==
9691                 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9692             << Base << BI.getType() << BaseSpec->getSourceRange();
9693 
9694           // Only diagnose each vbase once.
9695           Existing = 0;
9696         }
9697       } else {
9698         // Only walk over bases that have defaulted move assignment operators.
9699         // We assume that any user-provided move assignment operator handles
9700         // the multiple-moves-of-vbase case itself somehow.
9701         if (!SMOR->getMethod()->isDefaulted())
9702           continue;
9703 
9704         // We're going to move the base classes of Base. Add them to the list.
9705         for (auto &BI : Base->bases())
9706           Worklist.push_back(&BI);
9707       }
9708     }
9709   }
9710 }
9711 
9712 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9713                                         CXXMethodDecl *MoveAssignOperator) {
9714   assert((MoveAssignOperator->isDefaulted() &&
9715           MoveAssignOperator->isOverloadedOperator() &&
9716           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
9717           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9718           !MoveAssignOperator->isDeleted()) &&
9719          "DefineImplicitMoveAssignment called for wrong function");
9720 
9721   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9722 
9723   if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9724     MoveAssignOperator->setInvalidDecl();
9725     return;
9726   }
9727 
9728   MoveAssignOperator->markUsed(Context);
9729 
9730   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
9731   DiagnosticErrorTrap Trap(Diags);
9732 
9733   // C++0x [class.copy]p28:
9734   //   The implicitly-defined or move assignment operator for a non-union class
9735   //   X performs memberwise move assignment of its subobjects. The direct base
9736   //   classes of X are assigned first, in the order of their declaration in the
9737   //   base-specifier-list, and then the immediate non-static data members of X
9738   //   are assigned, in the order in which they were declared in the class
9739   //   definition.
9740 
9741   // Issue a warning if our implicit move assignment operator will move
9742   // from a virtual base more than once.
9743   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
9744 
9745   // The statements that form the synthesized function body.
9746   SmallVector<Stmt*, 8> Statements;
9747 
9748   // The parameter for the "other" object, which we are move from.
9749   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9750   QualType OtherRefType = Other->getType()->
9751       getAs<RValueReferenceType>()->getPointeeType();
9752   assert(!OtherRefType.getQualifiers() &&
9753          "Bad argument type of defaulted move assignment");
9754 
9755   // Our location for everything implicitly-generated.
9756   SourceLocation Loc = MoveAssignOperator->getLocation();
9757 
9758   // Builds a reference to the "other" object.
9759   RefBuilder OtherRef(Other, OtherRefType);
9760   // Cast to rvalue.
9761   MoveCastBuilder MoveOther(OtherRef);
9762 
9763   // Builds the "this" pointer.
9764   ThisBuilder This;
9765 
9766   // Assign base classes.
9767   bool Invalid = false;
9768   for (auto &Base : ClassDecl->bases()) {
9769     // C++11 [class.copy]p28:
9770     //   It is unspecified whether subobjects representing virtual base classes
9771     //   are assigned more than once by the implicitly-defined copy assignment
9772     //   operator.
9773     // FIXME: Do not assign to a vbase that will be assigned by some other base
9774     // class. For a move-assignment, this can result in the vbase being moved
9775     // multiple times.
9776 
9777     // Form the assignment:
9778     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9779     QualType BaseType = Base.getType().getUnqualifiedType();
9780     if (!BaseType->isRecordType()) {
9781       Invalid = true;
9782       continue;
9783     }
9784 
9785     CXXCastPath BasePath;
9786     BasePath.push_back(&Base);
9787 
9788     // Construct the "from" expression, which is an implicit cast to the
9789     // appropriately-qualified base type.
9790     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
9791 
9792     // Dereference "this".
9793     DerefBuilder DerefThis(This);
9794 
9795     // Implicitly cast "this" to the appropriately-qualified base type.
9796     CastBuilder To(DerefThis,
9797                    Context.getCVRQualifiedType(
9798                        BaseType, MoveAssignOperator->getTypeQualifiers()),
9799                    VK_LValue, BasePath);
9800 
9801     // Build the move.
9802     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
9803                                             To, From,
9804                                             /*CopyingBaseSubobject=*/true,
9805                                             /*Copying=*/false);
9806     if (Move.isInvalid()) {
9807       Diag(CurrentLocation, diag::note_member_synthesized_at)
9808         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9809       MoveAssignOperator->setInvalidDecl();
9810       return;
9811     }
9812 
9813     // Success! Record the move.
9814     Statements.push_back(Move.takeAs<Expr>());
9815   }
9816 
9817   // Assign non-static members.
9818   for (auto *Field : ClassDecl->fields()) {
9819     if (Field->isUnnamedBitfield())
9820       continue;
9821 
9822     if (Field->isInvalidDecl()) {
9823       Invalid = true;
9824       continue;
9825     }
9826 
9827     // Check for members of reference type; we can't move those.
9828     if (Field->getType()->isReferenceType()) {
9829       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9830         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9831       Diag(Field->getLocation(), diag::note_declared_at);
9832       Diag(CurrentLocation, diag::note_member_synthesized_at)
9833         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9834       Invalid = true;
9835       continue;
9836     }
9837 
9838     // Check for members of const-qualified, non-class type.
9839     QualType BaseType = Context.getBaseElementType(Field->getType());
9840     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9841       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9842         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9843       Diag(Field->getLocation(), diag::note_declared_at);
9844       Diag(CurrentLocation, diag::note_member_synthesized_at)
9845         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9846       Invalid = true;
9847       continue;
9848     }
9849 
9850     // Suppress assigning zero-width bitfields.
9851     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9852       continue;
9853 
9854     QualType FieldType = Field->getType().getNonReferenceType();
9855     if (FieldType->isIncompleteArrayType()) {
9856       assert(ClassDecl->hasFlexibleArrayMember() &&
9857              "Incomplete array type is not valid");
9858       continue;
9859     }
9860 
9861     // Build references to the field in the object we're copying from and to.
9862     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9863                               LookupMemberName);
9864     MemberLookup.addDecl(Field);
9865     MemberLookup.resolveKind();
9866     MemberBuilder From(MoveOther, OtherRefType,
9867                        /*IsArrow=*/false, MemberLookup);
9868     MemberBuilder To(This, getCurrentThisType(),
9869                      /*IsArrow=*/true, MemberLookup);
9870 
9871     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
9872         "Member reference with rvalue base must be rvalue except for reference "
9873         "members, which aren't allowed for move assignment.");
9874 
9875     // Build the move of this field.
9876     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
9877                                             To, From,
9878                                             /*CopyingBaseSubobject=*/false,
9879                                             /*Copying=*/false);
9880     if (Move.isInvalid()) {
9881       Diag(CurrentLocation, diag::note_member_synthesized_at)
9882         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9883       MoveAssignOperator->setInvalidDecl();
9884       return;
9885     }
9886 
9887     // Success! Record the copy.
9888     Statements.push_back(Move.takeAs<Stmt>());
9889   }
9890 
9891   if (!Invalid) {
9892     // Add a "return *this;"
9893     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
9894 
9895     StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9896     if (Return.isInvalid())
9897       Invalid = true;
9898     else {
9899       Statements.push_back(Return.takeAs<Stmt>());
9900 
9901       if (Trap.hasErrorOccurred()) {
9902         Diag(CurrentLocation, diag::note_member_synthesized_at)
9903           << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9904         Invalid = true;
9905       }
9906     }
9907   }
9908 
9909   if (Invalid) {
9910     MoveAssignOperator->setInvalidDecl();
9911     return;
9912   }
9913 
9914   StmtResult Body;
9915   {
9916     CompoundScopeRAII CompoundScope(*this);
9917     Body = ActOnCompoundStmt(Loc, Loc, Statements,
9918                              /*isStmtExpr=*/false);
9919     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9920   }
9921   MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9922 
9923   if (ASTMutationListener *L = getASTMutationListener()) {
9924     L->CompletedImplicitDefinition(MoveAssignOperator);
9925   }
9926 }
9927 
9928 Sema::ImplicitExceptionSpecification
9929 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9930   CXXRecordDecl *ClassDecl = MD->getParent();
9931 
9932   ImplicitExceptionSpecification ExceptSpec(*this);
9933   if (ClassDecl->isInvalidDecl())
9934     return ExceptSpec;
9935 
9936   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9937   assert(T->getNumParams() >= 1 && "not a copy ctor");
9938   unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
9939 
9940   // C++ [except.spec]p14:
9941   //   An implicitly declared special member function (Clause 12) shall have an
9942   //   exception-specification. [...]
9943   for (const auto &Base : ClassDecl->bases()) {
9944     // Virtual bases are handled below.
9945     if (Base.isVirtual())
9946       continue;
9947 
9948     CXXRecordDecl *BaseClassDecl
9949       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9950     if (CXXConstructorDecl *CopyConstructor =
9951           LookupCopyingConstructor(BaseClassDecl, Quals))
9952       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
9953   }
9954   for (const auto &Base : ClassDecl->vbases()) {
9955     CXXRecordDecl *BaseClassDecl
9956       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9957     if (CXXConstructorDecl *CopyConstructor =
9958           LookupCopyingConstructor(BaseClassDecl, Quals))
9959       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
9960   }
9961   for (const auto *Field : ClassDecl->fields()) {
9962     QualType FieldType = Context.getBaseElementType(Field->getType());
9963     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9964       if (CXXConstructorDecl *CopyConstructor =
9965               LookupCopyingConstructor(FieldClassDecl,
9966                                        Quals | FieldType.getCVRQualifiers()))
9967       ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
9968     }
9969   }
9970 
9971   return ExceptSpec;
9972 }
9973 
9974 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9975                                                     CXXRecordDecl *ClassDecl) {
9976   // C++ [class.copy]p4:
9977   //   If the class definition does not explicitly declare a copy
9978   //   constructor, one is declared implicitly.
9979   assert(ClassDecl->needsImplicitCopyConstructor());
9980 
9981   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9982   if (DSM.isAlreadyBeingDeclared())
9983     return 0;
9984 
9985   QualType ClassType = Context.getTypeDeclType(ClassDecl);
9986   QualType ArgType = ClassType;
9987   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
9988   if (Const)
9989     ArgType = ArgType.withConst();
9990   ArgType = Context.getLValueReferenceType(ArgType);
9991 
9992   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9993                                                      CXXCopyConstructor,
9994                                                      Const);
9995 
9996   DeclarationName Name
9997     = Context.DeclarationNames.getCXXConstructorName(
9998                                            Context.getCanonicalType(ClassType));
9999   SourceLocation ClassLoc = ClassDecl->getLocation();
10000   DeclarationNameInfo NameInfo(Name, ClassLoc);
10001 
10002   //   An implicitly-declared copy constructor is an inline public
10003   //   member of its class.
10004   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
10005       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
10006       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10007       Constexpr);
10008   CopyConstructor->setAccess(AS_public);
10009   CopyConstructor->setDefaulted();
10010 
10011   // Build an exception specification pointing back at this member.
10012   FunctionProtoType::ExtProtoInfo EPI =
10013       getImplicitMethodEPI(*this, CopyConstructor);
10014   CopyConstructor->setType(
10015       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10016 
10017   // Add the parameter to the constructor.
10018   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
10019                                                ClassLoc, ClassLoc,
10020                                                /*IdentifierInfo=*/0,
10021                                                ArgType, /*TInfo=*/0,
10022                                                SC_None, 0);
10023   CopyConstructor->setParams(FromParam);
10024 
10025   CopyConstructor->setTrivial(
10026     ClassDecl->needsOverloadResolutionForCopyConstructor()
10027       ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10028       : ClassDecl->hasTrivialCopyConstructor());
10029 
10030   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
10031     SetDeclDeleted(CopyConstructor, ClassLoc);
10032 
10033   // Note that we have declared this constructor.
10034   ++ASTContext::NumImplicitCopyConstructorsDeclared;
10035 
10036   if (Scope *S = getScopeForContext(ClassDecl))
10037     PushOnScopeChains(CopyConstructor, S, false);
10038   ClassDecl->addDecl(CopyConstructor);
10039 
10040   return CopyConstructor;
10041 }
10042 
10043 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
10044                                    CXXConstructorDecl *CopyConstructor) {
10045   assert((CopyConstructor->isDefaulted() &&
10046           CopyConstructor->isCopyConstructor() &&
10047           !CopyConstructor->doesThisDeclarationHaveABody() &&
10048           !CopyConstructor->isDeleted()) &&
10049          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
10050 
10051   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
10052   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
10053 
10054   // C++11 [class.copy]p7:
10055   //   The [definition of an implicitly declared copy constructor] is
10056   //   deprecated if the class has a user-declared copy assignment operator
10057   //   or a user-declared destructor.
10058   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10059     diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10060 
10061   SynthesizedFunctionScope Scope(*this, CopyConstructor);
10062   DiagnosticErrorTrap Trap(Diags);
10063 
10064   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
10065       Trap.hasErrorOccurred()) {
10066     Diag(CurrentLocation, diag::note_member_synthesized_at)
10067       << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
10068     CopyConstructor->setInvalidDecl();
10069   }  else {
10070     Sema::CompoundScopeRAII CompoundScope(*this);
10071     CopyConstructor->setBody(ActOnCompoundStmt(
10072         CopyConstructor->getLocation(), CopyConstructor->getLocation(), None,
10073         /*isStmtExpr=*/ false).takeAs<Stmt>());
10074   }
10075 
10076   CopyConstructor->markUsed(Context);
10077   if (ASTMutationListener *L = getASTMutationListener()) {
10078     L->CompletedImplicitDefinition(CopyConstructor);
10079   }
10080 }
10081 
10082 Sema::ImplicitExceptionSpecification
10083 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10084   CXXRecordDecl *ClassDecl = MD->getParent();
10085 
10086   // C++ [except.spec]p14:
10087   //   An implicitly declared special member function (Clause 12) shall have an
10088   //   exception-specification. [...]
10089   ImplicitExceptionSpecification ExceptSpec(*this);
10090   if (ClassDecl->isInvalidDecl())
10091     return ExceptSpec;
10092 
10093   // Direct base-class constructors.
10094   for (const auto &B : ClassDecl->bases()) {
10095     if (B.isVirtual()) // Handled below.
10096       continue;
10097 
10098     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
10099       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10100       CXXConstructorDecl *Constructor =
10101           LookupMovingConstructor(BaseClassDecl, 0);
10102       // If this is a deleted function, add it anyway. This might be conformant
10103       // with the standard. This might not. I'm not sure. It might not matter.
10104       if (Constructor)
10105         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
10106     }
10107   }
10108 
10109   // Virtual base-class constructors.
10110   for (const auto &B : ClassDecl->vbases()) {
10111     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
10112       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10113       CXXConstructorDecl *Constructor =
10114           LookupMovingConstructor(BaseClassDecl, 0);
10115       // If this is a deleted function, add it anyway. This might be conformant
10116       // with the standard. This might not. I'm not sure. It might not matter.
10117       if (Constructor)
10118         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
10119     }
10120   }
10121 
10122   // Field constructors.
10123   for (const auto *F : ClassDecl->fields()) {
10124     QualType FieldType = Context.getBaseElementType(F->getType());
10125     if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10126       CXXConstructorDecl *Constructor =
10127           LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
10128       // If this is a deleted function, add it anyway. This might be conformant
10129       // with the standard. This might not. I'm not sure. It might not matter.
10130       // In particular, the problem is that this function never gets called. It
10131       // might just be ill-formed because this function attempts to refer to
10132       // a deleted function here.
10133       if (Constructor)
10134         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
10135     }
10136   }
10137 
10138   return ExceptSpec;
10139 }
10140 
10141 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10142                                                     CXXRecordDecl *ClassDecl) {
10143   assert(ClassDecl->needsImplicitMoveConstructor());
10144 
10145   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10146   if (DSM.isAlreadyBeingDeclared())
10147     return 0;
10148 
10149   QualType ClassType = Context.getTypeDeclType(ClassDecl);
10150   QualType ArgType = Context.getRValueReferenceType(ClassType);
10151 
10152   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10153                                                      CXXMoveConstructor,
10154                                                      false);
10155 
10156   DeclarationName Name
10157     = Context.DeclarationNames.getCXXConstructorName(
10158                                            Context.getCanonicalType(ClassType));
10159   SourceLocation ClassLoc = ClassDecl->getLocation();
10160   DeclarationNameInfo NameInfo(Name, ClassLoc);
10161 
10162   // C++11 [class.copy]p11:
10163   //   An implicitly-declared copy/move constructor is an inline public
10164   //   member of its class.
10165   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
10166       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
10167       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10168       Constexpr);
10169   MoveConstructor->setAccess(AS_public);
10170   MoveConstructor->setDefaulted();
10171 
10172   // Build an exception specification pointing back at this member.
10173   FunctionProtoType::ExtProtoInfo EPI =
10174       getImplicitMethodEPI(*this, MoveConstructor);
10175   MoveConstructor->setType(
10176       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10177 
10178   // Add the parameter to the constructor.
10179   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10180                                                ClassLoc, ClassLoc,
10181                                                /*IdentifierInfo=*/0,
10182                                                ArgType, /*TInfo=*/0,
10183                                                SC_None, 0);
10184   MoveConstructor->setParams(FromParam);
10185 
10186   MoveConstructor->setTrivial(
10187     ClassDecl->needsOverloadResolutionForMoveConstructor()
10188       ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10189       : ClassDecl->hasTrivialMoveConstructor());
10190 
10191   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
10192     ClassDecl->setImplicitMoveConstructorIsDeleted();
10193     SetDeclDeleted(MoveConstructor, ClassLoc);
10194   }
10195 
10196   // Note that we have declared this constructor.
10197   ++ASTContext::NumImplicitMoveConstructorsDeclared;
10198 
10199   if (Scope *S = getScopeForContext(ClassDecl))
10200     PushOnScopeChains(MoveConstructor, S, false);
10201   ClassDecl->addDecl(MoveConstructor);
10202 
10203   return MoveConstructor;
10204 }
10205 
10206 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10207                                    CXXConstructorDecl *MoveConstructor) {
10208   assert((MoveConstructor->isDefaulted() &&
10209           MoveConstructor->isMoveConstructor() &&
10210           !MoveConstructor->doesThisDeclarationHaveABody() &&
10211           !MoveConstructor->isDeleted()) &&
10212          "DefineImplicitMoveConstructor - call it for implicit move ctor");
10213 
10214   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10215   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10216 
10217   SynthesizedFunctionScope Scope(*this, MoveConstructor);
10218   DiagnosticErrorTrap Trap(Diags);
10219 
10220   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
10221       Trap.hasErrorOccurred()) {
10222     Diag(CurrentLocation, diag::note_member_synthesized_at)
10223       << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10224     MoveConstructor->setInvalidDecl();
10225   }  else {
10226     Sema::CompoundScopeRAII CompoundScope(*this);
10227     MoveConstructor->setBody(ActOnCompoundStmt(
10228         MoveConstructor->getLocation(), MoveConstructor->getLocation(), None,
10229         /*isStmtExpr=*/ false).takeAs<Stmt>());
10230   }
10231 
10232   MoveConstructor->markUsed(Context);
10233 
10234   if (ASTMutationListener *L = getASTMutationListener()) {
10235     L->CompletedImplicitDefinition(MoveConstructor);
10236   }
10237 }
10238 
10239 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
10240   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
10241 }
10242 
10243 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
10244                             SourceLocation CurrentLocation,
10245                             CXXConversionDecl *Conv) {
10246   CXXRecordDecl *Lambda = Conv->getParent();
10247   CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10248   // If we are defining a specialization of a conversion to function-ptr
10249   // cache the deduced template arguments for this specialization
10250   // so that we can use them to retrieve the corresponding call-operator
10251   // and static-invoker.
10252   const TemplateArgumentList *DeducedTemplateArgs = 0;
10253 
10254 
10255   // Retrieve the corresponding call-operator specialization.
10256   if (Lambda->isGenericLambda()) {
10257     assert(Conv->isFunctionTemplateSpecialization());
10258     FunctionTemplateDecl *CallOpTemplate =
10259         CallOp->getDescribedFunctionTemplate();
10260     DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
10261     void *InsertPos = 0;
10262     FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
10263                                                 DeducedTemplateArgs->data(),
10264                                                 DeducedTemplateArgs->size(),
10265                                                 InsertPos);
10266     assert(CallOpSpec &&
10267           "Conversion operator must have a corresponding call operator");
10268     CallOp = cast<CXXMethodDecl>(CallOpSpec);
10269   }
10270   // Mark the call operator referenced (and add to pending instantiations
10271   // if necessary).
10272   // For both the conversion and static-invoker template specializations
10273   // we construct their body's in this function, so no need to add them
10274   // to the PendingInstantiations.
10275   MarkFunctionReferenced(CurrentLocation, CallOp);
10276 
10277   SynthesizedFunctionScope Scope(*this, Conv);
10278   DiagnosticErrorTrap Trap(Diags);
10279 
10280   // Retrieve the static invoker...
10281   CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10282   // ... and get the corresponding specialization for a generic lambda.
10283   if (Lambda->isGenericLambda()) {
10284     assert(DeducedTemplateArgs &&
10285       "Must have deduced template arguments from Conversion Operator");
10286     FunctionTemplateDecl *InvokeTemplate =
10287                           Invoker->getDescribedFunctionTemplate();
10288     void *InsertPos = 0;
10289     FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
10290                                                 DeducedTemplateArgs->data(),
10291                                                 DeducedTemplateArgs->size(),
10292                                                 InsertPos);
10293     assert(InvokeSpec &&
10294       "Must have a corresponding static invoker specialization");
10295     Invoker = cast<CXXMethodDecl>(InvokeSpec);
10296   }
10297   // Construct the body of the conversion function { return __invoke; }.
10298   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
10299                                         VK_LValue, Conv->getLocation()).take();
10300    assert(FunctionRef && "Can't refer to __invoke function?");
10301    Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
10302    Conv->setBody(new (Context) CompoundStmt(Context, Return,
10303                                             Conv->getLocation(),
10304                                             Conv->getLocation()));
10305 
10306   Conv->markUsed(Context);
10307   Conv->setReferenced();
10308 
10309   // Fill in the __invoke function with a dummy implementation. IR generation
10310   // will fill in the actual details.
10311   Invoker->markUsed(Context);
10312   Invoker->setReferenced();
10313   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10314 
10315   if (ASTMutationListener *L = getASTMutationListener()) {
10316     L->CompletedImplicitDefinition(Conv);
10317     L->CompletedImplicitDefinition(Invoker);
10318    }
10319 }
10320 
10321 
10322 
10323 void Sema::DefineImplicitLambdaToBlockPointerConversion(
10324        SourceLocation CurrentLocation,
10325        CXXConversionDecl *Conv)
10326 {
10327   assert(!Conv->getParent()->isGenericLambda());
10328 
10329   Conv->markUsed(Context);
10330 
10331   SynthesizedFunctionScope Scope(*this, Conv);
10332   DiagnosticErrorTrap Trap(Diags);
10333 
10334   // Copy-initialize the lambda object as needed to capture it.
10335   Expr *This = ActOnCXXThis(CurrentLocation).take();
10336   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
10337 
10338   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10339                                                         Conv->getLocation(),
10340                                                         Conv, DerefThis);
10341 
10342   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10343   // behavior.  Note that only the general conversion function does this
10344   // (since it's unusable otherwise); in the case where we inline the
10345   // block literal, it has block literal lifetime semantics.
10346   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
10347     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10348                                           CK_CopyAndAutoreleaseBlockObject,
10349                                           BuildBlock.get(), 0, VK_RValue);
10350 
10351   if (BuildBlock.isInvalid()) {
10352     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10353     Conv->setInvalidDecl();
10354     return;
10355   }
10356 
10357   // Create the return statement that returns the block from the conversion
10358   // function.
10359   StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
10360   if (Return.isInvalid()) {
10361     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10362     Conv->setInvalidDecl();
10363     return;
10364   }
10365 
10366   // Set the body of the conversion function.
10367   Stmt *ReturnS = Return.take();
10368   Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
10369                                            Conv->getLocation(),
10370                                            Conv->getLocation()));
10371 
10372   // We're done; notify the mutation listener, if any.
10373   if (ASTMutationListener *L = getASTMutationListener()) {
10374     L->CompletedImplicitDefinition(Conv);
10375   }
10376 }
10377 
10378 /// \brief Determine whether the given list arguments contains exactly one
10379 /// "real" (non-default) argument.
10380 static bool hasOneRealArgument(MultiExprArg Args) {
10381   switch (Args.size()) {
10382   case 0:
10383     return false;
10384 
10385   default:
10386     if (!Args[1]->isDefaultArgument())
10387       return false;
10388 
10389     // fall through
10390   case 1:
10391     return !Args[0]->isDefaultArgument();
10392   }
10393 
10394   return false;
10395 }
10396 
10397 ExprResult
10398 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10399                             CXXConstructorDecl *Constructor,
10400                             MultiExprArg ExprArgs,
10401                             bool HadMultipleCandidates,
10402                             bool IsListInitialization,
10403                             bool RequiresZeroInit,
10404                             unsigned ConstructKind,
10405                             SourceRange ParenRange) {
10406   bool Elidable = false;
10407 
10408   // C++0x [class.copy]p34:
10409   //   When certain criteria are met, an implementation is allowed to
10410   //   omit the copy/move construction of a class object, even if the
10411   //   copy/move constructor and/or destructor for the object have
10412   //   side effects. [...]
10413   //     - when a temporary class object that has not been bound to a
10414   //       reference (12.2) would be copied/moved to a class object
10415   //       with the same cv-unqualified type, the copy/move operation
10416   //       can be omitted by constructing the temporary object
10417   //       directly into the target of the omitted copy/move
10418   if (ConstructKind == CXXConstructExpr::CK_Complete &&
10419       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
10420     Expr *SubExpr = ExprArgs[0];
10421     Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
10422   }
10423 
10424   return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
10425                                Elidable, ExprArgs, HadMultipleCandidates,
10426                                IsListInitialization, RequiresZeroInit,
10427                                ConstructKind, ParenRange);
10428 }
10429 
10430 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
10431 /// including handling of its default argument expressions.
10432 ExprResult
10433 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10434                             CXXConstructorDecl *Constructor, bool Elidable,
10435                             MultiExprArg ExprArgs,
10436                             bool HadMultipleCandidates,
10437                             bool IsListInitialization,
10438                             bool RequiresZeroInit,
10439                             unsigned ConstructKind,
10440                             SourceRange ParenRange) {
10441   MarkFunctionReferenced(ConstructLoc, Constructor);
10442   return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
10443                                         Constructor, Elidable, ExprArgs,
10444                                         HadMultipleCandidates,
10445                                         IsListInitialization, RequiresZeroInit,
10446               static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10447                                         ParenRange));
10448 }
10449 
10450 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
10451   if (VD->isInvalidDecl()) return;
10452 
10453   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
10454   if (ClassDecl->isInvalidDecl()) return;
10455   if (ClassDecl->hasIrrelevantDestructor()) return;
10456   if (ClassDecl->isDependentContext()) return;
10457 
10458   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10459   MarkFunctionReferenced(VD->getLocation(), Destructor);
10460   CheckDestructorAccess(VD->getLocation(), Destructor,
10461                         PDiag(diag::err_access_dtor_var)
10462                         << VD->getDeclName()
10463                         << VD->getType());
10464   DiagnoseUseOfDecl(Destructor, VD->getLocation());
10465 
10466   if (Destructor->isTrivial()) return;
10467   if (!VD->hasGlobalStorage()) return;
10468 
10469   // Emit warning for non-trivial dtor in global scope (a real global,
10470   // class-static, function-static).
10471   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10472 
10473   // TODO: this should be re-enabled for static locals by !CXAAtExit
10474   if (!VD->isStaticLocal())
10475     Diag(VD->getLocation(), diag::warn_global_destructor);
10476 }
10477 
10478 /// \brief Given a constructor and the set of arguments provided for the
10479 /// constructor, convert the arguments and add any required default arguments
10480 /// to form a proper call to this constructor.
10481 ///
10482 /// \returns true if an error occurred, false otherwise.
10483 bool
10484 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10485                               MultiExprArg ArgsPtr,
10486                               SourceLocation Loc,
10487                               SmallVectorImpl<Expr*> &ConvertedArgs,
10488                               bool AllowExplicit,
10489                               bool IsListInitialization) {
10490   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10491   unsigned NumArgs = ArgsPtr.size();
10492   Expr **Args = ArgsPtr.data();
10493 
10494   const FunctionProtoType *Proto
10495     = Constructor->getType()->getAs<FunctionProtoType>();
10496   assert(Proto && "Constructor without a prototype?");
10497   unsigned NumParams = Proto->getNumParams();
10498 
10499   // If too few arguments are available, we'll fill in the rest with defaults.
10500   if (NumArgs < NumParams)
10501     ConvertedArgs.reserve(NumParams);
10502   else
10503     ConvertedArgs.reserve(NumArgs);
10504 
10505   VariadicCallType CallType =
10506     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
10507   SmallVector<Expr *, 8> AllArgs;
10508   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
10509                                         Proto, 0,
10510                                         llvm::makeArrayRef(Args, NumArgs),
10511                                         AllArgs,
10512                                         CallType, AllowExplicit,
10513                                         IsListInitialization);
10514   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
10515 
10516   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
10517 
10518   CheckConstructorCall(Constructor,
10519                        llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10520                                                         AllArgs.size()),
10521                        Proto, Loc);
10522 
10523   return Invalid;
10524 }
10525 
10526 static inline bool
10527 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10528                                        const FunctionDecl *FnDecl) {
10529   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
10530   if (isa<NamespaceDecl>(DC)) {
10531     return SemaRef.Diag(FnDecl->getLocation(),
10532                         diag::err_operator_new_delete_declared_in_namespace)
10533       << FnDecl->getDeclName();
10534   }
10535 
10536   if (isa<TranslationUnitDecl>(DC) &&
10537       FnDecl->getStorageClass() == SC_Static) {
10538     return SemaRef.Diag(FnDecl->getLocation(),
10539                         diag::err_operator_new_delete_declared_static)
10540       << FnDecl->getDeclName();
10541   }
10542 
10543   return false;
10544 }
10545 
10546 static inline bool
10547 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10548                             CanQualType ExpectedResultType,
10549                             CanQualType ExpectedFirstParamType,
10550                             unsigned DependentParamTypeDiag,
10551                             unsigned InvalidParamTypeDiag) {
10552   QualType ResultType =
10553       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
10554 
10555   // Check that the result type is not dependent.
10556   if (ResultType->isDependentType())
10557     return SemaRef.Diag(FnDecl->getLocation(),
10558                         diag::err_operator_new_delete_dependent_result_type)
10559     << FnDecl->getDeclName() << ExpectedResultType;
10560 
10561   // Check that the result type is what we expect.
10562   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10563     return SemaRef.Diag(FnDecl->getLocation(),
10564                         diag::err_operator_new_delete_invalid_result_type)
10565     << FnDecl->getDeclName() << ExpectedResultType;
10566 
10567   // A function template must have at least 2 parameters.
10568   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10569     return SemaRef.Diag(FnDecl->getLocation(),
10570                       diag::err_operator_new_delete_template_too_few_parameters)
10571         << FnDecl->getDeclName();
10572 
10573   // The function decl must have at least 1 parameter.
10574   if (FnDecl->getNumParams() == 0)
10575     return SemaRef.Diag(FnDecl->getLocation(),
10576                         diag::err_operator_new_delete_too_few_parameters)
10577       << FnDecl->getDeclName();
10578 
10579   // Check the first parameter type is not dependent.
10580   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10581   if (FirstParamType->isDependentType())
10582     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10583       << FnDecl->getDeclName() << ExpectedFirstParamType;
10584 
10585   // Check that the first parameter type is what we expect.
10586   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
10587       ExpectedFirstParamType)
10588     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10589     << FnDecl->getDeclName() << ExpectedFirstParamType;
10590 
10591   return false;
10592 }
10593 
10594 static bool
10595 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
10596   // C++ [basic.stc.dynamic.allocation]p1:
10597   //   A program is ill-formed if an allocation function is declared in a
10598   //   namespace scope other than global scope or declared static in global
10599   //   scope.
10600   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10601     return true;
10602 
10603   CanQualType SizeTy =
10604     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10605 
10606   // C++ [basic.stc.dynamic.allocation]p1:
10607   //  The return type shall be void*. The first parameter shall have type
10608   //  std::size_t.
10609   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10610                                   SizeTy,
10611                                   diag::err_operator_new_dependent_param_type,
10612                                   diag::err_operator_new_param_type))
10613     return true;
10614 
10615   // C++ [basic.stc.dynamic.allocation]p1:
10616   //  The first parameter shall not have an associated default argument.
10617   if (FnDecl->getParamDecl(0)->hasDefaultArg())
10618     return SemaRef.Diag(FnDecl->getLocation(),
10619                         diag::err_operator_new_default_arg)
10620       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10621 
10622   return false;
10623 }
10624 
10625 static bool
10626 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
10627   // C++ [basic.stc.dynamic.deallocation]p1:
10628   //   A program is ill-formed if deallocation functions are declared in a
10629   //   namespace scope other than global scope or declared static in global
10630   //   scope.
10631   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10632     return true;
10633 
10634   // C++ [basic.stc.dynamic.deallocation]p2:
10635   //   Each deallocation function shall return void and its first parameter
10636   //   shall be void*.
10637   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10638                                   SemaRef.Context.VoidPtrTy,
10639                                  diag::err_operator_delete_dependent_param_type,
10640                                  diag::err_operator_delete_param_type))
10641     return true;
10642 
10643   return false;
10644 }
10645 
10646 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
10647 /// of this overloaded operator is well-formed. If so, returns false;
10648 /// otherwise, emits appropriate diagnostics and returns true.
10649 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
10650   assert(FnDecl && FnDecl->isOverloadedOperator() &&
10651          "Expected an overloaded operator declaration");
10652 
10653   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10654 
10655   // C++ [over.oper]p5:
10656   //   The allocation and deallocation functions, operator new,
10657   //   operator new[], operator delete and operator delete[], are
10658   //   described completely in 3.7.3. The attributes and restrictions
10659   //   found in the rest of this subclause do not apply to them unless
10660   //   explicitly stated in 3.7.3.
10661   if (Op == OO_Delete || Op == OO_Array_Delete)
10662     return CheckOperatorDeleteDeclaration(*this, FnDecl);
10663 
10664   if (Op == OO_New || Op == OO_Array_New)
10665     return CheckOperatorNewDeclaration(*this, FnDecl);
10666 
10667   // C++ [over.oper]p6:
10668   //   An operator function shall either be a non-static member
10669   //   function or be a non-member function and have at least one
10670   //   parameter whose type is a class, a reference to a class, an
10671   //   enumeration, or a reference to an enumeration.
10672   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10673     if (MethodDecl->isStatic())
10674       return Diag(FnDecl->getLocation(),
10675                   diag::err_operator_overload_static) << FnDecl->getDeclName();
10676   } else {
10677     bool ClassOrEnumParam = false;
10678     for (auto Param : FnDecl->params()) {
10679       QualType ParamType = Param->getType().getNonReferenceType();
10680       if (ParamType->isDependentType() || ParamType->isRecordType() ||
10681           ParamType->isEnumeralType()) {
10682         ClassOrEnumParam = true;
10683         break;
10684       }
10685     }
10686 
10687     if (!ClassOrEnumParam)
10688       return Diag(FnDecl->getLocation(),
10689                   diag::err_operator_overload_needs_class_or_enum)
10690         << FnDecl->getDeclName();
10691   }
10692 
10693   // C++ [over.oper]p8:
10694   //   An operator function cannot have default arguments (8.3.6),
10695   //   except where explicitly stated below.
10696   //
10697   // Only the function-call operator allows default arguments
10698   // (C++ [over.call]p1).
10699   if (Op != OO_Call) {
10700     for (auto Param : FnDecl->params()) {
10701       if (Param->hasDefaultArg())
10702         return Diag(Param->getLocation(),
10703                     diag::err_operator_overload_default_arg)
10704           << FnDecl->getDeclName() << Param->getDefaultArgRange();
10705     }
10706   }
10707 
10708   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10709     { false, false, false }
10710 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10711     , { Unary, Binary, MemberOnly }
10712 #include "clang/Basic/OperatorKinds.def"
10713   };
10714 
10715   bool CanBeUnaryOperator = OperatorUses[Op][0];
10716   bool CanBeBinaryOperator = OperatorUses[Op][1];
10717   bool MustBeMemberOperator = OperatorUses[Op][2];
10718 
10719   // C++ [over.oper]p8:
10720   //   [...] Operator functions cannot have more or fewer parameters
10721   //   than the number required for the corresponding operator, as
10722   //   described in the rest of this subclause.
10723   unsigned NumParams = FnDecl->getNumParams()
10724                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
10725   if (Op != OO_Call &&
10726       ((NumParams == 1 && !CanBeUnaryOperator) ||
10727        (NumParams == 2 && !CanBeBinaryOperator) ||
10728        (NumParams < 1) || (NumParams > 2))) {
10729     // We have the wrong number of parameters.
10730     unsigned ErrorKind;
10731     if (CanBeUnaryOperator && CanBeBinaryOperator) {
10732       ErrorKind = 2;  // 2 -> unary or binary.
10733     } else if (CanBeUnaryOperator) {
10734       ErrorKind = 0;  // 0 -> unary
10735     } else {
10736       assert(CanBeBinaryOperator &&
10737              "All non-call overloaded operators are unary or binary!");
10738       ErrorKind = 1;  // 1 -> binary
10739     }
10740 
10741     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
10742       << FnDecl->getDeclName() << NumParams << ErrorKind;
10743   }
10744 
10745   // Overloaded operators other than operator() cannot be variadic.
10746   if (Op != OO_Call &&
10747       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
10748     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
10749       << FnDecl->getDeclName();
10750   }
10751 
10752   // Some operators must be non-static member functions.
10753   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10754     return Diag(FnDecl->getLocation(),
10755                 diag::err_operator_overload_must_be_member)
10756       << FnDecl->getDeclName();
10757   }
10758 
10759   // C++ [over.inc]p1:
10760   //   The user-defined function called operator++ implements the
10761   //   prefix and postfix ++ operator. If this function is a member
10762   //   function with no parameters, or a non-member function with one
10763   //   parameter of class or enumeration type, it defines the prefix
10764   //   increment operator ++ for objects of that type. If the function
10765   //   is a member function with one parameter (which shall be of type
10766   //   int) or a non-member function with two parameters (the second
10767   //   of which shall be of type int), it defines the postfix
10768   //   increment operator ++ for objects of that type.
10769   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10770     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10771     QualType ParamType = LastParam->getType();
10772 
10773     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
10774         !ParamType->isDependentType())
10775       return Diag(LastParam->getLocation(),
10776                   diag::err_operator_overload_post_incdec_must_be_int)
10777         << LastParam->getType() << (Op == OO_MinusMinus);
10778   }
10779 
10780   return false;
10781 }
10782 
10783 /// CheckLiteralOperatorDeclaration - Check whether the declaration
10784 /// of this literal operator function is well-formed. If so, returns
10785 /// false; otherwise, emits appropriate diagnostics and returns true.
10786 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
10787   if (isa<CXXMethodDecl>(FnDecl)) {
10788     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10789       << FnDecl->getDeclName();
10790     return true;
10791   }
10792 
10793   if (FnDecl->isExternC()) {
10794     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10795     return true;
10796   }
10797 
10798   bool Valid = false;
10799 
10800   // This might be the definition of a literal operator template.
10801   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10802   // This might be a specialization of a literal operator template.
10803   if (!TpDecl)
10804     TpDecl = FnDecl->getPrimaryTemplate();
10805 
10806   // template <char...> type operator "" name() and
10807   // template <class T, T...> type operator "" name() are the only valid
10808   // template signatures, and the only valid signatures with no parameters.
10809   if (TpDecl) {
10810     if (FnDecl->param_size() == 0) {
10811       // Must have one or two template parameters
10812       TemplateParameterList *Params = TpDecl->getTemplateParameters();
10813       if (Params->size() == 1) {
10814         NonTypeTemplateParmDecl *PmDecl =
10815           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
10816 
10817         // The template parameter must be a char parameter pack.
10818         if (PmDecl && PmDecl->isTemplateParameterPack() &&
10819             Context.hasSameType(PmDecl->getType(), Context.CharTy))
10820           Valid = true;
10821       } else if (Params->size() == 2) {
10822         TemplateTypeParmDecl *PmType =
10823           dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
10824         NonTypeTemplateParmDecl *PmArgs =
10825           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
10826 
10827         // The second template parameter must be a parameter pack with the
10828         // first template parameter as its type.
10829         if (PmType && PmArgs &&
10830             !PmType->isTemplateParameterPack() &&
10831             PmArgs->isTemplateParameterPack()) {
10832           const TemplateTypeParmType *TArgs =
10833             PmArgs->getType()->getAs<TemplateTypeParmType>();
10834           if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
10835               TArgs->getIndex() == PmType->getIndex()) {
10836             Valid = true;
10837             if (ActiveTemplateInstantiations.empty())
10838               Diag(FnDecl->getLocation(),
10839                    diag::ext_string_literal_operator_template);
10840           }
10841         }
10842       }
10843     }
10844   } else if (FnDecl->param_size()) {
10845     // Check the first parameter
10846     FunctionDecl::param_iterator Param = FnDecl->param_begin();
10847 
10848     QualType T = (*Param)->getType().getUnqualifiedType();
10849 
10850     // unsigned long long int, long double, and any character type are allowed
10851     // as the only parameters.
10852     if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10853         Context.hasSameType(T, Context.LongDoubleTy) ||
10854         Context.hasSameType(T, Context.CharTy) ||
10855         Context.hasSameType(T, Context.WideCharTy) ||
10856         Context.hasSameType(T, Context.Char16Ty) ||
10857         Context.hasSameType(T, Context.Char32Ty)) {
10858       if (++Param == FnDecl->param_end())
10859         Valid = true;
10860       goto FinishedParams;
10861     }
10862 
10863     // Otherwise it must be a pointer to const; let's strip those qualifiers.
10864     const PointerType *PT = T->getAs<PointerType>();
10865     if (!PT)
10866       goto FinishedParams;
10867     T = PT->getPointeeType();
10868     if (!T.isConstQualified() || T.isVolatileQualified())
10869       goto FinishedParams;
10870     T = T.getUnqualifiedType();
10871 
10872     // Move on to the second parameter;
10873     ++Param;
10874 
10875     // If there is no second parameter, the first must be a const char *
10876     if (Param == FnDecl->param_end()) {
10877       if (Context.hasSameType(T, Context.CharTy))
10878         Valid = true;
10879       goto FinishedParams;
10880     }
10881 
10882     // const char *, const wchar_t*, const char16_t*, and const char32_t*
10883     // are allowed as the first parameter to a two-parameter function
10884     if (!(Context.hasSameType(T, Context.CharTy) ||
10885           Context.hasSameType(T, Context.WideCharTy) ||
10886           Context.hasSameType(T, Context.Char16Ty) ||
10887           Context.hasSameType(T, Context.Char32Ty)))
10888       goto FinishedParams;
10889 
10890     // The second and final parameter must be an std::size_t
10891     T = (*Param)->getType().getUnqualifiedType();
10892     if (Context.hasSameType(T, Context.getSizeType()) &&
10893         ++Param == FnDecl->param_end())
10894       Valid = true;
10895   }
10896 
10897   // FIXME: This diagnostic is absolutely terrible.
10898 FinishedParams:
10899   if (!Valid) {
10900     Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10901       << FnDecl->getDeclName();
10902     return true;
10903   }
10904 
10905   // A parameter-declaration-clause containing a default argument is not
10906   // equivalent to any of the permitted forms.
10907   for (auto Param : FnDecl->params()) {
10908     if (Param->hasDefaultArg()) {
10909       Diag(Param->getDefaultArgRange().getBegin(),
10910            diag::err_literal_operator_default_argument)
10911         << Param->getDefaultArgRange();
10912       break;
10913     }
10914   }
10915 
10916   StringRef LiteralName
10917     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10918   if (LiteralName[0] != '_') {
10919     // C++11 [usrlit.suffix]p1:
10920     //   Literal suffix identifiers that do not start with an underscore
10921     //   are reserved for future standardization.
10922     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
10923       << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
10924   }
10925 
10926   return false;
10927 }
10928 
10929 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10930 /// linkage specification, including the language and (if present)
10931 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
10932 /// language string literal. LBraceLoc, if valid, provides the location of
10933 /// the '{' brace. Otherwise, this linkage specification does not
10934 /// have any braces.
10935 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10936                                            Expr *LangStr,
10937                                            SourceLocation LBraceLoc) {
10938   StringLiteral *Lit = cast<StringLiteral>(LangStr);
10939   if (!Lit->isAscii()) {
10940     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
10941       << LangStr->getSourceRange();
10942     return 0;
10943   }
10944 
10945   StringRef Lang = Lit->getString();
10946   LinkageSpecDecl::LanguageIDs Language;
10947   if (Lang == "C")
10948     Language = LinkageSpecDecl::lang_c;
10949   else if (Lang == "C++")
10950     Language = LinkageSpecDecl::lang_cxx;
10951   else {
10952     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
10953       << LangStr->getSourceRange();
10954     return 0;
10955   }
10956 
10957   // FIXME: Add all the various semantics of linkage specifications
10958 
10959   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
10960                                                LangStr->getExprLoc(), Language,
10961                                                LBraceLoc.isValid());
10962   CurContext->addDecl(D);
10963   PushDeclContext(S, D);
10964   return D;
10965 }
10966 
10967 /// ActOnFinishLinkageSpecification - Complete the definition of
10968 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
10969 /// valid, it's the position of the closing '}' brace in a linkage
10970 /// specification that uses braces.
10971 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
10972                                             Decl *LinkageSpec,
10973                                             SourceLocation RBraceLoc) {
10974   if (RBraceLoc.isValid()) {
10975     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10976     LSDecl->setRBraceLoc(RBraceLoc);
10977   }
10978   PopDeclContext();
10979   return LinkageSpec;
10980 }
10981 
10982 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10983                                   AttributeList *AttrList,
10984                                   SourceLocation SemiLoc) {
10985   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10986   // Attribute declarations appertain to empty declaration so we handle
10987   // them here.
10988   if (AttrList)
10989     ProcessDeclAttributeList(S, ED, AttrList);
10990 
10991   CurContext->addDecl(ED);
10992   return ED;
10993 }
10994 
10995 /// \brief Perform semantic analysis for the variable declaration that
10996 /// occurs within a C++ catch clause, returning the newly-created
10997 /// variable.
10998 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
10999                                          TypeSourceInfo *TInfo,
11000                                          SourceLocation StartLoc,
11001                                          SourceLocation Loc,
11002                                          IdentifierInfo *Name) {
11003   bool Invalid = false;
11004   QualType ExDeclType = TInfo->getType();
11005 
11006   // Arrays and functions decay.
11007   if (ExDeclType->isArrayType())
11008     ExDeclType = Context.getArrayDecayedType(ExDeclType);
11009   else if (ExDeclType->isFunctionType())
11010     ExDeclType = Context.getPointerType(ExDeclType);
11011 
11012   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11013   // The exception-declaration shall not denote a pointer or reference to an
11014   // incomplete type, other than [cv] void*.
11015   // N2844 forbids rvalue references.
11016   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
11017     Diag(Loc, diag::err_catch_rvalue_ref);
11018     Invalid = true;
11019   }
11020 
11021   QualType BaseType = ExDeclType;
11022   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
11023   unsigned DK = diag::err_catch_incomplete;
11024   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
11025     BaseType = Ptr->getPointeeType();
11026     Mode = 1;
11027     DK = diag::err_catch_incomplete_ptr;
11028   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
11029     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
11030     BaseType = Ref->getPointeeType();
11031     Mode = 2;
11032     DK = diag::err_catch_incomplete_ref;
11033   }
11034   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
11035       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
11036     Invalid = true;
11037 
11038   if (!Invalid && !ExDeclType->isDependentType() &&
11039       RequireNonAbstractType(Loc, ExDeclType,
11040                              diag::err_abstract_type_in_decl,
11041                              AbstractVariableType))
11042     Invalid = true;
11043 
11044   // Only the non-fragile NeXT runtime currently supports C++ catches
11045   // of ObjC types, and no runtime supports catching ObjC types by value.
11046   if (!Invalid && getLangOpts().ObjC1) {
11047     QualType T = ExDeclType;
11048     if (const ReferenceType *RT = T->getAs<ReferenceType>())
11049       T = RT->getPointeeType();
11050 
11051     if (T->isObjCObjectType()) {
11052       Diag(Loc, diag::err_objc_object_catch);
11053       Invalid = true;
11054     } else if (T->isObjCObjectPointerType()) {
11055       // FIXME: should this be a test for macosx-fragile specifically?
11056       if (getLangOpts().ObjCRuntime.isFragile())
11057         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
11058     }
11059   }
11060 
11061   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
11062                                     ExDeclType, TInfo, SC_None);
11063   ExDecl->setExceptionVariable(true);
11064 
11065   // In ARC, infer 'retaining' for variables of retainable type.
11066   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
11067     Invalid = true;
11068 
11069   if (!Invalid && !ExDeclType->isDependentType()) {
11070     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
11071       // Insulate this from anything else we might currently be parsing.
11072       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11073 
11074       // C++ [except.handle]p16:
11075       //   The object declared in an exception-declaration or, if the
11076       //   exception-declaration does not specify a name, a temporary (12.2) is
11077       //   copy-initialized (8.5) from the exception object. [...]
11078       //   The object is destroyed when the handler exits, after the destruction
11079       //   of any automatic objects initialized within the handler.
11080       //
11081       // We just pretend to initialize the object with itself, then make sure
11082       // it can be destroyed later.
11083       QualType initType = ExDeclType;
11084 
11085       InitializedEntity entity =
11086         InitializedEntity::InitializeVariable(ExDecl);
11087       InitializationKind initKind =
11088         InitializationKind::CreateCopy(Loc, SourceLocation());
11089 
11090       Expr *opaqueValue =
11091         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
11092       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11093       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
11094       if (result.isInvalid())
11095         Invalid = true;
11096       else {
11097         // If the constructor used was non-trivial, set this as the
11098         // "initializer".
11099         CXXConstructExpr *construct = result.takeAs<CXXConstructExpr>();
11100         if (!construct->getConstructor()->isTrivial()) {
11101           Expr *init = MaybeCreateExprWithCleanups(construct);
11102           ExDecl->setInit(init);
11103         }
11104 
11105         // And make sure it's destructable.
11106         FinalizeVarWithDestructor(ExDecl, recordType);
11107       }
11108     }
11109   }
11110 
11111   if (Invalid)
11112     ExDecl->setInvalidDecl();
11113 
11114   return ExDecl;
11115 }
11116 
11117 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11118 /// handler.
11119 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
11120   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11121   bool Invalid = D.isInvalidType();
11122 
11123   // Check for unexpanded parameter packs.
11124   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11125                                       UPPC_ExceptionType)) {
11126     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11127                                              D.getIdentifierLoc());
11128     Invalid = true;
11129   }
11130 
11131   IdentifierInfo *II = D.getIdentifier();
11132   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
11133                                              LookupOrdinaryName,
11134                                              ForRedeclaration)) {
11135     // The scope should be freshly made just for us. There is just no way
11136     // it contains any previous declaration.
11137     assert(!S->isDeclScope(PrevDecl));
11138     if (PrevDecl->isTemplateParameter()) {
11139       // Maybe we will complain about the shadowed template parameter.
11140       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11141       PrevDecl = 0;
11142     }
11143   }
11144 
11145   if (D.getCXXScopeSpec().isSet() && !Invalid) {
11146     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11147       << D.getCXXScopeSpec().getRange();
11148     Invalid = true;
11149   }
11150 
11151   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
11152                                               D.getLocStart(),
11153                                               D.getIdentifierLoc(),
11154                                               D.getIdentifier());
11155   if (Invalid)
11156     ExDecl->setInvalidDecl();
11157 
11158   // Add the exception declaration into this scope.
11159   if (II)
11160     PushOnScopeChains(ExDecl, S);
11161   else
11162     CurContext->addDecl(ExDecl);
11163 
11164   ProcessDeclAttributes(S, ExDecl, D);
11165   return ExDecl;
11166 }
11167 
11168 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11169                                          Expr *AssertExpr,
11170                                          Expr *AssertMessageExpr,
11171                                          SourceLocation RParenLoc) {
11172   StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
11173 
11174   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
11175     return 0;
11176 
11177   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11178                                       AssertMessage, RParenLoc, false);
11179 }
11180 
11181 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11182                                          Expr *AssertExpr,
11183                                          StringLiteral *AssertMessage,
11184                                          SourceLocation RParenLoc,
11185                                          bool Failed) {
11186   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11187       !Failed) {
11188     // In a static_assert-declaration, the constant-expression shall be a
11189     // constant expression that can be contextually converted to bool.
11190     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11191     if (Converted.isInvalid())
11192       Failed = true;
11193 
11194     llvm::APSInt Cond;
11195     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
11196           diag::err_static_assert_expression_is_not_constant,
11197           /*AllowFold=*/false).isInvalid())
11198       Failed = true;
11199 
11200     if (!Failed && !Cond) {
11201       SmallString<256> MsgBuffer;
11202       llvm::raw_svector_ostream Msg(MsgBuffer);
11203       AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
11204       Diag(StaticAssertLoc, diag::err_static_assert_failed)
11205         << Msg.str() << AssertExpr->getSourceRange();
11206       Failed = true;
11207     }
11208   }
11209 
11210   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
11211                                         AssertExpr, AssertMessage, RParenLoc,
11212                                         Failed);
11213 
11214   CurContext->addDecl(Decl);
11215   return Decl;
11216 }
11217 
11218 /// \brief Perform semantic analysis of the given friend type declaration.
11219 ///
11220 /// \returns A friend declaration that.
11221 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
11222                                       SourceLocation FriendLoc,
11223                                       TypeSourceInfo *TSInfo) {
11224   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11225 
11226   QualType T = TSInfo->getType();
11227   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
11228 
11229   // C++03 [class.friend]p2:
11230   //   An elaborated-type-specifier shall be used in a friend declaration
11231   //   for a class.*
11232   //
11233   //   * The class-key of the elaborated-type-specifier is required.
11234   if (!ActiveTemplateInstantiations.empty()) {
11235     // Do not complain about the form of friend template types during
11236     // template instantiation; we will already have complained when the
11237     // template was declared.
11238   } else {
11239     if (!T->isElaboratedTypeSpecifier()) {
11240       // If we evaluated the type to a record type, suggest putting
11241       // a tag in front.
11242       if (const RecordType *RT = T->getAs<RecordType>()) {
11243         RecordDecl *RD = RT->getDecl();
11244 
11245         std::string InsertionText = std::string(" ") + RD->getKindName();
11246 
11247         Diag(TypeRange.getBegin(),
11248              getLangOpts().CPlusPlus11 ?
11249                diag::warn_cxx98_compat_unelaborated_friend_type :
11250                diag::ext_unelaborated_friend_type)
11251           << (unsigned) RD->getTagKind()
11252           << T
11253           << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11254                                         InsertionText);
11255       } else {
11256         Diag(FriendLoc,
11257              getLangOpts().CPlusPlus11 ?
11258                diag::warn_cxx98_compat_nonclass_type_friend :
11259                diag::ext_nonclass_type_friend)
11260           << T
11261           << TypeRange;
11262       }
11263     } else if (T->getAs<EnumType>()) {
11264       Diag(FriendLoc,
11265            getLangOpts().CPlusPlus11 ?
11266              diag::warn_cxx98_compat_enum_friend :
11267              diag::ext_enum_friend)
11268         << T
11269         << TypeRange;
11270     }
11271 
11272     // C++11 [class.friend]p3:
11273     //   A friend declaration that does not declare a function shall have one
11274     //   of the following forms:
11275     //     friend elaborated-type-specifier ;
11276     //     friend simple-type-specifier ;
11277     //     friend typename-specifier ;
11278     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11279       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11280   }
11281 
11282   //   If the type specifier in a friend declaration designates a (possibly
11283   //   cv-qualified) class type, that class is declared as a friend; otherwise,
11284   //   the friend declaration is ignored.
11285   return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
11286 }
11287 
11288 /// Handle a friend tag declaration where the scope specifier was
11289 /// templated.
11290 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11291                                     unsigned TagSpec, SourceLocation TagLoc,
11292                                     CXXScopeSpec &SS,
11293                                     IdentifierInfo *Name,
11294                                     SourceLocation NameLoc,
11295                                     AttributeList *Attr,
11296                                     MultiTemplateParamsArg TempParamLists) {
11297   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11298 
11299   bool isExplicitSpecialization = false;
11300   bool Invalid = false;
11301 
11302   if (TemplateParameterList *TemplateParams =
11303           MatchTemplateParametersToScopeSpecifier(
11304               TagLoc, NameLoc, SS, TempParamLists, /*friend*/ true,
11305               isExplicitSpecialization, Invalid)) {
11306     if (TemplateParams->size() > 0) {
11307       // This is a declaration of a class template.
11308       if (Invalid)
11309         return 0;
11310 
11311       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
11312                                 SS, Name, NameLoc, Attr,
11313                                 TemplateParams, AS_public,
11314                                 /*ModulePrivateLoc=*/SourceLocation(),
11315                                 TempParamLists.size() - 1,
11316                                 TempParamLists.data()).take();
11317     } else {
11318       // The "template<>" header is extraneous.
11319       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11320         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11321       isExplicitSpecialization = true;
11322     }
11323   }
11324 
11325   if (Invalid) return 0;
11326 
11327   bool isAllExplicitSpecializations = true;
11328   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
11329     if (TempParamLists[I]->size()) {
11330       isAllExplicitSpecializations = false;
11331       break;
11332     }
11333   }
11334 
11335   // FIXME: don't ignore attributes.
11336 
11337   // If it's explicit specializations all the way down, just forget
11338   // about the template header and build an appropriate non-templated
11339   // friend.  TODO: for source fidelity, remember the headers.
11340   if (isAllExplicitSpecializations) {
11341     if (SS.isEmpty()) {
11342       bool Owned = false;
11343       bool IsDependent = false;
11344       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
11345                       Attr, AS_public,
11346                       /*ModulePrivateLoc=*/SourceLocation(),
11347                       MultiTemplateParamsArg(), Owned, IsDependent,
11348                       /*ScopedEnumKWLoc=*/SourceLocation(),
11349                       /*ScopedEnumUsesClassTag=*/false,
11350                       /*UnderlyingType=*/TypeResult(),
11351                       /*IsTypeSpecifier=*/false);
11352     }
11353 
11354     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11355     ElaboratedTypeKeyword Keyword
11356       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11357     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
11358                                    *Name, NameLoc);
11359     if (T.isNull())
11360       return 0;
11361 
11362     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11363     if (isa<DependentNameType>(T)) {
11364       DependentNameTypeLoc TL =
11365           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
11366       TL.setElaboratedKeywordLoc(TagLoc);
11367       TL.setQualifierLoc(QualifierLoc);
11368       TL.setNameLoc(NameLoc);
11369     } else {
11370       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
11371       TL.setElaboratedKeywordLoc(TagLoc);
11372       TL.setQualifierLoc(QualifierLoc);
11373       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
11374     }
11375 
11376     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
11377                                             TSI, FriendLoc, TempParamLists);
11378     Friend->setAccess(AS_public);
11379     CurContext->addDecl(Friend);
11380     return Friend;
11381   }
11382 
11383   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11384 
11385 
11386 
11387   // Handle the case of a templated-scope friend class.  e.g.
11388   //   template <class T> class A<T>::B;
11389   // FIXME: we don't support these right now.
11390   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
11391     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
11392   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11393   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11394   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11395   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
11396   TL.setElaboratedKeywordLoc(TagLoc);
11397   TL.setQualifierLoc(SS.getWithLocInContext(Context));
11398   TL.setNameLoc(NameLoc);
11399 
11400   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
11401                                           TSI, FriendLoc, TempParamLists);
11402   Friend->setAccess(AS_public);
11403   Friend->setUnsupportedFriend(true);
11404   CurContext->addDecl(Friend);
11405   return Friend;
11406 }
11407 
11408 
11409 /// Handle a friend type declaration.  This works in tandem with
11410 /// ActOnTag.
11411 ///
11412 /// Notes on friend class templates:
11413 ///
11414 /// We generally treat friend class declarations as if they were
11415 /// declaring a class.  So, for example, the elaborated type specifier
11416 /// in a friend declaration is required to obey the restrictions of a
11417 /// class-head (i.e. no typedefs in the scope chain), template
11418 /// parameters are required to match up with simple template-ids, &c.
11419 /// However, unlike when declaring a template specialization, it's
11420 /// okay to refer to a template specialization without an empty
11421 /// template parameter declaration, e.g.
11422 ///   friend class A<T>::B<unsigned>;
11423 /// We permit this as a special case; if there are any template
11424 /// parameters present at all, require proper matching, i.e.
11425 ///   template <> template \<class T> friend class A<int>::B;
11426 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
11427                                 MultiTemplateParamsArg TempParams) {
11428   SourceLocation Loc = DS.getLocStart();
11429 
11430   assert(DS.isFriendSpecified());
11431   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11432 
11433   // Try to convert the decl specifier to a type.  This works for
11434   // friend templates because ActOnTag never produces a ClassTemplateDecl
11435   // for a TUK_Friend.
11436   Declarator TheDeclarator(DS, Declarator::MemberContext);
11437   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11438   QualType T = TSI->getType();
11439   if (TheDeclarator.isInvalidType())
11440     return 0;
11441 
11442   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11443     return 0;
11444 
11445   // This is definitely an error in C++98.  It's probably meant to
11446   // be forbidden in C++0x, too, but the specification is just
11447   // poorly written.
11448   //
11449   // The problem is with declarations like the following:
11450   //   template <T> friend A<T>::foo;
11451   // where deciding whether a class C is a friend or not now hinges
11452   // on whether there exists an instantiation of A that causes
11453   // 'foo' to equal C.  There are restrictions on class-heads
11454   // (which we declare (by fiat) elaborated friend declarations to
11455   // be) that makes this tractable.
11456   //
11457   // FIXME: handle "template <> friend class A<T>;", which
11458   // is possibly well-formed?  Who even knows?
11459   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
11460     Diag(Loc, diag::err_tagless_friend_type_template)
11461       << DS.getSourceRange();
11462     return 0;
11463   }
11464 
11465   // C++98 [class.friend]p1: A friend of a class is a function
11466   //   or class that is not a member of the class . . .
11467   // This is fixed in DR77, which just barely didn't make the C++03
11468   // deadline.  It's also a very silly restriction that seriously
11469   // affects inner classes and which nobody else seems to implement;
11470   // thus we never diagnose it, not even in -pedantic.
11471   //
11472   // But note that we could warn about it: it's always useless to
11473   // friend one of your own members (it's not, however, worthless to
11474   // friend a member of an arbitrary specialization of your template).
11475 
11476   Decl *D;
11477   if (unsigned NumTempParamLists = TempParams.size())
11478     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
11479                                    NumTempParamLists,
11480                                    TempParams.data(),
11481                                    TSI,
11482                                    DS.getFriendSpecLoc());
11483   else
11484     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
11485 
11486   if (!D)
11487     return 0;
11488 
11489   D->setAccess(AS_public);
11490   CurContext->addDecl(D);
11491 
11492   return D;
11493 }
11494 
11495 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11496                                         MultiTemplateParamsArg TemplateParams) {
11497   const DeclSpec &DS = D.getDeclSpec();
11498 
11499   assert(DS.isFriendSpecified());
11500   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11501 
11502   SourceLocation Loc = D.getIdentifierLoc();
11503   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11504 
11505   // C++ [class.friend]p1
11506   //   A friend of a class is a function or class....
11507   // Note that this sees through typedefs, which is intended.
11508   // It *doesn't* see through dependent types, which is correct
11509   // according to [temp.arg.type]p3:
11510   //   If a declaration acquires a function type through a
11511   //   type dependent on a template-parameter and this causes
11512   //   a declaration that does not use the syntactic form of a
11513   //   function declarator to have a function type, the program
11514   //   is ill-formed.
11515   if (!TInfo->getType()->isFunctionType()) {
11516     Diag(Loc, diag::err_unexpected_friend);
11517 
11518     // It might be worthwhile to try to recover by creating an
11519     // appropriate declaration.
11520     return 0;
11521   }
11522 
11523   // C++ [namespace.memdef]p3
11524   //  - If a friend declaration in a non-local class first declares a
11525   //    class or function, the friend class or function is a member
11526   //    of the innermost enclosing namespace.
11527   //  - The name of the friend is not found by simple name lookup
11528   //    until a matching declaration is provided in that namespace
11529   //    scope (either before or after the class declaration granting
11530   //    friendship).
11531   //  - If a friend function is called, its name may be found by the
11532   //    name lookup that considers functions from namespaces and
11533   //    classes associated with the types of the function arguments.
11534   //  - When looking for a prior declaration of a class or a function
11535   //    declared as a friend, scopes outside the innermost enclosing
11536   //    namespace scope are not considered.
11537 
11538   CXXScopeSpec &SS = D.getCXXScopeSpec();
11539   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11540   DeclarationName Name = NameInfo.getName();
11541   assert(Name);
11542 
11543   // Check for unexpanded parameter packs.
11544   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11545       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11546       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11547     return 0;
11548 
11549   // The context we found the declaration in, or in which we should
11550   // create the declaration.
11551   DeclContext *DC;
11552   Scope *DCScope = S;
11553   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
11554                         ForRedeclaration);
11555 
11556   // There are five cases here.
11557   //   - There's no scope specifier and we're in a local class. Only look
11558   //     for functions declared in the immediately-enclosing block scope.
11559   // We recover from invalid scope qualifiers as if they just weren't there.
11560   FunctionDecl *FunctionContainingLocalClass = 0;
11561   if ((SS.isInvalid() || !SS.isSet()) &&
11562       (FunctionContainingLocalClass =
11563            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11564     // C++11 [class.friend]p11:
11565     //   If a friend declaration appears in a local class and the name
11566     //   specified is an unqualified name, a prior declaration is
11567     //   looked up without considering scopes that are outside the
11568     //   innermost enclosing non-class scope. For a friend function
11569     //   declaration, if there is no prior declaration, the program is
11570     //   ill-formed.
11571 
11572     // Find the innermost enclosing non-class scope. This is the block
11573     // scope containing the local class definition (or for a nested class,
11574     // the outer local class).
11575     DCScope = S->getFnParent();
11576 
11577     // Look up the function name in the scope.
11578     Previous.clear(LookupLocalFriendName);
11579     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11580 
11581     if (!Previous.empty()) {
11582       // All possible previous declarations must have the same context:
11583       // either they were declared at block scope or they are members of
11584       // one of the enclosing local classes.
11585       DC = Previous.getRepresentativeDecl()->getDeclContext();
11586     } else {
11587       // This is ill-formed, but provide the context that we would have
11588       // declared the function in, if we were permitted to, for error recovery.
11589       DC = FunctionContainingLocalClass;
11590     }
11591     adjustContextForLocalExternDecl(DC);
11592 
11593     // C++ [class.friend]p6:
11594     //   A function can be defined in a friend declaration of a class if and
11595     //   only if the class is a non-local class (9.8), the function name is
11596     //   unqualified, and the function has namespace scope.
11597     if (D.isFunctionDefinition()) {
11598       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11599     }
11600 
11601   //   - There's no scope specifier, in which case we just go to the
11602   //     appropriate scope and look for a function or function template
11603   //     there as appropriate.
11604   } else if (SS.isInvalid() || !SS.isSet()) {
11605     // C++11 [namespace.memdef]p3:
11606     //   If the name in a friend declaration is neither qualified nor
11607     //   a template-id and the declaration is a function or an
11608     //   elaborated-type-specifier, the lookup to determine whether
11609     //   the entity has been previously declared shall not consider
11610     //   any scopes outside the innermost enclosing namespace.
11611     bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
11612 
11613     // Find the appropriate context according to the above.
11614     DC = CurContext;
11615 
11616     // Skip class contexts.  If someone can cite chapter and verse
11617     // for this behavior, that would be nice --- it's what GCC and
11618     // EDG do, and it seems like a reasonable intent, but the spec
11619     // really only says that checks for unqualified existing
11620     // declarations should stop at the nearest enclosing namespace,
11621     // not that they should only consider the nearest enclosing
11622     // namespace.
11623     while (DC->isRecord())
11624       DC = DC->getParent();
11625 
11626     DeclContext *LookupDC = DC;
11627     while (LookupDC->isTransparentContext())
11628       LookupDC = LookupDC->getParent();
11629 
11630     while (true) {
11631       LookupQualifiedName(Previous, LookupDC);
11632 
11633       if (!Previous.empty()) {
11634         DC = LookupDC;
11635         break;
11636       }
11637 
11638       if (isTemplateId) {
11639         if (isa<TranslationUnitDecl>(LookupDC)) break;
11640       } else {
11641         if (LookupDC->isFileContext()) break;
11642       }
11643       LookupDC = LookupDC->getParent();
11644     }
11645 
11646     DCScope = getScopeForDeclContext(S, DC);
11647 
11648   //   - There's a non-dependent scope specifier, in which case we
11649   //     compute it and do a previous lookup there for a function
11650   //     or function template.
11651   } else if (!SS.getScopeRep()->isDependent()) {
11652     DC = computeDeclContext(SS);
11653     if (!DC) return 0;
11654 
11655     if (RequireCompleteDeclContext(SS, DC)) return 0;
11656 
11657     LookupQualifiedName(Previous, DC);
11658 
11659     // Ignore things found implicitly in the wrong scope.
11660     // TODO: better diagnostics for this case.  Suggesting the right
11661     // qualified scope would be nice...
11662     LookupResult::Filter F = Previous.makeFilter();
11663     while (F.hasNext()) {
11664       NamedDecl *D = F.next();
11665       if (!DC->InEnclosingNamespaceSetOf(
11666               D->getDeclContext()->getRedeclContext()))
11667         F.erase();
11668     }
11669     F.done();
11670 
11671     if (Previous.empty()) {
11672       D.setInvalidType();
11673       Diag(Loc, diag::err_qualified_friend_not_found)
11674           << Name << TInfo->getType();
11675       return 0;
11676     }
11677 
11678     // C++ [class.friend]p1: A friend of a class is a function or
11679     //   class that is not a member of the class . . .
11680     if (DC->Equals(CurContext))
11681       Diag(DS.getFriendSpecLoc(),
11682            getLangOpts().CPlusPlus11 ?
11683              diag::warn_cxx98_compat_friend_is_member :
11684              diag::err_friend_is_member);
11685 
11686     if (D.isFunctionDefinition()) {
11687       // C++ [class.friend]p6:
11688       //   A function can be defined in a friend declaration of a class if and
11689       //   only if the class is a non-local class (9.8), the function name is
11690       //   unqualified, and the function has namespace scope.
11691       SemaDiagnosticBuilder DB
11692         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11693 
11694       DB << SS.getScopeRep();
11695       if (DC->isFileContext())
11696         DB << FixItHint::CreateRemoval(SS.getRange());
11697       SS.clear();
11698     }
11699 
11700   //   - There's a scope specifier that does not match any template
11701   //     parameter lists, in which case we use some arbitrary context,
11702   //     create a method or method template, and wait for instantiation.
11703   //   - There's a scope specifier that does match some template
11704   //     parameter lists, which we don't handle right now.
11705   } else {
11706     if (D.isFunctionDefinition()) {
11707       // C++ [class.friend]p6:
11708       //   A function can be defined in a friend declaration of a class if and
11709       //   only if the class is a non-local class (9.8), the function name is
11710       //   unqualified, and the function has namespace scope.
11711       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11712         << SS.getScopeRep();
11713     }
11714 
11715     DC = CurContext;
11716     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
11717   }
11718 
11719   if (!DC->isRecord()) {
11720     // This implies that it has to be an operator or function.
11721     if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11722         D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11723         D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
11724       Diag(Loc, diag::err_introducing_special_friend) <<
11725         (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11726          D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
11727       return 0;
11728     }
11729   }
11730 
11731   // FIXME: This is an egregious hack to cope with cases where the scope stack
11732   // does not contain the declaration context, i.e., in an out-of-line
11733   // definition of a class.
11734   Scope FakeDCScope(S, Scope::DeclScope, Diags);
11735   if (!DCScope) {
11736     FakeDCScope.setEntity(DC);
11737     DCScope = &FakeDCScope;
11738   }
11739 
11740   bool AddToScope = true;
11741   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
11742                                           TemplateParams, AddToScope);
11743   if (!ND) return 0;
11744 
11745   assert(ND->getLexicalDeclContext() == CurContext);
11746 
11747   // If we performed typo correction, we might have added a scope specifier
11748   // and changed the decl context.
11749   DC = ND->getDeclContext();
11750 
11751   // Add the function declaration to the appropriate lookup tables,
11752   // adjusting the redeclarations list as necessary.  We don't
11753   // want to do this yet if the friending class is dependent.
11754   //
11755   // Also update the scope-based lookup if the target context's
11756   // lookup context is in lexical scope.
11757   if (!CurContext->isDependentContext()) {
11758     DC = DC->getRedeclContext();
11759     DC->makeDeclVisibleInContext(ND);
11760     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11761       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
11762   }
11763 
11764   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
11765                                        D.getIdentifierLoc(), ND,
11766                                        DS.getFriendSpecLoc());
11767   FrD->setAccess(AS_public);
11768   CurContext->addDecl(FrD);
11769 
11770   if (ND->isInvalidDecl()) {
11771     FrD->setInvalidDecl();
11772   } else {
11773     if (DC->isRecord()) CheckFriendAccess(ND);
11774 
11775     FunctionDecl *FD;
11776     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11777       FD = FTD->getTemplatedDecl();
11778     else
11779       FD = cast<FunctionDecl>(ND);
11780 
11781     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
11782     // default argument expression, that declaration shall be a definition
11783     // and shall be the only declaration of the function or function
11784     // template in the translation unit.
11785     if (functionDeclHasDefaultArgument(FD)) {
11786       if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
11787         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
11788         Diag(OldFD->getLocation(), diag::note_previous_declaration);
11789       } else if (!D.isFunctionDefinition())
11790         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
11791     }
11792 
11793     // Mark templated-scope function declarations as unsupported.
11794     if (FD->getNumTemplateParameterLists())
11795       FrD->setUnsupportedFriend(true);
11796   }
11797 
11798   return ND;
11799 }
11800 
11801 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11802   AdjustDeclIfTemplate(Dcl);
11803 
11804   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
11805   if (!Fn) {
11806     Diag(DelLoc, diag::err_deleted_non_function);
11807     return;
11808   }
11809 
11810   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
11811     // Don't consider the implicit declaration we generate for explicit
11812     // specializations. FIXME: Do not generate these implicit declarations.
11813     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
11814          Prev->getPreviousDecl()) &&
11815         !Prev->isDefined()) {
11816       Diag(DelLoc, diag::err_deleted_decl_not_first);
11817       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
11818            Prev->isImplicit() ? diag::note_previous_implicit_declaration
11819                               : diag::note_previous_declaration);
11820     }
11821     // If the declaration wasn't the first, we delete the function anyway for
11822     // recovery.
11823     Fn = Fn->getCanonicalDecl();
11824   }
11825 
11826   if (Fn->isDeleted())
11827     return;
11828 
11829   // See if we're deleting a function which is already known to override a
11830   // non-deleted virtual function.
11831   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11832     bool IssuedDiagnostic = false;
11833     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11834                                         E = MD->end_overridden_methods();
11835          I != E; ++I) {
11836       if (!(*MD->begin_overridden_methods())->isDeleted()) {
11837         if (!IssuedDiagnostic) {
11838           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11839           IssuedDiagnostic = true;
11840         }
11841         Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11842       }
11843     }
11844   }
11845 
11846   // C++11 [basic.start.main]p3:
11847   //   A program that defines main as deleted [...] is ill-formed.
11848   if (Fn->isMain())
11849     Diag(DelLoc, diag::err_deleted_main);
11850 
11851   Fn->setDeletedAsWritten();
11852 }
11853 
11854 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
11855   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
11856 
11857   if (MD) {
11858     if (MD->getParent()->isDependentType()) {
11859       MD->setDefaulted();
11860       MD->setExplicitlyDefaulted();
11861       return;
11862     }
11863 
11864     CXXSpecialMember Member = getSpecialMember(MD);
11865     if (Member == CXXInvalid) {
11866       if (!MD->isInvalidDecl())
11867         Diag(DefaultLoc, diag::err_default_special_members);
11868       return;
11869     }
11870 
11871     MD->setDefaulted();
11872     MD->setExplicitlyDefaulted();
11873 
11874     // If this definition appears within the record, do the checking when
11875     // the record is complete.
11876     const FunctionDecl *Primary = MD;
11877     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
11878       // Find the uninstantiated declaration that actually had the '= default'
11879       // on it.
11880       Pattern->isDefined(Primary);
11881 
11882     // If the method was defaulted on its first declaration, we will have
11883     // already performed the checking in CheckCompletedCXXClass. Such a
11884     // declaration doesn't trigger an implicit definition.
11885     if (Primary == Primary->getCanonicalDecl())
11886       return;
11887 
11888     CheckExplicitlyDefaultedSpecialMember(MD);
11889 
11890     // The exception specification is needed because we are defining the
11891     // function.
11892     ResolveExceptionSpec(DefaultLoc,
11893                          MD->getType()->castAs<FunctionProtoType>());
11894 
11895     if (MD->isInvalidDecl())
11896       return;
11897 
11898     switch (Member) {
11899     case CXXDefaultConstructor:
11900       DefineImplicitDefaultConstructor(DefaultLoc,
11901                                        cast<CXXConstructorDecl>(MD));
11902       break;
11903     case CXXCopyConstructor:
11904       DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
11905       break;
11906     case CXXCopyAssignment:
11907       DefineImplicitCopyAssignment(DefaultLoc, MD);
11908       break;
11909     case CXXDestructor:
11910       DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
11911       break;
11912     case CXXMoveConstructor:
11913       DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
11914       break;
11915     case CXXMoveAssignment:
11916       DefineImplicitMoveAssignment(DefaultLoc, MD);
11917       break;
11918     case CXXInvalid:
11919       llvm_unreachable("Invalid special member.");
11920     }
11921   } else {
11922     Diag(DefaultLoc, diag::err_default_special_members);
11923   }
11924 }
11925 
11926 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
11927   for (Stmt::child_range CI = S->children(); CI; ++CI) {
11928     Stmt *SubStmt = *CI;
11929     if (!SubStmt)
11930       continue;
11931     if (isa<ReturnStmt>(SubStmt))
11932       Self.Diag(SubStmt->getLocStart(),
11933            diag::err_return_in_constructor_handler);
11934     if (!isa<Expr>(SubStmt))
11935       SearchForReturnInStmt(Self, SubStmt);
11936   }
11937 }
11938 
11939 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11940   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11941     CXXCatchStmt *Handler = TryBlock->getHandler(I);
11942     SearchForReturnInStmt(*this, Handler);
11943   }
11944 }
11945 
11946 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
11947                                              const CXXMethodDecl *Old) {
11948   const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11949   const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11950 
11951   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11952 
11953   // If the calling conventions match, everything is fine
11954   if (NewCC == OldCC)
11955     return false;
11956 
11957   // If the calling conventions mismatch because the new function is static,
11958   // suppress the calling convention mismatch error; the error about static
11959   // function override (err_static_overrides_virtual from
11960   // Sema::CheckFunctionDeclaration) is more clear.
11961   if (New->getStorageClass() == SC_Static)
11962     return false;
11963 
11964   Diag(New->getLocation(),
11965        diag::err_conflicting_overriding_cc_attributes)
11966     << New->getDeclName() << New->getType() << Old->getType();
11967   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11968   return true;
11969 }
11970 
11971 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
11972                                              const CXXMethodDecl *Old) {
11973   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
11974   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
11975 
11976   if (Context.hasSameType(NewTy, OldTy) ||
11977       NewTy->isDependentType() || OldTy->isDependentType())
11978     return false;
11979 
11980   // Check if the return types are covariant
11981   QualType NewClassTy, OldClassTy;
11982 
11983   /// Both types must be pointers or references to classes.
11984   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11985     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
11986       NewClassTy = NewPT->getPointeeType();
11987       OldClassTy = OldPT->getPointeeType();
11988     }
11989   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11990     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11991       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11992         NewClassTy = NewRT->getPointeeType();
11993         OldClassTy = OldRT->getPointeeType();
11994       }
11995     }
11996   }
11997 
11998   // The return types aren't either both pointers or references to a class type.
11999   if (NewClassTy.isNull()) {
12000     Diag(New->getLocation(),
12001          diag::err_different_return_type_for_overriding_virtual_function)
12002       << New->getDeclName() << NewTy << OldTy;
12003     Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12004 
12005     return true;
12006   }
12007 
12008   // C++ [class.virtual]p6:
12009   //   If the return type of D::f differs from the return type of B::f, the
12010   //   class type in the return type of D::f shall be complete at the point of
12011   //   declaration of D::f or shall be the class type D.
12012   if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12013     if (!RT->isBeingDefined() &&
12014         RequireCompleteType(New->getLocation(), NewClassTy,
12015                             diag::err_covariant_return_incomplete,
12016                             New->getDeclName()))
12017     return true;
12018   }
12019 
12020   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
12021     // Check if the new class derives from the old class.
12022     if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12023       Diag(New->getLocation(),
12024            diag::err_covariant_return_not_derived)
12025       << New->getDeclName() << NewTy << OldTy;
12026       Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12027       return true;
12028     }
12029 
12030     // Check if we the conversion from derived to base is valid.
12031     if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
12032                     diag::err_covariant_return_inaccessible_base,
12033                     diag::err_covariant_return_ambiguous_derived_to_base_conv,
12034                     // FIXME: Should this point to the return type?
12035                     New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
12036       // FIXME: this note won't trigger for delayed access control
12037       // diagnostics, and it's impossible to get an undelayed error
12038       // here from access control during the original parse because
12039       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
12040       Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12041       return true;
12042     }
12043   }
12044 
12045   // The qualifiers of the return types must be the same.
12046   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
12047     Diag(New->getLocation(),
12048          diag::err_covariant_return_type_different_qualifications)
12049     << New->getDeclName() << NewTy << OldTy;
12050     Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12051     return true;
12052   };
12053 
12054 
12055   // The new class type must have the same or less qualifiers as the old type.
12056   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12057     Diag(New->getLocation(),
12058          diag::err_covariant_return_type_class_type_more_qualified)
12059     << New->getDeclName() << NewTy << OldTy;
12060     Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12061     return true;
12062   };
12063 
12064   return false;
12065 }
12066 
12067 /// \brief Mark the given method pure.
12068 ///
12069 /// \param Method the method to be marked pure.
12070 ///
12071 /// \param InitRange the source range that covers the "0" initializer.
12072 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
12073   SourceLocation EndLoc = InitRange.getEnd();
12074   if (EndLoc.isValid())
12075     Method->setRangeEnd(EndLoc);
12076 
12077   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12078     Method->setPure();
12079     return false;
12080   }
12081 
12082   if (!Method->isInvalidDecl())
12083     Diag(Method->getLocation(), diag::err_non_virtual_pure)
12084       << Method->getDeclName() << InitRange;
12085   return true;
12086 }
12087 
12088 /// \brief Determine whether the given declaration is a static data member.
12089 static bool isStaticDataMember(const Decl *D) {
12090   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12091     return Var->isStaticDataMember();
12092 
12093   return false;
12094 }
12095 
12096 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12097 /// an initializer for the out-of-line declaration 'Dcl'.  The scope
12098 /// is a fresh scope pushed for just this purpose.
12099 ///
12100 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12101 /// static data member of class X, names should be looked up in the scope of
12102 /// class X.
12103 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
12104   // If there is no declaration, there was an error parsing it.
12105   if (D == 0 || D->isInvalidDecl()) return;
12106 
12107   // We will always have a nested name specifier here, but this declaration
12108   // might not be out of line if the specifier names the current namespace:
12109   //   extern int n;
12110   //   int ::n = 0;
12111   if (D->isOutOfLine())
12112     EnterDeclaratorContext(S, D->getDeclContext());
12113 
12114   // If we are parsing the initializer for a static data member, push a
12115   // new expression evaluation context that is associated with this static
12116   // data member.
12117   if (isStaticDataMember(D))
12118     PushExpressionEvaluationContext(PotentiallyEvaluated, D);
12119 }
12120 
12121 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
12122 /// initializer for the out-of-line declaration 'D'.
12123 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
12124   // If there is no declaration, there was an error parsing it.
12125   if (D == 0 || D->isInvalidDecl()) return;
12126 
12127   if (isStaticDataMember(D))
12128     PopExpressionEvaluationContext();
12129 
12130   if (D->isOutOfLine())
12131     ExitDeclaratorContext(S);
12132 }
12133 
12134 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12135 /// C++ if/switch/while/for statement.
12136 /// e.g: "if (int x = f()) {...}"
12137 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
12138   // C++ 6.4p2:
12139   // The declarator shall not specify a function or an array.
12140   // The type-specifier-seq shall not contain typedef and shall not declare a
12141   // new class or enumeration.
12142   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12143          "Parser allowed 'typedef' as storage class of condition decl.");
12144 
12145   Decl *Dcl = ActOnDeclarator(S, D);
12146   if (!Dcl)
12147     return true;
12148 
12149   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12150     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
12151       << D.getSourceRange();
12152     return true;
12153   }
12154 
12155   return Dcl;
12156 }
12157 
12158 void Sema::LoadExternalVTableUses() {
12159   if (!ExternalSource)
12160     return;
12161 
12162   SmallVector<ExternalVTableUse, 4> VTables;
12163   ExternalSource->ReadUsedVTables(VTables);
12164   SmallVector<VTableUse, 4> NewUses;
12165   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12166     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12167       = VTablesUsed.find(VTables[I].Record);
12168     // Even if a definition wasn't required before, it may be required now.
12169     if (Pos != VTablesUsed.end()) {
12170       if (!Pos->second && VTables[I].DefinitionRequired)
12171         Pos->second = true;
12172       continue;
12173     }
12174 
12175     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12176     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12177   }
12178 
12179   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12180 }
12181 
12182 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12183                           bool DefinitionRequired) {
12184   // Ignore any vtable uses in unevaluated operands or for classes that do
12185   // not have a vtable.
12186   if (!Class->isDynamicClass() || Class->isDependentContext() ||
12187       CurContext->isDependentContext() || isUnevaluatedContext())
12188     return;
12189 
12190   // Try to insert this class into the map.
12191   LoadExternalVTableUses();
12192   Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12193   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12194     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12195   if (!Pos.second) {
12196     // If we already had an entry, check to see if we are promoting this vtable
12197     // to required a definition. If so, we need to reappend to the VTableUses
12198     // list, since we may have already processed the first entry.
12199     if (DefinitionRequired && !Pos.first->second) {
12200       Pos.first->second = true;
12201     } else {
12202       // Otherwise, we can early exit.
12203       return;
12204     }
12205   } else {
12206     // The Microsoft ABI requires that we perform the destructor body
12207     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
12208     // the deleting destructor is emitted with the vtable, not with the
12209     // destructor definition as in the Itanium ABI.
12210     // If it has a definition, we do the check at that point instead.
12211     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12212         Class->hasUserDeclaredDestructor() &&
12213         !Class->getDestructor()->isDefined() &&
12214         !Class->getDestructor()->isDeleted()) {
12215       CheckDestructor(Class->getDestructor());
12216     }
12217   }
12218 
12219   // Local classes need to have their virtual members marked
12220   // immediately. For all other classes, we mark their virtual members
12221   // at the end of the translation unit.
12222   if (Class->isLocalClass())
12223     MarkVirtualMembersReferenced(Loc, Class);
12224   else
12225     VTableUses.push_back(std::make_pair(Class, Loc));
12226 }
12227 
12228 bool Sema::DefineUsedVTables() {
12229   LoadExternalVTableUses();
12230   if (VTableUses.empty())
12231     return false;
12232 
12233   // Note: The VTableUses vector could grow as a result of marking
12234   // the members of a class as "used", so we check the size each
12235   // time through the loop and prefer indices (which are stable) to
12236   // iterators (which are not).
12237   bool DefinedAnything = false;
12238   for (unsigned I = 0; I != VTableUses.size(); ++I) {
12239     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
12240     if (!Class)
12241       continue;
12242 
12243     SourceLocation Loc = VTableUses[I].second;
12244 
12245     bool DefineVTable = true;
12246 
12247     // If this class has a key function, but that key function is
12248     // defined in another translation unit, we don't need to emit the
12249     // vtable even though we're using it.
12250     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
12251     if (KeyFunction && !KeyFunction->hasBody()) {
12252       // The key function is in another translation unit.
12253       DefineVTable = false;
12254       TemplateSpecializationKind TSK =
12255           KeyFunction->getTemplateSpecializationKind();
12256       assert(TSK != TSK_ExplicitInstantiationDefinition &&
12257              TSK != TSK_ImplicitInstantiation &&
12258              "Instantiations don't have key functions");
12259       (void)TSK;
12260     } else if (!KeyFunction) {
12261       // If we have a class with no key function that is the subject
12262       // of an explicit instantiation declaration, suppress the
12263       // vtable; it will live with the explicit instantiation
12264       // definition.
12265       bool IsExplicitInstantiationDeclaration
12266         = Class->getTemplateSpecializationKind()
12267                                       == TSK_ExplicitInstantiationDeclaration;
12268       for (auto R : Class->redecls()) {
12269         TemplateSpecializationKind TSK
12270           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
12271         if (TSK == TSK_ExplicitInstantiationDeclaration)
12272           IsExplicitInstantiationDeclaration = true;
12273         else if (TSK == TSK_ExplicitInstantiationDefinition) {
12274           IsExplicitInstantiationDeclaration = false;
12275           break;
12276         }
12277       }
12278 
12279       if (IsExplicitInstantiationDeclaration)
12280         DefineVTable = false;
12281     }
12282 
12283     // The exception specifications for all virtual members may be needed even
12284     // if we are not providing an authoritative form of the vtable in this TU.
12285     // We may choose to emit it available_externally anyway.
12286     if (!DefineVTable) {
12287       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12288       continue;
12289     }
12290 
12291     // Mark all of the virtual members of this class as referenced, so
12292     // that we can build a vtable. Then, tell the AST consumer that a
12293     // vtable for this class is required.
12294     DefinedAnything = true;
12295     MarkVirtualMembersReferenced(Loc, Class);
12296     CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12297     Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12298 
12299     // Optionally warn if we're emitting a weak vtable.
12300     if (Class->isExternallyVisible() &&
12301         Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
12302       const FunctionDecl *KeyFunctionDef = 0;
12303       if (!KeyFunction ||
12304           (KeyFunction->hasBody(KeyFunctionDef) &&
12305            KeyFunctionDef->isInlined()))
12306         Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12307              TSK_ExplicitInstantiationDefinition
12308              ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12309           << Class;
12310     }
12311   }
12312   VTableUses.clear();
12313 
12314   return DefinedAnything;
12315 }
12316 
12317 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12318                                                  const CXXRecordDecl *RD) {
12319   for (const auto *I : RD->methods())
12320     if (I->isVirtual() && !I->isPure())
12321       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
12322 }
12323 
12324 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12325                                         const CXXRecordDecl *RD) {
12326   // Mark all functions which will appear in RD's vtable as used.
12327   CXXFinalOverriderMap FinalOverriders;
12328   RD->getFinalOverriders(FinalOverriders);
12329   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12330                                             E = FinalOverriders.end();
12331        I != E; ++I) {
12332     for (OverridingMethods::const_iterator OI = I->second.begin(),
12333                                            OE = I->second.end();
12334          OI != OE; ++OI) {
12335       assert(OI->second.size() > 0 && "no final overrider");
12336       CXXMethodDecl *Overrider = OI->second.front().Method;
12337 
12338       // C++ [basic.def.odr]p2:
12339       //   [...] A virtual member function is used if it is not pure. [...]
12340       if (!Overrider->isPure())
12341         MarkFunctionReferenced(Loc, Overrider);
12342     }
12343   }
12344 
12345   // Only classes that have virtual bases need a VTT.
12346   if (RD->getNumVBases() == 0)
12347     return;
12348 
12349   for (const auto &I : RD->bases()) {
12350     const CXXRecordDecl *Base =
12351         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
12352     if (Base->getNumVBases() == 0)
12353       continue;
12354     MarkVirtualMembersReferenced(Loc, Base);
12355   }
12356 }
12357 
12358 /// SetIvarInitializers - This routine builds initialization ASTs for the
12359 /// Objective-C implementation whose ivars need be initialized.
12360 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
12361   if (!getLangOpts().CPlusPlus)
12362     return;
12363   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
12364     SmallVector<ObjCIvarDecl*, 8> ivars;
12365     CollectIvarsToConstructOrDestruct(OID, ivars);
12366     if (ivars.empty())
12367       return;
12368     SmallVector<CXXCtorInitializer*, 32> AllToInit;
12369     for (unsigned i = 0; i < ivars.size(); i++) {
12370       FieldDecl *Field = ivars[i];
12371       if (Field->isInvalidDecl())
12372         continue;
12373 
12374       CXXCtorInitializer *Member;
12375       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12376       InitializationKind InitKind =
12377         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
12378 
12379       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12380       ExprResult MemberInit =
12381         InitSeq.Perform(*this, InitEntity, InitKind, None);
12382       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
12383       // Note, MemberInit could actually come back empty if no initialization
12384       // is required (e.g., because it would call a trivial default constructor)
12385       if (!MemberInit.get() || MemberInit.isInvalid())
12386         continue;
12387 
12388       Member =
12389         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12390                                          SourceLocation(),
12391                                          MemberInit.takeAs<Expr>(),
12392                                          SourceLocation());
12393       AllToInit.push_back(Member);
12394 
12395       // Be sure that the destructor is accessible and is marked as referenced.
12396       if (const RecordType *RecordTy
12397                   = Context.getBaseElementType(Field->getType())
12398                                                         ->getAs<RecordType>()) {
12399                     CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
12400         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
12401           MarkFunctionReferenced(Field->getLocation(), Destructor);
12402           CheckDestructorAccess(Field->getLocation(), Destructor,
12403                             PDiag(diag::err_access_dtor_ivar)
12404                               << Context.getBaseElementType(Field->getType()));
12405         }
12406       }
12407     }
12408     ObjCImplementation->setIvarInitializers(Context,
12409                                             AllToInit.data(), AllToInit.size());
12410   }
12411 }
12412 
12413 static
12414 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12415                            llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12416                            llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12417                            llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12418                            Sema &S) {
12419   if (Ctor->isInvalidDecl())
12420     return;
12421 
12422   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12423 
12424   // Target may not be determinable yet, for instance if this is a dependent
12425   // call in an uninstantiated template.
12426   if (Target) {
12427     const FunctionDecl *FNTarget = 0;
12428     (void)Target->hasBody(FNTarget);
12429     Target = const_cast<CXXConstructorDecl*>(
12430       cast_or_null<CXXConstructorDecl>(FNTarget));
12431   }
12432 
12433   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12434                      // Avoid dereferencing a null pointer here.
12435                      *TCanonical = Target ? Target->getCanonicalDecl() : 0;
12436 
12437   if (!Current.insert(Canonical))
12438     return;
12439 
12440   // We know that beyond here, we aren't chaining into a cycle.
12441   if (!Target || !Target->isDelegatingConstructor() ||
12442       Target->isInvalidDecl() || Valid.count(TCanonical)) {
12443     Valid.insert(Current.begin(), Current.end());
12444     Current.clear();
12445   // We've hit a cycle.
12446   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12447              Current.count(TCanonical)) {
12448     // If we haven't diagnosed this cycle yet, do so now.
12449     if (!Invalid.count(TCanonical)) {
12450       S.Diag((*Ctor->init_begin())->getSourceLocation(),
12451              diag::warn_delegating_ctor_cycle)
12452         << Ctor;
12453 
12454       // Don't add a note for a function delegating directly to itself.
12455       if (TCanonical != Canonical)
12456         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12457 
12458       CXXConstructorDecl *C = Target;
12459       while (C->getCanonicalDecl() != Canonical) {
12460         const FunctionDecl *FNTarget = 0;
12461         (void)C->getTargetConstructor()->hasBody(FNTarget);
12462         assert(FNTarget && "Ctor cycle through bodiless function");
12463 
12464         C = const_cast<CXXConstructorDecl*>(
12465           cast<CXXConstructorDecl>(FNTarget));
12466         S.Diag(C->getLocation(), diag::note_which_delegates_to);
12467       }
12468     }
12469 
12470     Invalid.insert(Current.begin(), Current.end());
12471     Current.clear();
12472   } else {
12473     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12474   }
12475 }
12476 
12477 
12478 void Sema::CheckDelegatingCtorCycles() {
12479   llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12480 
12481   for (DelegatingCtorDeclsType::iterator
12482          I = DelegatingCtorDecls.begin(ExternalSource),
12483          E = DelegatingCtorDecls.end();
12484        I != E; ++I)
12485     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
12486 
12487   for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12488                                                          CE = Invalid.end();
12489        CI != CE; ++CI)
12490     (*CI)->setInvalidDecl();
12491 }
12492 
12493 namespace {
12494   /// \brief AST visitor that finds references to the 'this' expression.
12495   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12496     Sema &S;
12497 
12498   public:
12499     explicit FindCXXThisExpr(Sema &S) : S(S) { }
12500 
12501     bool VisitCXXThisExpr(CXXThisExpr *E) {
12502       S.Diag(E->getLocation(), diag::err_this_static_member_func)
12503         << E->isImplicit();
12504       return false;
12505     }
12506   };
12507 }
12508 
12509 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12510   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12511   if (!TSInfo)
12512     return false;
12513 
12514   TypeLoc TL = TSInfo->getTypeLoc();
12515   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
12516   if (!ProtoTL)
12517     return false;
12518 
12519   // C++11 [expr.prim.general]p3:
12520   //   [The expression this] shall not appear before the optional
12521   //   cv-qualifier-seq and it shall not appear within the declaration of a
12522   //   static member function (although its type and value category are defined
12523   //   within a static member function as they are within a non-static member
12524   //   function). [ Note: this is because declaration matching does not occur
12525   //  until the complete declarator is known. - end note ]
12526   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
12527   FindCXXThisExpr Finder(*this);
12528 
12529   // If the return type came after the cv-qualifier-seq, check it now.
12530   if (Proto->hasTrailingReturn() &&
12531       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
12532     return true;
12533 
12534   // Check the exception specification.
12535   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12536     return true;
12537 
12538   return checkThisInStaticMemberFunctionAttributes(Method);
12539 }
12540 
12541 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12542   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12543   if (!TSInfo)
12544     return false;
12545 
12546   TypeLoc TL = TSInfo->getTypeLoc();
12547   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
12548   if (!ProtoTL)
12549     return false;
12550 
12551   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
12552   FindCXXThisExpr Finder(*this);
12553 
12554   switch (Proto->getExceptionSpecType()) {
12555   case EST_Uninstantiated:
12556   case EST_Unevaluated:
12557   case EST_BasicNoexcept:
12558   case EST_DynamicNone:
12559   case EST_MSAny:
12560   case EST_None:
12561     break;
12562 
12563   case EST_ComputedNoexcept:
12564     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12565       return true;
12566 
12567   case EST_Dynamic:
12568     for (const auto &E : Proto->exceptions()) {
12569       if (!Finder.TraverseType(E))
12570         return true;
12571     }
12572     break;
12573   }
12574 
12575   return false;
12576 }
12577 
12578 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12579   FindCXXThisExpr Finder(*this);
12580 
12581   // Check attributes.
12582   for (const auto *A : Method->attrs()) {
12583     // FIXME: This should be emitted by tblgen.
12584     Expr *Arg = 0;
12585     ArrayRef<Expr *> Args;
12586     if (const auto *G = dyn_cast<GuardedByAttr>(A))
12587       Arg = G->getArg();
12588     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
12589       Arg = G->getArg();
12590     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
12591       Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12592     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
12593       Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12594     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
12595       Arg = ETLF->getSuccessValue();
12596       Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12597     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
12598       Arg = STLF->getSuccessValue();
12599       Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12600     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
12601       Arg = LR->getArg();
12602     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
12603       Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12604     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
12605       Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
12606     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
12607       Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
12608     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
12609       Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
12610     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
12611       Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
12612 
12613     if (Arg && !Finder.TraverseStmt(Arg))
12614       return true;
12615 
12616     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12617       if (!Finder.TraverseStmt(Args[I]))
12618         return true;
12619     }
12620   }
12621 
12622   return false;
12623 }
12624 
12625 void
12626 Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12627                                   ArrayRef<ParsedType> DynamicExceptions,
12628                                   ArrayRef<SourceRange> DynamicExceptionRanges,
12629                                   Expr *NoexceptExpr,
12630                                   SmallVectorImpl<QualType> &Exceptions,
12631                                   FunctionProtoType::ExtProtoInfo &EPI) {
12632   Exceptions.clear();
12633   EPI.ExceptionSpecType = EST;
12634   if (EST == EST_Dynamic) {
12635     Exceptions.reserve(DynamicExceptions.size());
12636     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12637       // FIXME: Preserve type source info.
12638       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12639 
12640       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12641       collectUnexpandedParameterPacks(ET, Unexpanded);
12642       if (!Unexpanded.empty()) {
12643         DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12644                                          UPPC_ExceptionType,
12645                                          Unexpanded);
12646         continue;
12647       }
12648 
12649       // Check that the type is valid for an exception spec, and
12650       // drop it if not.
12651       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12652         Exceptions.push_back(ET);
12653     }
12654     EPI.NumExceptions = Exceptions.size();
12655     EPI.Exceptions = Exceptions.data();
12656     return;
12657   }
12658 
12659   if (EST == EST_ComputedNoexcept) {
12660     // If an error occurred, there's no expression here.
12661     if (NoexceptExpr) {
12662       assert((NoexceptExpr->isTypeDependent() ||
12663               NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12664               Context.BoolTy) &&
12665              "Parser should have made sure that the expression is boolean");
12666       if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12667         EPI.ExceptionSpecType = EST_BasicNoexcept;
12668         return;
12669       }
12670 
12671       if (!NoexceptExpr->isValueDependent())
12672         NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
12673                          diag::err_noexcept_needs_constant_expression,
12674                          /*AllowFold*/ false).take();
12675       EPI.NoexceptExpr = NoexceptExpr;
12676     }
12677     return;
12678   }
12679 }
12680 
12681 /// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12682 Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12683   // Implicitly declared functions (e.g. copy constructors) are
12684   // __host__ __device__
12685   if (D->isImplicit())
12686     return CFT_HostDevice;
12687 
12688   if (D->hasAttr<CUDAGlobalAttr>())
12689     return CFT_Global;
12690 
12691   if (D->hasAttr<CUDADeviceAttr>()) {
12692     if (D->hasAttr<CUDAHostAttr>())
12693       return CFT_HostDevice;
12694     return CFT_Device;
12695   }
12696 
12697   return CFT_Host;
12698 }
12699 
12700 bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12701                            CUDAFunctionTarget CalleeTarget) {
12702   // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12703   // Callable from the device only."
12704   if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12705     return true;
12706 
12707   // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12708   // Callable from the host only."
12709   // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12710   // Callable from the host only."
12711   if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12712       (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12713     return true;
12714 
12715   if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12716     return true;
12717 
12718   return false;
12719 }
12720 
12721 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12722 ///
12723 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12724                                        SourceLocation DeclStart,
12725                                        Declarator &D, Expr *BitWidth,
12726                                        InClassInitStyle InitStyle,
12727                                        AccessSpecifier AS,
12728                                        AttributeList *MSPropertyAttr) {
12729   IdentifierInfo *II = D.getIdentifier();
12730   if (!II) {
12731     Diag(DeclStart, diag::err_anonymous_property);
12732     return NULL;
12733   }
12734   SourceLocation Loc = D.getIdentifierLoc();
12735 
12736   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12737   QualType T = TInfo->getType();
12738   if (getLangOpts().CPlusPlus) {
12739     CheckExtraCXXDefaultArguments(D);
12740 
12741     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12742                                         UPPC_DataMemberType)) {
12743       D.setInvalidType();
12744       T = Context.IntTy;
12745       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12746     }
12747   }
12748 
12749   DiagnoseFunctionSpecifiers(D.getDeclSpec());
12750 
12751   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12752     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12753          diag::err_invalid_thread)
12754       << DeclSpec::getSpecifierName(TSCS);
12755 
12756   // Check to see if this name was declared as a member previously
12757   NamedDecl *PrevDecl = 0;
12758   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12759   LookupName(Previous, S);
12760   switch (Previous.getResultKind()) {
12761   case LookupResult::Found:
12762   case LookupResult::FoundUnresolvedValue:
12763     PrevDecl = Previous.getAsSingle<NamedDecl>();
12764     break;
12765 
12766   case LookupResult::FoundOverloaded:
12767     PrevDecl = Previous.getRepresentativeDecl();
12768     break;
12769 
12770   case LookupResult::NotFound:
12771   case LookupResult::NotFoundInCurrentInstantiation:
12772   case LookupResult::Ambiguous:
12773     break;
12774   }
12775 
12776   if (PrevDecl && PrevDecl->isTemplateParameter()) {
12777     // Maybe we will complain about the shadowed template parameter.
12778     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12779     // Just pretend that we didn't see the previous declaration.
12780     PrevDecl = 0;
12781   }
12782 
12783   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12784     PrevDecl = 0;
12785 
12786   SourceLocation TSSL = D.getLocStart();
12787   const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12788   MSPropertyDecl *NewPD = MSPropertyDecl::Create(
12789       Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
12790   ProcessDeclAttributes(TUScope, NewPD, D);
12791   NewPD->setAccess(AS);
12792 
12793   if (NewPD->isInvalidDecl())
12794     Record->setInvalidDecl();
12795 
12796   if (D.getDeclSpec().isModulePrivateSpecified())
12797     NewPD->setModulePrivate();
12798 
12799   if (NewPD->isInvalidDecl() && PrevDecl) {
12800     // Don't introduce NewFD into scope; there's already something
12801     // with the same name in the same scope.
12802   } else if (II) {
12803     PushOnScopeChains(NewPD, S);
12804   } else
12805     Record->addDecl(NewPD);
12806 
12807   return NewPD;
12808 }
12809