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/ASTMutationListener.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/DeclVisitor.h"
21 #include "clang/AST/EvaluatedExprVisitor.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/RecordLayout.h"
24 #include "clang/AST/RecursiveASTVisitor.h"
25 #include "clang/AST/StmtVisitor.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "clang/AST/TypeOrdering.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/Preprocessor.h"
31 #include "clang/Sema/CXXFieldCollector.h"
32 #include "clang/Sema/DeclSpec.h"
33 #include "clang/Sema/Initialization.h"
34 #include "clang/Sema/Lookup.h"
35 #include "clang/Sema/ParsedTemplate.h"
36 #include "clang/Sema/Scope.h"
37 #include "clang/Sema/ScopeInfo.h"
38 #include "llvm/ADT/STLExtras.h"
39 #include "llvm/ADT/SmallString.h"
40 #include <map>
41 #include <set>
42 
43 using namespace clang;
44 
45 //===----------------------------------------------------------------------===//
46 // CheckDefaultArgumentVisitor
47 //===----------------------------------------------------------------------===//
48 
49 namespace {
50   /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
51   /// the default argument of a parameter to determine whether it
52   /// contains any ill-formed subexpressions. For example, this will
53   /// diagnose the use of local variables or parameters within the
54   /// default argument expression.
55   class CheckDefaultArgumentVisitor
56     : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
57     Expr *DefaultArg;
58     Sema *S;
59 
60   public:
61     CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
62       : DefaultArg(defarg), S(s) {}
63 
64     bool VisitExpr(Expr *Node);
65     bool VisitDeclRefExpr(DeclRefExpr *DRE);
66     bool VisitCXXThisExpr(CXXThisExpr *ThisE);
67     bool VisitLambdaExpr(LambdaExpr *Lambda);
68     bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
69   };
70 
71   /// VisitExpr - Visit all of the children of this expression.
72   bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
73     bool IsInvalid = false;
74     for (Stmt::child_range I = Node->children(); I; ++I)
75       IsInvalid |= Visit(*I);
76     return IsInvalid;
77   }
78 
79   /// VisitDeclRefExpr - Visit a reference to a declaration, to
80   /// determine whether this declaration can be used in the default
81   /// argument expression.
82   bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
83     NamedDecl *Decl = DRE->getDecl();
84     if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
85       // C++ [dcl.fct.default]p9
86       //   Default arguments are evaluated each time the function is
87       //   called. The order of evaluation of function arguments is
88       //   unspecified. Consequently, parameters of a function shall not
89       //   be used in default argument expressions, even if they are not
90       //   evaluated. Parameters of a function declared before a default
91       //   argument expression are in scope and can hide namespace and
92       //   class member names.
93       return S->Diag(DRE->getLocStart(),
94                      diag::err_param_default_argument_references_param)
95          << Param->getDeclName() << DefaultArg->getSourceRange();
96     } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
97       // C++ [dcl.fct.default]p7
98       //   Local variables shall not be used in default argument
99       //   expressions.
100       if (VDecl->isLocalVarDecl())
101         return S->Diag(DRE->getLocStart(),
102                        diag::err_param_default_argument_references_local)
103           << VDecl->getDeclName() << DefaultArg->getSourceRange();
104     }
105 
106     return false;
107   }
108 
109   /// VisitCXXThisExpr - Visit a C++ "this" expression.
110   bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
111     // C++ [dcl.fct.default]p8:
112     //   The keyword this shall not be used in a default argument of a
113     //   member function.
114     return S->Diag(ThisE->getLocStart(),
115                    diag::err_param_default_argument_references_this)
116                << ThisE->getSourceRange();
117   }
118 
119   bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
120     bool Invalid = false;
121     for (PseudoObjectExpr::semantics_iterator
122            i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
123       Expr *E = *i;
124 
125       // Look through bindings.
126       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
127         E = OVE->getSourceExpr();
128         assert(E && "pseudo-object binding without source expression?");
129       }
130 
131       Invalid |= Visit(E);
132     }
133     return Invalid;
134   }
135 
136   bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
137     // C++11 [expr.lambda.prim]p13:
138     //   A lambda-expression appearing in a default argument shall not
139     //   implicitly or explicitly capture any entity.
140     if (Lambda->capture_begin() == Lambda->capture_end())
141       return false;
142 
143     return S->Diag(Lambda->getLocStart(),
144                    diag::err_lambda_capture_default_arg);
145   }
146 }
147 
148 void
149 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
150                                                  const CXXMethodDecl *Method) {
151   // If we have an MSAny spec already, don't bother.
152   if (!Method || ComputedEST == EST_MSAny)
153     return;
154 
155   const FunctionProtoType *Proto
156     = Method->getType()->getAs<FunctionProtoType>();
157   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
158   if (!Proto)
159     return;
160 
161   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
162 
163   // If this function can throw any exceptions, make a note of that.
164   if (EST == EST_MSAny || EST == EST_None) {
165     ClearExceptions();
166     ComputedEST = EST;
167     return;
168   }
169 
170   // FIXME: If the call to this decl is using any of its default arguments, we
171   // need to search them for potentially-throwing calls.
172 
173   // If this function has a basic noexcept, it doesn't affect the outcome.
174   if (EST == EST_BasicNoexcept)
175     return;
176 
177   // If we have a throw-all spec at this point, ignore the function.
178   if (ComputedEST == EST_None)
179     return;
180 
181   // If we're still at noexcept(true) and there's a nothrow() callee,
182   // change to that specification.
183   if (EST == EST_DynamicNone) {
184     if (ComputedEST == EST_BasicNoexcept)
185       ComputedEST = EST_DynamicNone;
186     return;
187   }
188 
189   // Check out noexcept specs.
190   if (EST == EST_ComputedNoexcept) {
191     FunctionProtoType::NoexceptResult NR =
192         Proto->getNoexceptSpec(Self->Context);
193     assert(NR != FunctionProtoType::NR_NoNoexcept &&
194            "Must have noexcept result for EST_ComputedNoexcept.");
195     assert(NR != FunctionProtoType::NR_Dependent &&
196            "Should not generate implicit declarations for dependent cases, "
197            "and don't know how to handle them anyway.");
198 
199     // noexcept(false) -> no spec on the new function
200     if (NR == FunctionProtoType::NR_Throw) {
201       ClearExceptions();
202       ComputedEST = EST_None;
203     }
204     // noexcept(true) won't change anything either.
205     return;
206   }
207 
208   assert(EST == EST_Dynamic && "EST case not considered earlier.");
209   assert(ComputedEST != EST_None &&
210          "Shouldn't collect exceptions when throw-all is guaranteed.");
211   ComputedEST = EST_Dynamic;
212   // Record the exceptions in this function's exception specification.
213   for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
214                                           EEnd = Proto->exception_end();
215        E != EEnd; ++E)
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   if (Param)
343     Param->setUnparsedDefaultArg();
344 
345   UnparsedDefaultArgLocs[Param] = ArgLoc;
346 }
347 
348 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
349 /// the default argument for the parameter param failed.
350 void Sema::ActOnParamDefaultArgumentError(Decl *param) {
351   if (!param)
352     return;
353 
354   ParmVarDecl *Param = cast<ParmVarDecl>(param);
355 
356   Param->setInvalidDecl();
357 
358   UnparsedDefaultArgLocs.erase(Param);
359 }
360 
361 /// CheckExtraCXXDefaultArguments - Check for any extra default
362 /// arguments in the declarator, which is not a function declaration
363 /// or definition and therefore is not permitted to have default
364 /// arguments. This routine should be invoked for every declarator
365 /// that is not a function declaration or definition.
366 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
367   // C++ [dcl.fct.default]p3
368   //   A default argument expression shall be specified only in the
369   //   parameter-declaration-clause of a function declaration or in a
370   //   template-parameter (14.1). It shall not be specified for a
371   //   parameter pack. If it is specified in a
372   //   parameter-declaration-clause, it shall not occur within a
373   //   declarator or abstract-declarator of a parameter-declaration.
374   bool MightBeFunction = D.isFunctionDeclarationContext();
375   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
376     DeclaratorChunk &chunk = D.getTypeObject(i);
377     if (chunk.Kind == DeclaratorChunk::Function) {
378       if (MightBeFunction) {
379         // This is a function declaration. It can have default arguments, but
380         // keep looking in case its return type is a function type with default
381         // arguments.
382         MightBeFunction = false;
383         continue;
384       }
385       for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
386         ParmVarDecl *Param =
387           cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
388         if (Param->hasUnparsedDefaultArg()) {
389           CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
390           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
391             << SourceRange((*Toks)[1].getLocation(),
392                            Toks->back().getLocation());
393           delete Toks;
394           chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
395         } else if (Param->getDefaultArg()) {
396           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
397             << Param->getDefaultArg()->getSourceRange();
398           Param->setDefaultArg(0);
399         }
400       }
401     } else if (chunk.Kind != DeclaratorChunk::Paren) {
402       MightBeFunction = false;
403     }
404   }
405 }
406 
407 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
408 /// function, once we already know that they have the same
409 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
410 /// error, false otherwise.
411 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
412                                 Scope *S) {
413   bool Invalid = false;
414 
415   // C++ [dcl.fct.default]p4:
416   //   For non-template functions, default arguments can be added in
417   //   later declarations of a function in the same
418   //   scope. Declarations in different scopes have completely
419   //   distinct sets of default arguments. That is, declarations in
420   //   inner scopes do not acquire default arguments from
421   //   declarations in outer scopes, and vice versa. In a given
422   //   function declaration, all parameters subsequent to a
423   //   parameter with a default argument shall have default
424   //   arguments supplied in this or previous declarations. A
425   //   default argument shall not be redefined by a later
426   //   declaration (not even to the same value).
427   //
428   // C++ [dcl.fct.default]p6:
429   //   Except for member functions of class templates, the default arguments
430   //   in a member function definition that appears outside of the class
431   //   definition are added to the set of default arguments provided by the
432   //   member function declaration in the class definition.
433   for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
434     ParmVarDecl *OldParam = Old->getParamDecl(p);
435     ParmVarDecl *NewParam = New->getParamDecl(p);
436 
437     bool OldParamHasDfl = OldParam->hasDefaultArg();
438     bool NewParamHasDfl = NewParam->hasDefaultArg();
439 
440     NamedDecl *ND = Old;
441     if (S && !isDeclInScope(ND, New->getDeclContext(), S))
442       // Ignore default parameters of old decl if they are not in
443       // the same scope.
444       OldParamHasDfl = false;
445 
446     if (OldParamHasDfl && NewParamHasDfl) {
447 
448       unsigned DiagDefaultParamID =
449         diag::err_param_default_argument_redefinition;
450 
451       // MSVC accepts that default parameters be redefined for member functions
452       // of template class. The new default parameter's value is ignored.
453       Invalid = true;
454       if (getLangOpts().MicrosoftExt) {
455         CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
456         if (MD && MD->getParent()->getDescribedClassTemplate()) {
457           // Merge the old default argument into the new parameter.
458           NewParam->setHasInheritedDefaultArg();
459           if (OldParam->hasUninstantiatedDefaultArg())
460             NewParam->setUninstantiatedDefaultArg(
461                                       OldParam->getUninstantiatedDefaultArg());
462           else
463             NewParam->setDefaultArg(OldParam->getInit());
464           DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
465           Invalid = false;
466         }
467       }
468 
469       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
470       // hint here. Alternatively, we could walk the type-source information
471       // for NewParam to find the last source location in the type... but it
472       // isn't worth the effort right now. This is the kind of test case that
473       // is hard to get right:
474       //   int f(int);
475       //   void g(int (*fp)(int) = f);
476       //   void g(int (*fp)(int) = &f);
477       Diag(NewParam->getLocation(), DiagDefaultParamID)
478         << NewParam->getDefaultArgRange();
479 
480       // Look for the function declaration where the default argument was
481       // actually written, which may be a declaration prior to Old.
482       for (FunctionDecl *Older = Old->getPreviousDecl();
483            Older; Older = Older->getPreviousDecl()) {
484         if (!Older->getParamDecl(p)->hasDefaultArg())
485           break;
486 
487         OldParam = Older->getParamDecl(p);
488       }
489 
490       Diag(OldParam->getLocation(), diag::note_previous_definition)
491         << OldParam->getDefaultArgRange();
492     } else if (OldParamHasDfl) {
493       // Merge the old default argument into the new parameter.
494       // It's important to use getInit() here;  getDefaultArg()
495       // strips off any top-level ExprWithCleanups.
496       NewParam->setHasInheritedDefaultArg();
497       if (OldParam->hasUninstantiatedDefaultArg())
498         NewParam->setUninstantiatedDefaultArg(
499                                       OldParam->getUninstantiatedDefaultArg());
500       else
501         NewParam->setDefaultArg(OldParam->getInit());
502     } else if (NewParamHasDfl) {
503       if (New->getDescribedFunctionTemplate()) {
504         // Paragraph 4, quoted above, only applies to non-template functions.
505         Diag(NewParam->getLocation(),
506              diag::err_param_default_argument_template_redecl)
507           << NewParam->getDefaultArgRange();
508         Diag(Old->getLocation(), diag::note_template_prev_declaration)
509           << false;
510       } else if (New->getTemplateSpecializationKind()
511                    != TSK_ImplicitInstantiation &&
512                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
513         // C++ [temp.expr.spec]p21:
514         //   Default function arguments shall not be specified in a declaration
515         //   or a definition for one of the following explicit specializations:
516         //     - the explicit specialization of a function template;
517         //     - the explicit specialization of a member function template;
518         //     - the explicit specialization of a member function of a class
519         //       template where the class template specialization to which the
520         //       member function specialization belongs is implicitly
521         //       instantiated.
522         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
523           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
524           << New->getDeclName()
525           << NewParam->getDefaultArgRange();
526       } else if (New->getDeclContext()->isDependentContext()) {
527         // C++ [dcl.fct.default]p6 (DR217):
528         //   Default arguments for a member function of a class template shall
529         //   be specified on the initial declaration of the member function
530         //   within the class template.
531         //
532         // Reading the tea leaves a bit in DR217 and its reference to DR205
533         // leads me to the conclusion that one cannot add default function
534         // arguments for an out-of-line definition of a member function of a
535         // dependent type.
536         int WhichKind = 2;
537         if (CXXRecordDecl *Record
538               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
539           if (Record->getDescribedClassTemplate())
540             WhichKind = 0;
541           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
542             WhichKind = 1;
543           else
544             WhichKind = 2;
545         }
546 
547         Diag(NewParam->getLocation(),
548              diag::err_param_default_argument_member_template_redecl)
549           << WhichKind
550           << NewParam->getDefaultArgRange();
551       }
552     }
553   }
554 
555   // DR1344: If a default argument is added outside a class definition and that
556   // default argument makes the function a special member function, the program
557   // is ill-formed. This can only happen for constructors.
558   if (isa<CXXConstructorDecl>(New) &&
559       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
560     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
561                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
562     if (NewSM != OldSM) {
563       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
564       assert(NewParam->hasDefaultArg());
565       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
566         << NewParam->getDefaultArgRange() << NewSM;
567       Diag(Old->getLocation(), diag::note_previous_declaration);
568     }
569   }
570 
571   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
572   // template has a constexpr specifier then all its declarations shall
573   // contain the constexpr specifier.
574   if (New->isConstexpr() != Old->isConstexpr()) {
575     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
576       << New << New->isConstexpr();
577     Diag(Old->getLocation(), diag::note_previous_declaration);
578     Invalid = true;
579   }
580 
581   if (CheckEquivalentExceptionSpec(Old, New))
582     Invalid = true;
583 
584   return Invalid;
585 }
586 
587 /// \brief Merge the exception specifications of two variable declarations.
588 ///
589 /// This is called when there's a redeclaration of a VarDecl. The function
590 /// checks if the redeclaration might have an exception specification and
591 /// validates compatibility and merges the specs if necessary.
592 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
593   // Shortcut if exceptions are disabled.
594   if (!getLangOpts().CXXExceptions)
595     return;
596 
597   assert(Context.hasSameType(New->getType(), Old->getType()) &&
598          "Should only be called if types are otherwise the same.");
599 
600   QualType NewType = New->getType();
601   QualType OldType = Old->getType();
602 
603   // We're only interested in pointers and references to functions, as well
604   // as pointers to member functions.
605   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
606     NewType = R->getPointeeType();
607     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
608   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
609     NewType = P->getPointeeType();
610     OldType = OldType->getAs<PointerType>()->getPointeeType();
611   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
612     NewType = M->getPointeeType();
613     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
614   }
615 
616   if (!NewType->isFunctionProtoType())
617     return;
618 
619   // There's lots of special cases for functions. For function pointers, system
620   // libraries are hopefully not as broken so that we don't need these
621   // workarounds.
622   if (CheckEquivalentExceptionSpec(
623         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
624         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
625     New->setInvalidDecl();
626   }
627 }
628 
629 /// CheckCXXDefaultArguments - Verify that the default arguments for a
630 /// function declaration are well-formed according to C++
631 /// [dcl.fct.default].
632 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
633   unsigned NumParams = FD->getNumParams();
634   unsigned p;
635 
636   // Find first parameter with a default argument
637   for (p = 0; p < NumParams; ++p) {
638     ParmVarDecl *Param = FD->getParamDecl(p);
639     if (Param->hasDefaultArg())
640       break;
641   }
642 
643   // C++ [dcl.fct.default]p4:
644   //   In a given function declaration, all parameters
645   //   subsequent to a parameter with a default argument shall
646   //   have default arguments supplied in this or previous
647   //   declarations. A default argument shall not be redefined
648   //   by a later declaration (not even to the same value).
649   unsigned LastMissingDefaultArg = 0;
650   for (; p < NumParams; ++p) {
651     ParmVarDecl *Param = FD->getParamDecl(p);
652     if (!Param->hasDefaultArg()) {
653       if (Param->isInvalidDecl())
654         /* We already complained about this parameter. */;
655       else if (Param->getIdentifier())
656         Diag(Param->getLocation(),
657              diag::err_param_default_argument_missing_name)
658           << Param->getIdentifier();
659       else
660         Diag(Param->getLocation(),
661              diag::err_param_default_argument_missing);
662 
663       LastMissingDefaultArg = p;
664     }
665   }
666 
667   if (LastMissingDefaultArg > 0) {
668     // Some default arguments were missing. Clear out all of the
669     // default arguments up to (and including) the last missing
670     // default argument, so that we leave the function parameters
671     // in a semantically valid state.
672     for (p = 0; p <= LastMissingDefaultArg; ++p) {
673       ParmVarDecl *Param = FD->getParamDecl(p);
674       if (Param->hasDefaultArg()) {
675         Param->setDefaultArg(0);
676       }
677     }
678   }
679 }
680 
681 // CheckConstexprParameterTypes - Check whether a function's parameter types
682 // are all literal types. If so, return true. If not, produce a suitable
683 // diagnostic and return false.
684 static bool CheckConstexprParameterTypes(Sema &SemaRef,
685                                          const FunctionDecl *FD) {
686   unsigned ArgIndex = 0;
687   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
688   for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
689        e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
690     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
691     SourceLocation ParamLoc = PD->getLocation();
692     if (!(*i)->isDependentType() &&
693         SemaRef.RequireLiteralType(ParamLoc, *i,
694                                    diag::err_constexpr_non_literal_param,
695                                    ArgIndex+1, PD->getSourceRange(),
696                                    isa<CXXConstructorDecl>(FD)))
697       return false;
698   }
699   return true;
700 }
701 
702 /// \brief Get diagnostic %select index for tag kind for
703 /// record diagnostic message.
704 /// WARNING: Indexes apply to particular diagnostics only!
705 ///
706 /// \returns diagnostic %select index.
707 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
708   switch (Tag) {
709   case TTK_Struct: return 0;
710   case TTK_Interface: return 1;
711   case TTK_Class:  return 2;
712   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
713   }
714 }
715 
716 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
717 // the requirements of a constexpr function definition or a constexpr
718 // constructor definition. If so, return true. If not, produce appropriate
719 // diagnostics and return false.
720 //
721 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
722 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
723   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
724   if (MD && MD->isInstance()) {
725     // C++11 [dcl.constexpr]p4:
726     //  The definition of a constexpr constructor shall satisfy the following
727     //  constraints:
728     //  - the class shall not have any virtual base classes;
729     const CXXRecordDecl *RD = MD->getParent();
730     if (RD->getNumVBases()) {
731       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
732         << isa<CXXConstructorDecl>(NewFD)
733         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
734       for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
735              E = RD->vbases_end(); I != E; ++I)
736         Diag(I->getLocStart(),
737              diag::note_constexpr_virtual_base_here) << I->getSourceRange();
738       return false;
739     }
740   }
741 
742   if (!isa<CXXConstructorDecl>(NewFD)) {
743     // C++11 [dcl.constexpr]p3:
744     //  The definition of a constexpr function shall satisfy the following
745     //  constraints:
746     // - it shall not be virtual;
747     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
748     if (Method && Method->isVirtual()) {
749       Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
750 
751       // If it's not obvious why this function is virtual, find an overridden
752       // function which uses the 'virtual' keyword.
753       const CXXMethodDecl *WrittenVirtual = Method;
754       while (!WrittenVirtual->isVirtualAsWritten())
755         WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
756       if (WrittenVirtual != Method)
757         Diag(WrittenVirtual->getLocation(),
758              diag::note_overridden_virtual_function);
759       return false;
760     }
761 
762     // - its return type shall be a literal type;
763     QualType RT = NewFD->getResultType();
764     if (!RT->isDependentType() &&
765         RequireLiteralType(NewFD->getLocation(), RT,
766                            diag::err_constexpr_non_literal_return))
767       return false;
768   }
769 
770   // - each of its parameter types shall be a literal type;
771   if (!CheckConstexprParameterTypes(*this, NewFD))
772     return false;
773 
774   return true;
775 }
776 
777 /// Check the given declaration statement is legal within a constexpr function
778 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
779 ///
780 /// \return true if the body is OK (maybe only as an extension), false if we
781 ///         have diagnosed a problem.
782 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
783                                    DeclStmt *DS, SourceLocation &Cxx1yLoc) {
784   // C++11 [dcl.constexpr]p3 and p4:
785   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
786   //  contain only
787   for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
788          DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
789     switch ((*DclIt)->getKind()) {
790     case Decl::StaticAssert:
791     case Decl::Using:
792     case Decl::UsingShadow:
793     case Decl::UsingDirective:
794     case Decl::UnresolvedUsingTypename:
795     case Decl::UnresolvedUsingValue:
796       //   - static_assert-declarations
797       //   - using-declarations,
798       //   - using-directives,
799       continue;
800 
801     case Decl::Typedef:
802     case Decl::TypeAlias: {
803       //   - typedef declarations and alias-declarations that do not define
804       //     classes or enumerations,
805       TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
806       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
807         // Don't allow variably-modified types in constexpr functions.
808         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
809         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
810           << TL.getSourceRange() << TL.getType()
811           << isa<CXXConstructorDecl>(Dcl);
812         return false;
813       }
814       continue;
815     }
816 
817     case Decl::Enum:
818     case Decl::CXXRecord:
819       // C++1y allows types to be defined, not just declared.
820       if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition())
821         SemaRef.Diag(DS->getLocStart(),
822                      SemaRef.getLangOpts().CPlusPlus1y
823                        ? diag::warn_cxx11_compat_constexpr_type_definition
824                        : diag::ext_constexpr_type_definition)
825           << isa<CXXConstructorDecl>(Dcl);
826       continue;
827 
828     case Decl::EnumConstant:
829     case Decl::IndirectField:
830     case Decl::ParmVar:
831       // These can only appear with other declarations which are banned in
832       // C++11 and permitted in C++1y, so ignore them.
833       continue;
834 
835     case Decl::Var: {
836       // C++1y [dcl.constexpr]p3 allows anything except:
837       //   a definition of a variable of non-literal type or of static or
838       //   thread storage duration or for which no initialization is performed.
839       VarDecl *VD = cast<VarDecl>(*DclIt);
840       if (VD->isThisDeclarationADefinition()) {
841         if (VD->isStaticLocal()) {
842           SemaRef.Diag(VD->getLocation(),
843                        diag::err_constexpr_local_var_static)
844             << isa<CXXConstructorDecl>(Dcl)
845             << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
846           return false;
847         }
848         if (!VD->getType()->isDependentType() &&
849             SemaRef.RequireLiteralType(
850               VD->getLocation(), VD->getType(),
851               diag::err_constexpr_local_var_non_literal_type,
852               isa<CXXConstructorDecl>(Dcl)))
853           return false;
854         if (!VD->hasInit()) {
855           SemaRef.Diag(VD->getLocation(),
856                        diag::err_constexpr_local_var_no_init)
857             << isa<CXXConstructorDecl>(Dcl);
858           return false;
859         }
860       }
861       SemaRef.Diag(VD->getLocation(),
862                    SemaRef.getLangOpts().CPlusPlus1y
863                     ? diag::warn_cxx11_compat_constexpr_local_var
864                     : diag::ext_constexpr_local_var)
865         << isa<CXXConstructorDecl>(Dcl);
866       continue;
867     }
868 
869     case Decl::NamespaceAlias:
870     case Decl::Function:
871       // These are disallowed in C++11 and permitted in C++1y. Allow them
872       // everywhere as an extension.
873       if (!Cxx1yLoc.isValid())
874         Cxx1yLoc = DS->getLocStart();
875       continue;
876 
877     default:
878       SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
879         << isa<CXXConstructorDecl>(Dcl);
880       return false;
881     }
882   }
883 
884   return true;
885 }
886 
887 /// Check that the given field is initialized within a constexpr constructor.
888 ///
889 /// \param Dcl The constexpr constructor being checked.
890 /// \param Field The field being checked. This may be a member of an anonymous
891 ///        struct or union nested within the class being checked.
892 /// \param Inits All declarations, including anonymous struct/union members and
893 ///        indirect members, for which any initialization was provided.
894 /// \param Diagnosed Set to true if an error is produced.
895 static void CheckConstexprCtorInitializer(Sema &SemaRef,
896                                           const FunctionDecl *Dcl,
897                                           FieldDecl *Field,
898                                           llvm::SmallSet<Decl*, 16> &Inits,
899                                           bool &Diagnosed) {
900   if (Field->isUnnamedBitfield())
901     return;
902 
903   if (Field->isAnonymousStructOrUnion() &&
904       Field->getType()->getAsCXXRecordDecl()->isEmpty())
905     return;
906 
907   if (!Inits.count(Field)) {
908     if (!Diagnosed) {
909       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
910       Diagnosed = true;
911     }
912     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
913   } else if (Field->isAnonymousStructOrUnion()) {
914     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
915     for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
916          I != E; ++I)
917       // If an anonymous union contains an anonymous struct of which any member
918       // is initialized, all members must be initialized.
919       if (!RD->isUnion() || Inits.count(*I))
920         CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
921   }
922 }
923 
924 /// Check the provided statement is allowed in a constexpr function
925 /// definition.
926 static bool
927 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
928                            llvm::SmallVectorImpl<SourceLocation> &ReturnStmts,
929                            SourceLocation &Cxx1yLoc) {
930   // - its function-body shall be [...] a compound-statement that contains only
931   switch (S->getStmtClass()) {
932   case Stmt::NullStmtClass:
933     //   - null statements,
934     return true;
935 
936   case Stmt::DeclStmtClass:
937     //   - static_assert-declarations
938     //   - using-declarations,
939     //   - using-directives,
940     //   - typedef declarations and alias-declarations that do not define
941     //     classes or enumerations,
942     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
943       return false;
944     return true;
945 
946   case Stmt::ReturnStmtClass:
947     //   - and exactly one return statement;
948     if (isa<CXXConstructorDecl>(Dcl)) {
949       // C++1y allows return statements in constexpr constructors.
950       if (!Cxx1yLoc.isValid())
951         Cxx1yLoc = S->getLocStart();
952       return true;
953     }
954 
955     ReturnStmts.push_back(S->getLocStart());
956     return true;
957 
958   case Stmt::CompoundStmtClass: {
959     // C++1y allows compound-statements.
960     if (!Cxx1yLoc.isValid())
961       Cxx1yLoc = S->getLocStart();
962 
963     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
964     for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(),
965            BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) {
966       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts,
967                                       Cxx1yLoc))
968         return false;
969     }
970     return true;
971   }
972 
973   case Stmt::AttributedStmtClass:
974     if (!Cxx1yLoc.isValid())
975       Cxx1yLoc = S->getLocStart();
976     return true;
977 
978   case Stmt::IfStmtClass: {
979     // C++1y allows if-statements.
980     if (!Cxx1yLoc.isValid())
981       Cxx1yLoc = S->getLocStart();
982 
983     IfStmt *If = cast<IfStmt>(S);
984     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
985                                     Cxx1yLoc))
986       return false;
987     if (If->getElse() &&
988         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
989                                     Cxx1yLoc))
990       return false;
991     return true;
992   }
993 
994   case Stmt::WhileStmtClass:
995   case Stmt::DoStmtClass:
996   case Stmt::ForStmtClass:
997   case Stmt::CXXForRangeStmtClass:
998   case Stmt::ContinueStmtClass:
999     // C++1y allows all of these. We don't allow them as extensions in C++11,
1000     // because they don't make sense without variable mutation.
1001     if (!SemaRef.getLangOpts().CPlusPlus1y)
1002       break;
1003     if (!Cxx1yLoc.isValid())
1004       Cxx1yLoc = S->getLocStart();
1005     for (Stmt::child_range Children = S->children(); Children; ++Children)
1006       if (*Children &&
1007           !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1008                                       Cxx1yLoc))
1009         return false;
1010     return true;
1011 
1012   case Stmt::SwitchStmtClass:
1013   case Stmt::CaseStmtClass:
1014   case Stmt::DefaultStmtClass:
1015   case Stmt::BreakStmtClass:
1016     // C++1y allows switch-statements, and since they don't need variable
1017     // mutation, we can reasonably allow them in C++11 as an extension.
1018     if (!Cxx1yLoc.isValid())
1019       Cxx1yLoc = S->getLocStart();
1020     for (Stmt::child_range Children = S->children(); Children; ++Children)
1021       if (*Children &&
1022           !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1023                                       Cxx1yLoc))
1024         return false;
1025     return true;
1026 
1027   default:
1028     if (!isa<Expr>(S))
1029       break;
1030 
1031     // C++1y allows expression-statements.
1032     if (!Cxx1yLoc.isValid())
1033       Cxx1yLoc = S->getLocStart();
1034     return true;
1035   }
1036 
1037   SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1038     << isa<CXXConstructorDecl>(Dcl);
1039   return false;
1040 }
1041 
1042 /// Check the body for the given constexpr function declaration only contains
1043 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1044 ///
1045 /// \return true if the body is OK, false if we have diagnosed a problem.
1046 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1047   if (isa<CXXTryStmt>(Body)) {
1048     // C++11 [dcl.constexpr]p3:
1049     //  The definition of a constexpr function shall satisfy the following
1050     //  constraints: [...]
1051     // - its function-body shall be = delete, = default, or a
1052     //   compound-statement
1053     //
1054     // C++11 [dcl.constexpr]p4:
1055     //  In the definition of a constexpr constructor, [...]
1056     // - its function-body shall not be a function-try-block;
1057     Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1058       << isa<CXXConstructorDecl>(Dcl);
1059     return false;
1060   }
1061 
1062   SmallVector<SourceLocation, 4> ReturnStmts;
1063 
1064   // - its function-body shall be [...] a compound-statement that contains only
1065   //   [... list of cases ...]
1066   CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1067   SourceLocation Cxx1yLoc;
1068   for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
1069          BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
1070     if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc))
1071       return false;
1072   }
1073 
1074   if (Cxx1yLoc.isValid())
1075     Diag(Cxx1yLoc,
1076          getLangOpts().CPlusPlus1y
1077            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1078            : diag::ext_constexpr_body_invalid_stmt)
1079       << isa<CXXConstructorDecl>(Dcl);
1080 
1081   if (const CXXConstructorDecl *Constructor
1082         = dyn_cast<CXXConstructorDecl>(Dcl)) {
1083     const CXXRecordDecl *RD = Constructor->getParent();
1084     // DR1359:
1085     // - every non-variant non-static data member and base class sub-object
1086     //   shall be initialized;
1087     // - if the class is a non-empty union, or for each non-empty anonymous
1088     //   union member of a non-union class, exactly one non-static data member
1089     //   shall be initialized;
1090     if (RD->isUnion()) {
1091       if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
1092         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1093         return false;
1094       }
1095     } else if (!Constructor->isDependentContext() &&
1096                !Constructor->isDelegatingConstructor()) {
1097       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1098 
1099       // Skip detailed checking if we have enough initializers, and we would
1100       // allow at most one initializer per member.
1101       bool AnyAnonStructUnionMembers = false;
1102       unsigned Fields = 0;
1103       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1104            E = RD->field_end(); I != E; ++I, ++Fields) {
1105         if (I->isAnonymousStructOrUnion()) {
1106           AnyAnonStructUnionMembers = true;
1107           break;
1108         }
1109       }
1110       if (AnyAnonStructUnionMembers ||
1111           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1112         // Check initialization of non-static data members. Base classes are
1113         // always initialized so do not need to be checked. Dependent bases
1114         // might not have initializers in the member initializer list.
1115         llvm::SmallSet<Decl*, 16> Inits;
1116         for (CXXConstructorDecl::init_const_iterator
1117                I = Constructor->init_begin(), E = Constructor->init_end();
1118              I != E; ++I) {
1119           if (FieldDecl *FD = (*I)->getMember())
1120             Inits.insert(FD);
1121           else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
1122             Inits.insert(ID->chain_begin(), ID->chain_end());
1123         }
1124 
1125         bool Diagnosed = false;
1126         for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1127              E = RD->field_end(); I != E; ++I)
1128           CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
1129         if (Diagnosed)
1130           return false;
1131       }
1132     }
1133   } else {
1134     if (ReturnStmts.empty()) {
1135       // C++1y doesn't require constexpr functions to contain a 'return'
1136       // statement. We still do, unless the return type is void, because
1137       // otherwise if there's no return statement, the function cannot
1138       // be used in a core constant expression.
1139       bool OK = getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType();
1140       Diag(Dcl->getLocation(),
1141            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1142               : diag::err_constexpr_body_no_return);
1143       return OK;
1144     }
1145     if (ReturnStmts.size() > 1) {
1146       Diag(ReturnStmts.back(),
1147            getLangOpts().CPlusPlus1y
1148              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1149              : diag::ext_constexpr_body_multiple_return);
1150       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1151         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
1152     }
1153   }
1154 
1155   // C++11 [dcl.constexpr]p5:
1156   //   if no function argument values exist such that the function invocation
1157   //   substitution would produce a constant expression, the program is
1158   //   ill-formed; no diagnostic required.
1159   // C++11 [dcl.constexpr]p3:
1160   //   - every constructor call and implicit conversion used in initializing the
1161   //     return value shall be one of those allowed in a constant expression.
1162   // C++11 [dcl.constexpr]p4:
1163   //   - every constructor involved in initializing non-static data members and
1164   //     base class sub-objects shall be a constexpr constructor.
1165   SmallVector<PartialDiagnosticAt, 8> Diags;
1166   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
1167     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
1168       << isa<CXXConstructorDecl>(Dcl);
1169     for (size_t I = 0, N = Diags.size(); I != N; ++I)
1170       Diag(Diags[I].first, Diags[I].second);
1171     // Don't return false here: we allow this for compatibility in
1172     // system headers.
1173   }
1174 
1175   return true;
1176 }
1177 
1178 /// isCurrentClassName - Determine whether the identifier II is the
1179 /// name of the class type currently being defined. In the case of
1180 /// nested classes, this will only return true if II is the name of
1181 /// the innermost class.
1182 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1183                               const CXXScopeSpec *SS) {
1184   assert(getLangOpts().CPlusPlus && "No class names in C!");
1185 
1186   CXXRecordDecl *CurDecl;
1187   if (SS && SS->isSet() && !SS->isInvalid()) {
1188     DeclContext *DC = computeDeclContext(*SS, true);
1189     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1190   } else
1191     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1192 
1193   if (CurDecl && CurDecl->getIdentifier())
1194     return &II == CurDecl->getIdentifier();
1195   else
1196     return false;
1197 }
1198 
1199 /// \brief Determine whether the given class is a base class of the given
1200 /// class, including looking at dependent bases.
1201 static bool findCircularInheritance(const CXXRecordDecl *Class,
1202                                     const CXXRecordDecl *Current) {
1203   SmallVector<const CXXRecordDecl*, 8> Queue;
1204 
1205   Class = Class->getCanonicalDecl();
1206   while (true) {
1207     for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1208                                                   E = Current->bases_end();
1209          I != E; ++I) {
1210       CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1211       if (!Base)
1212         continue;
1213 
1214       Base = Base->getDefinition();
1215       if (!Base)
1216         continue;
1217 
1218       if (Base->getCanonicalDecl() == Class)
1219         return true;
1220 
1221       Queue.push_back(Base);
1222     }
1223 
1224     if (Queue.empty())
1225       return false;
1226 
1227     Current = Queue.back();
1228     Queue.pop_back();
1229   }
1230 
1231   return false;
1232 }
1233 
1234 /// \brief Check the validity of a C++ base class specifier.
1235 ///
1236 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1237 /// and returns NULL otherwise.
1238 CXXBaseSpecifier *
1239 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1240                          SourceRange SpecifierRange,
1241                          bool Virtual, AccessSpecifier Access,
1242                          TypeSourceInfo *TInfo,
1243                          SourceLocation EllipsisLoc) {
1244   QualType BaseType = TInfo->getType();
1245 
1246   // C++ [class.union]p1:
1247   //   A union shall not have base classes.
1248   if (Class->isUnion()) {
1249     Diag(Class->getLocation(), diag::err_base_clause_on_union)
1250       << SpecifierRange;
1251     return 0;
1252   }
1253 
1254   if (EllipsisLoc.isValid() &&
1255       !TInfo->getType()->containsUnexpandedParameterPack()) {
1256     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1257       << TInfo->getTypeLoc().getSourceRange();
1258     EllipsisLoc = SourceLocation();
1259   }
1260 
1261   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1262 
1263   if (BaseType->isDependentType()) {
1264     // Make sure that we don't have circular inheritance among our dependent
1265     // bases. For non-dependent bases, the check for completeness below handles
1266     // this.
1267     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1268       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1269           ((BaseDecl = BaseDecl->getDefinition()) &&
1270            findCircularInheritance(Class, BaseDecl))) {
1271         Diag(BaseLoc, diag::err_circular_inheritance)
1272           << BaseType << Context.getTypeDeclType(Class);
1273 
1274         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1275           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1276             << BaseType;
1277 
1278         return 0;
1279       }
1280     }
1281 
1282     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1283                                           Class->getTagKind() == TTK_Class,
1284                                           Access, TInfo, EllipsisLoc);
1285   }
1286 
1287   // Base specifiers must be record types.
1288   if (!BaseType->isRecordType()) {
1289     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1290     return 0;
1291   }
1292 
1293   // C++ [class.union]p1:
1294   //   A union shall not be used as a base class.
1295   if (BaseType->isUnionType()) {
1296     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1297     return 0;
1298   }
1299 
1300   // C++ [class.derived]p2:
1301   //   The class-name in a base-specifier shall not be an incompletely
1302   //   defined class.
1303   if (RequireCompleteType(BaseLoc, BaseType,
1304                           diag::err_incomplete_base_class, SpecifierRange)) {
1305     Class->setInvalidDecl();
1306     return 0;
1307   }
1308 
1309   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1310   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1311   assert(BaseDecl && "Record type has no declaration");
1312   BaseDecl = BaseDecl->getDefinition();
1313   assert(BaseDecl && "Base type is not incomplete, but has no definition");
1314   CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1315   assert(CXXBaseDecl && "Base type is not a C++ type");
1316 
1317   // C++ [class]p3:
1318   //   If a class is marked final and it appears as a base-type-specifier in
1319   //   base-clause, the program is ill-formed.
1320   if (CXXBaseDecl->hasAttr<FinalAttr>()) {
1321     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1322       << CXXBaseDecl->getDeclName();
1323     Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1324       << CXXBaseDecl->getDeclName();
1325     return 0;
1326   }
1327 
1328   if (BaseDecl->isInvalidDecl())
1329     Class->setInvalidDecl();
1330 
1331   // Create the base specifier.
1332   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1333                                         Class->getTagKind() == TTK_Class,
1334                                         Access, TInfo, EllipsisLoc);
1335 }
1336 
1337 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1338 /// one entry in the base class list of a class specifier, for
1339 /// example:
1340 ///    class foo : public bar, virtual private baz {
1341 /// 'public bar' and 'virtual private baz' are each base-specifiers.
1342 BaseResult
1343 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1344                          ParsedAttributes &Attributes,
1345                          bool Virtual, AccessSpecifier Access,
1346                          ParsedType basetype, SourceLocation BaseLoc,
1347                          SourceLocation EllipsisLoc) {
1348   if (!classdecl)
1349     return true;
1350 
1351   AdjustDeclIfTemplate(classdecl);
1352   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1353   if (!Class)
1354     return true;
1355 
1356   // We do not support any C++11 attributes on base-specifiers yet.
1357   // Diagnose any attributes we see.
1358   if (!Attributes.empty()) {
1359     for (AttributeList *Attr = Attributes.getList(); Attr;
1360          Attr = Attr->getNext()) {
1361       if (Attr->isInvalid() ||
1362           Attr->getKind() == AttributeList::IgnoredAttribute)
1363         continue;
1364       Diag(Attr->getLoc(),
1365            Attr->getKind() == AttributeList::UnknownAttribute
1366              ? diag::warn_unknown_attribute_ignored
1367              : diag::err_base_specifier_attribute)
1368         << Attr->getName();
1369     }
1370   }
1371 
1372   TypeSourceInfo *TInfo = 0;
1373   GetTypeFromParser(basetype, &TInfo);
1374 
1375   if (EllipsisLoc.isInvalid() &&
1376       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1377                                       UPPC_BaseType))
1378     return true;
1379 
1380   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1381                                                       Virtual, Access, TInfo,
1382                                                       EllipsisLoc))
1383     return BaseSpec;
1384   else
1385     Class->setInvalidDecl();
1386 
1387   return true;
1388 }
1389 
1390 /// \brief Performs the actual work of attaching the given base class
1391 /// specifiers to a C++ class.
1392 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1393                                 unsigned NumBases) {
1394  if (NumBases == 0)
1395     return false;
1396 
1397   // Used to keep track of which base types we have already seen, so
1398   // that we can properly diagnose redundant direct base types. Note
1399   // that the key is always the unqualified canonical type of the base
1400   // class.
1401   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1402 
1403   // Copy non-redundant base specifiers into permanent storage.
1404   unsigned NumGoodBases = 0;
1405   bool Invalid = false;
1406   for (unsigned idx = 0; idx < NumBases; ++idx) {
1407     QualType NewBaseType
1408       = Context.getCanonicalType(Bases[idx]->getType());
1409     NewBaseType = NewBaseType.getLocalUnqualifiedType();
1410 
1411     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1412     if (KnownBase) {
1413       // C++ [class.mi]p3:
1414       //   A class shall not be specified as a direct base class of a
1415       //   derived class more than once.
1416       Diag(Bases[idx]->getLocStart(),
1417            diag::err_duplicate_base_class)
1418         << KnownBase->getType()
1419         << Bases[idx]->getSourceRange();
1420 
1421       // Delete the duplicate base class specifier; we're going to
1422       // overwrite its pointer later.
1423       Context.Deallocate(Bases[idx]);
1424 
1425       Invalid = true;
1426     } else {
1427       // Okay, add this new base class.
1428       KnownBase = Bases[idx];
1429       Bases[NumGoodBases++] = Bases[idx];
1430       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1431         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1432         if (Class->isInterface() &&
1433               (!RD->isInterface() ||
1434                KnownBase->getAccessSpecifier() != AS_public)) {
1435           // The Microsoft extension __interface does not permit bases that
1436           // are not themselves public interfaces.
1437           Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1438             << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1439             << RD->getSourceRange();
1440           Invalid = true;
1441         }
1442         if (RD->hasAttr<WeakAttr>())
1443           Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1444       }
1445     }
1446   }
1447 
1448   // Attach the remaining base class specifiers to the derived class.
1449   Class->setBases(Bases, NumGoodBases);
1450 
1451   // Delete the remaining (good) base class specifiers, since their
1452   // data has been copied into the CXXRecordDecl.
1453   for (unsigned idx = 0; idx < NumGoodBases; ++idx)
1454     Context.Deallocate(Bases[idx]);
1455 
1456   return Invalid;
1457 }
1458 
1459 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
1460 /// class, after checking whether there are any duplicate base
1461 /// classes.
1462 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
1463                                unsigned NumBases) {
1464   if (!ClassDecl || !Bases || !NumBases)
1465     return;
1466 
1467   AdjustDeclIfTemplate(ClassDecl);
1468   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
1469                        (CXXBaseSpecifier**)(Bases), NumBases);
1470 }
1471 
1472 /// \brief Determine whether the type \p Derived is a C++ class that is
1473 /// derived from the type \p Base.
1474 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1475   if (!getLangOpts().CPlusPlus)
1476     return false;
1477 
1478   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1479   if (!DerivedRD)
1480     return false;
1481 
1482   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1483   if (!BaseRD)
1484     return false;
1485 
1486   // If either the base or the derived type is invalid, don't try to
1487   // check whether one is derived from the other.
1488   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1489     return false;
1490 
1491   // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
1492   return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
1493 }
1494 
1495 /// \brief Determine whether the type \p Derived is a C++ class that is
1496 /// derived from the type \p Base.
1497 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1498   if (!getLangOpts().CPlusPlus)
1499     return false;
1500 
1501   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1502   if (!DerivedRD)
1503     return false;
1504 
1505   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1506   if (!BaseRD)
1507     return false;
1508 
1509   return DerivedRD->isDerivedFrom(BaseRD, Paths);
1510 }
1511 
1512 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1513                               CXXCastPath &BasePathArray) {
1514   assert(BasePathArray.empty() && "Base path array must be empty!");
1515   assert(Paths.isRecordingPaths() && "Must record paths!");
1516 
1517   const CXXBasePath &Path = Paths.front();
1518 
1519   // We first go backward and check if we have a virtual base.
1520   // FIXME: It would be better if CXXBasePath had the base specifier for
1521   // the nearest virtual base.
1522   unsigned Start = 0;
1523   for (unsigned I = Path.size(); I != 0; --I) {
1524     if (Path[I - 1].Base->isVirtual()) {
1525       Start = I - 1;
1526       break;
1527     }
1528   }
1529 
1530   // Now add all bases.
1531   for (unsigned I = Start, E = Path.size(); I != E; ++I)
1532     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1533 }
1534 
1535 /// \brief Determine whether the given base path includes a virtual
1536 /// base class.
1537 bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1538   for (CXXCastPath::const_iterator B = BasePath.begin(),
1539                                 BEnd = BasePath.end();
1540        B != BEnd; ++B)
1541     if ((*B)->isVirtual())
1542       return true;
1543 
1544   return false;
1545 }
1546 
1547 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1548 /// conversion (where Derived and Base are class types) is
1549 /// well-formed, meaning that the conversion is unambiguous (and
1550 /// that all of the base classes are accessible). Returns true
1551 /// and emits a diagnostic if the code is ill-formed, returns false
1552 /// otherwise. Loc is the location where this routine should point to
1553 /// if there is an error, and Range is the source range to highlight
1554 /// if there is an error.
1555 bool
1556 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1557                                    unsigned InaccessibleBaseID,
1558                                    unsigned AmbigiousBaseConvID,
1559                                    SourceLocation Loc, SourceRange Range,
1560                                    DeclarationName Name,
1561                                    CXXCastPath *BasePath) {
1562   // First, determine whether the path from Derived to Base is
1563   // ambiguous. This is slightly more expensive than checking whether
1564   // the Derived to Base conversion exists, because here we need to
1565   // explore multiple paths to determine if there is an ambiguity.
1566   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1567                      /*DetectVirtual=*/false);
1568   bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1569   assert(DerivationOkay &&
1570          "Can only be used with a derived-to-base conversion");
1571   (void)DerivationOkay;
1572 
1573   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1574     if (InaccessibleBaseID) {
1575       // Check that the base class can be accessed.
1576       switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1577                                    InaccessibleBaseID)) {
1578         case AR_inaccessible:
1579           return true;
1580         case AR_accessible:
1581         case AR_dependent:
1582         case AR_delayed:
1583           break;
1584       }
1585     }
1586 
1587     // Build a base path if necessary.
1588     if (BasePath)
1589       BuildBasePathArray(Paths, *BasePath);
1590     return false;
1591   }
1592 
1593   // We know that the derived-to-base conversion is ambiguous, and
1594   // we're going to produce a diagnostic. Perform the derived-to-base
1595   // search just one more time to compute all of the possible paths so
1596   // that we can print them out. This is more expensive than any of
1597   // the previous derived-to-base checks we've done, but at this point
1598   // performance isn't as much of an issue.
1599   Paths.clear();
1600   Paths.setRecordingPaths(true);
1601   bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1602   assert(StillOkay && "Can only be used with a derived-to-base conversion");
1603   (void)StillOkay;
1604 
1605   // Build up a textual representation of the ambiguous paths, e.g.,
1606   // D -> B -> A, that will be used to illustrate the ambiguous
1607   // conversions in the diagnostic. We only print one of the paths
1608   // to each base class subobject.
1609   std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1610 
1611   Diag(Loc, AmbigiousBaseConvID)
1612   << Derived << Base << PathDisplayStr << Range << Name;
1613   return true;
1614 }
1615 
1616 bool
1617 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1618                                    SourceLocation Loc, SourceRange Range,
1619                                    CXXCastPath *BasePath,
1620                                    bool IgnoreAccess) {
1621   return CheckDerivedToBaseConversion(Derived, Base,
1622                                       IgnoreAccess ? 0
1623                                        : diag::err_upcast_to_inaccessible_base,
1624                                       diag::err_ambiguous_derived_to_base_conv,
1625                                       Loc, Range, DeclarationName(),
1626                                       BasePath);
1627 }
1628 
1629 
1630 /// @brief Builds a string representing ambiguous paths from a
1631 /// specific derived class to different subobjects of the same base
1632 /// class.
1633 ///
1634 /// This function builds a string that can be used in error messages
1635 /// to show the different paths that one can take through the
1636 /// inheritance hierarchy to go from the derived class to different
1637 /// subobjects of a base class. The result looks something like this:
1638 /// @code
1639 /// struct D -> struct B -> struct A
1640 /// struct D -> struct C -> struct A
1641 /// @endcode
1642 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1643   std::string PathDisplayStr;
1644   std::set<unsigned> DisplayedPaths;
1645   for (CXXBasePaths::paths_iterator Path = Paths.begin();
1646        Path != Paths.end(); ++Path) {
1647     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1648       // We haven't displayed a path to this particular base
1649       // class subobject yet.
1650       PathDisplayStr += "\n    ";
1651       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1652       for (CXXBasePath::const_iterator Element = Path->begin();
1653            Element != Path->end(); ++Element)
1654         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1655     }
1656   }
1657 
1658   return PathDisplayStr;
1659 }
1660 
1661 //===----------------------------------------------------------------------===//
1662 // C++ class member Handling
1663 //===----------------------------------------------------------------------===//
1664 
1665 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1666 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1667                                 SourceLocation ASLoc,
1668                                 SourceLocation ColonLoc,
1669                                 AttributeList *Attrs) {
1670   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1671   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1672                                                   ASLoc, ColonLoc);
1673   CurContext->addHiddenDecl(ASDecl);
1674   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1675 }
1676 
1677 /// CheckOverrideControl - Check C++11 override control semantics.
1678 void Sema::CheckOverrideControl(Decl *D) {
1679   if (D->isInvalidDecl())
1680     return;
1681 
1682   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1683 
1684   // Do we know which functions this declaration might be overriding?
1685   bool OverridesAreKnown = !MD ||
1686       (!MD->getParent()->hasAnyDependentBases() &&
1687        !MD->getType()->isDependentType());
1688 
1689   if (!MD || !MD->isVirtual()) {
1690     if (OverridesAreKnown) {
1691       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1692         Diag(OA->getLocation(),
1693              diag::override_keyword_only_allowed_on_virtual_member_functions)
1694           << "override" << FixItHint::CreateRemoval(OA->getLocation());
1695         D->dropAttr<OverrideAttr>();
1696       }
1697       if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1698         Diag(FA->getLocation(),
1699              diag::override_keyword_only_allowed_on_virtual_member_functions)
1700           << "final" << FixItHint::CreateRemoval(FA->getLocation());
1701         D->dropAttr<FinalAttr>();
1702       }
1703     }
1704     return;
1705   }
1706 
1707   if (!OverridesAreKnown)
1708     return;
1709 
1710   // C++11 [class.virtual]p5:
1711   //   If a virtual function is marked with the virt-specifier override and
1712   //   does not override a member function of a base class, the program is
1713   //   ill-formed.
1714   bool HasOverriddenMethods =
1715     MD->begin_overridden_methods() != MD->end_overridden_methods();
1716   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1717     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1718       << MD->getDeclName();
1719 }
1720 
1721 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1722 /// function overrides a virtual member function marked 'final', according to
1723 /// C++11 [class.virtual]p4.
1724 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1725                                                   const CXXMethodDecl *Old) {
1726   if (!Old->hasAttr<FinalAttr>())
1727     return false;
1728 
1729   Diag(New->getLocation(), diag::err_final_function_overridden)
1730     << New->getDeclName();
1731   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1732   return true;
1733 }
1734 
1735 static bool InitializationHasSideEffects(const FieldDecl &FD) {
1736   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1737   // FIXME: Destruction of ObjC lifetime types has side-effects.
1738   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1739     return !RD->isCompleteDefinition() ||
1740            !RD->hasTrivialDefaultConstructor() ||
1741            !RD->hasTrivialDestructor();
1742   return false;
1743 }
1744 
1745 static AttributeList *getMSPropertyAttr(AttributeList *list) {
1746   for (AttributeList* it = list; it != 0; it = it->getNext())
1747     if (it->isDeclspecPropertyAttribute())
1748       return it;
1749   return 0;
1750 }
1751 
1752 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1753 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1754 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
1755 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1756 /// present (but parsing it has been deferred).
1757 NamedDecl *
1758 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1759                                MultiTemplateParamsArg TemplateParameterLists,
1760                                Expr *BW, const VirtSpecifiers &VS,
1761                                InClassInitStyle InitStyle) {
1762   const DeclSpec &DS = D.getDeclSpec();
1763   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1764   DeclarationName Name = NameInfo.getName();
1765   SourceLocation Loc = NameInfo.getLoc();
1766 
1767   // For anonymous bitfields, the location should point to the type.
1768   if (Loc.isInvalid())
1769     Loc = D.getLocStart();
1770 
1771   Expr *BitWidth = static_cast<Expr*>(BW);
1772 
1773   assert(isa<CXXRecordDecl>(CurContext));
1774   assert(!DS.isFriendSpecified());
1775 
1776   bool isFunc = D.isDeclarationOfFunction();
1777 
1778   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1779     // The Microsoft extension __interface only permits public member functions
1780     // and prohibits constructors, destructors, operators, non-public member
1781     // functions, static methods and data members.
1782     unsigned InvalidDecl;
1783     bool ShowDeclName = true;
1784     if (!isFunc)
1785       InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1786     else if (AS != AS_public)
1787       InvalidDecl = 2;
1788     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1789       InvalidDecl = 3;
1790     else switch (Name.getNameKind()) {
1791       case DeclarationName::CXXConstructorName:
1792         InvalidDecl = 4;
1793         ShowDeclName = false;
1794         break;
1795 
1796       case DeclarationName::CXXDestructorName:
1797         InvalidDecl = 5;
1798         ShowDeclName = false;
1799         break;
1800 
1801       case DeclarationName::CXXOperatorName:
1802       case DeclarationName::CXXConversionFunctionName:
1803         InvalidDecl = 6;
1804         break;
1805 
1806       default:
1807         InvalidDecl = 0;
1808         break;
1809     }
1810 
1811     if (InvalidDecl) {
1812       if (ShowDeclName)
1813         Diag(Loc, diag::err_invalid_member_in_interface)
1814           << (InvalidDecl-1) << Name;
1815       else
1816         Diag(Loc, diag::err_invalid_member_in_interface)
1817           << (InvalidDecl-1) << "";
1818       return 0;
1819     }
1820   }
1821 
1822   // C++ 9.2p6: A member shall not be declared to have automatic storage
1823   // duration (auto, register) or with the extern storage-class-specifier.
1824   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1825   // data members and cannot be applied to names declared const or static,
1826   // and cannot be applied to reference members.
1827   switch (DS.getStorageClassSpec()) {
1828   case DeclSpec::SCS_unspecified:
1829   case DeclSpec::SCS_typedef:
1830   case DeclSpec::SCS_static:
1831     break;
1832   case DeclSpec::SCS_mutable:
1833     if (isFunc) {
1834       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
1835 
1836       // FIXME: It would be nicer if the keyword was ignored only for this
1837       // declarator. Otherwise we could get follow-up errors.
1838       D.getMutableDeclSpec().ClearStorageClassSpecs();
1839     }
1840     break;
1841   default:
1842     Diag(DS.getStorageClassSpecLoc(),
1843          diag::err_storageclass_invalid_for_member);
1844     D.getMutableDeclSpec().ClearStorageClassSpecs();
1845     break;
1846   }
1847 
1848   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1849                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
1850                       !isFunc);
1851 
1852   if (DS.isConstexprSpecified() && isInstField) {
1853     SemaDiagnosticBuilder B =
1854         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1855     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1856     if (InitStyle == ICIS_NoInit) {
1857       B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1858       D.getMutableDeclSpec().ClearConstexprSpec();
1859       const char *PrevSpec;
1860       unsigned DiagID;
1861       bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1862                                          PrevSpec, DiagID, getLangOpts());
1863       (void)Failed;
1864       assert(!Failed && "Making a constexpr member const shouldn't fail");
1865     } else {
1866       B << 1;
1867       const char *PrevSpec;
1868       unsigned DiagID;
1869       if (D.getMutableDeclSpec().SetStorageClassSpec(
1870           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
1871         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
1872                "This is the only DeclSpec that should fail to be applied");
1873         B << 1;
1874       } else {
1875         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1876         isInstField = false;
1877       }
1878     }
1879   }
1880 
1881   NamedDecl *Member;
1882   if (isInstField) {
1883     CXXScopeSpec &SS = D.getCXXScopeSpec();
1884 
1885     // Data members must have identifiers for names.
1886     if (!Name.isIdentifier()) {
1887       Diag(Loc, diag::err_bad_variable_name)
1888         << Name;
1889       return 0;
1890     }
1891 
1892     IdentifierInfo *II = Name.getAsIdentifierInfo();
1893 
1894     // Member field could not be with "template" keyword.
1895     // So TemplateParameterLists should be empty in this case.
1896     if (TemplateParameterLists.size()) {
1897       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
1898       if (TemplateParams->size()) {
1899         // There is no such thing as a member field template.
1900         Diag(D.getIdentifierLoc(), diag::err_template_member)
1901             << II
1902             << SourceRange(TemplateParams->getTemplateLoc(),
1903                 TemplateParams->getRAngleLoc());
1904       } else {
1905         // There is an extraneous 'template<>' for this member.
1906         Diag(TemplateParams->getTemplateLoc(),
1907             diag::err_template_member_noparams)
1908             << II
1909             << SourceRange(TemplateParams->getTemplateLoc(),
1910                 TemplateParams->getRAngleLoc());
1911       }
1912       return 0;
1913     }
1914 
1915     if (SS.isSet() && !SS.isInvalid()) {
1916       // The user provided a superfluous scope specifier inside a class
1917       // definition:
1918       //
1919       // class X {
1920       //   int X::member;
1921       // };
1922       if (DeclContext *DC = computeDeclContext(SS, false))
1923         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
1924       else
1925         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1926           << Name << SS.getRange();
1927 
1928       SS.clear();
1929     }
1930 
1931     AttributeList *MSPropertyAttr =
1932       getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
1933     if (MSPropertyAttr) {
1934       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1935                                 BitWidth, InitStyle, AS, MSPropertyAttr);
1936       isInstField = false;
1937     } else {
1938       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1939                                 BitWidth, InitStyle, AS);
1940     }
1941     assert(Member && "HandleField never returns null");
1942   } else {
1943     assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
1944 
1945     Member = HandleDeclarator(S, D, TemplateParameterLists);
1946     if (!Member) {
1947       return 0;
1948     }
1949 
1950     // Non-instance-fields can't have a bitfield.
1951     if (BitWidth) {
1952       if (Member->isInvalidDecl()) {
1953         // don't emit another diagnostic.
1954       } else if (isa<VarDecl>(Member)) {
1955         // C++ 9.6p3: A bit-field shall not be a static member.
1956         // "static member 'A' cannot be a bit-field"
1957         Diag(Loc, diag::err_static_not_bitfield)
1958           << Name << BitWidth->getSourceRange();
1959       } else if (isa<TypedefDecl>(Member)) {
1960         // "typedef member 'x' cannot be a bit-field"
1961         Diag(Loc, diag::err_typedef_not_bitfield)
1962           << Name << BitWidth->getSourceRange();
1963       } else {
1964         // A function typedef ("typedef int f(); f a;").
1965         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1966         Diag(Loc, diag::err_not_integral_type_bitfield)
1967           << Name << cast<ValueDecl>(Member)->getType()
1968           << BitWidth->getSourceRange();
1969       }
1970 
1971       BitWidth = 0;
1972       Member->setInvalidDecl();
1973     }
1974 
1975     Member->setAccess(AS);
1976 
1977     // If we have declared a member function template, set the access of the
1978     // templated declaration as well.
1979     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1980       FunTmpl->getTemplatedDecl()->setAccess(AS);
1981   }
1982 
1983   if (VS.isOverrideSpecified())
1984     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1985   if (VS.isFinalSpecified())
1986     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
1987 
1988   if (VS.getLastLocation().isValid()) {
1989     // Update the end location of a method that has a virt-specifiers.
1990     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1991       MD->setRangeEnd(VS.getLastLocation());
1992   }
1993 
1994   CheckOverrideControl(Member);
1995 
1996   assert((Name || isInstField) && "No identifier for non-field ?");
1997 
1998   if (isInstField) {
1999     FieldDecl *FD = cast<FieldDecl>(Member);
2000     FieldCollector->Add(FD);
2001 
2002     if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2003                                  FD->getLocation())
2004           != DiagnosticsEngine::Ignored) {
2005       // Remember all explicit private FieldDecls that have a name, no side
2006       // effects and are not part of a dependent type declaration.
2007       if (!FD->isImplicit() && FD->getDeclName() &&
2008           FD->getAccess() == AS_private &&
2009           !FD->hasAttr<UnusedAttr>() &&
2010           !FD->getParent()->isDependentContext() &&
2011           !InitializationHasSideEffects(*FD))
2012         UnusedPrivateFields.insert(FD);
2013     }
2014   }
2015 
2016   return Member;
2017 }
2018 
2019 namespace {
2020   class UninitializedFieldVisitor
2021       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2022     Sema &S;
2023     ValueDecl *VD;
2024   public:
2025     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2026     UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
2027                                                         S(S) {
2028       if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
2029         this->VD = IFD->getAnonField();
2030       else
2031         this->VD = VD;
2032     }
2033 
2034     void HandleExpr(Expr *E) {
2035       if (!E) return;
2036 
2037       // Expressions like x(x) sometimes lack the surrounding expressions
2038       // but need to be checked anyways.
2039       HandleValue(E);
2040       Visit(E);
2041     }
2042 
2043     void HandleValue(Expr *E) {
2044       E = E->IgnoreParens();
2045 
2046       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2047         if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2048           return;
2049 
2050         // FieldME is the inner-most MemberExpr that is not an anonymous struct
2051         // or union.
2052         MemberExpr *FieldME = ME;
2053 
2054         Expr *Base = E;
2055         while (isa<MemberExpr>(Base)) {
2056           ME = cast<MemberExpr>(Base);
2057 
2058           if (isa<VarDecl>(ME->getMemberDecl()))
2059             return;
2060 
2061           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2062             if (!FD->isAnonymousStructOrUnion())
2063               FieldME = ME;
2064 
2065           Base = ME->getBase();
2066         }
2067 
2068         if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
2069           unsigned diag = VD->getType()->isReferenceType()
2070               ? diag::warn_reference_field_is_uninit
2071               : diag::warn_field_is_uninit;
2072           S.Diag(FieldME->getExprLoc(), diag) << VD;
2073         }
2074         return;
2075       }
2076 
2077       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2078         HandleValue(CO->getTrueExpr());
2079         HandleValue(CO->getFalseExpr());
2080         return;
2081       }
2082 
2083       if (BinaryConditionalOperator *BCO =
2084               dyn_cast<BinaryConditionalOperator>(E)) {
2085         HandleValue(BCO->getCommon());
2086         HandleValue(BCO->getFalseExpr());
2087         return;
2088       }
2089 
2090       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2091         switch (BO->getOpcode()) {
2092         default:
2093           return;
2094         case(BO_PtrMemD):
2095         case(BO_PtrMemI):
2096           HandleValue(BO->getLHS());
2097           return;
2098         case(BO_Comma):
2099           HandleValue(BO->getRHS());
2100           return;
2101         }
2102       }
2103     }
2104 
2105     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2106       if (E->getCastKind() == CK_LValueToRValue)
2107         HandleValue(E->getSubExpr());
2108 
2109       Inherited::VisitImplicitCastExpr(E);
2110     }
2111 
2112     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2113       Expr *Callee = E->getCallee();
2114       if (isa<MemberExpr>(Callee))
2115         HandleValue(Callee);
2116 
2117       Inherited::VisitCXXMemberCallExpr(E);
2118     }
2119   };
2120   static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
2121                                                        ValueDecl *VD) {
2122     UninitializedFieldVisitor(S, VD).HandleExpr(E);
2123   }
2124 } // namespace
2125 
2126 /// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
2127 /// in-class initializer for a non-static C++ class member, and after
2128 /// instantiating an in-class initializer in a class template. Such actions
2129 /// are deferred until the class is complete.
2130 void
2131 Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
2132                                        Expr *InitExpr) {
2133   FieldDecl *FD = cast<FieldDecl>(D);
2134   assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2135          "must set init style when field is created");
2136 
2137   if (!InitExpr) {
2138     FD->setInvalidDecl();
2139     FD->removeInClassInitializer();
2140     return;
2141   }
2142 
2143   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2144     FD->setInvalidDecl();
2145     FD->removeInClassInitializer();
2146     return;
2147   }
2148 
2149   if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
2150       != DiagnosticsEngine::Ignored) {
2151     CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
2152   }
2153 
2154   ExprResult Init = InitExpr;
2155   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
2156     InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
2157     InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
2158         ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
2159         : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
2160     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2161     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
2162     if (Init.isInvalid()) {
2163       FD->setInvalidDecl();
2164       return;
2165     }
2166   }
2167 
2168   // C++11 [class.base.init]p7:
2169   //   The initialization of each base and member constitutes a
2170   //   full-expression.
2171   Init = ActOnFinishFullExpr(Init.take(), InitLoc);
2172   if (Init.isInvalid()) {
2173     FD->setInvalidDecl();
2174     return;
2175   }
2176 
2177   InitExpr = Init.release();
2178 
2179   FD->setInClassInitializer(InitExpr);
2180 }
2181 
2182 /// \brief Find the direct and/or virtual base specifiers that
2183 /// correspond to the given base type, for use in base initialization
2184 /// within a constructor.
2185 static bool FindBaseInitializer(Sema &SemaRef,
2186                                 CXXRecordDecl *ClassDecl,
2187                                 QualType BaseType,
2188                                 const CXXBaseSpecifier *&DirectBaseSpec,
2189                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
2190   // First, check for a direct base class.
2191   DirectBaseSpec = 0;
2192   for (CXXRecordDecl::base_class_const_iterator Base
2193          = ClassDecl->bases_begin();
2194        Base != ClassDecl->bases_end(); ++Base) {
2195     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2196       // We found a direct base of this type. That's what we're
2197       // initializing.
2198       DirectBaseSpec = &*Base;
2199       break;
2200     }
2201   }
2202 
2203   // Check for a virtual base class.
2204   // FIXME: We might be able to short-circuit this if we know in advance that
2205   // there are no virtual bases.
2206   VirtualBaseSpec = 0;
2207   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2208     // We haven't found a base yet; search the class hierarchy for a
2209     // virtual base class.
2210     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2211                        /*DetectVirtual=*/false);
2212     if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2213                               BaseType, Paths)) {
2214       for (CXXBasePaths::paths_iterator Path = Paths.begin();
2215            Path != Paths.end(); ++Path) {
2216         if (Path->back().Base->isVirtual()) {
2217           VirtualBaseSpec = Path->back().Base;
2218           break;
2219         }
2220       }
2221     }
2222   }
2223 
2224   return DirectBaseSpec || VirtualBaseSpec;
2225 }
2226 
2227 /// \brief Handle a C++ member initializer using braced-init-list syntax.
2228 MemInitResult
2229 Sema::ActOnMemInitializer(Decl *ConstructorD,
2230                           Scope *S,
2231                           CXXScopeSpec &SS,
2232                           IdentifierInfo *MemberOrBase,
2233                           ParsedType TemplateTypeTy,
2234                           const DeclSpec &DS,
2235                           SourceLocation IdLoc,
2236                           Expr *InitList,
2237                           SourceLocation EllipsisLoc) {
2238   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2239                              DS, IdLoc, InitList,
2240                              EllipsisLoc);
2241 }
2242 
2243 /// \brief Handle a C++ member initializer using parentheses syntax.
2244 MemInitResult
2245 Sema::ActOnMemInitializer(Decl *ConstructorD,
2246                           Scope *S,
2247                           CXXScopeSpec &SS,
2248                           IdentifierInfo *MemberOrBase,
2249                           ParsedType TemplateTypeTy,
2250                           const DeclSpec &DS,
2251                           SourceLocation IdLoc,
2252                           SourceLocation LParenLoc,
2253                           ArrayRef<Expr *> Args,
2254                           SourceLocation RParenLoc,
2255                           SourceLocation EllipsisLoc) {
2256   Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2257                                            Args, RParenLoc);
2258   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2259                              DS, IdLoc, List, EllipsisLoc);
2260 }
2261 
2262 namespace {
2263 
2264 // Callback to only accept typo corrections that can be a valid C++ member
2265 // intializer: either a non-static field member or a base class.
2266 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2267  public:
2268   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2269       : ClassDecl(ClassDecl) {}
2270 
2271   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2272     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2273       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2274         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2275       else
2276         return isa<TypeDecl>(ND);
2277     }
2278     return false;
2279   }
2280 
2281  private:
2282   CXXRecordDecl *ClassDecl;
2283 };
2284 
2285 }
2286 
2287 /// \brief Handle a C++ member initializer.
2288 MemInitResult
2289 Sema::BuildMemInitializer(Decl *ConstructorD,
2290                           Scope *S,
2291                           CXXScopeSpec &SS,
2292                           IdentifierInfo *MemberOrBase,
2293                           ParsedType TemplateTypeTy,
2294                           const DeclSpec &DS,
2295                           SourceLocation IdLoc,
2296                           Expr *Init,
2297                           SourceLocation EllipsisLoc) {
2298   if (!ConstructorD)
2299     return true;
2300 
2301   AdjustDeclIfTemplate(ConstructorD);
2302 
2303   CXXConstructorDecl *Constructor
2304     = dyn_cast<CXXConstructorDecl>(ConstructorD);
2305   if (!Constructor) {
2306     // The user wrote a constructor initializer on a function that is
2307     // not a C++ constructor. Ignore the error for now, because we may
2308     // have more member initializers coming; we'll diagnose it just
2309     // once in ActOnMemInitializers.
2310     return true;
2311   }
2312 
2313   CXXRecordDecl *ClassDecl = Constructor->getParent();
2314 
2315   // C++ [class.base.init]p2:
2316   //   Names in a mem-initializer-id are looked up in the scope of the
2317   //   constructor's class and, if not found in that scope, are looked
2318   //   up in the scope containing the constructor's definition.
2319   //   [Note: if the constructor's class contains a member with the
2320   //   same name as a direct or virtual base class of the class, a
2321   //   mem-initializer-id naming the member or base class and composed
2322   //   of a single identifier refers to the class member. A
2323   //   mem-initializer-id for the hidden base class may be specified
2324   //   using a qualified name. ]
2325   if (!SS.getScopeRep() && !TemplateTypeTy) {
2326     // Look for a member, first.
2327     DeclContext::lookup_result Result
2328       = ClassDecl->lookup(MemberOrBase);
2329     if (!Result.empty()) {
2330       ValueDecl *Member;
2331       if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2332           (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
2333         if (EllipsisLoc.isValid())
2334           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
2335             << MemberOrBase
2336             << SourceRange(IdLoc, Init->getSourceRange().getEnd());
2337 
2338         return BuildMemberInitializer(Member, Init, IdLoc);
2339       }
2340     }
2341   }
2342   // It didn't name a member, so see if it names a class.
2343   QualType BaseType;
2344   TypeSourceInfo *TInfo = 0;
2345 
2346   if (TemplateTypeTy) {
2347     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
2348   } else if (DS.getTypeSpecType() == TST_decltype) {
2349     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
2350   } else {
2351     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2352     LookupParsedName(R, S, &SS);
2353 
2354     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2355     if (!TyD) {
2356       if (R.isAmbiguous()) return true;
2357 
2358       // We don't want access-control diagnostics here.
2359       R.suppressDiagnostics();
2360 
2361       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2362         bool NotUnknownSpecialization = false;
2363         DeclContext *DC = computeDeclContext(SS, false);
2364         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2365           NotUnknownSpecialization = !Record->hasAnyDependentBases();
2366 
2367         if (!NotUnknownSpecialization) {
2368           // When the scope specifier can refer to a member of an unknown
2369           // specialization, we take it as a type name.
2370           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2371                                        SS.getWithLocInContext(Context),
2372                                        *MemberOrBase, IdLoc);
2373           if (BaseType.isNull())
2374             return true;
2375 
2376           R.clear();
2377           R.setLookupName(MemberOrBase);
2378         }
2379       }
2380 
2381       // If no results were found, try to correct typos.
2382       TypoCorrection Corr;
2383       MemInitializerValidatorCCC Validator(ClassDecl);
2384       if (R.empty() && BaseType.isNull() &&
2385           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2386                               Validator, ClassDecl))) {
2387         std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2388         std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
2389         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
2390           // We have found a non-static data member with a similar
2391           // name to what was typed; complain and initialize that
2392           // member.
2393           Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2394             << MemberOrBase << true << CorrectedQuotedStr
2395             << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2396           Diag(Member->getLocation(), diag::note_previous_decl)
2397             << CorrectedQuotedStr;
2398 
2399           return BuildMemberInitializer(Member, Init, IdLoc);
2400         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
2401           const CXXBaseSpecifier *DirectBaseSpec;
2402           const CXXBaseSpecifier *VirtualBaseSpec;
2403           if (FindBaseInitializer(*this, ClassDecl,
2404                                   Context.getTypeDeclType(Type),
2405                                   DirectBaseSpec, VirtualBaseSpec)) {
2406             // We have found a direct or virtual base class with a
2407             // similar name to what was typed; complain and initialize
2408             // that base class.
2409             Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2410               << MemberOrBase << false << CorrectedQuotedStr
2411               << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2412 
2413             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2414                                                              : VirtualBaseSpec;
2415             Diag(BaseSpec->getLocStart(),
2416                  diag::note_base_class_specified_here)
2417               << BaseSpec->getType()
2418               << BaseSpec->getSourceRange();
2419 
2420             TyD = Type;
2421           }
2422         }
2423       }
2424 
2425       if (!TyD && BaseType.isNull()) {
2426         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
2427           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
2428         return true;
2429       }
2430     }
2431 
2432     if (BaseType.isNull()) {
2433       BaseType = Context.getTypeDeclType(TyD);
2434       if (SS.isSet()) {
2435         NestedNameSpecifier *Qualifier =
2436           static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2437 
2438         // FIXME: preserve source range information
2439         BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
2440       }
2441     }
2442   }
2443 
2444   if (!TInfo)
2445     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
2446 
2447   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
2448 }
2449 
2450 /// Checks a member initializer expression for cases where reference (or
2451 /// pointer) members are bound to by-value parameters (or their addresses).
2452 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2453                                                Expr *Init,
2454                                                SourceLocation IdLoc) {
2455   QualType MemberTy = Member->getType();
2456 
2457   // We only handle pointers and references currently.
2458   // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2459   if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2460     return;
2461 
2462   const bool IsPointer = MemberTy->isPointerType();
2463   if (IsPointer) {
2464     if (const UnaryOperator *Op
2465           = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2466       // The only case we're worried about with pointers requires taking the
2467       // address.
2468       if (Op->getOpcode() != UO_AddrOf)
2469         return;
2470 
2471       Init = Op->getSubExpr();
2472     } else {
2473       // We only handle address-of expression initializers for pointers.
2474       return;
2475     }
2476   }
2477 
2478   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2479     // We only warn when referring to a non-reference parameter declaration.
2480     const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2481     if (!Parameter || Parameter->getType()->isReferenceType())
2482       return;
2483 
2484     S.Diag(Init->getExprLoc(),
2485            IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2486                      : diag::warn_bind_ref_member_to_parameter)
2487       << Member << Parameter << Init->getSourceRange();
2488   } else {
2489     // Other initializers are fine.
2490     return;
2491   }
2492 
2493   S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2494     << (unsigned)IsPointer;
2495 }
2496 
2497 MemInitResult
2498 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
2499                              SourceLocation IdLoc) {
2500   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2501   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2502   assert((DirectMember || IndirectMember) &&
2503          "Member must be a FieldDecl or IndirectFieldDecl");
2504 
2505   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2506     return true;
2507 
2508   if (Member->isInvalidDecl())
2509     return true;
2510 
2511   // Diagnose value-uses of fields to initialize themselves, e.g.
2512   //   foo(foo)
2513   // where foo is not also a parameter to the constructor.
2514   // TODO: implement -Wuninitialized and fold this into that framework.
2515   MultiExprArg Args;
2516   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2517     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2518   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2519     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
2520   } else {
2521     // Template instantiation doesn't reconstruct ParenListExprs for us.
2522     Args = Init;
2523   }
2524 
2525   if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2526         != DiagnosticsEngine::Ignored)
2527     for (unsigned i = 0, e = Args.size(); i != e; ++i)
2528       // FIXME: Warn about the case when other fields are used before being
2529       // initialized. For example, let this field be the i'th field. When
2530       // initializing the i'th field, throw a warning if any of the >= i'th
2531       // fields are used, as they are not yet initialized.
2532       // Right now we are only handling the case where the i'th field uses
2533       // itself in its initializer.
2534       // Also need to take into account that some fields may be initialized by
2535       // in-class initializers, see C++11 [class.base.init]p9.
2536       CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
2537 
2538   SourceRange InitRange = Init->getSourceRange();
2539 
2540   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
2541     // Can't check initialization for a member of dependent type or when
2542     // any of the arguments are type-dependent expressions.
2543     DiscardCleanupsInEvaluationContext();
2544   } else {
2545     bool InitList = false;
2546     if (isa<InitListExpr>(Init)) {
2547       InitList = true;
2548       Args = Init;
2549     }
2550 
2551     // Initialize the member.
2552     InitializedEntity MemberEntity =
2553       DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2554                    : InitializedEntity::InitializeMember(IndirectMember, 0);
2555     InitializationKind Kind =
2556       InitList ? InitializationKind::CreateDirectList(IdLoc)
2557                : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2558                                                   InitRange.getEnd());
2559 
2560     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2561     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
2562     if (MemberInit.isInvalid())
2563       return true;
2564 
2565     CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2566 
2567     // C++11 [class.base.init]p7:
2568     //   The initialization of each base and member constitutes a
2569     //   full-expression.
2570     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
2571     if (MemberInit.isInvalid())
2572       return true;
2573 
2574     Init = MemberInit.get();
2575   }
2576 
2577   if (DirectMember) {
2578     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2579                                             InitRange.getBegin(), Init,
2580                                             InitRange.getEnd());
2581   } else {
2582     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2583                                             InitRange.getBegin(), Init,
2584                                             InitRange.getEnd());
2585   }
2586 }
2587 
2588 MemInitResult
2589 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
2590                                  CXXRecordDecl *ClassDecl) {
2591   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
2592   if (!LangOpts.CPlusPlus11)
2593     return Diag(NameLoc, diag::err_delegating_ctor)
2594       << TInfo->getTypeLoc().getLocalSourceRange();
2595   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
2596 
2597   bool InitList = true;
2598   MultiExprArg Args = Init;
2599   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2600     InitList = false;
2601     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2602   }
2603 
2604   SourceRange InitRange = Init->getSourceRange();
2605   // Initialize the object.
2606   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2607                                      QualType(ClassDecl->getTypeForDecl(), 0));
2608   InitializationKind Kind =
2609     InitList ? InitializationKind::CreateDirectList(NameLoc)
2610              : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2611                                                 InitRange.getEnd());
2612   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
2613   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2614                                               Args, 0);
2615   if (DelegationInit.isInvalid())
2616     return true;
2617 
2618   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2619          "Delegating constructor with no target?");
2620 
2621   // C++11 [class.base.init]p7:
2622   //   The initialization of each base and member constitutes a
2623   //   full-expression.
2624   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2625                                        InitRange.getBegin());
2626   if (DelegationInit.isInvalid())
2627     return true;
2628 
2629   // If we are in a dependent context, template instantiation will
2630   // perform this type-checking again. Just save the arguments that we
2631   // received in a ParenListExpr.
2632   // FIXME: This isn't quite ideal, since our ASTs don't capture all
2633   // of the information that we have about the base
2634   // initializer. However, deconstructing the ASTs is a dicey process,
2635   // and this approach is far more likely to get the corner cases right.
2636   if (CurContext->isDependentContext())
2637     DelegationInit = Owned(Init);
2638 
2639   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
2640                                           DelegationInit.takeAs<Expr>(),
2641                                           InitRange.getEnd());
2642 }
2643 
2644 MemInitResult
2645 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
2646                            Expr *Init, CXXRecordDecl *ClassDecl,
2647                            SourceLocation EllipsisLoc) {
2648   SourceLocation BaseLoc
2649     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
2650 
2651   if (!BaseType->isDependentType() && !BaseType->isRecordType())
2652     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2653              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2654 
2655   // C++ [class.base.init]p2:
2656   //   [...] Unless the mem-initializer-id names a nonstatic data
2657   //   member of the constructor's class or a direct or virtual base
2658   //   of that class, the mem-initializer is ill-formed. A
2659   //   mem-initializer-list can initialize a base class using any
2660   //   name that denotes that base class type.
2661   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
2662 
2663   SourceRange InitRange = Init->getSourceRange();
2664   if (EllipsisLoc.isValid()) {
2665     // This is a pack expansion.
2666     if (!BaseType->containsUnexpandedParameterPack())  {
2667       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2668         << SourceRange(BaseLoc, InitRange.getEnd());
2669 
2670       EllipsisLoc = SourceLocation();
2671     }
2672   } else {
2673     // Check for any unexpanded parameter packs.
2674     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2675       return true;
2676 
2677     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2678       return true;
2679   }
2680 
2681   // Check for direct and virtual base classes.
2682   const CXXBaseSpecifier *DirectBaseSpec = 0;
2683   const CXXBaseSpecifier *VirtualBaseSpec = 0;
2684   if (!Dependent) {
2685     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2686                                        BaseType))
2687       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
2688 
2689     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2690                         VirtualBaseSpec);
2691 
2692     // C++ [base.class.init]p2:
2693     // Unless the mem-initializer-id names a nonstatic data member of the
2694     // constructor's class or a direct or virtual base of that class, the
2695     // mem-initializer is ill-formed.
2696     if (!DirectBaseSpec && !VirtualBaseSpec) {
2697       // If the class has any dependent bases, then it's possible that
2698       // one of those types will resolve to the same type as
2699       // BaseType. Therefore, just treat this as a dependent base
2700       // class initialization.  FIXME: Should we try to check the
2701       // initialization anyway? It seems odd.
2702       if (ClassDecl->hasAnyDependentBases())
2703         Dependent = true;
2704       else
2705         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2706           << BaseType << Context.getTypeDeclType(ClassDecl)
2707           << BaseTInfo->getTypeLoc().getLocalSourceRange();
2708     }
2709   }
2710 
2711   if (Dependent) {
2712     DiscardCleanupsInEvaluationContext();
2713 
2714     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2715                                             /*IsVirtual=*/false,
2716                                             InitRange.getBegin(), Init,
2717                                             InitRange.getEnd(), EllipsisLoc);
2718   }
2719 
2720   // C++ [base.class.init]p2:
2721   //   If a mem-initializer-id is ambiguous because it designates both
2722   //   a direct non-virtual base class and an inherited virtual base
2723   //   class, the mem-initializer is ill-formed.
2724   if (DirectBaseSpec && VirtualBaseSpec)
2725     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
2726       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2727 
2728   CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
2729   if (!BaseSpec)
2730     BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2731 
2732   // Initialize the base.
2733   bool InitList = true;
2734   MultiExprArg Args = Init;
2735   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2736     InitList = false;
2737     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2738   }
2739 
2740   InitializedEntity BaseEntity =
2741     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2742   InitializationKind Kind =
2743     InitList ? InitializationKind::CreateDirectList(BaseLoc)
2744              : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2745                                                 InitRange.getEnd());
2746   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2747   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
2748   if (BaseInit.isInvalid())
2749     return true;
2750 
2751   // C++11 [class.base.init]p7:
2752   //   The initialization of each base and member constitutes a
2753   //   full-expression.
2754   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
2755   if (BaseInit.isInvalid())
2756     return true;
2757 
2758   // If we are in a dependent context, template instantiation will
2759   // perform this type-checking again. Just save the arguments that we
2760   // received in a ParenListExpr.
2761   // FIXME: This isn't quite ideal, since our ASTs don't capture all
2762   // of the information that we have about the base
2763   // initializer. However, deconstructing the ASTs is a dicey process,
2764   // and this approach is far more likely to get the corner cases right.
2765   if (CurContext->isDependentContext())
2766     BaseInit = Owned(Init);
2767 
2768   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2769                                           BaseSpec->isVirtual(),
2770                                           InitRange.getBegin(),
2771                                           BaseInit.takeAs<Expr>(),
2772                                           InitRange.getEnd(), EllipsisLoc);
2773 }
2774 
2775 // Create a static_cast\<T&&>(expr).
2776 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2777   if (T.isNull()) T = E->getType();
2778   QualType TargetType = SemaRef.BuildReferenceType(
2779       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
2780   SourceLocation ExprLoc = E->getLocStart();
2781   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2782       TargetType, ExprLoc);
2783 
2784   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2785                                    SourceRange(ExprLoc, ExprLoc),
2786                                    E->getSourceRange()).take();
2787 }
2788 
2789 /// ImplicitInitializerKind - How an implicit base or member initializer should
2790 /// initialize its base or member.
2791 enum ImplicitInitializerKind {
2792   IIK_Default,
2793   IIK_Copy,
2794   IIK_Move,
2795   IIK_Inherit
2796 };
2797 
2798 static bool
2799 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2800                              ImplicitInitializerKind ImplicitInitKind,
2801                              CXXBaseSpecifier *BaseSpec,
2802                              bool IsInheritedVirtualBase,
2803                              CXXCtorInitializer *&CXXBaseInit) {
2804   InitializedEntity InitEntity
2805     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2806                                         IsInheritedVirtualBase);
2807 
2808   ExprResult BaseInit;
2809 
2810   switch (ImplicitInitKind) {
2811   case IIK_Inherit: {
2812     const CXXRecordDecl *Inherited =
2813         Constructor->getInheritedConstructor()->getParent();
2814     const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2815     if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2816       // C++11 [class.inhctor]p8:
2817       //   Each expression in the expression-list is of the form
2818       //   static_cast<T&&>(p), where p is the name of the corresponding
2819       //   constructor parameter and T is the declared type of p.
2820       SmallVector<Expr*, 16> Args;
2821       for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2822         ParmVarDecl *PD = Constructor->getParamDecl(I);
2823         ExprResult ArgExpr =
2824             SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2825                                      VK_LValue, SourceLocation());
2826         if (ArgExpr.isInvalid())
2827           return true;
2828         Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2829       }
2830 
2831       InitializationKind InitKind = InitializationKind::CreateDirect(
2832           Constructor->getLocation(), SourceLocation(), SourceLocation());
2833       InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
2834       BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
2835       break;
2836     }
2837   }
2838   // Fall through.
2839   case IIK_Default: {
2840     InitializationKind InitKind
2841       = InitializationKind::CreateDefault(Constructor->getLocation());
2842     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
2843     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
2844     break;
2845   }
2846 
2847   case IIK_Move:
2848   case IIK_Copy: {
2849     bool Moving = ImplicitInitKind == IIK_Move;
2850     ParmVarDecl *Param = Constructor->getParamDecl(0);
2851     QualType ParamType = Param->getType().getNonReferenceType();
2852 
2853     Expr *CopyCtorArg =
2854       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2855                           SourceLocation(), Param, false,
2856                           Constructor->getLocation(), ParamType,
2857                           VK_LValue, 0);
2858 
2859     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2860 
2861     // Cast to the base class to avoid ambiguities.
2862     QualType ArgTy =
2863       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2864                                        ParamType.getQualifiers());
2865 
2866     if (Moving) {
2867       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2868     }
2869 
2870     CXXCastPath BasePath;
2871     BasePath.push_back(BaseSpec);
2872     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2873                                             CK_UncheckedDerivedToBase,
2874                                             Moving ? VK_XValue : VK_LValue,
2875                                             &BasePath).take();
2876 
2877     InitializationKind InitKind
2878       = InitializationKind::CreateDirect(Constructor->getLocation(),
2879                                          SourceLocation(), SourceLocation());
2880     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
2881     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
2882     break;
2883   }
2884   }
2885 
2886   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
2887   if (BaseInit.isInvalid())
2888     return true;
2889 
2890   CXXBaseInit =
2891     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2892                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2893                                                         SourceLocation()),
2894                                              BaseSpec->isVirtual(),
2895                                              SourceLocation(),
2896                                              BaseInit.takeAs<Expr>(),
2897                                              SourceLocation(),
2898                                              SourceLocation());
2899 
2900   return false;
2901 }
2902 
2903 static bool RefersToRValueRef(Expr *MemRef) {
2904   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2905   return Referenced->getType()->isRValueReferenceType();
2906 }
2907 
2908 static bool
2909 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2910                                ImplicitInitializerKind ImplicitInitKind,
2911                                FieldDecl *Field, IndirectFieldDecl *Indirect,
2912                                CXXCtorInitializer *&CXXMemberInit) {
2913   if (Field->isInvalidDecl())
2914     return true;
2915 
2916   SourceLocation Loc = Constructor->getLocation();
2917 
2918   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2919     bool Moving = ImplicitInitKind == IIK_Move;
2920     ParmVarDecl *Param = Constructor->getParamDecl(0);
2921     QualType ParamType = Param->getType().getNonReferenceType();
2922 
2923     // Suppress copying zero-width bitfields.
2924     if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2925       return false;
2926 
2927     Expr *MemberExprBase =
2928       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2929                           SourceLocation(), Param, false,
2930                           Loc, ParamType, VK_LValue, 0);
2931 
2932     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2933 
2934     if (Moving) {
2935       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2936     }
2937 
2938     // Build a reference to this field within the parameter.
2939     CXXScopeSpec SS;
2940     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2941                               Sema::LookupMemberName);
2942     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2943                                   : cast<ValueDecl>(Field), AS_public);
2944     MemberLookup.resolveKind();
2945     ExprResult CtorArg
2946       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
2947                                          ParamType, Loc,
2948                                          /*IsArrow=*/false,
2949                                          SS,
2950                                          /*TemplateKWLoc=*/SourceLocation(),
2951                                          /*FirstQualifierInScope=*/0,
2952                                          MemberLookup,
2953                                          /*TemplateArgs=*/0);
2954     if (CtorArg.isInvalid())
2955       return true;
2956 
2957     // C++11 [class.copy]p15:
2958     //   - if a member m has rvalue reference type T&&, it is direct-initialized
2959     //     with static_cast<T&&>(x.m);
2960     if (RefersToRValueRef(CtorArg.get())) {
2961       CtorArg = CastForMoving(SemaRef, CtorArg.take());
2962     }
2963 
2964     // When the field we are copying is an array, create index variables for
2965     // each dimension of the array. We use these index variables to subscript
2966     // the source array, and other clients (e.g., CodeGen) will perform the
2967     // necessary iteration with these index variables.
2968     SmallVector<VarDecl *, 4> IndexVariables;
2969     QualType BaseType = Field->getType();
2970     QualType SizeType = SemaRef.Context.getSizeType();
2971     bool InitializingArray = false;
2972     while (const ConstantArrayType *Array
2973                           = SemaRef.Context.getAsConstantArrayType(BaseType)) {
2974       InitializingArray = true;
2975       // Create the iteration variable for this array index.
2976       IdentifierInfo *IterationVarName = 0;
2977       {
2978         SmallString<8> Str;
2979         llvm::raw_svector_ostream OS(Str);
2980         OS << "__i" << IndexVariables.size();
2981         IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2982       }
2983       VarDecl *IterationVar
2984         = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
2985                           IterationVarName, SizeType,
2986                         SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
2987                           SC_None);
2988       IndexVariables.push_back(IterationVar);
2989 
2990       // Create a reference to the iteration variable.
2991       ExprResult IterationVarRef
2992         = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
2993       assert(!IterationVarRef.isInvalid() &&
2994              "Reference to invented variable cannot fail!");
2995       IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2996       assert(!IterationVarRef.isInvalid() &&
2997              "Conversion of invented variable cannot fail!");
2998 
2999       // Subscript the array with this iteration variable.
3000       CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
3001                                                         IterationVarRef.take(),
3002                                                         Loc);
3003       if (CtorArg.isInvalid())
3004         return true;
3005 
3006       BaseType = Array->getElementType();
3007     }
3008 
3009     // The array subscript expression is an lvalue, which is wrong for moving.
3010     if (Moving && InitializingArray)
3011       CtorArg = CastForMoving(SemaRef, CtorArg.take());
3012 
3013     // Construct the entity that we will be initializing. For an array, this
3014     // will be first element in the array, which may require several levels
3015     // of array-subscript entities.
3016     SmallVector<InitializedEntity, 4> Entities;
3017     Entities.reserve(1 + IndexVariables.size());
3018     if (Indirect)
3019       Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3020     else
3021       Entities.push_back(InitializedEntity::InitializeMember(Field));
3022     for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3023       Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3024                                                               0,
3025                                                               Entities.back()));
3026 
3027     // Direct-initialize to use the copy constructor.
3028     InitializationKind InitKind =
3029       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3030 
3031     Expr *CtorArgE = CtorArg.takeAs<Expr>();
3032     InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
3033 
3034     ExprResult MemberInit
3035       = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
3036                         MultiExprArg(&CtorArgE, 1));
3037     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3038     if (MemberInit.isInvalid())
3039       return true;
3040 
3041     if (Indirect) {
3042       assert(IndexVariables.size() == 0 &&
3043              "Indirect field improperly initialized");
3044       CXXMemberInit
3045         = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3046                                                    Loc, Loc,
3047                                                    MemberInit.takeAs<Expr>(),
3048                                                    Loc);
3049     } else
3050       CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3051                                                  Loc, MemberInit.takeAs<Expr>(),
3052                                                  Loc,
3053                                                  IndexVariables.data(),
3054                                                  IndexVariables.size());
3055     return false;
3056   }
3057 
3058   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3059          "Unhandled implicit init kind!");
3060 
3061   QualType FieldBaseElementType =
3062     SemaRef.Context.getBaseElementType(Field->getType());
3063 
3064   if (FieldBaseElementType->isRecordType()) {
3065     InitializedEntity InitEntity
3066       = Indirect? InitializedEntity::InitializeMember(Indirect)
3067                 : InitializedEntity::InitializeMember(Field);
3068     InitializationKind InitKind =
3069       InitializationKind::CreateDefault(Loc);
3070 
3071     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3072     ExprResult MemberInit =
3073       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3074 
3075     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3076     if (MemberInit.isInvalid())
3077       return true;
3078 
3079     if (Indirect)
3080       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3081                                                                Indirect, Loc,
3082                                                                Loc,
3083                                                                MemberInit.get(),
3084                                                                Loc);
3085     else
3086       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3087                                                                Field, Loc, Loc,
3088                                                                MemberInit.get(),
3089                                                                Loc);
3090     return false;
3091   }
3092 
3093   if (!Field->getParent()->isUnion()) {
3094     if (FieldBaseElementType->isReferenceType()) {
3095       SemaRef.Diag(Constructor->getLocation(),
3096                    diag::err_uninitialized_member_in_ctor)
3097       << (int)Constructor->isImplicit()
3098       << SemaRef.Context.getTagDeclType(Constructor->getParent())
3099       << 0 << Field->getDeclName();
3100       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3101       return true;
3102     }
3103 
3104     if (FieldBaseElementType.isConstQualified()) {
3105       SemaRef.Diag(Constructor->getLocation(),
3106                    diag::err_uninitialized_member_in_ctor)
3107       << (int)Constructor->isImplicit()
3108       << SemaRef.Context.getTagDeclType(Constructor->getParent())
3109       << 1 << Field->getDeclName();
3110       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3111       return true;
3112     }
3113   }
3114 
3115   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
3116       FieldBaseElementType->isObjCRetainableType() &&
3117       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3118       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
3119     // ARC:
3120     //   Default-initialize Objective-C pointers to NULL.
3121     CXXMemberInit
3122       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3123                                                  Loc, Loc,
3124                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3125                                                  Loc);
3126     return false;
3127   }
3128 
3129   // Nothing to initialize.
3130   CXXMemberInit = 0;
3131   return false;
3132 }
3133 
3134 namespace {
3135 struct BaseAndFieldInfo {
3136   Sema &S;
3137   CXXConstructorDecl *Ctor;
3138   bool AnyErrorsInInits;
3139   ImplicitInitializerKind IIK;
3140   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
3141   SmallVector<CXXCtorInitializer*, 8> AllToInit;
3142 
3143   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3144     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
3145     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3146     if (Generated && Ctor->isCopyConstructor())
3147       IIK = IIK_Copy;
3148     else if (Generated && Ctor->isMoveConstructor())
3149       IIK = IIK_Move;
3150     else if (Ctor->getInheritedConstructor())
3151       IIK = IIK_Inherit;
3152     else
3153       IIK = IIK_Default;
3154   }
3155 
3156   bool isImplicitCopyOrMove() const {
3157     switch (IIK) {
3158     case IIK_Copy:
3159     case IIK_Move:
3160       return true;
3161 
3162     case IIK_Default:
3163     case IIK_Inherit:
3164       return false;
3165     }
3166 
3167     llvm_unreachable("Invalid ImplicitInitializerKind!");
3168   }
3169 
3170   bool addFieldInitializer(CXXCtorInitializer *Init) {
3171     AllToInit.push_back(Init);
3172 
3173     // Check whether this initializer makes the field "used".
3174     if (Init->getInit()->HasSideEffects(S.Context))
3175       S.UnusedPrivateFields.remove(Init->getAnyMember());
3176 
3177     return false;
3178   }
3179 };
3180 }
3181 
3182 /// \brief Determine whether the given indirect field declaration is somewhere
3183 /// within an anonymous union.
3184 static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3185   for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3186                                       CEnd = F->chain_end();
3187        C != CEnd; ++C)
3188     if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3189       if (Record->isUnion())
3190         return true;
3191 
3192   return false;
3193 }
3194 
3195 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
3196 /// array type.
3197 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3198   if (T->isIncompleteArrayType())
3199     return true;
3200 
3201   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3202     if (!ArrayT->getSize())
3203       return true;
3204 
3205     T = ArrayT->getElementType();
3206   }
3207 
3208   return false;
3209 }
3210 
3211 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
3212                                     FieldDecl *Field,
3213                                     IndirectFieldDecl *Indirect = 0) {
3214 
3215   // Overwhelmingly common case: we have a direct initializer for this field.
3216   if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3217     return Info.addFieldInitializer(Init);
3218 
3219   // C++11 [class.base.init]p8: if the entity is a non-static data member that
3220   // has a brace-or-equal-initializer, the entity is initialized as specified
3221   // in [dcl.init].
3222   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
3223     Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3224                                            Info.Ctor->getLocation(), Field);
3225     CXXCtorInitializer *Init;
3226     if (Indirect)
3227       Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3228                                                       SourceLocation(),
3229                                                       SourceLocation(), DIE,
3230                                                       SourceLocation());
3231     else
3232       Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3233                                                       SourceLocation(),
3234                                                       SourceLocation(), DIE,
3235                                                       SourceLocation());
3236     return Info.addFieldInitializer(Init);
3237   }
3238 
3239   // Don't build an implicit initializer for union members if none was
3240   // explicitly specified.
3241   if (Field->getParent()->isUnion() ||
3242       (Indirect && isWithinAnonymousUnion(Indirect)))
3243     return false;
3244 
3245   // Don't initialize incomplete or zero-length arrays.
3246   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3247     return false;
3248 
3249   // Don't try to build an implicit initializer if there were semantic
3250   // errors in any of the initializers (and therefore we might be
3251   // missing some that the user actually wrote).
3252   if (Info.AnyErrorsInInits || Field->isInvalidDecl())
3253     return false;
3254 
3255   CXXCtorInitializer *Init = 0;
3256   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3257                                      Indirect, Init))
3258     return true;
3259 
3260   if (!Init)
3261     return false;
3262 
3263   return Info.addFieldInitializer(Init);
3264 }
3265 
3266 bool
3267 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3268                                CXXCtorInitializer *Initializer) {
3269   assert(Initializer->isDelegatingInitializer());
3270   Constructor->setNumCtorInitializers(1);
3271   CXXCtorInitializer **initializer =
3272     new (Context) CXXCtorInitializer*[1];
3273   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3274   Constructor->setCtorInitializers(initializer);
3275 
3276   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
3277     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
3278     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3279   }
3280 
3281   DelegatingCtorDecls.push_back(Constructor);
3282 
3283   return false;
3284 }
3285 
3286 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3287                                ArrayRef<CXXCtorInitializer *> Initializers) {
3288   if (Constructor->isDependentContext()) {
3289     // Just store the initializers as written, they will be checked during
3290     // instantiation.
3291     if (!Initializers.empty()) {
3292       Constructor->setNumCtorInitializers(Initializers.size());
3293       CXXCtorInitializer **baseOrMemberInitializers =
3294         new (Context) CXXCtorInitializer*[Initializers.size()];
3295       memcpy(baseOrMemberInitializers, Initializers.data(),
3296              Initializers.size() * sizeof(CXXCtorInitializer*));
3297       Constructor->setCtorInitializers(baseOrMemberInitializers);
3298     }
3299 
3300     // Let template instantiation know whether we had errors.
3301     if (AnyErrors)
3302       Constructor->setInvalidDecl();
3303 
3304     return false;
3305   }
3306 
3307   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
3308 
3309   // We need to build the initializer AST according to order of construction
3310   // and not what user specified in the Initializers list.
3311   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
3312   if (!ClassDecl)
3313     return true;
3314 
3315   bool HadError = false;
3316 
3317   for (unsigned i = 0; i < Initializers.size(); i++) {
3318     CXXCtorInitializer *Member = Initializers[i];
3319 
3320     if (Member->isBaseInitializer())
3321       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
3322     else
3323       Info.AllBaseFields[Member->getAnyMember()] = Member;
3324   }
3325 
3326   // Keep track of the direct virtual bases.
3327   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3328   for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3329        E = ClassDecl->bases_end(); I != E; ++I) {
3330     if (I->isVirtual())
3331       DirectVBases.insert(I);
3332   }
3333 
3334   // Push virtual bases before others.
3335   for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3336        E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3337 
3338     if (CXXCtorInitializer *Value
3339         = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3340       Info.AllToInit.push_back(Value);
3341     } else if (!AnyErrors) {
3342       bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
3343       CXXCtorInitializer *CXXBaseInit;
3344       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3345                                        VBase, IsInheritedVirtualBase,
3346                                        CXXBaseInit)) {
3347         HadError = true;
3348         continue;
3349       }
3350 
3351       Info.AllToInit.push_back(CXXBaseInit);
3352     }
3353   }
3354 
3355   // Non-virtual bases.
3356   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3357        E = ClassDecl->bases_end(); Base != E; ++Base) {
3358     // Virtuals are in the virtual base list and already constructed.
3359     if (Base->isVirtual())
3360       continue;
3361 
3362     if (CXXCtorInitializer *Value
3363           = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3364       Info.AllToInit.push_back(Value);
3365     } else if (!AnyErrors) {
3366       CXXCtorInitializer *CXXBaseInit;
3367       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3368                                        Base, /*IsInheritedVirtualBase=*/false,
3369                                        CXXBaseInit)) {
3370         HadError = true;
3371         continue;
3372       }
3373 
3374       Info.AllToInit.push_back(CXXBaseInit);
3375     }
3376   }
3377 
3378   // Fields.
3379   for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3380                                MemEnd = ClassDecl->decls_end();
3381        Mem != MemEnd; ++Mem) {
3382     if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
3383       // C++ [class.bit]p2:
3384       //   A declaration for a bit-field that omits the identifier declares an
3385       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
3386       //   initialized.
3387       if (F->isUnnamedBitfield())
3388         continue;
3389 
3390       // If we're not generating the implicit copy/move constructor, then we'll
3391       // handle anonymous struct/union fields based on their individual
3392       // indirect fields.
3393       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
3394         continue;
3395 
3396       if (CollectFieldInitializer(*this, Info, F))
3397         HadError = true;
3398       continue;
3399     }
3400 
3401     // Beyond this point, we only consider default initialization.
3402     if (Info.isImplicitCopyOrMove())
3403       continue;
3404 
3405     if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3406       if (F->getType()->isIncompleteArrayType()) {
3407         assert(ClassDecl->hasFlexibleArrayMember() &&
3408                "Incomplete array type is not valid");
3409         continue;
3410       }
3411 
3412       // Initialize each field of an anonymous struct individually.
3413       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3414         HadError = true;
3415 
3416       continue;
3417     }
3418   }
3419 
3420   unsigned NumInitializers = Info.AllToInit.size();
3421   if (NumInitializers > 0) {
3422     Constructor->setNumCtorInitializers(NumInitializers);
3423     CXXCtorInitializer **baseOrMemberInitializers =
3424       new (Context) CXXCtorInitializer*[NumInitializers];
3425     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
3426            NumInitializers * sizeof(CXXCtorInitializer*));
3427     Constructor->setCtorInitializers(baseOrMemberInitializers);
3428 
3429     // Constructors implicitly reference the base and member
3430     // destructors.
3431     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3432                                            Constructor->getParent());
3433   }
3434 
3435   return HadError;
3436 }
3437 
3438 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
3439   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
3440     const RecordDecl *RD = RT->getDecl();
3441     if (RD->isAnonymousStructOrUnion()) {
3442       for (RecordDecl::field_iterator Field = RD->field_begin(),
3443           E = RD->field_end(); Field != E; ++Field)
3444         PopulateKeysForFields(*Field, IdealInits);
3445       return;
3446     }
3447   }
3448   IdealInits.push_back(Field);
3449 }
3450 
3451 static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3452   return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
3453 }
3454 
3455 static void *GetKeyForMember(ASTContext &Context,
3456                              CXXCtorInitializer *Member) {
3457   if (!Member->isAnyMemberInitializer())
3458     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
3459 
3460   return Member->getAnyMember();
3461 }
3462 
3463 static void DiagnoseBaseOrMemInitializerOrder(
3464     Sema &SemaRef, const CXXConstructorDecl *Constructor,
3465     ArrayRef<CXXCtorInitializer *> Inits) {
3466   if (Constructor->getDeclContext()->isDependentContext())
3467     return;
3468 
3469   // Don't check initializers order unless the warning is enabled at the
3470   // location of at least one initializer.
3471   bool ShouldCheckOrder = false;
3472   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3473     CXXCtorInitializer *Init = Inits[InitIndex];
3474     if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3475                                          Init->getSourceLocation())
3476           != DiagnosticsEngine::Ignored) {
3477       ShouldCheckOrder = true;
3478       break;
3479     }
3480   }
3481   if (!ShouldCheckOrder)
3482     return;
3483 
3484   // Build the list of bases and members in the order that they'll
3485   // actually be initialized.  The explicit initializers should be in
3486   // this same order but may be missing things.
3487   SmallVector<const void*, 32> IdealInitKeys;
3488 
3489   const CXXRecordDecl *ClassDecl = Constructor->getParent();
3490 
3491   // 1. Virtual bases.
3492   for (CXXRecordDecl::base_class_const_iterator VBase =
3493        ClassDecl->vbases_begin(),
3494        E = ClassDecl->vbases_end(); VBase != E; ++VBase)
3495     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
3496 
3497   // 2. Non-virtual bases.
3498   for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
3499        E = ClassDecl->bases_end(); Base != E; ++Base) {
3500     if (Base->isVirtual())
3501       continue;
3502     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
3503   }
3504 
3505   // 3. Direct fields.
3506   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3507        E = ClassDecl->field_end(); Field != E; ++Field) {
3508     if (Field->isUnnamedBitfield())
3509       continue;
3510 
3511     PopulateKeysForFields(*Field, IdealInitKeys);
3512   }
3513 
3514   unsigned NumIdealInits = IdealInitKeys.size();
3515   unsigned IdealIndex = 0;
3516 
3517   CXXCtorInitializer *PrevInit = 0;
3518   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3519     CXXCtorInitializer *Init = Inits[InitIndex];
3520     void *InitKey = GetKeyForMember(SemaRef.Context, Init);
3521 
3522     // Scan forward to try to find this initializer in the idealized
3523     // initializers list.
3524     for (; IdealIndex != NumIdealInits; ++IdealIndex)
3525       if (InitKey == IdealInitKeys[IdealIndex])
3526         break;
3527 
3528     // If we didn't find this initializer, it must be because we
3529     // scanned past it on a previous iteration.  That can only
3530     // happen if we're out of order;  emit a warning.
3531     if (IdealIndex == NumIdealInits && PrevInit) {
3532       Sema::SemaDiagnosticBuilder D =
3533         SemaRef.Diag(PrevInit->getSourceLocation(),
3534                      diag::warn_initializer_out_of_order);
3535 
3536       if (PrevInit->isAnyMemberInitializer())
3537         D << 0 << PrevInit->getAnyMember()->getDeclName();
3538       else
3539         D << 1 << PrevInit->getTypeSourceInfo()->getType();
3540 
3541       if (Init->isAnyMemberInitializer())
3542         D << 0 << Init->getAnyMember()->getDeclName();
3543       else
3544         D << 1 << Init->getTypeSourceInfo()->getType();
3545 
3546       // Move back to the initializer's location in the ideal list.
3547       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3548         if (InitKey == IdealInitKeys[IdealIndex])
3549           break;
3550 
3551       assert(IdealIndex != NumIdealInits &&
3552              "initializer not found in initializer list");
3553     }
3554 
3555     PrevInit = Init;
3556   }
3557 }
3558 
3559 namespace {
3560 bool CheckRedundantInit(Sema &S,
3561                         CXXCtorInitializer *Init,
3562                         CXXCtorInitializer *&PrevInit) {
3563   if (!PrevInit) {
3564     PrevInit = Init;
3565     return false;
3566   }
3567 
3568   if (FieldDecl *Field = Init->getAnyMember())
3569     S.Diag(Init->getSourceLocation(),
3570            diag::err_multiple_mem_initialization)
3571       << Field->getDeclName()
3572       << Init->getSourceRange();
3573   else {
3574     const Type *BaseClass = Init->getBaseClass();
3575     assert(BaseClass && "neither field nor base");
3576     S.Diag(Init->getSourceLocation(),
3577            diag::err_multiple_base_initialization)
3578       << QualType(BaseClass, 0)
3579       << Init->getSourceRange();
3580   }
3581   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3582     << 0 << PrevInit->getSourceRange();
3583 
3584   return true;
3585 }
3586 
3587 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
3588 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3589 
3590 bool CheckRedundantUnionInit(Sema &S,
3591                              CXXCtorInitializer *Init,
3592                              RedundantUnionMap &Unions) {
3593   FieldDecl *Field = Init->getAnyMember();
3594   RecordDecl *Parent = Field->getParent();
3595   NamedDecl *Child = Field;
3596 
3597   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
3598     if (Parent->isUnion()) {
3599       UnionEntry &En = Unions[Parent];
3600       if (En.first && En.first != Child) {
3601         S.Diag(Init->getSourceLocation(),
3602                diag::err_multiple_mem_union_initialization)
3603           << Field->getDeclName()
3604           << Init->getSourceRange();
3605         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3606           << 0 << En.second->getSourceRange();
3607         return true;
3608       }
3609       if (!En.first) {
3610         En.first = Child;
3611         En.second = Init;
3612       }
3613       if (!Parent->isAnonymousStructOrUnion())
3614         return false;
3615     }
3616 
3617     Child = Parent;
3618     Parent = cast<RecordDecl>(Parent->getDeclContext());
3619   }
3620 
3621   return false;
3622 }
3623 }
3624 
3625 /// ActOnMemInitializers - Handle the member initializers for a constructor.
3626 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
3627                                 SourceLocation ColonLoc,
3628                                 ArrayRef<CXXCtorInitializer*> MemInits,
3629                                 bool AnyErrors) {
3630   if (!ConstructorDecl)
3631     return;
3632 
3633   AdjustDeclIfTemplate(ConstructorDecl);
3634 
3635   CXXConstructorDecl *Constructor
3636     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
3637 
3638   if (!Constructor) {
3639     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3640     return;
3641   }
3642 
3643   // Mapping for the duplicate initializers check.
3644   // For member initializers, this is keyed with a FieldDecl*.
3645   // For base initializers, this is keyed with a Type*.
3646   llvm::DenseMap<void*, CXXCtorInitializer *> Members;
3647 
3648   // Mapping for the inconsistent anonymous-union initializers check.
3649   RedundantUnionMap MemberUnions;
3650 
3651   bool HadError = false;
3652   for (unsigned i = 0; i < MemInits.size(); i++) {
3653     CXXCtorInitializer *Init = MemInits[i];
3654 
3655     // Set the source order index.
3656     Init->setSourceOrder(i);
3657 
3658     if (Init->isAnyMemberInitializer()) {
3659       FieldDecl *Field = Init->getAnyMember();
3660       if (CheckRedundantInit(*this, Init, Members[Field]) ||
3661           CheckRedundantUnionInit(*this, Init, MemberUnions))
3662         HadError = true;
3663     } else if (Init->isBaseInitializer()) {
3664       void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3665       if (CheckRedundantInit(*this, Init, Members[Key]))
3666         HadError = true;
3667     } else {
3668       assert(Init->isDelegatingInitializer());
3669       // This must be the only initializer
3670       if (MemInits.size() != 1) {
3671         Diag(Init->getSourceLocation(),
3672              diag::err_delegating_initializer_alone)
3673           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
3674         // We will treat this as being the only initializer.
3675       }
3676       SetDelegatingInitializer(Constructor, MemInits[i]);
3677       // Return immediately as the initializer is set.
3678       return;
3679     }
3680   }
3681 
3682   if (HadError)
3683     return;
3684 
3685   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
3686 
3687   SetCtorInitializers(Constructor, AnyErrors, MemInits);
3688 }
3689 
3690 void
3691 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3692                                              CXXRecordDecl *ClassDecl) {
3693   // Ignore dependent contexts. Also ignore unions, since their members never
3694   // have destructors implicitly called.
3695   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
3696     return;
3697 
3698   // FIXME: all the access-control diagnostics are positioned on the
3699   // field/base declaration.  That's probably good; that said, the
3700   // user might reasonably want to know why the destructor is being
3701   // emitted, and we currently don't say.
3702 
3703   // Non-static data members.
3704   for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3705        E = ClassDecl->field_end(); I != E; ++I) {
3706     FieldDecl *Field = *I;
3707     if (Field->isInvalidDecl())
3708       continue;
3709 
3710     // Don't destroy incomplete or zero-length arrays.
3711     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3712       continue;
3713 
3714     QualType FieldType = Context.getBaseElementType(Field->getType());
3715 
3716     const RecordType* RT = FieldType->getAs<RecordType>();
3717     if (!RT)
3718       continue;
3719 
3720     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3721     if (FieldClassDecl->isInvalidDecl())
3722       continue;
3723     if (FieldClassDecl->hasIrrelevantDestructor())
3724       continue;
3725     // The destructor for an implicit anonymous union member is never invoked.
3726     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3727       continue;
3728 
3729     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
3730     assert(Dtor && "No dtor found for FieldClassDecl!");
3731     CheckDestructorAccess(Field->getLocation(), Dtor,
3732                           PDiag(diag::err_access_dtor_field)
3733                             << Field->getDeclName()
3734                             << FieldType);
3735 
3736     MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3737     DiagnoseUseOfDecl(Dtor, Location);
3738   }
3739 
3740   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3741 
3742   // Bases.
3743   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3744        E = ClassDecl->bases_end(); Base != E; ++Base) {
3745     // Bases are always records in a well-formed non-dependent class.
3746     const RecordType *RT = Base->getType()->getAs<RecordType>();
3747 
3748     // Remember direct virtual bases.
3749     if (Base->isVirtual())
3750       DirectVirtualBases.insert(RT);
3751 
3752     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3753     // If our base class is invalid, we probably can't get its dtor anyway.
3754     if (BaseClassDecl->isInvalidDecl())
3755       continue;
3756     if (BaseClassDecl->hasIrrelevantDestructor())
3757       continue;
3758 
3759     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3760     assert(Dtor && "No dtor found for BaseClassDecl!");
3761 
3762     // FIXME: caret should be on the start of the class name
3763     CheckDestructorAccess(Base->getLocStart(), Dtor,
3764                           PDiag(diag::err_access_dtor_base)
3765                             << Base->getType()
3766                             << Base->getSourceRange(),
3767                           Context.getTypeDeclType(ClassDecl));
3768 
3769     MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3770     DiagnoseUseOfDecl(Dtor, Location);
3771   }
3772 
3773   // Virtual bases.
3774   for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3775        E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3776 
3777     // Bases are always records in a well-formed non-dependent class.
3778     const RecordType *RT = VBase->getType()->castAs<RecordType>();
3779 
3780     // Ignore direct virtual bases.
3781     if (DirectVirtualBases.count(RT))
3782       continue;
3783 
3784     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3785     // If our base class is invalid, we probably can't get its dtor anyway.
3786     if (BaseClassDecl->isInvalidDecl())
3787       continue;
3788     if (BaseClassDecl->hasIrrelevantDestructor())
3789       continue;
3790 
3791     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3792     assert(Dtor && "No dtor found for BaseClassDecl!");
3793     CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
3794                           PDiag(diag::err_access_dtor_vbase)
3795                             << VBase->getType(),
3796                           Context.getTypeDeclType(ClassDecl));
3797 
3798     MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3799     DiagnoseUseOfDecl(Dtor, Location);
3800   }
3801 }
3802 
3803 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
3804   if (!CDtorDecl)
3805     return;
3806 
3807   if (CXXConstructorDecl *Constructor
3808       = dyn_cast<CXXConstructorDecl>(CDtorDecl))
3809     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
3810 }
3811 
3812 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3813                                   unsigned DiagID, AbstractDiagSelID SelID) {
3814   class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3815     unsigned DiagID;
3816     AbstractDiagSelID SelID;
3817 
3818   public:
3819     NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3820       : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3821 
3822     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
3823       if (Suppressed) return;
3824       if (SelID == -1)
3825         S.Diag(Loc, DiagID) << T;
3826       else
3827         S.Diag(Loc, DiagID) << SelID << T;
3828     }
3829   } Diagnoser(DiagID, SelID);
3830 
3831   return RequireNonAbstractType(Loc, T, Diagnoser);
3832 }
3833 
3834 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3835                                   TypeDiagnoser &Diagnoser) {
3836   if (!getLangOpts().CPlusPlus)
3837     return false;
3838 
3839   if (const ArrayType *AT = Context.getAsArrayType(T))
3840     return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
3841 
3842   if (const PointerType *PT = T->getAs<PointerType>()) {
3843     // Find the innermost pointer type.
3844     while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
3845       PT = T;
3846 
3847     if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
3848       return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
3849   }
3850 
3851   const RecordType *RT = T->getAs<RecordType>();
3852   if (!RT)
3853     return false;
3854 
3855   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3856 
3857   // We can't answer whether something is abstract until it has a
3858   // definition.  If it's currently being defined, we'll walk back
3859   // over all the declarations when we have a full definition.
3860   const CXXRecordDecl *Def = RD->getDefinition();
3861   if (!Def || Def->isBeingDefined())
3862     return false;
3863 
3864   if (!RD->isAbstract())
3865     return false;
3866 
3867   Diagnoser.diagnose(*this, Loc, T);
3868   DiagnoseAbstractType(RD);
3869 
3870   return true;
3871 }
3872 
3873 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3874   // Check if we've already emitted the list of pure virtual functions
3875   // for this class.
3876   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
3877     return;
3878 
3879   CXXFinalOverriderMap FinalOverriders;
3880   RD->getFinalOverriders(FinalOverriders);
3881 
3882   // Keep a set of seen pure methods so we won't diagnose the same method
3883   // more than once.
3884   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3885 
3886   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3887                                    MEnd = FinalOverriders.end();
3888        M != MEnd;
3889        ++M) {
3890     for (OverridingMethods::iterator SO = M->second.begin(),
3891                                   SOEnd = M->second.end();
3892          SO != SOEnd; ++SO) {
3893       // C++ [class.abstract]p4:
3894       //   A class is abstract if it contains or inherits at least one
3895       //   pure virtual function for which the final overrider is pure
3896       //   virtual.
3897 
3898       //
3899       if (SO->second.size() != 1)
3900         continue;
3901 
3902       if (!SO->second.front().Method->isPure())
3903         continue;
3904 
3905       if (!SeenPureMethods.insert(SO->second.front().Method))
3906         continue;
3907 
3908       Diag(SO->second.front().Method->getLocation(),
3909            diag::note_pure_virtual_function)
3910         << SO->second.front().Method->getDeclName() << RD->getDeclName();
3911     }
3912   }
3913 
3914   if (!PureVirtualClassDiagSet)
3915     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3916   PureVirtualClassDiagSet->insert(RD);
3917 }
3918 
3919 namespace {
3920 struct AbstractUsageInfo {
3921   Sema &S;
3922   CXXRecordDecl *Record;
3923   CanQualType AbstractType;
3924   bool Invalid;
3925 
3926   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3927     : S(S), Record(Record),
3928       AbstractType(S.Context.getCanonicalType(
3929                    S.Context.getTypeDeclType(Record))),
3930       Invalid(false) {}
3931 
3932   void DiagnoseAbstractType() {
3933     if (Invalid) return;
3934     S.DiagnoseAbstractType(Record);
3935     Invalid = true;
3936   }
3937 
3938   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3939 };
3940 
3941 struct CheckAbstractUsage {
3942   AbstractUsageInfo &Info;
3943   const NamedDecl *Ctx;
3944 
3945   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3946     : Info(Info), Ctx(Ctx) {}
3947 
3948   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3949     switch (TL.getTypeLocClass()) {
3950 #define ABSTRACT_TYPELOC(CLASS, PARENT)
3951 #define TYPELOC(CLASS, PARENT) \
3952     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
3953 #include "clang/AST/TypeLocNodes.def"
3954     }
3955   }
3956 
3957   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3958     Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3959     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3960       if (!TL.getArg(I))
3961         continue;
3962 
3963       TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3964       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
3965     }
3966   }
3967 
3968   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3969     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3970   }
3971 
3972   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3973     // Visit the type parameters from a permissive context.
3974     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3975       TemplateArgumentLoc TAL = TL.getArgLoc(I);
3976       if (TAL.getArgument().getKind() == TemplateArgument::Type)
3977         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3978           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3979       // TODO: other template argument types?
3980     }
3981   }
3982 
3983   // Visit pointee types from a permissive context.
3984 #define CheckPolymorphic(Type) \
3985   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3986     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3987   }
3988   CheckPolymorphic(PointerTypeLoc)
3989   CheckPolymorphic(ReferenceTypeLoc)
3990   CheckPolymorphic(MemberPointerTypeLoc)
3991   CheckPolymorphic(BlockPointerTypeLoc)
3992   CheckPolymorphic(AtomicTypeLoc)
3993 
3994   /// Handle all the types we haven't given a more specific
3995   /// implementation for above.
3996   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3997     // Every other kind of type that we haven't called out already
3998     // that has an inner type is either (1) sugar or (2) contains that
3999     // inner type in some way as a subobject.
4000     if (TypeLoc Next = TL.getNextTypeLoc())
4001       return Visit(Next, Sel);
4002 
4003     // If there's no inner type and we're in a permissive context,
4004     // don't diagnose.
4005     if (Sel == Sema::AbstractNone) return;
4006 
4007     // Check whether the type matches the abstract type.
4008     QualType T = TL.getType();
4009     if (T->isArrayType()) {
4010       Sel = Sema::AbstractArrayType;
4011       T = Info.S.Context.getBaseElementType(T);
4012     }
4013     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4014     if (CT != Info.AbstractType) return;
4015 
4016     // It matched; do some magic.
4017     if (Sel == Sema::AbstractArrayType) {
4018       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4019         << T << TL.getSourceRange();
4020     } else {
4021       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4022         << Sel << T << TL.getSourceRange();
4023     }
4024     Info.DiagnoseAbstractType();
4025   }
4026 };
4027 
4028 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4029                                   Sema::AbstractDiagSelID Sel) {
4030   CheckAbstractUsage(*this, D).Visit(TL, Sel);
4031 }
4032 
4033 }
4034 
4035 /// Check for invalid uses of an abstract type in a method declaration.
4036 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4037                                     CXXMethodDecl *MD) {
4038   // No need to do the check on definitions, which require that
4039   // the return/param types be complete.
4040   if (MD->doesThisDeclarationHaveABody())
4041     return;
4042 
4043   // For safety's sake, just ignore it if we don't have type source
4044   // information.  This should never happen for non-implicit methods,
4045   // but...
4046   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4047     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4048 }
4049 
4050 /// Check for invalid uses of an abstract type within a class definition.
4051 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4052                                     CXXRecordDecl *RD) {
4053   for (CXXRecordDecl::decl_iterator
4054          I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
4055     Decl *D = *I;
4056     if (D->isImplicit()) continue;
4057 
4058     // Methods and method templates.
4059     if (isa<CXXMethodDecl>(D)) {
4060       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4061     } else if (isa<FunctionTemplateDecl>(D)) {
4062       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4063       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4064 
4065     // Fields and static variables.
4066     } else if (isa<FieldDecl>(D)) {
4067       FieldDecl *FD = cast<FieldDecl>(D);
4068       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4069         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4070     } else if (isa<VarDecl>(D)) {
4071       VarDecl *VD = cast<VarDecl>(D);
4072       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4073         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4074 
4075     // Nested classes and class templates.
4076     } else if (isa<CXXRecordDecl>(D)) {
4077       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4078     } else if (isa<ClassTemplateDecl>(D)) {
4079       CheckAbstractClassUsage(Info,
4080                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4081     }
4082   }
4083 }
4084 
4085 /// \brief Perform semantic checks on a class definition that has been
4086 /// completing, introducing implicitly-declared members, checking for
4087 /// abstract types, etc.
4088 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
4089   if (!Record)
4090     return;
4091 
4092   if (Record->isAbstract() && !Record->isInvalidDecl()) {
4093     AbstractUsageInfo Info(*this, Record);
4094     CheckAbstractClassUsage(Info, Record);
4095   }
4096 
4097   // If this is not an aggregate type and has no user-declared constructor,
4098   // complain about any non-static data members of reference or const scalar
4099   // type, since they will never get initializers.
4100   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
4101       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4102       !Record->isLambda()) {
4103     bool Complained = false;
4104     for (RecordDecl::field_iterator F = Record->field_begin(),
4105                                  FEnd = Record->field_end();
4106          F != FEnd; ++F) {
4107       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
4108         continue;
4109 
4110       if (F->getType()->isReferenceType() ||
4111           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
4112         if (!Complained) {
4113           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4114             << Record->getTagKind() << Record;
4115           Complained = true;
4116         }
4117 
4118         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4119           << F->getType()->isReferenceType()
4120           << F->getDeclName();
4121       }
4122     }
4123   }
4124 
4125   if (Record->isDynamicClass() && !Record->isDependentType())
4126     DynamicClasses.push_back(Record);
4127 
4128   if (Record->getIdentifier()) {
4129     // C++ [class.mem]p13:
4130     //   If T is the name of a class, then each of the following shall have a
4131     //   name different from T:
4132     //     - every member of every anonymous union that is a member of class T.
4133     //
4134     // C++ [class.mem]p14:
4135     //   In addition, if class T has a user-declared constructor (12.1), every
4136     //   non-static data member of class T shall have a name different from T.
4137     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4138     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4139          ++I) {
4140       NamedDecl *D = *I;
4141       if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4142           isa<IndirectFieldDecl>(D)) {
4143         Diag(D->getLocation(), diag::err_member_name_of_class)
4144           << D->getDeclName();
4145         break;
4146       }
4147     }
4148   }
4149 
4150   // Warn if the class has virtual methods but non-virtual public destructor.
4151   if (Record->isPolymorphic() && !Record->isDependentType()) {
4152     CXXDestructorDecl *dtor = Record->getDestructor();
4153     if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
4154       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4155            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4156   }
4157 
4158   if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
4159     Diag(Record->getLocation(), diag::warn_abstract_final_class);
4160     DiagnoseAbstractType(Record);
4161   }
4162 
4163   if (!Record->isDependentType()) {
4164     for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4165                                      MEnd = Record->method_end();
4166          M != MEnd; ++M) {
4167       // See if a method overloads virtual methods in a base
4168       // class without overriding any.
4169       if (!M->isStatic())
4170         DiagnoseHiddenVirtualMethods(Record, *M);
4171 
4172       // Check whether the explicitly-defaulted special members are valid.
4173       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4174         CheckExplicitlyDefaultedSpecialMember(*M);
4175 
4176       // For an explicitly defaulted or deleted special member, we defer
4177       // determining triviality until the class is complete. That time is now!
4178       if (!M->isImplicit() && !M->isUserProvided()) {
4179         CXXSpecialMember CSM = getSpecialMember(*M);
4180         if (CSM != CXXInvalid) {
4181           M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4182 
4183           // Inform the class that we've finished declaring this member.
4184           Record->finishedDefaultedOrDeletedMember(*M);
4185         }
4186       }
4187     }
4188   }
4189 
4190   // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4191   // function that is not a constructor declares that member function to be
4192   // const. [...] The class of which that function is a member shall be
4193   // a literal type.
4194   //
4195   // If the class has virtual bases, any constexpr members will already have
4196   // been diagnosed by the checks performed on the member declaration, so
4197   // suppress this (less useful) diagnostic.
4198   //
4199   // We delay this until we know whether an explicitly-defaulted (or deleted)
4200   // destructor for the class is trivial.
4201   if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
4202       !Record->isLiteral() && !Record->getNumVBases()) {
4203     for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4204                                      MEnd = Record->method_end();
4205          M != MEnd; ++M) {
4206       if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4207         switch (Record->getTemplateSpecializationKind()) {
4208         case TSK_ImplicitInstantiation:
4209         case TSK_ExplicitInstantiationDeclaration:
4210         case TSK_ExplicitInstantiationDefinition:
4211           // If a template instantiates to a non-literal type, but its members
4212           // instantiate to constexpr functions, the template is technically
4213           // ill-formed, but we allow it for sanity.
4214           continue;
4215 
4216         case TSK_Undeclared:
4217         case TSK_ExplicitSpecialization:
4218           RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4219                              diag::err_constexpr_method_non_literal);
4220           break;
4221         }
4222 
4223         // Only produce one error per class.
4224         break;
4225       }
4226     }
4227   }
4228 
4229   // Declare inheriting constructors. We do this eagerly here because:
4230   // - The standard requires an eager diagnostic for conflicting inheriting
4231   //   constructors from different classes.
4232   // - The lazy declaration of the other implicit constructors is so as to not
4233   //   waste space and performance on classes that are not meant to be
4234   //   instantiated (e.g. meta-functions). This doesn't apply to classes that
4235   //   have inheriting constructors.
4236   DeclareInheritingConstructors(Record);
4237 }
4238 
4239 /// Is the special member function which would be selected to perform the
4240 /// specified operation on the specified class type a constexpr constructor?
4241 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4242                                      Sema::CXXSpecialMember CSM,
4243                                      bool ConstArg) {
4244   Sema::SpecialMemberOverloadResult *SMOR =
4245       S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4246                             false, false, false, false);
4247   if (!SMOR || !SMOR->getMethod())
4248     // A constructor we wouldn't select can't be "involved in initializing"
4249     // anything.
4250     return true;
4251   return SMOR->getMethod()->isConstexpr();
4252 }
4253 
4254 /// Determine whether the specified special member function would be constexpr
4255 /// if it were implicitly defined.
4256 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4257                                               Sema::CXXSpecialMember CSM,
4258                                               bool ConstArg) {
4259   if (!S.getLangOpts().CPlusPlus11)
4260     return false;
4261 
4262   // C++11 [dcl.constexpr]p4:
4263   // In the definition of a constexpr constructor [...]
4264   bool Ctor = true;
4265   switch (CSM) {
4266   case Sema::CXXDefaultConstructor:
4267     // Since default constructor lookup is essentially trivial (and cannot
4268     // involve, for instance, template instantiation), we compute whether a
4269     // defaulted default constructor is constexpr directly within CXXRecordDecl.
4270     //
4271     // This is important for performance; we need to know whether the default
4272     // constructor is constexpr to determine whether the type is a literal type.
4273     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4274 
4275   case Sema::CXXCopyConstructor:
4276   case Sema::CXXMoveConstructor:
4277     // For copy or move constructors, we need to perform overload resolution.
4278     break;
4279 
4280   case Sema::CXXCopyAssignment:
4281   case Sema::CXXMoveAssignment:
4282     if (!S.getLangOpts().CPlusPlus1y)
4283       return false;
4284     // In C++1y, we need to perform overload resolution.
4285     Ctor = false;
4286     break;
4287 
4288   case Sema::CXXDestructor:
4289   case Sema::CXXInvalid:
4290     return false;
4291   }
4292 
4293   //   -- if the class is a non-empty union, or for each non-empty anonymous
4294   //      union member of a non-union class, exactly one non-static data member
4295   //      shall be initialized; [DR1359]
4296   //
4297   // If we squint, this is guaranteed, since exactly one non-static data member
4298   // will be initialized (if the constructor isn't deleted), we just don't know
4299   // which one.
4300   if (Ctor && ClassDecl->isUnion())
4301     return true;
4302 
4303   //   -- the class shall not have any virtual base classes;
4304   if (Ctor && ClassDecl->getNumVBases())
4305     return false;
4306 
4307   // C++1y [class.copy]p26:
4308   //   -- [the class] is a literal type, and
4309   if (!Ctor && !ClassDecl->isLiteral())
4310     return false;
4311 
4312   //   -- every constructor involved in initializing [...] base class
4313   //      sub-objects shall be a constexpr constructor;
4314   //   -- the assignment operator selected to copy/move each direct base
4315   //      class is a constexpr function, and
4316   for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4317                                        BEnd = ClassDecl->bases_end();
4318        B != BEnd; ++B) {
4319     const RecordType *BaseType = B->getType()->getAs<RecordType>();
4320     if (!BaseType) continue;
4321 
4322     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4323     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4324       return false;
4325   }
4326 
4327   //   -- every constructor involved in initializing non-static data members
4328   //      [...] shall be a constexpr constructor;
4329   //   -- every non-static data member and base class sub-object shall be
4330   //      initialized
4331   //   -- for each non-stastic data member of X that is of class type (or array
4332   //      thereof), the assignment operator selected to copy/move that member is
4333   //      a constexpr function
4334   for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4335                                FEnd = ClassDecl->field_end();
4336        F != FEnd; ++F) {
4337     if (F->isInvalidDecl())
4338       continue;
4339     if (const RecordType *RecordTy =
4340             S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4341       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4342       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4343         return false;
4344     }
4345   }
4346 
4347   // All OK, it's constexpr!
4348   return true;
4349 }
4350 
4351 static Sema::ImplicitExceptionSpecification
4352 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4353   switch (S.getSpecialMember(MD)) {
4354   case Sema::CXXDefaultConstructor:
4355     return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4356   case Sema::CXXCopyConstructor:
4357     return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4358   case Sema::CXXCopyAssignment:
4359     return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4360   case Sema::CXXMoveConstructor:
4361     return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4362   case Sema::CXXMoveAssignment:
4363     return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4364   case Sema::CXXDestructor:
4365     return S.ComputeDefaultedDtorExceptionSpec(MD);
4366   case Sema::CXXInvalid:
4367     break;
4368   }
4369   assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4370          "only special members have implicit exception specs");
4371   return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
4372 }
4373 
4374 static void
4375 updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4376                     const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4377   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4378   ExceptSpec.getEPI(EPI);
4379   FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4380                                         FPT->getArgTypes(), EPI));
4381 }
4382 
4383 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4384   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4385   if (FPT->getExceptionSpecType() != EST_Unevaluated)
4386     return;
4387 
4388   // Evaluate the exception specification.
4389   ImplicitExceptionSpecification ExceptSpec =
4390       computeImplicitExceptionSpec(*this, Loc, MD);
4391 
4392   // Update the type of the special member to use it.
4393   updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4394 
4395   // A user-provided destructor can be defined outside the class. When that
4396   // happens, be sure to update the exception specification on both
4397   // declarations.
4398   const FunctionProtoType *CanonicalFPT =
4399     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4400   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4401     updateExceptionSpec(*this, MD->getCanonicalDecl(),
4402                         CanonicalFPT, ExceptSpec);
4403 }
4404 
4405 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4406   CXXRecordDecl *RD = MD->getParent();
4407   CXXSpecialMember CSM = getSpecialMember(MD);
4408 
4409   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4410          "not an explicitly-defaulted special member");
4411 
4412   // Whether this was the first-declared instance of the constructor.
4413   // This affects whether we implicitly add an exception spec and constexpr.
4414   bool First = MD == MD->getCanonicalDecl();
4415 
4416   bool HadError = false;
4417 
4418   // C++11 [dcl.fct.def.default]p1:
4419   //   A function that is explicitly defaulted shall
4420   //     -- be a special member function (checked elsewhere),
4421   //     -- have the same type (except for ref-qualifiers, and except that a
4422   //        copy operation can take a non-const reference) as an implicit
4423   //        declaration, and
4424   //     -- not have default arguments.
4425   unsigned ExpectedParams = 1;
4426   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4427     ExpectedParams = 0;
4428   if (MD->getNumParams() != ExpectedParams) {
4429     // This also checks for default arguments: a copy or move constructor with a
4430     // default argument is classified as a default constructor, and assignment
4431     // operations and destructors can't have default arguments.
4432     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4433       << CSM << MD->getSourceRange();
4434     HadError = true;
4435   } else if (MD->isVariadic()) {
4436     Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4437       << CSM << MD->getSourceRange();
4438     HadError = true;
4439   }
4440 
4441   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
4442 
4443   bool CanHaveConstParam = false;
4444   if (CSM == CXXCopyConstructor)
4445     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
4446   else if (CSM == CXXCopyAssignment)
4447     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
4448 
4449   QualType ReturnType = Context.VoidTy;
4450   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4451     // Check for return type matching.
4452     ReturnType = Type->getResultType();
4453     QualType ExpectedReturnType =
4454         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4455     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4456       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4457         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4458       HadError = true;
4459     }
4460 
4461     // A defaulted special member cannot have cv-qualifiers.
4462     if (Type->getTypeQuals()) {
4463       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4464         << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
4465       HadError = true;
4466     }
4467   }
4468 
4469   // Check for parameter type matching.
4470   QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
4471   bool HasConstParam = false;
4472   if (ExpectedParams && ArgType->isReferenceType()) {
4473     // Argument must be reference to possibly-const T.
4474     QualType ReferentType = ArgType->getPointeeType();
4475     HasConstParam = ReferentType.isConstQualified();
4476 
4477     if (ReferentType.isVolatileQualified()) {
4478       Diag(MD->getLocation(),
4479            diag::err_defaulted_special_member_volatile_param) << CSM;
4480       HadError = true;
4481     }
4482 
4483     if (HasConstParam && !CanHaveConstParam) {
4484       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4485         Diag(MD->getLocation(),
4486              diag::err_defaulted_special_member_copy_const_param)
4487           << (CSM == CXXCopyAssignment);
4488         // FIXME: Explain why this special member can't be const.
4489       } else {
4490         Diag(MD->getLocation(),
4491              diag::err_defaulted_special_member_move_const_param)
4492           << (CSM == CXXMoveAssignment);
4493       }
4494       HadError = true;
4495     }
4496   } else if (ExpectedParams) {
4497     // A copy assignment operator can take its argument by value, but a
4498     // defaulted one cannot.
4499     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
4500     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
4501     HadError = true;
4502   }
4503 
4504   // C++11 [dcl.fct.def.default]p2:
4505   //   An explicitly-defaulted function may be declared constexpr only if it
4506   //   would have been implicitly declared as constexpr,
4507   // Do not apply this rule to members of class templates, since core issue 1358
4508   // makes such functions always instantiate to constexpr functions. For
4509   // functions which cannot be constexpr (for non-constructors in C++11 and for
4510   // destructors in C++1y), this is checked elsewhere.
4511   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4512                                                      HasConstParam);
4513   if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4514                                  : isa<CXXConstructorDecl>(MD)) &&
4515       MD->isConstexpr() && !Constexpr &&
4516       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4517     Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
4518     // FIXME: Explain why the special member can't be constexpr.
4519     HadError = true;
4520   }
4521 
4522   //   and may have an explicit exception-specification only if it is compatible
4523   //   with the exception-specification on the implicit declaration.
4524   if (Type->hasExceptionSpec()) {
4525     // Delay the check if this is the first declaration of the special member,
4526     // since we may not have parsed some necessary in-class initializers yet.
4527     if (First) {
4528       // If the exception specification needs to be instantiated, do so now,
4529       // before we clobber it with an EST_Unevaluated specification below.
4530       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4531         InstantiateExceptionSpec(MD->getLocStart(), MD);
4532         Type = MD->getType()->getAs<FunctionProtoType>();
4533       }
4534       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
4535     } else
4536       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4537   }
4538 
4539   //   If a function is explicitly defaulted on its first declaration,
4540   if (First) {
4541     //  -- it is implicitly considered to be constexpr if the implicit
4542     //     definition would be,
4543     MD->setConstexpr(Constexpr);
4544 
4545     //  -- it is implicitly considered to have the same exception-specification
4546     //     as if it had been implicitly declared,
4547     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4548     EPI.ExceptionSpecType = EST_Unevaluated;
4549     EPI.ExceptionSpecDecl = MD;
4550     MD->setType(Context.getFunctionType(ReturnType,
4551                                         ArrayRef<QualType>(&ArgType,
4552                                                            ExpectedParams),
4553                                         EPI));
4554   }
4555 
4556   if (ShouldDeleteSpecialMember(MD, CSM)) {
4557     if (First) {
4558       SetDeclDeleted(MD, MD->getLocation());
4559     } else {
4560       // C++11 [dcl.fct.def.default]p4:
4561       //   [For a] user-provided explicitly-defaulted function [...] if such a
4562       //   function is implicitly defined as deleted, the program is ill-formed.
4563       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4564       HadError = true;
4565     }
4566   }
4567 
4568   if (HadError)
4569     MD->setInvalidDecl();
4570 }
4571 
4572 /// Check whether the exception specification provided for an
4573 /// explicitly-defaulted special member matches the exception specification
4574 /// that would have been generated for an implicit special member, per
4575 /// C++11 [dcl.fct.def.default]p2.
4576 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4577     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4578   // Compute the implicit exception specification.
4579   FunctionProtoType::ExtProtoInfo EPI;
4580   computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4581   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
4582     Context.getFunctionType(Context.VoidTy, None, EPI));
4583 
4584   // Ensure that it matches.
4585   CheckEquivalentExceptionSpec(
4586     PDiag(diag::err_incorrect_defaulted_exception_spec)
4587       << getSpecialMember(MD), PDiag(),
4588     ImplicitType, SourceLocation(),
4589     SpecifiedType, MD->getLocation());
4590 }
4591 
4592 void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4593   for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4594        I != N; ++I)
4595     CheckExplicitlyDefaultedMemberExceptionSpec(
4596       DelayedDefaultedMemberExceptionSpecs[I].first,
4597       DelayedDefaultedMemberExceptionSpecs[I].second);
4598 
4599   DelayedDefaultedMemberExceptionSpecs.clear();
4600 }
4601 
4602 namespace {
4603 struct SpecialMemberDeletionInfo {
4604   Sema &S;
4605   CXXMethodDecl *MD;
4606   Sema::CXXSpecialMember CSM;
4607   bool Diagnose;
4608 
4609   // Properties of the special member, computed for convenience.
4610   bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4611   SourceLocation Loc;
4612 
4613   bool AllFieldsAreConst;
4614 
4615   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
4616                             Sema::CXXSpecialMember CSM, bool Diagnose)
4617     : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
4618       IsConstructor(false), IsAssignment(false), IsMove(false),
4619       ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4620       AllFieldsAreConst(true) {
4621     switch (CSM) {
4622       case Sema::CXXDefaultConstructor:
4623       case Sema::CXXCopyConstructor:
4624         IsConstructor = true;
4625         break;
4626       case Sema::CXXMoveConstructor:
4627         IsConstructor = true;
4628         IsMove = true;
4629         break;
4630       case Sema::CXXCopyAssignment:
4631         IsAssignment = true;
4632         break;
4633       case Sema::CXXMoveAssignment:
4634         IsAssignment = true;
4635         IsMove = true;
4636         break;
4637       case Sema::CXXDestructor:
4638         break;
4639       case Sema::CXXInvalid:
4640         llvm_unreachable("invalid special member kind");
4641     }
4642 
4643     if (MD->getNumParams()) {
4644       ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4645       VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4646     }
4647   }
4648 
4649   bool inUnion() const { return MD->getParent()->isUnion(); }
4650 
4651   /// Look up the corresponding special member in the given class.
4652   Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4653                                               unsigned Quals) {
4654     unsigned TQ = MD->getTypeQualifiers();
4655     // cv-qualifiers on class members don't affect default ctor / dtor calls.
4656     if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4657       Quals = 0;
4658     return S.LookupSpecialMember(Class, CSM,
4659                                  ConstArg || (Quals & Qualifiers::Const),
4660                                  VolatileArg || (Quals & Qualifiers::Volatile),
4661                                  MD->getRefQualifier() == RQ_RValue,
4662                                  TQ & Qualifiers::Const,
4663                                  TQ & Qualifiers::Volatile);
4664   }
4665 
4666   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
4667 
4668   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
4669   bool shouldDeleteForField(FieldDecl *FD);
4670   bool shouldDeleteForAllConstMembers();
4671 
4672   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4673                                      unsigned Quals);
4674   bool shouldDeleteForSubobjectCall(Subobject Subobj,
4675                                     Sema::SpecialMemberOverloadResult *SMOR,
4676                                     bool IsDtorCallInCtor);
4677 
4678   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
4679 };
4680 }
4681 
4682 /// Is the given special member inaccessible when used on the given
4683 /// sub-object.
4684 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4685                                              CXXMethodDecl *target) {
4686   /// If we're operating on a base class, the object type is the
4687   /// type of this special member.
4688   QualType objectTy;
4689   AccessSpecifier access = target->getAccess();
4690   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4691     objectTy = S.Context.getTypeDeclType(MD->getParent());
4692     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4693 
4694   // If we're operating on a field, the object type is the type of the field.
4695   } else {
4696     objectTy = S.Context.getTypeDeclType(target->getParent());
4697   }
4698 
4699   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4700 }
4701 
4702 /// Check whether we should delete a special member due to the implicit
4703 /// definition containing a call to a special member of a subobject.
4704 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4705     Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4706     bool IsDtorCallInCtor) {
4707   CXXMethodDecl *Decl = SMOR->getMethod();
4708   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4709 
4710   int DiagKind = -1;
4711 
4712   if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4713     DiagKind = !Decl ? 0 : 1;
4714   else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4715     DiagKind = 2;
4716   else if (!isAccessible(Subobj, Decl))
4717     DiagKind = 3;
4718   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4719            !Decl->isTrivial()) {
4720     // A member of a union must have a trivial corresponding special member.
4721     // As a weird special case, a destructor call from a union's constructor
4722     // must be accessible and non-deleted, but need not be trivial. Such a
4723     // destructor is never actually called, but is semantically checked as
4724     // if it were.
4725     DiagKind = 4;
4726   }
4727 
4728   if (DiagKind == -1)
4729     return false;
4730 
4731   if (Diagnose) {
4732     if (Field) {
4733       S.Diag(Field->getLocation(),
4734              diag::note_deleted_special_member_class_subobject)
4735         << CSM << MD->getParent() << /*IsField*/true
4736         << Field << DiagKind << IsDtorCallInCtor;
4737     } else {
4738       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4739       S.Diag(Base->getLocStart(),
4740              diag::note_deleted_special_member_class_subobject)
4741         << CSM << MD->getParent() << /*IsField*/false
4742         << Base->getType() << DiagKind << IsDtorCallInCtor;
4743     }
4744 
4745     if (DiagKind == 1)
4746       S.NoteDeletedFunction(Decl);
4747     // FIXME: Explain inaccessibility if DiagKind == 3.
4748   }
4749 
4750   return true;
4751 }
4752 
4753 /// Check whether we should delete a special member function due to having a
4754 /// direct or virtual base class or non-static data member of class type M.
4755 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
4756     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
4757   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4758 
4759   // C++11 [class.ctor]p5:
4760   // -- any direct or virtual base class, or non-static data member with no
4761   //    brace-or-equal-initializer, has class type M (or array thereof) and
4762   //    either M has no default constructor or overload resolution as applied
4763   //    to M's default constructor results in an ambiguity or in a function
4764   //    that is deleted or inaccessible
4765   // C++11 [class.copy]p11, C++11 [class.copy]p23:
4766   // -- a direct or virtual base class B that cannot be copied/moved because
4767   //    overload resolution, as applied to B's corresponding special member,
4768   //    results in an ambiguity or a function that is deleted or inaccessible
4769   //    from the defaulted special member
4770   // C++11 [class.dtor]p5:
4771   // -- any direct or virtual base class [...] has a type with a destructor
4772   //    that is deleted or inaccessible
4773   if (!(CSM == Sema::CXXDefaultConstructor &&
4774         Field && Field->hasInClassInitializer()) &&
4775       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
4776     return true;
4777 
4778   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4779   // -- any direct or virtual base class or non-static data member has a
4780   //    type with a destructor that is deleted or inaccessible
4781   if (IsConstructor) {
4782     Sema::SpecialMemberOverloadResult *SMOR =
4783         S.LookupSpecialMember(Class, Sema::CXXDestructor,
4784                               false, false, false, false, false);
4785     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4786       return true;
4787   }
4788 
4789   return false;
4790 }
4791 
4792 /// Check whether we should delete a special member function due to the class
4793 /// having a particular direct or virtual base class.
4794 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
4795   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
4796   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
4797 }
4798 
4799 /// Check whether we should delete a special member function due to the class
4800 /// having a particular non-static data member.
4801 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4802   QualType FieldType = S.Context.getBaseElementType(FD->getType());
4803   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4804 
4805   if (CSM == Sema::CXXDefaultConstructor) {
4806     // For a default constructor, all references must be initialized in-class
4807     // and, if a union, it must have a non-const member.
4808     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4809       if (Diagnose)
4810         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4811           << MD->getParent() << FD << FieldType << /*Reference*/0;
4812       return true;
4813     }
4814     // C++11 [class.ctor]p5: any non-variant non-static data member of
4815     // const-qualified type (or array thereof) with no
4816     // brace-or-equal-initializer does not have a user-provided default
4817     // constructor.
4818     if (!inUnion() && FieldType.isConstQualified() &&
4819         !FD->hasInClassInitializer() &&
4820         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4821       if (Diagnose)
4822         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4823           << MD->getParent() << FD << FD->getType() << /*Const*/1;
4824       return true;
4825     }
4826 
4827     if (inUnion() && !FieldType.isConstQualified())
4828       AllFieldsAreConst = false;
4829   } else if (CSM == Sema::CXXCopyConstructor) {
4830     // For a copy constructor, data members must not be of rvalue reference
4831     // type.
4832     if (FieldType->isRValueReferenceType()) {
4833       if (Diagnose)
4834         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4835           << MD->getParent() << FD << FieldType;
4836       return true;
4837     }
4838   } else if (IsAssignment) {
4839     // For an assignment operator, data members must not be of reference type.
4840     if (FieldType->isReferenceType()) {
4841       if (Diagnose)
4842         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4843           << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
4844       return true;
4845     }
4846     if (!FieldRecord && FieldType.isConstQualified()) {
4847       // C++11 [class.copy]p23:
4848       // -- a non-static data member of const non-class type (or array thereof)
4849       if (Diagnose)
4850         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4851           << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
4852       return true;
4853     }
4854   }
4855 
4856   if (FieldRecord) {
4857     // Some additional restrictions exist on the variant members.
4858     if (!inUnion() && FieldRecord->isUnion() &&
4859         FieldRecord->isAnonymousStructOrUnion()) {
4860       bool AllVariantFieldsAreConst = true;
4861 
4862       // FIXME: Handle anonymous unions declared within anonymous unions.
4863       for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4864                                          UE = FieldRecord->field_end();
4865            UI != UE; ++UI) {
4866         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
4867 
4868         if (!UnionFieldType.isConstQualified())
4869           AllVariantFieldsAreConst = false;
4870 
4871         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4872         if (UnionFieldRecord &&
4873             shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4874                                           UnionFieldType.getCVRQualifiers()))
4875           return true;
4876       }
4877 
4878       // At least one member in each anonymous union must be non-const
4879       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
4880           FieldRecord->field_begin() != FieldRecord->field_end()) {
4881         if (Diagnose)
4882           S.Diag(FieldRecord->getLocation(),
4883                  diag::note_deleted_default_ctor_all_const)
4884             << MD->getParent() << /*anonymous union*/1;
4885         return true;
4886       }
4887 
4888       // Don't check the implicit member of the anonymous union type.
4889       // This is technically non-conformant, but sanity demands it.
4890       return false;
4891     }
4892 
4893     if (shouldDeleteForClassSubobject(FieldRecord, FD,
4894                                       FieldType.getCVRQualifiers()))
4895       return true;
4896   }
4897 
4898   return false;
4899 }
4900 
4901 /// C++11 [class.ctor] p5:
4902 ///   A defaulted default constructor for a class X is defined as deleted if
4903 /// X is a union and all of its variant members are of const-qualified type.
4904 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
4905   // This is a silly definition, because it gives an empty union a deleted
4906   // default constructor. Don't do that.
4907   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4908       (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4909     if (Diagnose)
4910       S.Diag(MD->getParent()->getLocation(),
4911              diag::note_deleted_default_ctor_all_const)
4912         << MD->getParent() << /*not anonymous union*/0;
4913     return true;
4914   }
4915   return false;
4916 }
4917 
4918 /// Determine whether a defaulted special member function should be defined as
4919 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4920 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
4921 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4922                                      bool Diagnose) {
4923   if (MD->isInvalidDecl())
4924     return false;
4925   CXXRecordDecl *RD = MD->getParent();
4926   assert(!RD->isDependentType() && "do deletion after instantiation");
4927   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
4928     return false;
4929 
4930   // C++11 [expr.lambda.prim]p19:
4931   //   The closure type associated with a lambda-expression has a
4932   //   deleted (8.4.3) default constructor and a deleted copy
4933   //   assignment operator.
4934   if (RD->isLambda() &&
4935       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4936     if (Diagnose)
4937       Diag(RD->getLocation(), diag::note_lambda_decl);
4938     return true;
4939   }
4940 
4941   // For an anonymous struct or union, the copy and assignment special members
4942   // will never be used, so skip the check. For an anonymous union declared at
4943   // namespace scope, the constructor and destructor are used.
4944   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4945       RD->isAnonymousStructOrUnion())
4946     return false;
4947 
4948   // C++11 [class.copy]p7, p18:
4949   //   If the class definition declares a move constructor or move assignment
4950   //   operator, an implicitly declared copy constructor or copy assignment
4951   //   operator is defined as deleted.
4952   if (MD->isImplicit() &&
4953       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4954     CXXMethodDecl *UserDeclaredMove = 0;
4955 
4956     // In Microsoft mode, a user-declared move only causes the deletion of the
4957     // corresponding copy operation, not both copy operations.
4958     if (RD->hasUserDeclaredMoveConstructor() &&
4959         (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4960       if (!Diagnose) return true;
4961 
4962       // Find any user-declared move constructor.
4963       for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4964                                         E = RD->ctor_end(); I != E; ++I) {
4965         if (I->isMoveConstructor()) {
4966           UserDeclaredMove = *I;
4967           break;
4968         }
4969       }
4970       assert(UserDeclaredMove);
4971     } else if (RD->hasUserDeclaredMoveAssignment() &&
4972                (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4973       if (!Diagnose) return true;
4974 
4975       // Find any user-declared move assignment operator.
4976       for (CXXRecordDecl::method_iterator I = RD->method_begin(),
4977                                           E = RD->method_end(); I != E; ++I) {
4978         if (I->isMoveAssignmentOperator()) {
4979           UserDeclaredMove = *I;
4980           break;
4981         }
4982       }
4983       assert(UserDeclaredMove);
4984     }
4985 
4986     if (UserDeclaredMove) {
4987       Diag(UserDeclaredMove->getLocation(),
4988            diag::note_deleted_copy_user_declared_move)
4989         << (CSM == CXXCopyAssignment) << RD
4990         << UserDeclaredMove->isMoveAssignmentOperator();
4991       return true;
4992     }
4993   }
4994 
4995   // Do access control from the special member function
4996   ContextRAII MethodContext(*this, MD);
4997 
4998   // C++11 [class.dtor]p5:
4999   // -- for a virtual destructor, lookup of the non-array deallocation function
5000   //    results in an ambiguity or in a function that is deleted or inaccessible
5001   if (CSM == CXXDestructor && MD->isVirtual()) {
5002     FunctionDecl *OperatorDelete = 0;
5003     DeclarationName Name =
5004       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5005     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
5006                                  OperatorDelete, false)) {
5007       if (Diagnose)
5008         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
5009       return true;
5010     }
5011   }
5012 
5013   SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
5014 
5015   for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5016                                           BE = RD->bases_end(); BI != BE; ++BI)
5017     if (!BI->isVirtual() &&
5018         SMI.shouldDeleteForBase(BI))
5019       return true;
5020 
5021   for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
5022                                           BE = RD->vbases_end(); BI != BE; ++BI)
5023     if (SMI.shouldDeleteForBase(BI))
5024       return true;
5025 
5026   for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5027                                      FE = RD->field_end(); FI != FE; ++FI)
5028     if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
5029         SMI.shouldDeleteForField(*FI))
5030       return true;
5031 
5032   if (SMI.shouldDeleteForAllConstMembers())
5033     return true;
5034 
5035   return false;
5036 }
5037 
5038 /// Perform lookup for a special member of the specified kind, and determine
5039 /// whether it is trivial. If the triviality can be determined without the
5040 /// lookup, skip it. This is intended for use when determining whether a
5041 /// special member of a containing object is trivial, and thus does not ever
5042 /// perform overload resolution for default constructors.
5043 ///
5044 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5045 /// member that was most likely to be intended to be trivial, if any.
5046 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5047                                      Sema::CXXSpecialMember CSM, unsigned Quals,
5048                                      CXXMethodDecl **Selected) {
5049   if (Selected)
5050     *Selected = 0;
5051 
5052   switch (CSM) {
5053   case Sema::CXXInvalid:
5054     llvm_unreachable("not a special member");
5055 
5056   case Sema::CXXDefaultConstructor:
5057     // C++11 [class.ctor]p5:
5058     //   A default constructor is trivial if:
5059     //    - all the [direct subobjects] have trivial default constructors
5060     //
5061     // Note, no overload resolution is performed in this case.
5062     if (RD->hasTrivialDefaultConstructor())
5063       return true;
5064 
5065     if (Selected) {
5066       // If there's a default constructor which could have been trivial, dig it
5067       // out. Otherwise, if there's any user-provided default constructor, point
5068       // to that as an example of why there's not a trivial one.
5069       CXXConstructorDecl *DefCtor = 0;
5070       if (RD->needsImplicitDefaultConstructor())
5071         S.DeclareImplicitDefaultConstructor(RD);
5072       for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
5073                                         CE = RD->ctor_end(); CI != CE; ++CI) {
5074         if (!CI->isDefaultConstructor())
5075           continue;
5076         DefCtor = *CI;
5077         if (!DefCtor->isUserProvided())
5078           break;
5079       }
5080 
5081       *Selected = DefCtor;
5082     }
5083 
5084     return false;
5085 
5086   case Sema::CXXDestructor:
5087     // C++11 [class.dtor]p5:
5088     //   A destructor is trivial if:
5089     //    - all the direct [subobjects] have trivial destructors
5090     if (RD->hasTrivialDestructor())
5091       return true;
5092 
5093     if (Selected) {
5094       if (RD->needsImplicitDestructor())
5095         S.DeclareImplicitDestructor(RD);
5096       *Selected = RD->getDestructor();
5097     }
5098 
5099     return false;
5100 
5101   case Sema::CXXCopyConstructor:
5102     // C++11 [class.copy]p12:
5103     //   A copy constructor is trivial if:
5104     //    - the constructor selected to copy each direct [subobject] is trivial
5105     if (RD->hasTrivialCopyConstructor()) {
5106       if (Quals == Qualifiers::Const)
5107         // We must either select the trivial copy constructor or reach an
5108         // ambiguity; no need to actually perform overload resolution.
5109         return true;
5110     } else if (!Selected) {
5111       return false;
5112     }
5113     // In C++98, we are not supposed to perform overload resolution here, but we
5114     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5115     // cases like B as having a non-trivial copy constructor:
5116     //   struct A { template<typename T> A(T&); };
5117     //   struct B { mutable A a; };
5118     goto NeedOverloadResolution;
5119 
5120   case Sema::CXXCopyAssignment:
5121     // C++11 [class.copy]p25:
5122     //   A copy assignment operator is trivial if:
5123     //    - the assignment operator selected to copy each direct [subobject] is
5124     //      trivial
5125     if (RD->hasTrivialCopyAssignment()) {
5126       if (Quals == Qualifiers::Const)
5127         return true;
5128     } else if (!Selected) {
5129       return false;
5130     }
5131     // In C++98, we are not supposed to perform overload resolution here, but we
5132     // treat that as a language defect.
5133     goto NeedOverloadResolution;
5134 
5135   case Sema::CXXMoveConstructor:
5136   case Sema::CXXMoveAssignment:
5137   NeedOverloadResolution:
5138     Sema::SpecialMemberOverloadResult *SMOR =
5139       S.LookupSpecialMember(RD, CSM,
5140                             Quals & Qualifiers::Const,
5141                             Quals & Qualifiers::Volatile,
5142                             /*RValueThis*/false, /*ConstThis*/false,
5143                             /*VolatileThis*/false);
5144 
5145     // The standard doesn't describe how to behave if the lookup is ambiguous.
5146     // We treat it as not making the member non-trivial, just like the standard
5147     // mandates for the default constructor. This should rarely matter, because
5148     // the member will also be deleted.
5149     if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5150       return true;
5151 
5152     if (!SMOR->getMethod()) {
5153       assert(SMOR->getKind() ==
5154              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5155       return false;
5156     }
5157 
5158     // We deliberately don't check if we found a deleted special member. We're
5159     // not supposed to!
5160     if (Selected)
5161       *Selected = SMOR->getMethod();
5162     return SMOR->getMethod()->isTrivial();
5163   }
5164 
5165   llvm_unreachable("unknown special method kind");
5166 }
5167 
5168 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
5169   for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5170        CI != CE; ++CI)
5171     if (!CI->isImplicit())
5172       return *CI;
5173 
5174   // Look for constructor templates.
5175   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5176   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5177     if (CXXConstructorDecl *CD =
5178           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5179       return CD;
5180   }
5181 
5182   return 0;
5183 }
5184 
5185 /// The kind of subobject we are checking for triviality. The values of this
5186 /// enumeration are used in diagnostics.
5187 enum TrivialSubobjectKind {
5188   /// The subobject is a base class.
5189   TSK_BaseClass,
5190   /// The subobject is a non-static data member.
5191   TSK_Field,
5192   /// The object is actually the complete object.
5193   TSK_CompleteObject
5194 };
5195 
5196 /// Check whether the special member selected for a given type would be trivial.
5197 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5198                                       QualType SubType,
5199                                       Sema::CXXSpecialMember CSM,
5200                                       TrivialSubobjectKind Kind,
5201                                       bool Diagnose) {
5202   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5203   if (!SubRD)
5204     return true;
5205 
5206   CXXMethodDecl *Selected;
5207   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5208                                Diagnose ? &Selected : 0))
5209     return true;
5210 
5211   if (Diagnose) {
5212     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5213       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5214         << Kind << SubType.getUnqualifiedType();
5215       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5216         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5217     } else if (!Selected)
5218       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5219         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5220     else if (Selected->isUserProvided()) {
5221       if (Kind == TSK_CompleteObject)
5222         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5223           << Kind << SubType.getUnqualifiedType() << CSM;
5224       else {
5225         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5226           << Kind << SubType.getUnqualifiedType() << CSM;
5227         S.Diag(Selected->getLocation(), diag::note_declared_at);
5228       }
5229     } else {
5230       if (Kind != TSK_CompleteObject)
5231         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5232           << Kind << SubType.getUnqualifiedType() << CSM;
5233 
5234       // Explain why the defaulted or deleted special member isn't trivial.
5235       S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5236     }
5237   }
5238 
5239   return false;
5240 }
5241 
5242 /// Check whether the members of a class type allow a special member to be
5243 /// trivial.
5244 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5245                                      Sema::CXXSpecialMember CSM,
5246                                      bool ConstArg, bool Diagnose) {
5247   for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5248                                      FE = RD->field_end(); FI != FE; ++FI) {
5249     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5250       continue;
5251 
5252     QualType FieldType = S.Context.getBaseElementType(FI->getType());
5253 
5254     // Pretend anonymous struct or union members are members of this class.
5255     if (FI->isAnonymousStructOrUnion()) {
5256       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5257                                     CSM, ConstArg, Diagnose))
5258         return false;
5259       continue;
5260     }
5261 
5262     // C++11 [class.ctor]p5:
5263     //   A default constructor is trivial if [...]
5264     //    -- no non-static data member of its class has a
5265     //       brace-or-equal-initializer
5266     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5267       if (Diagnose)
5268         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5269       return false;
5270     }
5271 
5272     // Objective C ARC 4.3.5:
5273     //   [...] nontrivally ownership-qualified types are [...] not trivially
5274     //   default constructible, copy constructible, move constructible, copy
5275     //   assignable, move assignable, or destructible [...]
5276     if (S.getLangOpts().ObjCAutoRefCount &&
5277         FieldType.hasNonTrivialObjCLifetime()) {
5278       if (Diagnose)
5279         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5280           << RD << FieldType.getObjCLifetime();
5281       return false;
5282     }
5283 
5284     if (ConstArg && !FI->isMutable())
5285       FieldType.addConst();
5286     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5287                                    TSK_Field, Diagnose))
5288       return false;
5289   }
5290 
5291   return true;
5292 }
5293 
5294 /// Diagnose why the specified class does not have a trivial special member of
5295 /// the given kind.
5296 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5297   QualType Ty = Context.getRecordType(RD);
5298   if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5299     Ty.addConst();
5300 
5301   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5302                             TSK_CompleteObject, /*Diagnose*/true);
5303 }
5304 
5305 /// Determine whether a defaulted or deleted special member function is trivial,
5306 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5307 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5308 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5309                                   bool Diagnose) {
5310   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5311 
5312   CXXRecordDecl *RD = MD->getParent();
5313 
5314   bool ConstArg = false;
5315 
5316   // C++11 [class.copy]p12, p25:
5317   //   A [special member] is trivial if its declared parameter type is the same
5318   //   as if it had been implicitly declared [...]
5319   switch (CSM) {
5320   case CXXDefaultConstructor:
5321   case CXXDestructor:
5322     // Trivial default constructors and destructors cannot have parameters.
5323     break;
5324 
5325   case CXXCopyConstructor:
5326   case CXXCopyAssignment: {
5327     // Trivial copy operations always have const, non-volatile parameter types.
5328     ConstArg = true;
5329     const ParmVarDecl *Param0 = MD->getParamDecl(0);
5330     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5331     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5332       if (Diagnose)
5333         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5334           << Param0->getSourceRange() << Param0->getType()
5335           << Context.getLValueReferenceType(
5336                Context.getRecordType(RD).withConst());
5337       return false;
5338     }
5339     break;
5340   }
5341 
5342   case CXXMoveConstructor:
5343   case CXXMoveAssignment: {
5344     // Trivial move operations always have non-cv-qualified parameters.
5345     const ParmVarDecl *Param0 = MD->getParamDecl(0);
5346     const RValueReferenceType *RT =
5347       Param0->getType()->getAs<RValueReferenceType>();
5348     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5349       if (Diagnose)
5350         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5351           << Param0->getSourceRange() << Param0->getType()
5352           << Context.getRValueReferenceType(Context.getRecordType(RD));
5353       return false;
5354     }
5355     break;
5356   }
5357 
5358   case CXXInvalid:
5359     llvm_unreachable("not a special member");
5360   }
5361 
5362   // FIXME: We require that the parameter-declaration-clause is equivalent to
5363   // that of an implicit declaration, not just that the declared parameter type
5364   // matches, in order to prevent absuridities like a function simultaneously
5365   // being a trivial copy constructor and a non-trivial default constructor.
5366   // This issue has not yet been assigned a core issue number.
5367   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5368     if (Diagnose)
5369       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5370            diag::note_nontrivial_default_arg)
5371         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5372     return false;
5373   }
5374   if (MD->isVariadic()) {
5375     if (Diagnose)
5376       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5377     return false;
5378   }
5379 
5380   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5381   //   A copy/move [constructor or assignment operator] is trivial if
5382   //    -- the [member] selected to copy/move each direct base class subobject
5383   //       is trivial
5384   //
5385   // C++11 [class.copy]p12, C++11 [class.copy]p25:
5386   //   A [default constructor or destructor] is trivial if
5387   //    -- all the direct base classes have trivial [default constructors or
5388   //       destructors]
5389   for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5390                                           BE = RD->bases_end(); BI != BE; ++BI)
5391     if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5392                                    ConstArg ? BI->getType().withConst()
5393                                             : BI->getType(),
5394                                    CSM, TSK_BaseClass, Diagnose))
5395       return false;
5396 
5397   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5398   //   A copy/move [constructor or assignment operator] for a class X is
5399   //   trivial if
5400   //    -- for each non-static data member of X that is of class type (or array
5401   //       thereof), the constructor selected to copy/move that member is
5402   //       trivial
5403   //
5404   // C++11 [class.copy]p12, C++11 [class.copy]p25:
5405   //   A [default constructor or destructor] is trivial if
5406   //    -- for all of the non-static data members of its class that are of class
5407   //       type (or array thereof), each such class has a trivial [default
5408   //       constructor or destructor]
5409   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5410     return false;
5411 
5412   // C++11 [class.dtor]p5:
5413   //   A destructor is trivial if [...]
5414   //    -- the destructor is not virtual
5415   if (CSM == CXXDestructor && MD->isVirtual()) {
5416     if (Diagnose)
5417       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5418     return false;
5419   }
5420 
5421   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5422   //   A [special member] for class X is trivial if [...]
5423   //    -- class X has no virtual functions and no virtual base classes
5424   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5425     if (!Diagnose)
5426       return false;
5427 
5428     if (RD->getNumVBases()) {
5429       // Check for virtual bases. We already know that the corresponding
5430       // member in all bases is trivial, so vbases must all be direct.
5431       CXXBaseSpecifier &BS = *RD->vbases_begin();
5432       assert(BS.isVirtual());
5433       Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5434       return false;
5435     }
5436 
5437     // Must have a virtual method.
5438     for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5439                                         ME = RD->method_end(); MI != ME; ++MI) {
5440       if (MI->isVirtual()) {
5441         SourceLocation MLoc = MI->getLocStart();
5442         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5443         return false;
5444       }
5445     }
5446 
5447     llvm_unreachable("dynamic class with no vbases and no virtual functions");
5448   }
5449 
5450   // Looks like it's trivial!
5451   return true;
5452 }
5453 
5454 /// \brief Data used with FindHiddenVirtualMethod
5455 namespace {
5456   struct FindHiddenVirtualMethodData {
5457     Sema *S;
5458     CXXMethodDecl *Method;
5459     llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
5460     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5461   };
5462 }
5463 
5464 /// \brief Check whether any most overriden method from MD in Methods
5465 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5466                    const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5467   if (MD->size_overridden_methods() == 0)
5468     return Methods.count(MD->getCanonicalDecl());
5469   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5470                                       E = MD->end_overridden_methods();
5471        I != E; ++I)
5472     if (CheckMostOverridenMethods(*I, Methods))
5473       return true;
5474   return false;
5475 }
5476 
5477 /// \brief Member lookup function that determines whether a given C++
5478 /// method overloads virtual methods in a base class without overriding any,
5479 /// to be used with CXXRecordDecl::lookupInBases().
5480 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5481                                     CXXBasePath &Path,
5482                                     void *UserData) {
5483   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5484 
5485   FindHiddenVirtualMethodData &Data
5486     = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5487 
5488   DeclarationName Name = Data.Method->getDeclName();
5489   assert(Name.getNameKind() == DeclarationName::Identifier);
5490 
5491   bool foundSameNameMethod = false;
5492   SmallVector<CXXMethodDecl *, 8> overloadedMethods;
5493   for (Path.Decls = BaseRecord->lookup(Name);
5494        !Path.Decls.empty();
5495        Path.Decls = Path.Decls.slice(1)) {
5496     NamedDecl *D = Path.Decls.front();
5497     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5498       MD = MD->getCanonicalDecl();
5499       foundSameNameMethod = true;
5500       // Interested only in hidden virtual methods.
5501       if (!MD->isVirtual())
5502         continue;
5503       // If the method we are checking overrides a method from its base
5504       // don't warn about the other overloaded methods.
5505       if (!Data.S->IsOverload(Data.Method, MD, false))
5506         return true;
5507       // Collect the overload only if its hidden.
5508       if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
5509         overloadedMethods.push_back(MD);
5510     }
5511   }
5512 
5513   if (foundSameNameMethod)
5514     Data.OverloadedMethods.append(overloadedMethods.begin(),
5515                                    overloadedMethods.end());
5516   return foundSameNameMethod;
5517 }
5518 
5519 /// \brief Add the most overriden methods from MD to Methods
5520 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5521                          llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5522   if (MD->size_overridden_methods() == 0)
5523     Methods.insert(MD->getCanonicalDecl());
5524   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5525                                       E = MD->end_overridden_methods();
5526        I != E; ++I)
5527     AddMostOverridenMethods(*I, Methods);
5528 }
5529 
5530 /// \brief See if a method overloads virtual methods in a base class without
5531 /// overriding any.
5532 void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5533   if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
5534                                MD->getLocation()) == DiagnosticsEngine::Ignored)
5535     return;
5536   if (!MD->getDeclName().isIdentifier())
5537     return;
5538 
5539   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5540                      /*bool RecordPaths=*/false,
5541                      /*bool DetectVirtual=*/false);
5542   FindHiddenVirtualMethodData Data;
5543   Data.Method = MD;
5544   Data.S = this;
5545 
5546   // Keep the base methods that were overriden or introduced in the subclass
5547   // by 'using' in a set. A base method not in this set is hidden.
5548   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5549   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5550     NamedDecl *ND = *I;
5551     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
5552       ND = shad->getTargetDecl();
5553     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5554       AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
5555   }
5556 
5557   if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5558       !Data.OverloadedMethods.empty()) {
5559     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5560       << MD << (Data.OverloadedMethods.size() > 1);
5561 
5562     for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5563       CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
5564       PartialDiagnostic PD = PDiag(
5565            diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5566       HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5567       Diag(overloadedMD->getLocation(), PD);
5568     }
5569   }
5570 }
5571 
5572 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5573                                              Decl *TagDecl,
5574                                              SourceLocation LBrac,
5575                                              SourceLocation RBrac,
5576                                              AttributeList *AttrList) {
5577   if (!TagDecl)
5578     return;
5579 
5580   AdjustDeclIfTemplate(TagDecl);
5581 
5582   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5583     if (l->getKind() != AttributeList::AT_Visibility)
5584       continue;
5585     l->setInvalid();
5586     Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5587       l->getName();
5588   }
5589 
5590   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
5591               // strict aliasing violation!
5592               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
5593               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
5594 
5595   CheckCompletedCXXClass(
5596                         dyn_cast_or_null<CXXRecordDecl>(TagDecl));
5597 }
5598 
5599 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5600 /// special functions, such as the default constructor, copy
5601 /// constructor, or destructor, to the given C++ class (C++
5602 /// [special]p1).  This routine can only be executed just before the
5603 /// definition of the class is complete.
5604 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
5605   if (!ClassDecl->hasUserDeclaredConstructor())
5606     ++ASTContext::NumImplicitDefaultConstructors;
5607 
5608   if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
5609     ++ASTContext::NumImplicitCopyConstructors;
5610 
5611     // If the properties or semantics of the copy constructor couldn't be
5612     // determined while the class was being declared, force a declaration
5613     // of it now.
5614     if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5615       DeclareImplicitCopyConstructor(ClassDecl);
5616   }
5617 
5618   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
5619     ++ASTContext::NumImplicitMoveConstructors;
5620 
5621     if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5622       DeclareImplicitMoveConstructor(ClassDecl);
5623   }
5624 
5625   if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5626     ++ASTContext::NumImplicitCopyAssignmentOperators;
5627 
5628     // If we have a dynamic class, then the copy assignment operator may be
5629     // virtual, so we have to declare it immediately. This ensures that, e.g.,
5630     // it shows up in the right place in the vtable and that we diagnose
5631     // problems with the implicit exception specification.
5632     if (ClassDecl->isDynamicClass() ||
5633         ClassDecl->needsOverloadResolutionForCopyAssignment())
5634       DeclareImplicitCopyAssignment(ClassDecl);
5635   }
5636 
5637   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
5638     ++ASTContext::NumImplicitMoveAssignmentOperators;
5639 
5640     // Likewise for the move assignment operator.
5641     if (ClassDecl->isDynamicClass() ||
5642         ClassDecl->needsOverloadResolutionForMoveAssignment())
5643       DeclareImplicitMoveAssignment(ClassDecl);
5644   }
5645 
5646   if (!ClassDecl->hasUserDeclaredDestructor()) {
5647     ++ASTContext::NumImplicitDestructors;
5648 
5649     // If we have a dynamic class, then the destructor may be virtual, so we
5650     // have to declare the destructor immediately. This ensures that, e.g., it
5651     // shows up in the right place in the vtable and that we diagnose problems
5652     // with the implicit exception specification.
5653     if (ClassDecl->isDynamicClass() ||
5654         ClassDecl->needsOverloadResolutionForDestructor())
5655       DeclareImplicitDestructor(ClassDecl);
5656   }
5657 }
5658 
5659 void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5660   if (!D)
5661     return;
5662 
5663   int NumParamList = D->getNumTemplateParameterLists();
5664   for (int i = 0; i < NumParamList; i++) {
5665     TemplateParameterList* Params = D->getTemplateParameterList(i);
5666     for (TemplateParameterList::iterator Param = Params->begin(),
5667                                       ParamEnd = Params->end();
5668           Param != ParamEnd; ++Param) {
5669       NamedDecl *Named = cast<NamedDecl>(*Param);
5670       if (Named->getDeclName()) {
5671         S->AddDecl(Named);
5672         IdResolver.AddDecl(Named);
5673       }
5674     }
5675   }
5676 }
5677 
5678 void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
5679   if (!D)
5680     return;
5681 
5682   TemplateParameterList *Params = 0;
5683   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5684     Params = Template->getTemplateParameters();
5685   else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5686            = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5687     Params = PartialSpec->getTemplateParameters();
5688   else
5689     return;
5690 
5691   for (TemplateParameterList::iterator Param = Params->begin(),
5692                                     ParamEnd = Params->end();
5693        Param != ParamEnd; ++Param) {
5694     NamedDecl *Named = cast<NamedDecl>(*Param);
5695     if (Named->getDeclName()) {
5696       S->AddDecl(Named);
5697       IdResolver.AddDecl(Named);
5698     }
5699   }
5700 }
5701 
5702 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
5703   if (!RecordD) return;
5704   AdjustDeclIfTemplate(RecordD);
5705   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
5706   PushDeclContext(S, Record);
5707 }
5708 
5709 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
5710   if (!RecordD) return;
5711   PopDeclContext();
5712 }
5713 
5714 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
5715 /// parsing a top-level (non-nested) C++ class, and we are now
5716 /// parsing those parts of the given Method declaration that could
5717 /// not be parsed earlier (C++ [class.mem]p2), such as default
5718 /// arguments. This action should enter the scope of the given
5719 /// Method declaration as if we had just parsed the qualified method
5720 /// name. However, it should not bring the parameters into scope;
5721 /// that will be performed by ActOnDelayedCXXMethodParameter.
5722 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
5723 }
5724 
5725 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
5726 /// C++ method declaration. We're (re-)introducing the given
5727 /// function parameter into scope for use in parsing later parts of
5728 /// the method declaration. For example, we could see an
5729 /// ActOnParamDefaultArgument event for this parameter.
5730 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
5731   if (!ParamD)
5732     return;
5733 
5734   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
5735 
5736   // If this parameter has an unparsed default argument, clear it out
5737   // to make way for the parsed default argument.
5738   if (Param->hasUnparsedDefaultArg())
5739     Param->setDefaultArg(0);
5740 
5741   S->AddDecl(Param);
5742   if (Param->getDeclName())
5743     IdResolver.AddDecl(Param);
5744 }
5745 
5746 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5747 /// processing the delayed method declaration for Method. The method
5748 /// declaration is now considered finished. There may be a separate
5749 /// ActOnStartOfFunctionDef action later (not necessarily
5750 /// immediately!) for this method, if it was also defined inside the
5751 /// class body.
5752 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
5753   if (!MethodD)
5754     return;
5755 
5756   AdjustDeclIfTemplate(MethodD);
5757 
5758   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
5759 
5760   // Now that we have our default arguments, check the constructor
5761   // again. It could produce additional diagnostics or affect whether
5762   // the class has implicitly-declared destructors, among other
5763   // things.
5764   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5765     CheckConstructor(Constructor);
5766 
5767   // Check the default arguments, which we may have added.
5768   if (!Method->isInvalidDecl())
5769     CheckCXXDefaultArguments(Method);
5770 }
5771 
5772 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
5773 /// the well-formedness of the constructor declarator @p D with type @p
5774 /// R. If there are any errors in the declarator, this routine will
5775 /// emit diagnostics and set the invalid bit to true.  In any case, the type
5776 /// will be updated to reflect a well-formed type for the constructor and
5777 /// returned.
5778 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
5779                                           StorageClass &SC) {
5780   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
5781 
5782   // C++ [class.ctor]p3:
5783   //   A constructor shall not be virtual (10.3) or static (9.4). A
5784   //   constructor can be invoked for a const, volatile or const
5785   //   volatile object. A constructor shall not be declared const,
5786   //   volatile, or const volatile (9.3.2).
5787   if (isVirtual) {
5788     if (!D.isInvalidType())
5789       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5790         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5791         << SourceRange(D.getIdentifierLoc());
5792     D.setInvalidType();
5793   }
5794   if (SC == SC_Static) {
5795     if (!D.isInvalidType())
5796       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5797         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5798         << SourceRange(D.getIdentifierLoc());
5799     D.setInvalidType();
5800     SC = SC_None;
5801   }
5802 
5803   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5804   if (FTI.TypeQuals != 0) {
5805     if (FTI.TypeQuals & Qualifiers::Const)
5806       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5807         << "const" << SourceRange(D.getIdentifierLoc());
5808     if (FTI.TypeQuals & Qualifiers::Volatile)
5809       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5810         << "volatile" << SourceRange(D.getIdentifierLoc());
5811     if (FTI.TypeQuals & Qualifiers::Restrict)
5812       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5813         << "restrict" << SourceRange(D.getIdentifierLoc());
5814     D.setInvalidType();
5815   }
5816 
5817   // C++0x [class.ctor]p4:
5818   //   A constructor shall not be declared with a ref-qualifier.
5819   if (FTI.hasRefQualifier()) {
5820     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5821       << FTI.RefQualifierIsLValueRef
5822       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5823     D.setInvalidType();
5824   }
5825 
5826   // Rebuild the function type "R" without any type qualifiers (in
5827   // case any of the errors above fired) and with "void" as the
5828   // return type, since constructors don't have return types.
5829   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5830   if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5831     return R;
5832 
5833   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5834   EPI.TypeQuals = 0;
5835   EPI.RefQualifier = RQ_None;
5836 
5837   return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
5838 }
5839 
5840 /// CheckConstructor - Checks a fully-formed constructor for
5841 /// well-formedness, issuing any diagnostics required. Returns true if
5842 /// the constructor declarator is invalid.
5843 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
5844   CXXRecordDecl *ClassDecl
5845     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5846   if (!ClassDecl)
5847     return Constructor->setInvalidDecl();
5848 
5849   // C++ [class.copy]p3:
5850   //   A declaration of a constructor for a class X is ill-formed if
5851   //   its first parameter is of type (optionally cv-qualified) X and
5852   //   either there are no other parameters or else all other
5853   //   parameters have default arguments.
5854   if (!Constructor->isInvalidDecl() &&
5855       ((Constructor->getNumParams() == 1) ||
5856        (Constructor->getNumParams() > 1 &&
5857         Constructor->getParamDecl(1)->hasDefaultArg())) &&
5858       Constructor->getTemplateSpecializationKind()
5859                                               != TSK_ImplicitInstantiation) {
5860     QualType ParamType = Constructor->getParamDecl(0)->getType();
5861     QualType ClassTy = Context.getTagDeclType(ClassDecl);
5862     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
5863       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
5864       const char *ConstRef
5865         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5866                                                         : " const &";
5867       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
5868         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
5869 
5870       // FIXME: Rather that making the constructor invalid, we should endeavor
5871       // to fix the type.
5872       Constructor->setInvalidDecl();
5873     }
5874   }
5875 }
5876 
5877 /// CheckDestructor - Checks a fully-formed destructor definition for
5878 /// well-formedness, issuing any diagnostics required.  Returns true
5879 /// on error.
5880 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
5881   CXXRecordDecl *RD = Destructor->getParent();
5882 
5883   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
5884     SourceLocation Loc;
5885 
5886     if (!Destructor->isImplicit())
5887       Loc = Destructor->getLocation();
5888     else
5889       Loc = RD->getLocation();
5890 
5891     // If we have a virtual destructor, look up the deallocation function
5892     FunctionDecl *OperatorDelete = 0;
5893     DeclarationName Name =
5894     Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5895     if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
5896       return true;
5897 
5898     MarkFunctionReferenced(Loc, OperatorDelete);
5899 
5900     Destructor->setOperatorDelete(OperatorDelete);
5901   }
5902 
5903   return false;
5904 }
5905 
5906 static inline bool
5907 FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5908   return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5909           FTI.ArgInfo[0].Param &&
5910           cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
5911 }
5912 
5913 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5914 /// the well-formednes of the destructor declarator @p D with type @p
5915 /// R. If there are any errors in the declarator, this routine will
5916 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
5917 /// will be updated to reflect a well-formed type for the destructor and
5918 /// returned.
5919 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
5920                                          StorageClass& SC) {
5921   // C++ [class.dtor]p1:
5922   //   [...] A typedef-name that names a class is a class-name
5923   //   (7.1.3); however, a typedef-name that names a class shall not
5924   //   be used as the identifier in the declarator for a destructor
5925   //   declaration.
5926   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
5927   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
5928     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5929       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
5930   else if (const TemplateSpecializationType *TST =
5931              DeclaratorType->getAs<TemplateSpecializationType>())
5932     if (TST->isTypeAlias())
5933       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5934         << DeclaratorType << 1;
5935 
5936   // C++ [class.dtor]p2:
5937   //   A destructor is used to destroy objects of its class type. A
5938   //   destructor takes no parameters, and no return type can be
5939   //   specified for it (not even void). The address of a destructor
5940   //   shall not be taken. A destructor shall not be static. A
5941   //   destructor can be invoked for a const, volatile or const
5942   //   volatile object. A destructor shall not be declared const,
5943   //   volatile or const volatile (9.3.2).
5944   if (SC == SC_Static) {
5945     if (!D.isInvalidType())
5946       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5947         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5948         << SourceRange(D.getIdentifierLoc())
5949         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5950 
5951     SC = SC_None;
5952   }
5953   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
5954     // Destructors don't have return types, but the parser will
5955     // happily parse something like:
5956     //
5957     //   class X {
5958     //     float ~X();
5959     //   };
5960     //
5961     // The return type will be eliminated later.
5962     Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5963       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5964       << SourceRange(D.getIdentifierLoc());
5965   }
5966 
5967   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5968   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
5969     if (FTI.TypeQuals & Qualifiers::Const)
5970       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5971         << "const" << SourceRange(D.getIdentifierLoc());
5972     if (FTI.TypeQuals & Qualifiers::Volatile)
5973       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5974         << "volatile" << SourceRange(D.getIdentifierLoc());
5975     if (FTI.TypeQuals & Qualifiers::Restrict)
5976       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5977         << "restrict" << SourceRange(D.getIdentifierLoc());
5978     D.setInvalidType();
5979   }
5980 
5981   // C++0x [class.dtor]p2:
5982   //   A destructor shall not be declared with a ref-qualifier.
5983   if (FTI.hasRefQualifier()) {
5984     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5985       << FTI.RefQualifierIsLValueRef
5986       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5987     D.setInvalidType();
5988   }
5989 
5990   // Make sure we don't have any parameters.
5991   if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
5992     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5993 
5994     // Delete the parameters.
5995     FTI.freeArgs();
5996     D.setInvalidType();
5997   }
5998 
5999   // Make sure the destructor isn't variadic.
6000   if (FTI.isVariadic) {
6001     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
6002     D.setInvalidType();
6003   }
6004 
6005   // Rebuild the function type "R" without any type qualifiers or
6006   // parameters (in case any of the errors above fired) and with
6007   // "void" as the return type, since destructors don't have return
6008   // types.
6009   if (!D.isInvalidType())
6010     return R;
6011 
6012   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6013   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6014   EPI.Variadic = false;
6015   EPI.TypeQuals = 0;
6016   EPI.RefQualifier = RQ_None;
6017   return Context.getFunctionType(Context.VoidTy, None, EPI);
6018 }
6019 
6020 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6021 /// well-formednes of the conversion function declarator @p D with
6022 /// type @p R. If there are any errors in the declarator, this routine
6023 /// will emit diagnostics and return true. Otherwise, it will return
6024 /// false. Either way, the type @p R will be updated to reflect a
6025 /// well-formed type for the conversion operator.
6026 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
6027                                      StorageClass& SC) {
6028   // C++ [class.conv.fct]p1:
6029   //   Neither parameter types nor return type can be specified. The
6030   //   type of a conversion function (8.3.5) is "function taking no
6031   //   parameter returning conversion-type-id."
6032   if (SC == SC_Static) {
6033     if (!D.isInvalidType())
6034       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
6035         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6036         << D.getName().getSourceRange();
6037     D.setInvalidType();
6038     SC = SC_None;
6039   }
6040 
6041   QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6042 
6043   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
6044     // Conversion functions don't have return types, but the parser will
6045     // happily parse something like:
6046     //
6047     //   class X {
6048     //     float operator bool();
6049     //   };
6050     //
6051     // The return type will be changed later anyway.
6052     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6053       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6054       << SourceRange(D.getIdentifierLoc());
6055     D.setInvalidType();
6056   }
6057 
6058   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6059 
6060   // Make sure we don't have any parameters.
6061   if (Proto->getNumArgs() > 0) {
6062     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6063 
6064     // Delete the parameters.
6065     D.getFunctionTypeInfo().freeArgs();
6066     D.setInvalidType();
6067   } else if (Proto->isVariadic()) {
6068     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
6069     D.setInvalidType();
6070   }
6071 
6072   // Diagnose "&operator bool()" and other such nonsense.  This
6073   // is actually a gcc extension which we don't support.
6074   if (Proto->getResultType() != ConvType) {
6075     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6076       << Proto->getResultType();
6077     D.setInvalidType();
6078     ConvType = Proto->getResultType();
6079   }
6080 
6081   // C++ [class.conv.fct]p4:
6082   //   The conversion-type-id shall not represent a function type nor
6083   //   an array type.
6084   if (ConvType->isArrayType()) {
6085     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6086     ConvType = Context.getPointerType(ConvType);
6087     D.setInvalidType();
6088   } else if (ConvType->isFunctionType()) {
6089     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6090     ConvType = Context.getPointerType(ConvType);
6091     D.setInvalidType();
6092   }
6093 
6094   // Rebuild the function type "R" without any parameters (in case any
6095   // of the errors above fired) and with the conversion type as the
6096   // return type.
6097   if (D.isInvalidType())
6098     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
6099 
6100   // C++0x explicit conversion operators.
6101   if (D.getDeclSpec().isExplicitSpecified())
6102     Diag(D.getDeclSpec().getExplicitSpecLoc(),
6103          getLangOpts().CPlusPlus11 ?
6104            diag::warn_cxx98_compat_explicit_conversion_functions :
6105            diag::ext_explicit_conversion_functions)
6106       << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
6107 }
6108 
6109 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6110 /// the declaration of the given C++ conversion function. This routine
6111 /// is responsible for recording the conversion function in the C++
6112 /// class, if possible.
6113 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
6114   assert(Conversion && "Expected to receive a conversion function declaration");
6115 
6116   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
6117 
6118   // Make sure we aren't redeclaring the conversion function.
6119   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
6120 
6121   // C++ [class.conv.fct]p1:
6122   //   [...] A conversion function is never used to convert a
6123   //   (possibly cv-qualified) object to the (possibly cv-qualified)
6124   //   same object type (or a reference to it), to a (possibly
6125   //   cv-qualified) base class of that type (or a reference to it),
6126   //   or to (possibly cv-qualified) void.
6127   // FIXME: Suppress this warning if the conversion function ends up being a
6128   // virtual function that overrides a virtual function in a base class.
6129   QualType ClassType
6130     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6131   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
6132     ConvType = ConvTypeRef->getPointeeType();
6133   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6134       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
6135     /* Suppress diagnostics for instantiations. */;
6136   else if (ConvType->isRecordType()) {
6137     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6138     if (ConvType == ClassType)
6139       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
6140         << ClassType;
6141     else if (IsDerivedFrom(ClassType, ConvType))
6142       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
6143         <<  ClassType << ConvType;
6144   } else if (ConvType->isVoidType()) {
6145     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
6146       << ClassType << ConvType;
6147   }
6148 
6149   if (FunctionTemplateDecl *ConversionTemplate
6150                                 = Conversion->getDescribedFunctionTemplate())
6151     return ConversionTemplate;
6152 
6153   return Conversion;
6154 }
6155 
6156 //===----------------------------------------------------------------------===//
6157 // Namespace Handling
6158 //===----------------------------------------------------------------------===//
6159 
6160 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6161 /// reopened.
6162 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6163                                             SourceLocation Loc,
6164                                             IdentifierInfo *II, bool *IsInline,
6165                                             NamespaceDecl *PrevNS) {
6166   assert(*IsInline != PrevNS->isInline());
6167 
6168   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6169   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6170   // inline namespaces, with the intention of bringing names into namespace std.
6171   //
6172   // We support this just well enough to get that case working; this is not
6173   // sufficient to support reopening namespaces as inline in general.
6174   if (*IsInline && II && II->getName().startswith("__atomic") &&
6175       S.getSourceManager().isInSystemHeader(Loc)) {
6176     // Mark all prior declarations of the namespace as inline.
6177     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6178          NS = NS->getPreviousDecl())
6179       NS->setInline(*IsInline);
6180     // Patch up the lookup table for the containing namespace. This isn't really
6181     // correct, but it's good enough for this particular case.
6182     for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6183                                     E = PrevNS->decls_end(); I != E; ++I)
6184       if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6185         PrevNS->getParent()->makeDeclVisibleInContext(ND);
6186     return;
6187   }
6188 
6189   if (PrevNS->isInline())
6190     // The user probably just forgot the 'inline', so suggest that it
6191     // be added back.
6192     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6193       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6194   else
6195     S.Diag(Loc, diag::err_inline_namespace_mismatch)
6196       << IsInline;
6197 
6198   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6199   *IsInline = PrevNS->isInline();
6200 }
6201 
6202 /// ActOnStartNamespaceDef - This is called at the start of a namespace
6203 /// definition.
6204 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
6205                                    SourceLocation InlineLoc,
6206                                    SourceLocation NamespaceLoc,
6207                                    SourceLocation IdentLoc,
6208                                    IdentifierInfo *II,
6209                                    SourceLocation LBrace,
6210                                    AttributeList *AttrList) {
6211   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6212   // For anonymous namespace, take the location of the left brace.
6213   SourceLocation Loc = II ? IdentLoc : LBrace;
6214   bool IsInline = InlineLoc.isValid();
6215   bool IsInvalid = false;
6216   bool IsStd = false;
6217   bool AddToKnown = false;
6218   Scope *DeclRegionScope = NamespcScope->getParent();
6219 
6220   NamespaceDecl *PrevNS = 0;
6221   if (II) {
6222     // C++ [namespace.def]p2:
6223     //   The identifier in an original-namespace-definition shall not
6224     //   have been previously defined in the declarative region in
6225     //   which the original-namespace-definition appears. The
6226     //   identifier in an original-namespace-definition is the name of
6227     //   the namespace. Subsequently in that declarative region, it is
6228     //   treated as an original-namespace-name.
6229     //
6230     // Since namespace names are unique in their scope, and we don't
6231     // look through using directives, just look for any ordinary names.
6232 
6233     const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
6234     Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6235     Decl::IDNS_Namespace;
6236     NamedDecl *PrevDecl = 0;
6237     DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6238     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6239          ++I) {
6240       if ((*I)->getIdentifierNamespace() & IDNS) {
6241         PrevDecl = *I;
6242         break;
6243       }
6244     }
6245 
6246     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6247 
6248     if (PrevNS) {
6249       // This is an extended namespace definition.
6250       if (IsInline != PrevNS->isInline())
6251         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6252                                         &IsInline, PrevNS);
6253     } else if (PrevDecl) {
6254       // This is an invalid name redefinition.
6255       Diag(Loc, diag::err_redefinition_different_kind)
6256         << II;
6257       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6258       IsInvalid = true;
6259       // Continue on to push Namespc as current DeclContext and return it.
6260     } else if (II->isStr("std") &&
6261                CurContext->getRedeclContext()->isTranslationUnit()) {
6262       // This is the first "real" definition of the namespace "std", so update
6263       // our cache of the "std" namespace to point at this definition.
6264       PrevNS = getStdNamespace();
6265       IsStd = true;
6266       AddToKnown = !IsInline;
6267     } else {
6268       // We've seen this namespace for the first time.
6269       AddToKnown = !IsInline;
6270     }
6271   } else {
6272     // Anonymous namespaces.
6273 
6274     // Determine whether the parent already has an anonymous namespace.
6275     DeclContext *Parent = CurContext->getRedeclContext();
6276     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6277       PrevNS = TU->getAnonymousNamespace();
6278     } else {
6279       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
6280       PrevNS = ND->getAnonymousNamespace();
6281     }
6282 
6283     if (PrevNS && IsInline != PrevNS->isInline())
6284       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6285                                       &IsInline, PrevNS);
6286   }
6287 
6288   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6289                                                  StartLoc, Loc, II, PrevNS);
6290   if (IsInvalid)
6291     Namespc->setInvalidDecl();
6292 
6293   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
6294 
6295   // FIXME: Should we be merging attributes?
6296   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
6297     PushNamespaceVisibilityAttr(Attr, Loc);
6298 
6299   if (IsStd)
6300     StdNamespace = Namespc;
6301   if (AddToKnown)
6302     KnownNamespaces[Namespc] = false;
6303 
6304   if (II) {
6305     PushOnScopeChains(Namespc, DeclRegionScope);
6306   } else {
6307     // Link the anonymous namespace into its parent.
6308     DeclContext *Parent = CurContext->getRedeclContext();
6309     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6310       TU->setAnonymousNamespace(Namespc);
6311     } else {
6312       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
6313     }
6314 
6315     CurContext->addDecl(Namespc);
6316 
6317     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
6318     //   behaves as if it were replaced by
6319     //     namespace unique { /* empty body */ }
6320     //     using namespace unique;
6321     //     namespace unique { namespace-body }
6322     //   where all occurrences of 'unique' in a translation unit are
6323     //   replaced by the same identifier and this identifier differs
6324     //   from all other identifiers in the entire program.
6325 
6326     // We just create the namespace with an empty name and then add an
6327     // implicit using declaration, just like the standard suggests.
6328     //
6329     // CodeGen enforces the "universally unique" aspect by giving all
6330     // declarations semantically contained within an anonymous
6331     // namespace internal linkage.
6332 
6333     if (!PrevNS) {
6334       UsingDirectiveDecl* UD
6335         = UsingDirectiveDecl::Create(Context, Parent,
6336                                      /* 'using' */ LBrace,
6337                                      /* 'namespace' */ SourceLocation(),
6338                                      /* qualifier */ NestedNameSpecifierLoc(),
6339                                      /* identifier */ SourceLocation(),
6340                                      Namespc,
6341                                      /* Ancestor */ Parent);
6342       UD->setImplicit();
6343       Parent->addDecl(UD);
6344     }
6345   }
6346 
6347   ActOnDocumentableDecl(Namespc);
6348 
6349   // Although we could have an invalid decl (i.e. the namespace name is a
6350   // redefinition), push it as current DeclContext and try to continue parsing.
6351   // FIXME: We should be able to push Namespc here, so that the each DeclContext
6352   // for the namespace has the declarations that showed up in that particular
6353   // namespace definition.
6354   PushDeclContext(NamespcScope, Namespc);
6355   return Namespc;
6356 }
6357 
6358 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6359 /// is a namespace alias, returns the namespace it points to.
6360 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6361   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6362     return AD->getNamespace();
6363   return dyn_cast_or_null<NamespaceDecl>(D);
6364 }
6365 
6366 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
6367 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
6368 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
6369   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6370   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
6371   Namespc->setRBraceLoc(RBrace);
6372   PopDeclContext();
6373   if (Namespc->hasAttr<VisibilityAttr>())
6374     PopPragmaVisibility(true, RBrace);
6375 }
6376 
6377 CXXRecordDecl *Sema::getStdBadAlloc() const {
6378   return cast_or_null<CXXRecordDecl>(
6379                                   StdBadAlloc.get(Context.getExternalSource()));
6380 }
6381 
6382 NamespaceDecl *Sema::getStdNamespace() const {
6383   return cast_or_null<NamespaceDecl>(
6384                                  StdNamespace.get(Context.getExternalSource()));
6385 }
6386 
6387 /// \brief Retrieve the special "std" namespace, which may require us to
6388 /// implicitly define the namespace.
6389 NamespaceDecl *Sema::getOrCreateStdNamespace() {
6390   if (!StdNamespace) {
6391     // The "std" namespace has not yet been defined, so build one implicitly.
6392     StdNamespace = NamespaceDecl::Create(Context,
6393                                          Context.getTranslationUnitDecl(),
6394                                          /*Inline=*/false,
6395                                          SourceLocation(), SourceLocation(),
6396                                          &PP.getIdentifierTable().get("std"),
6397                                          /*PrevDecl=*/0);
6398     getStdNamespace()->setImplicit(true);
6399   }
6400 
6401   return getStdNamespace();
6402 }
6403 
6404 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
6405   assert(getLangOpts().CPlusPlus &&
6406          "Looking for std::initializer_list outside of C++.");
6407 
6408   // We're looking for implicit instantiations of
6409   // template <typename E> class std::initializer_list.
6410 
6411   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6412     return false;
6413 
6414   ClassTemplateDecl *Template = 0;
6415   const TemplateArgument *Arguments = 0;
6416 
6417   if (const RecordType *RT = Ty->getAs<RecordType>()) {
6418 
6419     ClassTemplateSpecializationDecl *Specialization =
6420         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6421     if (!Specialization)
6422       return false;
6423 
6424     Template = Specialization->getSpecializedTemplate();
6425     Arguments = Specialization->getTemplateArgs().data();
6426   } else if (const TemplateSpecializationType *TST =
6427                  Ty->getAs<TemplateSpecializationType>()) {
6428     Template = dyn_cast_or_null<ClassTemplateDecl>(
6429         TST->getTemplateName().getAsTemplateDecl());
6430     Arguments = TST->getArgs();
6431   }
6432   if (!Template)
6433     return false;
6434 
6435   if (!StdInitializerList) {
6436     // Haven't recognized std::initializer_list yet, maybe this is it.
6437     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6438     if (TemplateClass->getIdentifier() !=
6439             &PP.getIdentifierTable().get("initializer_list") ||
6440         !getStdNamespace()->InEnclosingNamespaceSetOf(
6441             TemplateClass->getDeclContext()))
6442       return false;
6443     // This is a template called std::initializer_list, but is it the right
6444     // template?
6445     TemplateParameterList *Params = Template->getTemplateParameters();
6446     if (Params->getMinRequiredArguments() != 1)
6447       return false;
6448     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6449       return false;
6450 
6451     // It's the right template.
6452     StdInitializerList = Template;
6453   }
6454 
6455   if (Template != StdInitializerList)
6456     return false;
6457 
6458   // This is an instance of std::initializer_list. Find the argument type.
6459   if (Element)
6460     *Element = Arguments[0].getAsType();
6461   return true;
6462 }
6463 
6464 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6465   NamespaceDecl *Std = S.getStdNamespace();
6466   if (!Std) {
6467     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6468     return 0;
6469   }
6470 
6471   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6472                       Loc, Sema::LookupOrdinaryName);
6473   if (!S.LookupQualifiedName(Result, Std)) {
6474     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6475     return 0;
6476   }
6477   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6478   if (!Template) {
6479     Result.suppressDiagnostics();
6480     // We found something weird. Complain about the first thing we found.
6481     NamedDecl *Found = *Result.begin();
6482     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6483     return 0;
6484   }
6485 
6486   // We found some template called std::initializer_list. Now verify that it's
6487   // correct.
6488   TemplateParameterList *Params = Template->getTemplateParameters();
6489   if (Params->getMinRequiredArguments() != 1 ||
6490       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6491     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6492     return 0;
6493   }
6494 
6495   return Template;
6496 }
6497 
6498 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6499   if (!StdInitializerList) {
6500     StdInitializerList = LookupStdInitializerList(*this, Loc);
6501     if (!StdInitializerList)
6502       return QualType();
6503   }
6504 
6505   TemplateArgumentListInfo Args(Loc, Loc);
6506   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6507                                        Context.getTrivialTypeSourceInfo(Element,
6508                                                                         Loc)));
6509   return Context.getCanonicalType(
6510       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6511 }
6512 
6513 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6514   // C++ [dcl.init.list]p2:
6515   //   A constructor is an initializer-list constructor if its first parameter
6516   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
6517   //   std::initializer_list<E> for some type E, and either there are no other
6518   //   parameters or else all other parameters have default arguments.
6519   if (Ctor->getNumParams() < 1 ||
6520       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6521     return false;
6522 
6523   QualType ArgType = Ctor->getParamDecl(0)->getType();
6524   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6525     ArgType = RT->getPointeeType().getUnqualifiedType();
6526 
6527   return isStdInitializerList(ArgType, 0);
6528 }
6529 
6530 /// \brief Determine whether a using statement is in a context where it will be
6531 /// apply in all contexts.
6532 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6533   switch (CurContext->getDeclKind()) {
6534     case Decl::TranslationUnit:
6535       return true;
6536     case Decl::LinkageSpec:
6537       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6538     default:
6539       return false;
6540   }
6541 }
6542 
6543 namespace {
6544 
6545 // Callback to only accept typo corrections that are namespaces.
6546 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6547  public:
6548   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6549     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6550       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6551     }
6552     return false;
6553   }
6554 };
6555 
6556 }
6557 
6558 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6559                                        CXXScopeSpec &SS,
6560                                        SourceLocation IdentLoc,
6561                                        IdentifierInfo *Ident) {
6562   NamespaceValidatorCCC Validator;
6563   R.clear();
6564   if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
6565                                                R.getLookupKind(), Sc, &SS,
6566                                                Validator)) {
6567     std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6568     std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
6569     if (DeclContext *DC = S.computeDeclContext(SS, false))
6570       S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6571         << Ident << DC << CorrectedQuotedStr << SS.getRange()
6572         << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
6573                                         CorrectedStr);
6574     else
6575       S.Diag(IdentLoc, diag::err_using_directive_suggest)
6576         << Ident << CorrectedQuotedStr
6577         << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
6578 
6579     S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6580          diag::note_namespace_defined_here) << CorrectedQuotedStr;
6581 
6582     R.addDecl(Corrected.getCorrectionDecl());
6583     return true;
6584   }
6585   return false;
6586 }
6587 
6588 Decl *Sema::ActOnUsingDirective(Scope *S,
6589                                           SourceLocation UsingLoc,
6590                                           SourceLocation NamespcLoc,
6591                                           CXXScopeSpec &SS,
6592                                           SourceLocation IdentLoc,
6593                                           IdentifierInfo *NamespcName,
6594                                           AttributeList *AttrList) {
6595   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6596   assert(NamespcName && "Invalid NamespcName.");
6597   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
6598 
6599   // This can only happen along a recovery path.
6600   while (S->getFlags() & Scope::TemplateParamScope)
6601     S = S->getParent();
6602   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
6603 
6604   UsingDirectiveDecl *UDir = 0;
6605   NestedNameSpecifier *Qualifier = 0;
6606   if (SS.isSet())
6607     Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6608 
6609   // Lookup namespace name.
6610   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6611   LookupParsedName(R, S, &SS);
6612   if (R.isAmbiguous())
6613     return 0;
6614 
6615   if (R.empty()) {
6616     R.clear();
6617     // Allow "using namespace std;" or "using namespace ::std;" even if
6618     // "std" hasn't been defined yet, for GCC compatibility.
6619     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6620         NamespcName->isStr("std")) {
6621       Diag(IdentLoc, diag::ext_using_undefined_std);
6622       R.addDecl(getOrCreateStdNamespace());
6623       R.resolveKind();
6624     }
6625     // Otherwise, attempt typo correction.
6626     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
6627   }
6628 
6629   if (!R.empty()) {
6630     NamedDecl *Named = R.getFoundDecl();
6631     assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6632         && "expected namespace decl");
6633     // C++ [namespace.udir]p1:
6634     //   A using-directive specifies that the names in the nominated
6635     //   namespace can be used in the scope in which the
6636     //   using-directive appears after the using-directive. During
6637     //   unqualified name lookup (3.4.1), the names appear as if they
6638     //   were declared in the nearest enclosing namespace which
6639     //   contains both the using-directive and the nominated
6640     //   namespace. [Note: in this context, "contains" means "contains
6641     //   directly or indirectly". ]
6642 
6643     // Find enclosing context containing both using-directive and
6644     // nominated namespace.
6645     NamespaceDecl *NS = getNamespaceDecl(Named);
6646     DeclContext *CommonAncestor = cast<DeclContext>(NS);
6647     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6648       CommonAncestor = CommonAncestor->getParent();
6649 
6650     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
6651                                       SS.getWithLocInContext(Context),
6652                                       IdentLoc, Named, CommonAncestor);
6653 
6654     if (IsUsingDirectiveInToplevelContext(CurContext) &&
6655         !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
6656       Diag(IdentLoc, diag::warn_using_directive_in_header);
6657     }
6658 
6659     PushUsingDirective(S, UDir);
6660   } else {
6661     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
6662   }
6663 
6664   if (UDir)
6665     ProcessDeclAttributeList(S, UDir, AttrList);
6666 
6667   return UDir;
6668 }
6669 
6670 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
6671   // If the scope has an associated entity and the using directive is at
6672   // namespace or translation unit scope, add the UsingDirectiveDecl into
6673   // its lookup structure so qualified name lookup can find it.
6674   DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6675   if (Ctx && !Ctx->isFunctionOrMethod())
6676     Ctx->addDecl(UDir);
6677   else
6678     // Otherwise, it is at block sope. The using-directives will affect lookup
6679     // only to the end of the scope.
6680     S->PushUsingDirective(UDir);
6681 }
6682 
6683 
6684 Decl *Sema::ActOnUsingDeclaration(Scope *S,
6685                                   AccessSpecifier AS,
6686                                   bool HasUsingKeyword,
6687                                   SourceLocation UsingLoc,
6688                                   CXXScopeSpec &SS,
6689                                   UnqualifiedId &Name,
6690                                   AttributeList *AttrList,
6691                                   bool IsTypeName,
6692                                   SourceLocation TypenameLoc) {
6693   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
6694 
6695   switch (Name.getKind()) {
6696   case UnqualifiedId::IK_ImplicitSelfParam:
6697   case UnqualifiedId::IK_Identifier:
6698   case UnqualifiedId::IK_OperatorFunctionId:
6699   case UnqualifiedId::IK_LiteralOperatorId:
6700   case UnqualifiedId::IK_ConversionFunctionId:
6701     break;
6702 
6703   case UnqualifiedId::IK_ConstructorName:
6704   case UnqualifiedId::IK_ConstructorTemplateId:
6705     // C++11 inheriting constructors.
6706     Diag(Name.getLocStart(),
6707          getLangOpts().CPlusPlus11 ?
6708            diag::warn_cxx98_compat_using_decl_constructor :
6709            diag::err_using_decl_constructor)
6710       << SS.getRange();
6711 
6712     if (getLangOpts().CPlusPlus11) break;
6713 
6714     return 0;
6715 
6716   case UnqualifiedId::IK_DestructorName:
6717     Diag(Name.getLocStart(), diag::err_using_decl_destructor)
6718       << SS.getRange();
6719     return 0;
6720 
6721   case UnqualifiedId::IK_TemplateId:
6722     Diag(Name.getLocStart(), diag::err_using_decl_template_id)
6723       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
6724     return 0;
6725   }
6726 
6727   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6728   DeclarationName TargetName = TargetNameInfo.getName();
6729   if (!TargetName)
6730     return 0;
6731 
6732   // Warn about access declarations.
6733   // TODO: store that the declaration was written without 'using' and
6734   // talk about access decls instead of using decls in the
6735   // diagnostics.
6736   if (!HasUsingKeyword) {
6737     UsingLoc = Name.getLocStart();
6738 
6739     Diag(UsingLoc,
6740          getLangOpts().CPlusPlus11 ? diag::err_access_decl
6741                                    : diag::warn_access_decl_deprecated)
6742       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
6743   }
6744 
6745   if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6746       DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6747     return 0;
6748 
6749   NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
6750                                         TargetNameInfo, AttrList,
6751                                         /* IsInstantiation */ false,
6752                                         IsTypeName, TypenameLoc);
6753   if (UD)
6754     PushOnScopeChains(UD, S, /*AddToContext*/ false);
6755 
6756   return UD;
6757 }
6758 
6759 /// \brief Determine whether a using declaration considers the given
6760 /// declarations as "equivalent", e.g., if they are redeclarations of
6761 /// the same entity or are both typedefs of the same type.
6762 static bool
6763 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6764                          bool &SuppressRedeclaration) {
6765   if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6766     SuppressRedeclaration = false;
6767     return true;
6768   }
6769 
6770   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6771     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
6772       SuppressRedeclaration = true;
6773       return Context.hasSameType(TD1->getUnderlyingType(),
6774                                  TD2->getUnderlyingType());
6775     }
6776 
6777   return false;
6778 }
6779 
6780 
6781 /// Determines whether to create a using shadow decl for a particular
6782 /// decl, given the set of decls existing prior to this using lookup.
6783 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6784                                 const LookupResult &Previous) {
6785   // Diagnose finding a decl which is not from a base class of the
6786   // current class.  We do this now because there are cases where this
6787   // function will silently decide not to build a shadow decl, which
6788   // will pre-empt further diagnostics.
6789   //
6790   // We don't need to do this in C++0x because we do the check once on
6791   // the qualifier.
6792   //
6793   // FIXME: diagnose the following if we care enough:
6794   //   struct A { int foo; };
6795   //   struct B : A { using A::foo; };
6796   //   template <class T> struct C : A {};
6797   //   template <class T> struct D : C<T> { using B::foo; } // <---
6798   // This is invalid (during instantiation) in C++03 because B::foo
6799   // resolves to the using decl in B, which is not a base class of D<T>.
6800   // We can't diagnose it immediately because C<T> is an unknown
6801   // specialization.  The UsingShadowDecl in D<T> then points directly
6802   // to A::foo, which will look well-formed when we instantiate.
6803   // The right solution is to not collapse the shadow-decl chain.
6804   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
6805     DeclContext *OrigDC = Orig->getDeclContext();
6806 
6807     // Handle enums and anonymous structs.
6808     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6809     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6810     while (OrigRec->isAnonymousStructOrUnion())
6811       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6812 
6813     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6814       if (OrigDC == CurContext) {
6815         Diag(Using->getLocation(),
6816              diag::err_using_decl_nested_name_specifier_is_current_class)
6817           << Using->getQualifierLoc().getSourceRange();
6818         Diag(Orig->getLocation(), diag::note_using_decl_target);
6819         return true;
6820       }
6821 
6822       Diag(Using->getQualifierLoc().getBeginLoc(),
6823            diag::err_using_decl_nested_name_specifier_is_not_base_class)
6824         << Using->getQualifier()
6825         << cast<CXXRecordDecl>(CurContext)
6826         << Using->getQualifierLoc().getSourceRange();
6827       Diag(Orig->getLocation(), diag::note_using_decl_target);
6828       return true;
6829     }
6830   }
6831 
6832   if (Previous.empty()) return false;
6833 
6834   NamedDecl *Target = Orig;
6835   if (isa<UsingShadowDecl>(Target))
6836     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6837 
6838   // If the target happens to be one of the previous declarations, we
6839   // don't have a conflict.
6840   //
6841   // FIXME: but we might be increasing its access, in which case we
6842   // should redeclare it.
6843   NamedDecl *NonTag = 0, *Tag = 0;
6844   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6845          I != E; ++I) {
6846     NamedDecl *D = (*I)->getUnderlyingDecl();
6847     bool Result;
6848     if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6849       return Result;
6850 
6851     (isa<TagDecl>(D) ? Tag : NonTag) = D;
6852   }
6853 
6854   if (Target->isFunctionOrFunctionTemplate()) {
6855     FunctionDecl *FD;
6856     if (isa<FunctionTemplateDecl>(Target))
6857       FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6858     else
6859       FD = cast<FunctionDecl>(Target);
6860 
6861     NamedDecl *OldDecl = 0;
6862     switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
6863     case Ovl_Overload:
6864       return false;
6865 
6866     case Ovl_NonFunction:
6867       Diag(Using->getLocation(), diag::err_using_decl_conflict);
6868       break;
6869 
6870     // We found a decl with the exact signature.
6871     case Ovl_Match:
6872       // If we're in a record, we want to hide the target, so we
6873       // return true (without a diagnostic) to tell the caller not to
6874       // build a shadow decl.
6875       if (CurContext->isRecord())
6876         return true;
6877 
6878       // If we're not in a record, this is an error.
6879       Diag(Using->getLocation(), diag::err_using_decl_conflict);
6880       break;
6881     }
6882 
6883     Diag(Target->getLocation(), diag::note_using_decl_target);
6884     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6885     return true;
6886   }
6887 
6888   // Target is not a function.
6889 
6890   if (isa<TagDecl>(Target)) {
6891     // No conflict between a tag and a non-tag.
6892     if (!Tag) return false;
6893 
6894     Diag(Using->getLocation(), diag::err_using_decl_conflict);
6895     Diag(Target->getLocation(), diag::note_using_decl_target);
6896     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6897     return true;
6898   }
6899 
6900   // No conflict between a tag and a non-tag.
6901   if (!NonTag) return false;
6902 
6903   Diag(Using->getLocation(), diag::err_using_decl_conflict);
6904   Diag(Target->getLocation(), diag::note_using_decl_target);
6905   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6906   return true;
6907 }
6908 
6909 /// Builds a shadow declaration corresponding to a 'using' declaration.
6910 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
6911                                             UsingDecl *UD,
6912                                             NamedDecl *Orig) {
6913 
6914   // If we resolved to another shadow declaration, just coalesce them.
6915   NamedDecl *Target = Orig;
6916   if (isa<UsingShadowDecl>(Target)) {
6917     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6918     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
6919   }
6920 
6921   UsingShadowDecl *Shadow
6922     = UsingShadowDecl::Create(Context, CurContext,
6923                               UD->getLocation(), UD, Target);
6924   UD->addShadowDecl(Shadow);
6925 
6926   Shadow->setAccess(UD->getAccess());
6927   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6928     Shadow->setInvalidDecl();
6929 
6930   if (S)
6931     PushOnScopeChains(Shadow, S);
6932   else
6933     CurContext->addDecl(Shadow);
6934 
6935 
6936   return Shadow;
6937 }
6938 
6939 /// Hides a using shadow declaration.  This is required by the current
6940 /// using-decl implementation when a resolvable using declaration in a
6941 /// class is followed by a declaration which would hide or override
6942 /// one or more of the using decl's targets; for example:
6943 ///
6944 ///   struct Base { void foo(int); };
6945 ///   struct Derived : Base {
6946 ///     using Base::foo;
6947 ///     void foo(int);
6948 ///   };
6949 ///
6950 /// The governing language is C++03 [namespace.udecl]p12:
6951 ///
6952 ///   When a using-declaration brings names from a base class into a
6953 ///   derived class scope, member functions in the derived class
6954 ///   override and/or hide member functions with the same name and
6955 ///   parameter types in a base class (rather than conflicting).
6956 ///
6957 /// There are two ways to implement this:
6958 ///   (1) optimistically create shadow decls when they're not hidden
6959 ///       by existing declarations, or
6960 ///   (2) don't create any shadow decls (or at least don't make them
6961 ///       visible) until we've fully parsed/instantiated the class.
6962 /// The problem with (1) is that we might have to retroactively remove
6963 /// a shadow decl, which requires several O(n) operations because the
6964 /// decl structures are (very reasonably) not designed for removal.
6965 /// (2) avoids this but is very fiddly and phase-dependent.
6966 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
6967   if (Shadow->getDeclName().getNameKind() ==
6968         DeclarationName::CXXConversionFunctionName)
6969     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6970 
6971   // Remove it from the DeclContext...
6972   Shadow->getDeclContext()->removeDecl(Shadow);
6973 
6974   // ...and the scope, if applicable...
6975   if (S) {
6976     S->RemoveDecl(Shadow);
6977     IdResolver.RemoveDecl(Shadow);
6978   }
6979 
6980   // ...and the using decl.
6981   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6982 
6983   // TODO: complain somehow if Shadow was used.  It shouldn't
6984   // be possible for this to happen, because...?
6985 }
6986 
6987 /// Builds a using declaration.
6988 ///
6989 /// \param IsInstantiation - Whether this call arises from an
6990 ///   instantiation of an unresolved using declaration.  We treat
6991 ///   the lookup differently for these declarations.
6992 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6993                                        SourceLocation UsingLoc,
6994                                        CXXScopeSpec &SS,
6995                                        const DeclarationNameInfo &NameInfo,
6996                                        AttributeList *AttrList,
6997                                        bool IsInstantiation,
6998                                        bool IsTypeName,
6999                                        SourceLocation TypenameLoc) {
7000   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7001   SourceLocation IdentLoc = NameInfo.getLoc();
7002   assert(IdentLoc.isValid() && "Invalid TargetName location.");
7003 
7004   // FIXME: We ignore attributes for now.
7005 
7006   if (SS.isEmpty()) {
7007     Diag(IdentLoc, diag::err_using_requires_qualname);
7008     return 0;
7009   }
7010 
7011   // Do the redeclaration lookup in the current scope.
7012   LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
7013                         ForRedeclaration);
7014   Previous.setHideTags(false);
7015   if (S) {
7016     LookupName(Previous, S);
7017 
7018     // It is really dumb that we have to do this.
7019     LookupResult::Filter F = Previous.makeFilter();
7020     while (F.hasNext()) {
7021       NamedDecl *D = F.next();
7022       if (!isDeclInScope(D, CurContext, S))
7023         F.erase();
7024     }
7025     F.done();
7026   } else {
7027     assert(IsInstantiation && "no scope in non-instantiation");
7028     assert(CurContext->isRecord() && "scope not record in instantiation");
7029     LookupQualifiedName(Previous, CurContext);
7030   }
7031 
7032   // Check for invalid redeclarations.
7033   if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
7034     return 0;
7035 
7036   // Check for bad qualifiers.
7037   if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7038     return 0;
7039 
7040   DeclContext *LookupContext = computeDeclContext(SS);
7041   NamedDecl *D;
7042   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
7043   if (!LookupContext) {
7044     if (IsTypeName) {
7045       // FIXME: not all declaration name kinds are legal here
7046       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7047                                               UsingLoc, TypenameLoc,
7048                                               QualifierLoc,
7049                                               IdentLoc, NameInfo.getName());
7050     } else {
7051       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7052                                            QualifierLoc, NameInfo);
7053     }
7054   } else {
7055     D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
7056                           NameInfo, IsTypeName);
7057   }
7058   D->setAccess(AS);
7059   CurContext->addDecl(D);
7060 
7061   if (!LookupContext) return D;
7062   UsingDecl *UD = cast<UsingDecl>(D);
7063 
7064   if (RequireCompleteDeclContext(SS, LookupContext)) {
7065     UD->setInvalidDecl();
7066     return UD;
7067   }
7068 
7069   // The normal rules do not apply to inheriting constructor declarations.
7070   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
7071     if (CheckInheritingConstructorUsingDecl(UD))
7072       UD->setInvalidDecl();
7073     return UD;
7074   }
7075 
7076   // Otherwise, look up the target name.
7077 
7078   LookupResult R(*this, NameInfo, LookupOrdinaryName);
7079 
7080   // Unlike most lookups, we don't always want to hide tag
7081   // declarations: tag names are visible through the using declaration
7082   // even if hidden by ordinary names, *except* in a dependent context
7083   // where it's important for the sanity of two-phase lookup.
7084   if (!IsInstantiation)
7085     R.setHideTags(false);
7086 
7087   // For the purposes of this lookup, we have a base object type
7088   // equal to that of the current context.
7089   if (CurContext->isRecord()) {
7090     R.setBaseObjectType(
7091                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7092   }
7093 
7094   LookupQualifiedName(R, LookupContext);
7095 
7096   if (R.empty()) {
7097     Diag(IdentLoc, diag::err_no_member)
7098       << NameInfo.getName() << LookupContext << SS.getRange();
7099     UD->setInvalidDecl();
7100     return UD;
7101   }
7102 
7103   if (R.isAmbiguous()) {
7104     UD->setInvalidDecl();
7105     return UD;
7106   }
7107 
7108   if (IsTypeName) {
7109     // If we asked for a typename and got a non-type decl, error out.
7110     if (!R.getAsSingle<TypeDecl>()) {
7111       Diag(IdentLoc, diag::err_using_typename_non_type);
7112       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7113         Diag((*I)->getUnderlyingDecl()->getLocation(),
7114              diag::note_using_decl_target);
7115       UD->setInvalidDecl();
7116       return UD;
7117     }
7118   } else {
7119     // If we asked for a non-typename and we got a type, error out,
7120     // but only if this is an instantiation of an unresolved using
7121     // decl.  Otherwise just silently find the type name.
7122     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
7123       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7124       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
7125       UD->setInvalidDecl();
7126       return UD;
7127     }
7128   }
7129 
7130   // C++0x N2914 [namespace.udecl]p6:
7131   // A using-declaration shall not name a namespace.
7132   if (R.getAsSingle<NamespaceDecl>()) {
7133     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7134       << SS.getRange();
7135     UD->setInvalidDecl();
7136     return UD;
7137   }
7138 
7139   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7140     if (!CheckUsingShadowDecl(UD, *I, Previous))
7141       BuildUsingShadowDecl(S, UD, *I);
7142   }
7143 
7144   return UD;
7145 }
7146 
7147 /// Additional checks for a using declaration referring to a constructor name.
7148 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
7149   assert(!UD->isTypeName() && "expecting a constructor name");
7150 
7151   const Type *SourceType = UD->getQualifier()->getAsType();
7152   assert(SourceType &&
7153          "Using decl naming constructor doesn't have type in scope spec.");
7154   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7155 
7156   // Check whether the named type is a direct base class.
7157   CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7158   CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7159   for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7160        BaseIt != BaseE; ++BaseIt) {
7161     CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7162     if (CanonicalSourceType == BaseType)
7163       break;
7164     if (BaseIt->getType()->isDependentType())
7165       break;
7166   }
7167 
7168   if (BaseIt == BaseE) {
7169     // Did not find SourceType in the bases.
7170     Diag(UD->getUsingLocation(),
7171          diag::err_using_decl_constructor_not_in_direct_base)
7172       << UD->getNameInfo().getSourceRange()
7173       << QualType(SourceType, 0) << TargetClass;
7174     return true;
7175   }
7176 
7177   if (!CurContext->isDependentContext())
7178     BaseIt->setInheritConstructors();
7179 
7180   return false;
7181 }
7182 
7183 /// Checks that the given using declaration is not an invalid
7184 /// redeclaration.  Note that this is checking only for the using decl
7185 /// itself, not for any ill-formedness among the UsingShadowDecls.
7186 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7187                                        bool isTypeName,
7188                                        const CXXScopeSpec &SS,
7189                                        SourceLocation NameLoc,
7190                                        const LookupResult &Prev) {
7191   // C++03 [namespace.udecl]p8:
7192   // C++0x [namespace.udecl]p10:
7193   //   A using-declaration is a declaration and can therefore be used
7194   //   repeatedly where (and only where) multiple declarations are
7195   //   allowed.
7196   //
7197   // That's in non-member contexts.
7198   if (!CurContext->getRedeclContext()->isRecord())
7199     return false;
7200 
7201   NestedNameSpecifier *Qual
7202     = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7203 
7204   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7205     NamedDecl *D = *I;
7206 
7207     bool DTypename;
7208     NestedNameSpecifier *DQual;
7209     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7210       DTypename = UD->isTypeName();
7211       DQual = UD->getQualifier();
7212     } else if (UnresolvedUsingValueDecl *UD
7213                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7214       DTypename = false;
7215       DQual = UD->getQualifier();
7216     } else if (UnresolvedUsingTypenameDecl *UD
7217                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7218       DTypename = true;
7219       DQual = UD->getQualifier();
7220     } else continue;
7221 
7222     // using decls differ if one says 'typename' and the other doesn't.
7223     // FIXME: non-dependent using decls?
7224     if (isTypeName != DTypename) continue;
7225 
7226     // using decls differ if they name different scopes (but note that
7227     // template instantiation can cause this check to trigger when it
7228     // didn't before instantiation).
7229     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7230         Context.getCanonicalNestedNameSpecifier(DQual))
7231       continue;
7232 
7233     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
7234     Diag(D->getLocation(), diag::note_using_decl) << 1;
7235     return true;
7236   }
7237 
7238   return false;
7239 }
7240 
7241 
7242 /// Checks that the given nested-name qualifier used in a using decl
7243 /// in the current context is appropriately related to the current
7244 /// scope.  If an error is found, diagnoses it and returns true.
7245 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7246                                    const CXXScopeSpec &SS,
7247                                    SourceLocation NameLoc) {
7248   DeclContext *NamedContext = computeDeclContext(SS);
7249 
7250   if (!CurContext->isRecord()) {
7251     // C++03 [namespace.udecl]p3:
7252     // C++0x [namespace.udecl]p8:
7253     //   A using-declaration for a class member shall be a member-declaration.
7254 
7255     // If we weren't able to compute a valid scope, it must be a
7256     // dependent class scope.
7257     if (!NamedContext || NamedContext->isRecord()) {
7258       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7259         << SS.getRange();
7260       return true;
7261     }
7262 
7263     // Otherwise, everything is known to be fine.
7264     return false;
7265   }
7266 
7267   // The current scope is a record.
7268 
7269   // If the named context is dependent, we can't decide much.
7270   if (!NamedContext) {
7271     // FIXME: in C++0x, we can diagnose if we can prove that the
7272     // nested-name-specifier does not refer to a base class, which is
7273     // still possible in some cases.
7274 
7275     // Otherwise we have to conservatively report that things might be
7276     // okay.
7277     return false;
7278   }
7279 
7280   if (!NamedContext->isRecord()) {
7281     // Ideally this would point at the last name in the specifier,
7282     // but we don't have that level of source info.
7283     Diag(SS.getRange().getBegin(),
7284          diag::err_using_decl_nested_name_specifier_is_not_class)
7285       << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7286     return true;
7287   }
7288 
7289   if (!NamedContext->isDependentContext() &&
7290       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7291     return true;
7292 
7293   if (getLangOpts().CPlusPlus11) {
7294     // C++0x [namespace.udecl]p3:
7295     //   In a using-declaration used as a member-declaration, the
7296     //   nested-name-specifier shall name a base class of the class
7297     //   being defined.
7298 
7299     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7300                                  cast<CXXRecordDecl>(NamedContext))) {
7301       if (CurContext == NamedContext) {
7302         Diag(NameLoc,
7303              diag::err_using_decl_nested_name_specifier_is_current_class)
7304           << SS.getRange();
7305         return true;
7306       }
7307 
7308       Diag(SS.getRange().getBegin(),
7309            diag::err_using_decl_nested_name_specifier_is_not_base_class)
7310         << (NestedNameSpecifier*) SS.getScopeRep()
7311         << cast<CXXRecordDecl>(CurContext)
7312         << SS.getRange();
7313       return true;
7314     }
7315 
7316     return false;
7317   }
7318 
7319   // C++03 [namespace.udecl]p4:
7320   //   A using-declaration used as a member-declaration shall refer
7321   //   to a member of a base class of the class being defined [etc.].
7322 
7323   // Salient point: SS doesn't have to name a base class as long as
7324   // lookup only finds members from base classes.  Therefore we can
7325   // diagnose here only if we can prove that that can't happen,
7326   // i.e. if the class hierarchies provably don't intersect.
7327 
7328   // TODO: it would be nice if "definitely valid" results were cached
7329   // in the UsingDecl and UsingShadowDecl so that these checks didn't
7330   // need to be repeated.
7331 
7332   struct UserData {
7333     llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
7334 
7335     static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7336       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7337       Data->Bases.insert(Base);
7338       return true;
7339     }
7340 
7341     bool hasDependentBases(const CXXRecordDecl *Class) {
7342       return !Class->forallBases(collect, this);
7343     }
7344 
7345     /// Returns true if the base is dependent or is one of the
7346     /// accumulated base classes.
7347     static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7348       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7349       return !Data->Bases.count(Base);
7350     }
7351 
7352     bool mightShareBases(const CXXRecordDecl *Class) {
7353       return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7354     }
7355   };
7356 
7357   UserData Data;
7358 
7359   // Returns false if we find a dependent base.
7360   if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7361     return false;
7362 
7363   // Returns false if the class has a dependent base or if it or one
7364   // of its bases is present in the base set of the current context.
7365   if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7366     return false;
7367 
7368   Diag(SS.getRange().getBegin(),
7369        diag::err_using_decl_nested_name_specifier_is_not_base_class)
7370     << (NestedNameSpecifier*) SS.getScopeRep()
7371     << cast<CXXRecordDecl>(CurContext)
7372     << SS.getRange();
7373 
7374   return true;
7375 }
7376 
7377 Decl *Sema::ActOnAliasDeclaration(Scope *S,
7378                                   AccessSpecifier AS,
7379                                   MultiTemplateParamsArg TemplateParamLists,
7380                                   SourceLocation UsingLoc,
7381                                   UnqualifiedId &Name,
7382                                   AttributeList *AttrList,
7383                                   TypeResult Type) {
7384   // Skip up to the relevant declaration scope.
7385   while (S->getFlags() & Scope::TemplateParamScope)
7386     S = S->getParent();
7387   assert((S->getFlags() & Scope::DeclScope) &&
7388          "got alias-declaration outside of declaration scope");
7389 
7390   if (Type.isInvalid())
7391     return 0;
7392 
7393   bool Invalid = false;
7394   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7395   TypeSourceInfo *TInfo = 0;
7396   GetTypeFromParser(Type.get(), &TInfo);
7397 
7398   if (DiagnoseClassNameShadow(CurContext, NameInfo))
7399     return 0;
7400 
7401   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
7402                                       UPPC_DeclarationType)) {
7403     Invalid = true;
7404     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7405                                              TInfo->getTypeLoc().getBeginLoc());
7406   }
7407 
7408   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7409   LookupName(Previous, S);
7410 
7411   // Warn about shadowing the name of a template parameter.
7412   if (Previous.isSingleResult() &&
7413       Previous.getFoundDecl()->isTemplateParameter()) {
7414     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
7415     Previous.clear();
7416   }
7417 
7418   assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7419          "name in alias declaration must be an identifier");
7420   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7421                                                Name.StartLocation,
7422                                                Name.Identifier, TInfo);
7423 
7424   NewTD->setAccess(AS);
7425 
7426   if (Invalid)
7427     NewTD->setInvalidDecl();
7428 
7429   ProcessDeclAttributeList(S, NewTD, AttrList);
7430 
7431   CheckTypedefForVariablyModifiedType(S, NewTD);
7432   Invalid |= NewTD->isInvalidDecl();
7433 
7434   bool Redeclaration = false;
7435 
7436   NamedDecl *NewND;
7437   if (TemplateParamLists.size()) {
7438     TypeAliasTemplateDecl *OldDecl = 0;
7439     TemplateParameterList *OldTemplateParams = 0;
7440 
7441     if (TemplateParamLists.size() != 1) {
7442       Diag(UsingLoc, diag::err_alias_template_extra_headers)
7443         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7444          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
7445     }
7446     TemplateParameterList *TemplateParams = TemplateParamLists[0];
7447 
7448     // Only consider previous declarations in the same scope.
7449     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7450                          /*ExplicitInstantiationOrSpecialization*/false);
7451     if (!Previous.empty()) {
7452       Redeclaration = true;
7453 
7454       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7455       if (!OldDecl && !Invalid) {
7456         Diag(UsingLoc, diag::err_redefinition_different_kind)
7457           << Name.Identifier;
7458 
7459         NamedDecl *OldD = Previous.getRepresentativeDecl();
7460         if (OldD->getLocation().isValid())
7461           Diag(OldD->getLocation(), diag::note_previous_definition);
7462 
7463         Invalid = true;
7464       }
7465 
7466       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7467         if (TemplateParameterListsAreEqual(TemplateParams,
7468                                            OldDecl->getTemplateParameters(),
7469                                            /*Complain=*/true,
7470                                            TPL_TemplateMatch))
7471           OldTemplateParams = OldDecl->getTemplateParameters();
7472         else
7473           Invalid = true;
7474 
7475         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7476         if (!Invalid &&
7477             !Context.hasSameType(OldTD->getUnderlyingType(),
7478                                  NewTD->getUnderlyingType())) {
7479           // FIXME: The C++0x standard does not clearly say this is ill-formed,
7480           // but we can't reasonably accept it.
7481           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7482             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7483           if (OldTD->getLocation().isValid())
7484             Diag(OldTD->getLocation(), diag::note_previous_definition);
7485           Invalid = true;
7486         }
7487       }
7488     }
7489 
7490     // Merge any previous default template arguments into our parameters,
7491     // and check the parameter list.
7492     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7493                                    TPC_TypeAliasTemplate))
7494       return 0;
7495 
7496     TypeAliasTemplateDecl *NewDecl =
7497       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7498                                     Name.Identifier, TemplateParams,
7499                                     NewTD);
7500 
7501     NewDecl->setAccess(AS);
7502 
7503     if (Invalid)
7504       NewDecl->setInvalidDecl();
7505     else if (OldDecl)
7506       NewDecl->setPreviousDeclaration(OldDecl);
7507 
7508     NewND = NewDecl;
7509   } else {
7510     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7511     NewND = NewTD;
7512   }
7513 
7514   if (!Redeclaration)
7515     PushOnScopeChains(NewND, S);
7516 
7517   ActOnDocumentableDecl(NewND);
7518   return NewND;
7519 }
7520 
7521 Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
7522                                              SourceLocation NamespaceLoc,
7523                                              SourceLocation AliasLoc,
7524                                              IdentifierInfo *Alias,
7525                                              CXXScopeSpec &SS,
7526                                              SourceLocation IdentLoc,
7527                                              IdentifierInfo *Ident) {
7528 
7529   // Lookup the namespace name.
7530   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7531   LookupParsedName(R, S, &SS);
7532 
7533   // Check if we have a previous declaration with the same name.
7534   NamedDecl *PrevDecl
7535     = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7536                        ForRedeclaration);
7537   if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7538     PrevDecl = 0;
7539 
7540   if (PrevDecl) {
7541     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
7542       // We already have an alias with the same name that points to the same
7543       // namespace, so don't create a new one.
7544       // FIXME: At some point, we'll want to create the (redundant)
7545       // declaration to maintain better source information.
7546       if (!R.isAmbiguous() && !R.empty() &&
7547           AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
7548         return 0;
7549     }
7550 
7551     unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7552       diag::err_redefinition_different_kind;
7553     Diag(AliasLoc, DiagID) << Alias;
7554     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
7555     return 0;
7556   }
7557 
7558   if (R.isAmbiguous())
7559     return 0;
7560 
7561   if (R.empty()) {
7562     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
7563       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
7564       return 0;
7565     }
7566   }
7567 
7568   NamespaceAliasDecl *AliasDecl =
7569     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
7570                                Alias, SS.getWithLocInContext(Context),
7571                                IdentLoc, R.getFoundDecl());
7572 
7573   PushOnScopeChains(AliasDecl, S);
7574   return AliasDecl;
7575 }
7576 
7577 Sema::ImplicitExceptionSpecification
7578 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7579                                                CXXMethodDecl *MD) {
7580   CXXRecordDecl *ClassDecl = MD->getParent();
7581 
7582   // C++ [except.spec]p14:
7583   //   An implicitly declared special member function (Clause 12) shall have an
7584   //   exception-specification. [...]
7585   ImplicitExceptionSpecification ExceptSpec(*this);
7586   if (ClassDecl->isInvalidDecl())
7587     return ExceptSpec;
7588 
7589   // Direct base-class constructors.
7590   for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7591                                        BEnd = ClassDecl->bases_end();
7592        B != BEnd; ++B) {
7593     if (B->isVirtual()) // Handled below.
7594       continue;
7595 
7596     if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7597       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7598       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7599       // If this is a deleted function, add it anyway. This might be conformant
7600       // with the standard. This might not. I'm not sure. It might not matter.
7601       if (Constructor)
7602         ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7603     }
7604   }
7605 
7606   // Virtual base-class constructors.
7607   for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7608                                        BEnd = ClassDecl->vbases_end();
7609        B != BEnd; ++B) {
7610     if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7611       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7612       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7613       // If this is a deleted function, add it anyway. This might be conformant
7614       // with the standard. This might not. I'm not sure. It might not matter.
7615       if (Constructor)
7616         ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7617     }
7618   }
7619 
7620   // Field constructors.
7621   for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7622                                FEnd = ClassDecl->field_end();
7623        F != FEnd; ++F) {
7624     if (F->hasInClassInitializer()) {
7625       if (Expr *E = F->getInClassInitializer())
7626         ExceptSpec.CalledExpr(E);
7627       else if (!F->isInvalidDecl())
7628         // DR1351:
7629         //   If the brace-or-equal-initializer of a non-static data member
7630         //   invokes a defaulted default constructor of its class or of an
7631         //   enclosing class in a potentially evaluated subexpression, the
7632         //   program is ill-formed.
7633         //
7634         // This resolution is unworkable: the exception specification of the
7635         // default constructor can be needed in an unevaluated context, in
7636         // particular, in the operand of a noexcept-expression, and we can be
7637         // unable to compute an exception specification for an enclosed class.
7638         //
7639         // We do not allow an in-class initializer to require the evaluation
7640         // of the exception specification for any in-class initializer whose
7641         // definition is not lexically complete.
7642         Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
7643     } else if (const RecordType *RecordTy
7644               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7645       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7646       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7647       // If this is a deleted function, add it anyway. This might be conformant
7648       // with the standard. This might not. I'm not sure. It might not matter.
7649       // In particular, the problem is that this function never gets called. It
7650       // might just be ill-formed because this function attempts to refer to
7651       // a deleted function here.
7652       if (Constructor)
7653         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7654     }
7655   }
7656 
7657   return ExceptSpec;
7658 }
7659 
7660 Sema::ImplicitExceptionSpecification
7661 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
7662   CXXRecordDecl *ClassDecl = CD->getParent();
7663 
7664   // C++ [except.spec]p14:
7665   //   An inheriting constructor [...] shall have an exception-specification. [...]
7666   ImplicitExceptionSpecification ExceptSpec(*this);
7667   if (ClassDecl->isInvalidDecl())
7668     return ExceptSpec;
7669 
7670   // Inherited constructor.
7671   const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
7672   const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
7673   // FIXME: Copying or moving the parameters could add extra exceptions to the
7674   // set, as could the default arguments for the inherited constructor. This
7675   // will be addressed when we implement the resolution of core issue 1351.
7676   ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
7677 
7678   // Direct base-class constructors.
7679   for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7680                                        BEnd = ClassDecl->bases_end();
7681        B != BEnd; ++B) {
7682     if (B->isVirtual()) // Handled below.
7683       continue;
7684 
7685     if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7686       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7687       if (BaseClassDecl == InheritedDecl)
7688         continue;
7689       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7690       if (Constructor)
7691         ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7692     }
7693   }
7694 
7695   // Virtual base-class constructors.
7696   for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7697                                        BEnd = ClassDecl->vbases_end();
7698        B != BEnd; ++B) {
7699     if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7700       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7701       if (BaseClassDecl == InheritedDecl)
7702         continue;
7703       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7704       if (Constructor)
7705         ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7706     }
7707   }
7708 
7709   // Field constructors.
7710   for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7711                                FEnd = ClassDecl->field_end();
7712        F != FEnd; ++F) {
7713     if (F->hasInClassInitializer()) {
7714       if (Expr *E = F->getInClassInitializer())
7715         ExceptSpec.CalledExpr(E);
7716       else if (!F->isInvalidDecl())
7717         Diag(CD->getLocation(),
7718              diag::err_in_class_initializer_references_def_ctor) << CD;
7719     } else if (const RecordType *RecordTy
7720               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7721       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7722       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7723       if (Constructor)
7724         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7725     }
7726   }
7727 
7728   return ExceptSpec;
7729 }
7730 
7731 namespace {
7732 /// RAII object to register a special member as being currently declared.
7733 struct DeclaringSpecialMember {
7734   Sema &S;
7735   Sema::SpecialMemberDecl D;
7736   bool WasAlreadyBeingDeclared;
7737 
7738   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7739     : S(S), D(RD, CSM) {
7740     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7741     if (WasAlreadyBeingDeclared)
7742       // This almost never happens, but if it does, ensure that our cache
7743       // doesn't contain a stale result.
7744       S.SpecialMemberCache.clear();
7745 
7746     // FIXME: Register a note to be produced if we encounter an error while
7747     // declaring the special member.
7748   }
7749   ~DeclaringSpecialMember() {
7750     if (!WasAlreadyBeingDeclared)
7751       S.SpecialMembersBeingDeclared.erase(D);
7752   }
7753 
7754   /// \brief Are we already trying to declare this special member?
7755   bool isAlreadyBeingDeclared() const {
7756     return WasAlreadyBeingDeclared;
7757   }
7758 };
7759 }
7760 
7761 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7762                                                      CXXRecordDecl *ClassDecl) {
7763   // C++ [class.ctor]p5:
7764   //   A default constructor for a class X is a constructor of class X
7765   //   that can be called without an argument. If there is no
7766   //   user-declared constructor for class X, a default constructor is
7767   //   implicitly declared. An implicitly-declared default constructor
7768   //   is an inline public member of its class.
7769   assert(ClassDecl->needsImplicitDefaultConstructor() &&
7770          "Should not build implicit default constructor!");
7771 
7772   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7773   if (DSM.isAlreadyBeingDeclared())
7774     return 0;
7775 
7776   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7777                                                      CXXDefaultConstructor,
7778                                                      false);
7779 
7780   // Create the actual constructor declaration.
7781   CanQualType ClassType
7782     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
7783   SourceLocation ClassLoc = ClassDecl->getLocation();
7784   DeclarationName Name
7785     = Context.DeclarationNames.getCXXConstructorName(ClassType);
7786   DeclarationNameInfo NameInfo(Name, ClassLoc);
7787   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
7788       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
7789       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
7790       Constexpr);
7791   DefaultCon->setAccess(AS_public);
7792   DefaultCon->setDefaulted();
7793   DefaultCon->setImplicit();
7794 
7795   // Build an exception specification pointing back at this constructor.
7796   FunctionProtoType::ExtProtoInfo EPI;
7797   EPI.ExceptionSpecType = EST_Unevaluated;
7798   EPI.ExceptionSpecDecl = DefaultCon;
7799   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
7800 
7801   // We don't need to use SpecialMemberIsTrivial here; triviality for default
7802   // constructors is easy to compute.
7803   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7804 
7805   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
7806     SetDeclDeleted(DefaultCon, ClassLoc);
7807 
7808   // Note that we have declared this constructor.
7809   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
7810 
7811   if (Scope *S = getScopeForContext(ClassDecl))
7812     PushOnScopeChains(DefaultCon, S, false);
7813   ClassDecl->addDecl(DefaultCon);
7814 
7815   return DefaultCon;
7816 }
7817 
7818 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7819                                             CXXConstructorDecl *Constructor) {
7820   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
7821           !Constructor->doesThisDeclarationHaveABody() &&
7822           !Constructor->isDeleted()) &&
7823     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
7824 
7825   CXXRecordDecl *ClassDecl = Constructor->getParent();
7826   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
7827 
7828   SynthesizedFunctionScope Scope(*this, Constructor);
7829   DiagnosticErrorTrap Trap(Diags);
7830   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
7831       Trap.hasErrorOccurred()) {
7832     Diag(CurrentLocation, diag::note_member_synthesized_at)
7833       << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
7834     Constructor->setInvalidDecl();
7835     return;
7836   }
7837 
7838   SourceLocation Loc = Constructor->getLocation();
7839   Constructor->setBody(new (Context) CompoundStmt(Loc));
7840 
7841   Constructor->setUsed();
7842   MarkVTableUsed(CurrentLocation, ClassDecl);
7843 
7844   if (ASTMutationListener *L = getASTMutationListener()) {
7845     L->CompletedImplicitDefinition(Constructor);
7846   }
7847 }
7848 
7849 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
7850   // Check that any explicitly-defaulted methods have exception specifications
7851   // compatible with their implicit exception specifications.
7852   CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
7853 }
7854 
7855 namespace {
7856 /// Information on inheriting constructors to declare.
7857 class InheritingConstructorInfo {
7858 public:
7859   InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
7860       : SemaRef(SemaRef), Derived(Derived) {
7861     // Mark the constructors that we already have in the derived class.
7862     //
7863     // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7864     //   unless there is a user-declared constructor with the same signature in
7865     //   the class where the using-declaration appears.
7866     visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
7867   }
7868 
7869   void inheritAll(CXXRecordDecl *RD) {
7870     visitAll(RD, &InheritingConstructorInfo::inherit);
7871   }
7872 
7873 private:
7874   /// Information about an inheriting constructor.
7875   struct InheritingConstructor {
7876     InheritingConstructor()
7877       : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
7878 
7879     /// If \c true, a constructor with this signature is already declared
7880     /// in the derived class.
7881     bool DeclaredInDerived;
7882 
7883     /// The constructor which is inherited.
7884     const CXXConstructorDecl *BaseCtor;
7885 
7886     /// The derived constructor we declared.
7887     CXXConstructorDecl *DerivedCtor;
7888   };
7889 
7890   /// Inheriting constructors with a given canonical type. There can be at
7891   /// most one such non-template constructor, and any number of templated
7892   /// constructors.
7893   struct InheritingConstructorsForType {
7894     InheritingConstructor NonTemplate;
7895     llvm::SmallVector<
7896       std::pair<TemplateParameterList*, InheritingConstructor>, 4> Templates;
7897 
7898     InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
7899       if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
7900         TemplateParameterList *ParamList = FTD->getTemplateParameters();
7901         for (unsigned I = 0, N = Templates.size(); I != N; ++I)
7902           if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
7903                                                false, S.TPL_TemplateMatch))
7904             return Templates[I].second;
7905         Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
7906         return Templates.back().second;
7907       }
7908 
7909       return NonTemplate;
7910     }
7911   };
7912 
7913   /// Get or create the inheriting constructor record for a constructor.
7914   InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
7915                                   QualType CtorType) {
7916     return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
7917         .getEntry(SemaRef, Ctor);
7918   }
7919 
7920   typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
7921 
7922   /// Process all constructors for a class.
7923   void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
7924     for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
7925                                       CtorE = RD->ctor_end();
7926          CtorIt != CtorE; ++CtorIt)
7927       (this->*Callback)(*CtorIt);
7928     for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
7929              I(RD->decls_begin()), E(RD->decls_end());
7930          I != E; ++I) {
7931       const FunctionDecl *FD = (*I)->getTemplatedDecl();
7932       if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
7933         (this->*Callback)(CD);
7934     }
7935   }
7936 
7937   /// Note that a constructor (or constructor template) was declared in Derived.
7938   void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
7939     getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
7940   }
7941 
7942   /// Inherit a single constructor.
7943   void inherit(const CXXConstructorDecl *Ctor) {
7944     const FunctionProtoType *CtorType =
7945         Ctor->getType()->castAs<FunctionProtoType>();
7946     ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
7947     FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
7948 
7949     SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
7950 
7951     // Core issue (no number yet): the ellipsis is always discarded.
7952     if (EPI.Variadic) {
7953       SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
7954       SemaRef.Diag(Ctor->getLocation(),
7955                    diag::note_using_decl_constructor_ellipsis);
7956       EPI.Variadic = false;
7957     }
7958 
7959     // Declare a constructor for each number of parameters.
7960     //
7961     // C++11 [class.inhctor]p1:
7962     //   The candidate set of inherited constructors from the class X named in
7963     //   the using-declaration consists of [... modulo defects ...] for each
7964     //   constructor or constructor template of X, the set of constructors or
7965     //   constructor templates that results from omitting any ellipsis parameter
7966     //   specification and successively omitting parameters with a default
7967     //   argument from the end of the parameter-type-list
7968     unsigned MinParams = minParamsToInherit(Ctor);
7969     unsigned Params = Ctor->getNumParams();
7970     if (Params >= MinParams) {
7971       do
7972         declareCtor(UsingLoc, Ctor,
7973                     SemaRef.Context.getFunctionType(
7974                         Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
7975       while (Params > MinParams &&
7976              Ctor->getParamDecl(--Params)->hasDefaultArg());
7977     }
7978   }
7979 
7980   /// Find the using-declaration which specified that we should inherit the
7981   /// constructors of \p Base.
7982   SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
7983     // No fancy lookup required; just look for the base constructor name
7984     // directly within the derived class.
7985     ASTContext &Context = SemaRef.Context;
7986     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
7987         Context.getCanonicalType(Context.getRecordType(Base)));
7988     DeclContext::lookup_const_result Decls = Derived->lookup(Name);
7989     return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
7990   }
7991 
7992   unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
7993     // C++11 [class.inhctor]p3:
7994     //   [F]or each constructor template in the candidate set of inherited
7995     //   constructors, a constructor template is implicitly declared
7996     if (Ctor->getDescribedFunctionTemplate())
7997       return 0;
7998 
7999     //   For each non-template constructor in the candidate set of inherited
8000     //   constructors other than a constructor having no parameters or a
8001     //   copy/move constructor having a single parameter, a constructor is
8002     //   implicitly declared [...]
8003     if (Ctor->getNumParams() == 0)
8004       return 1;
8005     if (Ctor->isCopyOrMoveConstructor())
8006       return 2;
8007 
8008     // Per discussion on core reflector, never inherit a constructor which
8009     // would become a default, copy, or move constructor of Derived either.
8010     const ParmVarDecl *PD = Ctor->getParamDecl(0);
8011     const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8012     return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8013   }
8014 
8015   /// Declare a single inheriting constructor, inheriting the specified
8016   /// constructor, with the given type.
8017   void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8018                    QualType DerivedType) {
8019     InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8020 
8021     // C++11 [class.inhctor]p3:
8022     //   ... a constructor is implicitly declared with the same constructor
8023     //   characteristics unless there is a user-declared constructor with
8024     //   the same signature in the class where the using-declaration appears
8025     if (Entry.DeclaredInDerived)
8026       return;
8027 
8028     // C++11 [class.inhctor]p7:
8029     //   If two using-declarations declare inheriting constructors with the
8030     //   same signature, the program is ill-formed
8031     if (Entry.DerivedCtor) {
8032       if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8033         // Only diagnose this once per constructor.
8034         if (Entry.DerivedCtor->isInvalidDecl())
8035           return;
8036         Entry.DerivedCtor->setInvalidDecl();
8037 
8038         SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8039         SemaRef.Diag(BaseCtor->getLocation(),
8040                      diag::note_using_decl_constructor_conflict_current_ctor);
8041         SemaRef.Diag(Entry.BaseCtor->getLocation(),
8042                      diag::note_using_decl_constructor_conflict_previous_ctor);
8043         SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8044                      diag::note_using_decl_constructor_conflict_previous_using);
8045       } else {
8046         // Core issue (no number): if the same inheriting constructor is
8047         // produced by multiple base class constructors from the same base
8048         // class, the inheriting constructor is defined as deleted.
8049         SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8050       }
8051 
8052       return;
8053     }
8054 
8055     ASTContext &Context = SemaRef.Context;
8056     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8057         Context.getCanonicalType(Context.getRecordType(Derived)));
8058     DeclarationNameInfo NameInfo(Name, UsingLoc);
8059 
8060     TemplateParameterList *TemplateParams = 0;
8061     if (const FunctionTemplateDecl *FTD =
8062             BaseCtor->getDescribedFunctionTemplate()) {
8063       TemplateParams = FTD->getTemplateParameters();
8064       // We're reusing template parameters from a different DeclContext. This
8065       // is questionable at best, but works out because the template depth in
8066       // both places is guaranteed to be 0.
8067       // FIXME: Rebuild the template parameters in the new context, and
8068       // transform the function type to refer to them.
8069     }
8070 
8071     // Build type source info pointing at the using-declaration. This is
8072     // required by template instantiation.
8073     TypeSourceInfo *TInfo =
8074         Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8075     FunctionProtoTypeLoc ProtoLoc =
8076         TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8077 
8078     CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8079         Context, Derived, UsingLoc, NameInfo, DerivedType,
8080         TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8081         /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8082 
8083     // Build an unevaluated exception specification for this constructor.
8084     const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8085     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8086     EPI.ExceptionSpecType = EST_Unevaluated;
8087     EPI.ExceptionSpecDecl = DerivedCtor;
8088     DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
8089                                                  FPT->getArgTypes(), EPI));
8090 
8091     // Build the parameter declarations.
8092     SmallVector<ParmVarDecl *, 16> ParamDecls;
8093     for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
8094       TypeSourceInfo *TInfo =
8095           Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
8096       ParmVarDecl *PD = ParmVarDecl::Create(
8097           Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
8098           FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
8099       PD->setScopeInfo(0, I);
8100       PD->setImplicit();
8101       ParamDecls.push_back(PD);
8102       ProtoLoc.setArg(I, PD);
8103     }
8104 
8105     // Set up the new constructor.
8106     DerivedCtor->setAccess(BaseCtor->getAccess());
8107     DerivedCtor->setParams(ParamDecls);
8108     DerivedCtor->setInheritedConstructor(BaseCtor);
8109     if (BaseCtor->isDeleted())
8110       SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8111 
8112     // If this is a constructor template, build the template declaration.
8113     if (TemplateParams) {
8114       FunctionTemplateDecl *DerivedTemplate =
8115           FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8116                                        TemplateParams, DerivedCtor);
8117       DerivedTemplate->setAccess(BaseCtor->getAccess());
8118       DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8119       Derived->addDecl(DerivedTemplate);
8120     } else {
8121       Derived->addDecl(DerivedCtor);
8122     }
8123 
8124     Entry.BaseCtor = BaseCtor;
8125     Entry.DerivedCtor = DerivedCtor;
8126   }
8127 
8128   Sema &SemaRef;
8129   CXXRecordDecl *Derived;
8130   typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8131   MapType Map;
8132 };
8133 }
8134 
8135 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8136   // Defer declaring the inheriting constructors until the class is
8137   // instantiated.
8138   if (ClassDecl->isDependentContext())
8139     return;
8140 
8141   // Find base classes from which we might inherit constructors.
8142   SmallVector<CXXRecordDecl*, 4> InheritedBases;
8143   for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8144                                           BaseE = ClassDecl->bases_end();
8145        BaseIt != BaseE; ++BaseIt)
8146     if (BaseIt->getInheritConstructors())
8147       InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
8148 
8149   // Go no further if we're not inheriting any constructors.
8150   if (InheritedBases.empty())
8151     return;
8152 
8153   // Declare the inherited constructors.
8154   InheritingConstructorInfo ICI(*this, ClassDecl);
8155   for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8156     ICI.inheritAll(InheritedBases[I]);
8157 }
8158 
8159 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8160                                        CXXConstructorDecl *Constructor) {
8161   CXXRecordDecl *ClassDecl = Constructor->getParent();
8162   assert(Constructor->getInheritedConstructor() &&
8163          !Constructor->doesThisDeclarationHaveABody() &&
8164          !Constructor->isDeleted());
8165 
8166   SynthesizedFunctionScope Scope(*this, Constructor);
8167   DiagnosticErrorTrap Trap(Diags);
8168   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8169       Trap.hasErrorOccurred()) {
8170     Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8171       << Context.getTagDeclType(ClassDecl);
8172     Constructor->setInvalidDecl();
8173     return;
8174   }
8175 
8176   SourceLocation Loc = Constructor->getLocation();
8177   Constructor->setBody(new (Context) CompoundStmt(Loc));
8178 
8179   Constructor->setUsed();
8180   MarkVTableUsed(CurrentLocation, ClassDecl);
8181 
8182   if (ASTMutationListener *L = getASTMutationListener()) {
8183     L->CompletedImplicitDefinition(Constructor);
8184   }
8185 }
8186 
8187 
8188 Sema::ImplicitExceptionSpecification
8189 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8190   CXXRecordDecl *ClassDecl = MD->getParent();
8191 
8192   // C++ [except.spec]p14:
8193   //   An implicitly declared special member function (Clause 12) shall have
8194   //   an exception-specification.
8195   ImplicitExceptionSpecification ExceptSpec(*this);
8196   if (ClassDecl->isInvalidDecl())
8197     return ExceptSpec;
8198 
8199   // Direct base-class destructors.
8200   for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8201                                        BEnd = ClassDecl->bases_end();
8202        B != BEnd; ++B) {
8203     if (B->isVirtual()) // Handled below.
8204       continue;
8205 
8206     if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
8207       ExceptSpec.CalledDecl(B->getLocStart(),
8208                    LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
8209   }
8210 
8211   // Virtual base-class destructors.
8212   for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8213                                        BEnd = ClassDecl->vbases_end();
8214        B != BEnd; ++B) {
8215     if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
8216       ExceptSpec.CalledDecl(B->getLocStart(),
8217                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
8218   }
8219 
8220   // Field destructors.
8221   for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8222                                FEnd = ClassDecl->field_end();
8223        F != FEnd; ++F) {
8224     if (const RecordType *RecordTy
8225         = Context.getBaseElementType(F->getType())->getAs<RecordType>())
8226       ExceptSpec.CalledDecl(F->getLocation(),
8227                   LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
8228   }
8229 
8230   return ExceptSpec;
8231 }
8232 
8233 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8234   // C++ [class.dtor]p2:
8235   //   If a class has no user-declared destructor, a destructor is
8236   //   declared implicitly. An implicitly-declared destructor is an
8237   //   inline public member of its class.
8238   assert(ClassDecl->needsImplicitDestructor());
8239 
8240   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8241   if (DSM.isAlreadyBeingDeclared())
8242     return 0;
8243 
8244   // Create the actual destructor declaration.
8245   CanQualType ClassType
8246     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8247   SourceLocation ClassLoc = ClassDecl->getLocation();
8248   DeclarationName Name
8249     = Context.DeclarationNames.getCXXDestructorName(ClassType);
8250   DeclarationNameInfo NameInfo(Name, ClassLoc);
8251   CXXDestructorDecl *Destructor
8252       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8253                                   QualType(), 0, /*isInline=*/true,
8254                                   /*isImplicitlyDeclared=*/true);
8255   Destructor->setAccess(AS_public);
8256   Destructor->setDefaulted();
8257   Destructor->setImplicit();
8258 
8259   // Build an exception specification pointing back at this destructor.
8260   FunctionProtoType::ExtProtoInfo EPI;
8261   EPI.ExceptionSpecType = EST_Unevaluated;
8262   EPI.ExceptionSpecDecl = Destructor;
8263   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8264 
8265   AddOverriddenMethods(ClassDecl, Destructor);
8266 
8267   // We don't need to use SpecialMemberIsTrivial here; triviality for
8268   // destructors is easy to compute.
8269   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8270 
8271   if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
8272     SetDeclDeleted(Destructor, ClassLoc);
8273 
8274   // Note that we have declared this destructor.
8275   ++ASTContext::NumImplicitDestructorsDeclared;
8276 
8277   // Introduce this destructor into its scope.
8278   if (Scope *S = getScopeForContext(ClassDecl))
8279     PushOnScopeChains(Destructor, S, false);
8280   ClassDecl->addDecl(Destructor);
8281 
8282   return Destructor;
8283 }
8284 
8285 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
8286                                     CXXDestructorDecl *Destructor) {
8287   assert((Destructor->isDefaulted() &&
8288           !Destructor->doesThisDeclarationHaveABody() &&
8289           !Destructor->isDeleted()) &&
8290          "DefineImplicitDestructor - call it for implicit default dtor");
8291   CXXRecordDecl *ClassDecl = Destructor->getParent();
8292   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
8293 
8294   if (Destructor->isInvalidDecl())
8295     return;
8296 
8297   SynthesizedFunctionScope Scope(*this, Destructor);
8298 
8299   DiagnosticErrorTrap Trap(Diags);
8300   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8301                                          Destructor->getParent());
8302 
8303   if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
8304     Diag(CurrentLocation, diag::note_member_synthesized_at)
8305       << CXXDestructor << Context.getTagDeclType(ClassDecl);
8306 
8307     Destructor->setInvalidDecl();
8308     return;
8309   }
8310 
8311   SourceLocation Loc = Destructor->getLocation();
8312   Destructor->setBody(new (Context) CompoundStmt(Loc));
8313   Destructor->setImplicitlyDefined(true);
8314   Destructor->setUsed();
8315   MarkVTableUsed(CurrentLocation, ClassDecl);
8316 
8317   if (ASTMutationListener *L = getASTMutationListener()) {
8318     L->CompletedImplicitDefinition(Destructor);
8319   }
8320 }
8321 
8322 /// \brief Perform any semantic analysis which needs to be delayed until all
8323 /// pending class member declarations have been parsed.
8324 void Sema::ActOnFinishCXXMemberDecls() {
8325   // If the context is an invalid C++ class, just suppress these checks.
8326   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8327     if (Record->isInvalidDecl()) {
8328       DelayedDestructorExceptionSpecChecks.clear();
8329       return;
8330     }
8331   }
8332 
8333   // Perform any deferred checking of exception specifications for virtual
8334   // destructors.
8335   for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
8336        i != e; ++i) {
8337     const CXXDestructorDecl *Dtor =
8338         DelayedDestructorExceptionSpecChecks[i].first;
8339     assert(!Dtor->getParent()->isDependentType() &&
8340            "Should not ever add destructors of templates into the list.");
8341     CheckOverridingFunctionExceptionSpec(Dtor,
8342         DelayedDestructorExceptionSpecChecks[i].second);
8343   }
8344   DelayedDestructorExceptionSpecChecks.clear();
8345 }
8346 
8347 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8348                                          CXXDestructorDecl *Destructor) {
8349   assert(getLangOpts().CPlusPlus11 &&
8350          "adjusting dtor exception specs was introduced in c++11");
8351 
8352   // C++11 [class.dtor]p3:
8353   //   A declaration of a destructor that does not have an exception-
8354   //   specification is implicitly considered to have the same exception-
8355   //   specification as an implicit declaration.
8356   const FunctionProtoType *DtorType = Destructor->getType()->
8357                                         getAs<FunctionProtoType>();
8358   if (DtorType->hasExceptionSpec())
8359     return;
8360 
8361   // Replace the destructor's type, building off the existing one. Fortunately,
8362   // the only thing of interest in the destructor type is its extended info.
8363   // The return and arguments are fixed.
8364   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8365   EPI.ExceptionSpecType = EST_Unevaluated;
8366   EPI.ExceptionSpecDecl = Destructor;
8367   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8368 
8369   // FIXME: If the destructor has a body that could throw, and the newly created
8370   // spec doesn't allow exceptions, we should emit a warning, because this
8371   // change in behavior can break conforming C++03 programs at runtime.
8372   // However, we don't have a body or an exception specification yet, so it
8373   // needs to be done somewhere else.
8374 }
8375 
8376 /// When generating a defaulted copy or move assignment operator, if a field
8377 /// should be copied with __builtin_memcpy rather than via explicit assignments,
8378 /// do so. This optimization only applies for arrays of scalars, and for arrays
8379 /// of class type where the selected copy/move-assignment operator is trivial.
8380 static StmtResult
8381 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
8382                            Expr *To, Expr *From) {
8383   // Compute the size of the memory buffer to be copied.
8384   QualType SizeType = S.Context.getSizeType();
8385   llvm::APInt Size(S.Context.getTypeSize(SizeType),
8386                    S.Context.getTypeSizeInChars(T).getQuantity());
8387 
8388   // Take the address of the field references for "from" and "to". We
8389   // directly construct UnaryOperators here because semantic analysis
8390   // does not permit us to take the address of an xvalue.
8391   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8392                          S.Context.getPointerType(From->getType()),
8393                          VK_RValue, OK_Ordinary, Loc);
8394   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8395                        S.Context.getPointerType(To->getType()),
8396                        VK_RValue, OK_Ordinary, Loc);
8397 
8398   const Type *E = T->getBaseElementTypeUnsafe();
8399   bool NeedsCollectableMemCpy =
8400     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8401 
8402   // Create a reference to the __builtin_objc_memmove_collectable function
8403   StringRef MemCpyName = NeedsCollectableMemCpy ?
8404     "__builtin_objc_memmove_collectable" :
8405     "__builtin_memcpy";
8406   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8407                  Sema::LookupOrdinaryName);
8408   S.LookupName(R, S.TUScope, true);
8409 
8410   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8411   if (!MemCpy)
8412     // Something went horribly wrong earlier, and we will have complained
8413     // about it.
8414     return StmtError();
8415 
8416   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8417                                             VK_RValue, Loc, 0);
8418   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8419 
8420   Expr *CallArgs[] = {
8421     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8422   };
8423   ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8424                                     Loc, CallArgs, Loc);
8425 
8426   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8427   return S.Owned(Call.takeAs<Stmt>());
8428 }
8429 
8430 /// \brief Builds a statement that copies/moves the given entity from \p From to
8431 /// \c To.
8432 ///
8433 /// This routine is used to copy/move the members of a class with an
8434 /// implicitly-declared copy/move assignment operator. When the entities being
8435 /// copied are arrays, this routine builds for loops to copy them.
8436 ///
8437 /// \param S The Sema object used for type-checking.
8438 ///
8439 /// \param Loc The location where the implicit copy/move is being generated.
8440 ///
8441 /// \param T The type of the expressions being copied/moved. Both expressions
8442 /// must have this type.
8443 ///
8444 /// \param To The expression we are copying/moving to.
8445 ///
8446 /// \param From The expression we are copying/moving from.
8447 ///
8448 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
8449 /// Otherwise, it's a non-static member subobject.
8450 ///
8451 /// \param Copying Whether we're copying or moving.
8452 ///
8453 /// \param Depth Internal parameter recording the depth of the recursion.
8454 ///
8455 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8456 /// if a memcpy should be used instead.
8457 static StmtResult
8458 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8459                                  Expr *To, Expr *From,
8460                                  bool CopyingBaseSubobject, bool Copying,
8461                                  unsigned Depth = 0) {
8462   // C++11 [class.copy]p28:
8463   //   Each subobject is assigned in the manner appropriate to its type:
8464   //
8465   //     - if the subobject is of class type, as if by a call to operator= with
8466   //       the subobject as the object expression and the corresponding
8467   //       subobject of x as a single function argument (as if by explicit
8468   //       qualification; that is, ignoring any possible virtual overriding
8469   //       functions in more derived classes);
8470   //
8471   // C++03 [class.copy]p13:
8472   //     - if the subobject is of class type, the copy assignment operator for
8473   //       the class is used (as if by explicit qualification; that is,
8474   //       ignoring any possible virtual overriding functions in more derived
8475   //       classes);
8476   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8477     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8478 
8479     // Look for operator=.
8480     DeclarationName Name
8481       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8482     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8483     S.LookupQualifiedName(OpLookup, ClassDecl, false);
8484 
8485     // Prior to C++11, filter out any result that isn't a copy/move-assignment
8486     // operator.
8487     if (!S.getLangOpts().CPlusPlus11) {
8488       LookupResult::Filter F = OpLookup.makeFilter();
8489       while (F.hasNext()) {
8490         NamedDecl *D = F.next();
8491         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8492           if (Method->isCopyAssignmentOperator() ||
8493               (!Copying && Method->isMoveAssignmentOperator()))
8494             continue;
8495 
8496         F.erase();
8497       }
8498       F.done();
8499     }
8500 
8501     // Suppress the protected check (C++ [class.protected]) for each of the
8502     // assignment operators we found. This strange dance is required when
8503     // we're assigning via a base classes's copy-assignment operator. To
8504     // ensure that we're getting the right base class subobject (without
8505     // ambiguities), we need to cast "this" to that subobject type; to
8506     // ensure that we don't go through the virtual call mechanism, we need
8507     // to qualify the operator= name with the base class (see below). However,
8508     // this means that if the base class has a protected copy assignment
8509     // operator, the protected member access check will fail. So, we
8510     // rewrite "protected" access to "public" access in this case, since we
8511     // know by construction that we're calling from a derived class.
8512     if (CopyingBaseSubobject) {
8513       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8514            L != LEnd; ++L) {
8515         if (L.getAccess() == AS_protected)
8516           L.setAccess(AS_public);
8517       }
8518     }
8519 
8520     // Create the nested-name-specifier that will be used to qualify the
8521     // reference to operator=; this is required to suppress the virtual
8522     // call mechanism.
8523     CXXScopeSpec SS;
8524     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
8525     SS.MakeTrivial(S.Context,
8526                    NestedNameSpecifier::Create(S.Context, 0, false,
8527                                                CanonicalT),
8528                    Loc);
8529 
8530     // Create the reference to operator=.
8531     ExprResult OpEqualRef
8532       = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
8533                                    /*TemplateKWLoc=*/SourceLocation(),
8534                                    /*FirstQualifierInScope=*/0,
8535                                    OpLookup,
8536                                    /*TemplateArgs=*/0,
8537                                    /*SuppressQualifierCheck=*/true);
8538     if (OpEqualRef.isInvalid())
8539       return StmtError();
8540 
8541     // Build the call to the assignment operator.
8542 
8543     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
8544                                                   OpEqualRef.takeAs<Expr>(),
8545                                                   Loc, From, Loc);
8546     if (Call.isInvalid())
8547       return StmtError();
8548 
8549     // If we built a call to a trivial 'operator=' while copying an array,
8550     // bail out. We'll replace the whole shebang with a memcpy.
8551     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8552     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8553       return StmtResult((Stmt*)0);
8554 
8555     // Convert to an expression-statement, and clean up any produced
8556     // temporaries.
8557     return S.ActOnExprStmt(Call);
8558   }
8559 
8560   //     - if the subobject is of scalar type, the built-in assignment
8561   //       operator is used.
8562   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
8563   if (!ArrayTy) {
8564     ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
8565     if (Assignment.isInvalid())
8566       return StmtError();
8567     return S.ActOnExprStmt(Assignment);
8568   }
8569 
8570   //     - if the subobject is an array, each element is assigned, in the
8571   //       manner appropriate to the element type;
8572 
8573   // Construct a loop over the array bounds, e.g.,
8574   //
8575   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8576   //
8577   // that will copy each of the array elements.
8578   QualType SizeType = S.Context.getSizeType();
8579 
8580   // Create the iteration variable.
8581   IdentifierInfo *IterationVarName = 0;
8582   {
8583     SmallString<8> Str;
8584     llvm::raw_svector_ostream OS(Str);
8585     OS << "__i" << Depth;
8586     IterationVarName = &S.Context.Idents.get(OS.str());
8587   }
8588   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
8589                                           IterationVarName, SizeType,
8590                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
8591                                           SC_None);
8592 
8593   // Initialize the iteration variable to zero.
8594   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8595   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8596 
8597   // Create a reference to the iteration variable; we'll use this several
8598   // times throughout.
8599   Expr *IterationVarRef
8600     = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
8601   assert(IterationVarRef && "Reference to invented variable cannot fail!");
8602   Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8603   assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8604 
8605   // Create the DeclStmt that holds the iteration variable.
8606   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
8607 
8608   // Subscript the "from" and "to" expressions with the iteration variable.
8609   From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
8610                                                          IterationVarRefRVal,
8611                                                          Loc));
8612   To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
8613                                                        IterationVarRefRVal,
8614                                                        Loc));
8615   if (!Copying) // Cast to rvalue
8616     From = CastForMoving(S, From);
8617 
8618   // Build the copy/move for an individual element of the array.
8619   StmtResult Copy =
8620     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8621                                      To, From, CopyingBaseSubobject,
8622                                      Copying, Depth + 1);
8623   // Bail out if copying fails or if we determined that we should use memcpy.
8624   if (Copy.isInvalid() || !Copy.get())
8625     return Copy;
8626 
8627   // Create the comparison against the array bound.
8628   llvm::APInt Upper
8629     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8630   Expr *Comparison
8631     = new (S.Context) BinaryOperator(IterationVarRefRVal,
8632                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8633                                      BO_NE, S.Context.BoolTy,
8634                                      VK_RValue, OK_Ordinary, Loc, false);
8635 
8636   // Create the pre-increment of the iteration variable.
8637   Expr *Increment
8638     = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8639                                     VK_LValue, OK_Ordinary, Loc);
8640 
8641   // Construct the loop that copies all elements of this array.
8642   return S.ActOnForStmt(Loc, Loc, InitStmt,
8643                         S.MakeFullExpr(Comparison),
8644                         0, S.MakeFullDiscardedValueExpr(Increment),
8645                         Loc, Copy.take());
8646 }
8647 
8648 static StmtResult
8649 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8650                       Expr *To, Expr *From,
8651                       bool CopyingBaseSubobject, bool Copying) {
8652   // Maybe we should use a memcpy?
8653   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8654       T.isTriviallyCopyableType(S.Context))
8655     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8656 
8657   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8658                                                      CopyingBaseSubobject,
8659                                                      Copying, 0));
8660 
8661   // If we ended up picking a trivial assignment operator for an array of a
8662   // non-trivially-copyable class type, just emit a memcpy.
8663   if (!Result.isInvalid() && !Result.get())
8664     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8665 
8666   return Result;
8667 }
8668 
8669 Sema::ImplicitExceptionSpecification
8670 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8671   CXXRecordDecl *ClassDecl = MD->getParent();
8672 
8673   ImplicitExceptionSpecification ExceptSpec(*this);
8674   if (ClassDecl->isInvalidDecl())
8675     return ExceptSpec;
8676 
8677   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8678   assert(T->getNumArgs() == 1 && "not a copy assignment op");
8679   unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8680 
8681   // C++ [except.spec]p14:
8682   //   An implicitly declared special member function (Clause 12) shall have an
8683   //   exception-specification. [...]
8684 
8685   // It is unspecified whether or not an implicit copy assignment operator
8686   // attempts to deduplicate calls to assignment operators of virtual bases are
8687   // made. As such, this exception specification is effectively unspecified.
8688   // Based on a similar decision made for constness in C++0x, we're erring on
8689   // the side of assuming such calls to be made regardless of whether they
8690   // actually happen.
8691   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8692                                        BaseEnd = ClassDecl->bases_end();
8693        Base != BaseEnd; ++Base) {
8694     if (Base->isVirtual())
8695       continue;
8696 
8697     CXXRecordDecl *BaseClassDecl
8698       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8699     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8700                                                             ArgQuals, false, 0))
8701       ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
8702   }
8703 
8704   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8705                                        BaseEnd = ClassDecl->vbases_end();
8706        Base != BaseEnd; ++Base) {
8707     CXXRecordDecl *BaseClassDecl
8708       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8709     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8710                                                             ArgQuals, false, 0))
8711       ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
8712   }
8713 
8714   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8715                                   FieldEnd = ClassDecl->field_end();
8716        Field != FieldEnd;
8717        ++Field) {
8718     QualType FieldType = Context.getBaseElementType(Field->getType());
8719     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8720       if (CXXMethodDecl *CopyAssign =
8721           LookupCopyingAssignment(FieldClassDecl,
8722                                   ArgQuals | FieldType.getCVRQualifiers(),
8723                                   false, 0))
8724         ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
8725     }
8726   }
8727 
8728   return ExceptSpec;
8729 }
8730 
8731 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8732   // Note: The following rules are largely analoguous to the copy
8733   // constructor rules. Note that virtual bases are not taken into account
8734   // for determining the argument type of the operator. Note also that
8735   // operators taking an object instead of a reference are allowed.
8736   assert(ClassDecl->needsImplicitCopyAssignment());
8737 
8738   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8739   if (DSM.isAlreadyBeingDeclared())
8740     return 0;
8741 
8742   QualType ArgType = Context.getTypeDeclType(ClassDecl);
8743   QualType RetType = Context.getLValueReferenceType(ArgType);
8744   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
8745   if (Const)
8746     ArgType = ArgType.withConst();
8747   ArgType = Context.getLValueReferenceType(ArgType);
8748 
8749   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8750                                                      CXXCopyAssignment,
8751                                                      Const);
8752 
8753   //   An implicitly-declared copy assignment operator is an inline public
8754   //   member of its class.
8755   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8756   SourceLocation ClassLoc = ClassDecl->getLocation();
8757   DeclarationNameInfo NameInfo(Name, ClassLoc);
8758   CXXMethodDecl *CopyAssignment =
8759       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
8760                             /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
8761                             /*isInline=*/ true, Constexpr, SourceLocation());
8762   CopyAssignment->setAccess(AS_public);
8763   CopyAssignment->setDefaulted();
8764   CopyAssignment->setImplicit();
8765 
8766   // Build an exception specification pointing back at this member.
8767   FunctionProtoType::ExtProtoInfo EPI;
8768   EPI.ExceptionSpecType = EST_Unevaluated;
8769   EPI.ExceptionSpecDecl = CopyAssignment;
8770   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
8771 
8772   // Add the parameter to the operator.
8773   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
8774                                                ClassLoc, ClassLoc, /*Id=*/0,
8775                                                ArgType, /*TInfo=*/0,
8776                                                SC_None, 0);
8777   CopyAssignment->setParams(FromParam);
8778 
8779   AddOverriddenMethods(ClassDecl, CopyAssignment);
8780 
8781   CopyAssignment->setTrivial(
8782     ClassDecl->needsOverloadResolutionForCopyAssignment()
8783       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8784       : ClassDecl->hasTrivialCopyAssignment());
8785 
8786   // C++11 [class.copy]p19:
8787   //   ....  If the class definition does not explicitly declare a copy
8788   //   assignment operator, there is no user-declared move constructor, and
8789   //   there is no user-declared move assignment operator, a copy assignment
8790   //   operator is implicitly declared as defaulted.
8791   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
8792     SetDeclDeleted(CopyAssignment, ClassLoc);
8793 
8794   // Note that we have added this copy-assignment operator.
8795   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8796 
8797   if (Scope *S = getScopeForContext(ClassDecl))
8798     PushOnScopeChains(CopyAssignment, S, false);
8799   ClassDecl->addDecl(CopyAssignment);
8800 
8801   return CopyAssignment;
8802 }
8803 
8804 /// Diagnose an implicit copy operation for a class which is odr-used, but
8805 /// which is deprecated because the class has a user-declared copy constructor,
8806 /// copy assignment operator, or destructor.
8807 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
8808                                             SourceLocation UseLoc) {
8809   assert(CopyOp->isImplicit());
8810 
8811   CXXRecordDecl *RD = CopyOp->getParent();
8812   CXXMethodDecl *UserDeclaredOperation = 0;
8813 
8814   // In Microsoft mode, assignment operations don't affect constructors and
8815   // vice versa.
8816   if (RD->hasUserDeclaredDestructor()) {
8817     UserDeclaredOperation = RD->getDestructor();
8818   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
8819              RD->hasUserDeclaredCopyConstructor() &&
8820              !S.getLangOpts().MicrosoftMode) {
8821     // Find any user-declared copy constructor.
8822     for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
8823                                       E = RD->ctor_end(); I != E; ++I) {
8824       if (I->isCopyConstructor()) {
8825         UserDeclaredOperation = *I;
8826         break;
8827       }
8828     }
8829     assert(UserDeclaredOperation);
8830   } else if (isa<CXXConstructorDecl>(CopyOp) &&
8831              RD->hasUserDeclaredCopyAssignment() &&
8832              !S.getLangOpts().MicrosoftMode) {
8833     // Find any user-declared move assignment operator.
8834     for (CXXRecordDecl::method_iterator I = RD->method_begin(),
8835                                         E = RD->method_end(); I != E; ++I) {
8836       if (I->isCopyAssignmentOperator()) {
8837         UserDeclaredOperation = *I;
8838         break;
8839       }
8840     }
8841     assert(UserDeclaredOperation);
8842   }
8843 
8844   if (UserDeclaredOperation) {
8845     S.Diag(UserDeclaredOperation->getLocation(),
8846          diag::warn_deprecated_copy_operation)
8847       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
8848       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
8849     S.Diag(UseLoc, diag::note_member_synthesized_at)
8850       << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
8851                                           : Sema::CXXCopyAssignment)
8852       << RD;
8853   }
8854 }
8855 
8856 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8857                                         CXXMethodDecl *CopyAssignOperator) {
8858   assert((CopyAssignOperator->isDefaulted() &&
8859           CopyAssignOperator->isOverloadedOperator() &&
8860           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
8861           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8862           !CopyAssignOperator->isDeleted()) &&
8863          "DefineImplicitCopyAssignment called for wrong function");
8864 
8865   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8866 
8867   if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8868     CopyAssignOperator->setInvalidDecl();
8869     return;
8870   }
8871 
8872   // C++11 [class.copy]p18:
8873   //   The [definition of an implicitly declared copy assignment operator] is
8874   //   deprecated if the class has a user-declared copy constructor or a
8875   //   user-declared destructor.
8876   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
8877     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
8878 
8879   CopyAssignOperator->setUsed();
8880 
8881   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
8882   DiagnosticErrorTrap Trap(Diags);
8883 
8884   // C++0x [class.copy]p30:
8885   //   The implicitly-defined or explicitly-defaulted copy assignment operator
8886   //   for a non-union class X performs memberwise copy assignment of its
8887   //   subobjects. The direct base classes of X are assigned first, in the
8888   //   order of their declaration in the base-specifier-list, and then the
8889   //   immediate non-static data members of X are assigned, in the order in
8890   //   which they were declared in the class definition.
8891 
8892   // The statements that form the synthesized function body.
8893   SmallVector<Stmt*, 8> Statements;
8894 
8895   // The parameter for the "other" object, which we are copying from.
8896   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8897   Qualifiers OtherQuals = Other->getType().getQualifiers();
8898   QualType OtherRefType = Other->getType();
8899   if (const LValueReferenceType *OtherRef
8900                                 = OtherRefType->getAs<LValueReferenceType>()) {
8901     OtherRefType = OtherRef->getPointeeType();
8902     OtherQuals = OtherRefType.getQualifiers();
8903   }
8904 
8905   // Our location for everything implicitly-generated.
8906   SourceLocation Loc = CopyAssignOperator->getLocation();
8907 
8908   // Construct a reference to the "other" object. We'll be using this
8909   // throughout the generated ASTs.
8910   Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8911   assert(OtherRef && "Reference to parameter cannot fail!");
8912 
8913   // Construct the "this" pointer. We'll be using this throughout the generated
8914   // ASTs.
8915   Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8916   assert(This && "Reference to this cannot fail!");
8917 
8918   // Assign base classes.
8919   bool Invalid = false;
8920   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8921        E = ClassDecl->bases_end(); Base != E; ++Base) {
8922     // Form the assignment:
8923     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8924     QualType BaseType = Base->getType().getUnqualifiedType();
8925     if (!BaseType->isRecordType()) {
8926       Invalid = true;
8927       continue;
8928     }
8929 
8930     CXXCastPath BasePath;
8931     BasePath.push_back(Base);
8932 
8933     // Construct the "from" expression, which is an implicit cast to the
8934     // appropriately-qualified base type.
8935     Expr *From = OtherRef;
8936     From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8937                              CK_UncheckedDerivedToBase,
8938                              VK_LValue, &BasePath).take();
8939 
8940     // Dereference "this".
8941     ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8942 
8943     // Implicitly cast "this" to the appropriately-qualified base type.
8944     To = ImpCastExprToType(To.take(),
8945                            Context.getCVRQualifiedType(BaseType,
8946                                      CopyAssignOperator->getTypeQualifiers()),
8947                            CK_UncheckedDerivedToBase,
8948                            VK_LValue, &BasePath);
8949 
8950     // Build the copy.
8951     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
8952                                             To.get(), From,
8953                                             /*CopyingBaseSubobject=*/true,
8954                                             /*Copying=*/true);
8955     if (Copy.isInvalid()) {
8956       Diag(CurrentLocation, diag::note_member_synthesized_at)
8957         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8958       CopyAssignOperator->setInvalidDecl();
8959       return;
8960     }
8961 
8962     // Success! Record the copy.
8963     Statements.push_back(Copy.takeAs<Expr>());
8964   }
8965 
8966   // Assign non-static members.
8967   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8968                                   FieldEnd = ClassDecl->field_end();
8969        Field != FieldEnd; ++Field) {
8970     if (Field->isUnnamedBitfield())
8971       continue;
8972 
8973     if (Field->isInvalidDecl()) {
8974       Invalid = true;
8975       continue;
8976     }
8977 
8978     // Check for members of reference type; we can't copy those.
8979     if (Field->getType()->isReferenceType()) {
8980       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8981         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8982       Diag(Field->getLocation(), diag::note_declared_at);
8983       Diag(CurrentLocation, diag::note_member_synthesized_at)
8984         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8985       Invalid = true;
8986       continue;
8987     }
8988 
8989     // Check for members of const-qualified, non-class type.
8990     QualType BaseType = Context.getBaseElementType(Field->getType());
8991     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8992       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8993         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8994       Diag(Field->getLocation(), diag::note_declared_at);
8995       Diag(CurrentLocation, diag::note_member_synthesized_at)
8996         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8997       Invalid = true;
8998       continue;
8999     }
9000 
9001     // Suppress assigning zero-width bitfields.
9002     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9003       continue;
9004 
9005     QualType FieldType = Field->getType().getNonReferenceType();
9006     if (FieldType->isIncompleteArrayType()) {
9007       assert(ClassDecl->hasFlexibleArrayMember() &&
9008              "Incomplete array type is not valid");
9009       continue;
9010     }
9011 
9012     // Build references to the field in the object we're copying from and to.
9013     CXXScopeSpec SS; // Intentionally empty
9014     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9015                               LookupMemberName);
9016     MemberLookup.addDecl(*Field);
9017     MemberLookup.resolveKind();
9018     ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
9019                                                Loc, /*IsArrow=*/false,
9020                                                SS, SourceLocation(), 0,
9021                                                MemberLookup, 0);
9022     ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
9023                                              Loc, /*IsArrow=*/true,
9024                                              SS, SourceLocation(), 0,
9025                                              MemberLookup, 0);
9026     assert(!From.isInvalid() && "Implicit field reference cannot fail");
9027     assert(!To.isInvalid() && "Implicit field reference cannot fail");
9028 
9029     // Build the copy of this field.
9030     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
9031                                             To.get(), From.get(),
9032                                             /*CopyingBaseSubobject=*/false,
9033                                             /*Copying=*/true);
9034     if (Copy.isInvalid()) {
9035       Diag(CurrentLocation, diag::note_member_synthesized_at)
9036         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9037       CopyAssignOperator->setInvalidDecl();
9038       return;
9039     }
9040 
9041     // Success! Record the copy.
9042     Statements.push_back(Copy.takeAs<Stmt>());
9043   }
9044 
9045   if (!Invalid) {
9046     // Add a "return *this;"
9047     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9048 
9049     StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9050     if (Return.isInvalid())
9051       Invalid = true;
9052     else {
9053       Statements.push_back(Return.takeAs<Stmt>());
9054 
9055       if (Trap.hasErrorOccurred()) {
9056         Diag(CurrentLocation, diag::note_member_synthesized_at)
9057           << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9058         Invalid = true;
9059       }
9060     }
9061   }
9062 
9063   if (Invalid) {
9064     CopyAssignOperator->setInvalidDecl();
9065     return;
9066   }
9067 
9068   StmtResult Body;
9069   {
9070     CompoundScopeRAII CompoundScope(*this);
9071     Body = ActOnCompoundStmt(Loc, Loc, Statements,
9072                              /*isStmtExpr=*/false);
9073     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9074   }
9075   CopyAssignOperator->setBody(Body.takeAs<Stmt>());
9076 
9077   if (ASTMutationListener *L = getASTMutationListener()) {
9078     L->CompletedImplicitDefinition(CopyAssignOperator);
9079   }
9080 }
9081 
9082 Sema::ImplicitExceptionSpecification
9083 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9084   CXXRecordDecl *ClassDecl = MD->getParent();
9085 
9086   ImplicitExceptionSpecification ExceptSpec(*this);
9087   if (ClassDecl->isInvalidDecl())
9088     return ExceptSpec;
9089 
9090   // C++0x [except.spec]p14:
9091   //   An implicitly declared special member function (Clause 12) shall have an
9092   //   exception-specification. [...]
9093 
9094   // It is unspecified whether or not an implicit move assignment operator
9095   // attempts to deduplicate calls to assignment operators of virtual bases are
9096   // made. As such, this exception specification is effectively unspecified.
9097   // Based on a similar decision made for constness in C++0x, we're erring on
9098   // the side of assuming such calls to be made regardless of whether they
9099   // actually happen.
9100   // Note that a move constructor is not implicitly declared when there are
9101   // virtual bases, but it can still be user-declared and explicitly defaulted.
9102   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9103                                        BaseEnd = ClassDecl->bases_end();
9104        Base != BaseEnd; ++Base) {
9105     if (Base->isVirtual())
9106       continue;
9107 
9108     CXXRecordDecl *BaseClassDecl
9109       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9110     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
9111                                                            0, false, 0))
9112       ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
9113   }
9114 
9115   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9116                                        BaseEnd = ClassDecl->vbases_end();
9117        Base != BaseEnd; ++Base) {
9118     CXXRecordDecl *BaseClassDecl
9119       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9120     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
9121                                                            0, false, 0))
9122       ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
9123   }
9124 
9125   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9126                                   FieldEnd = ClassDecl->field_end();
9127        Field != FieldEnd;
9128        ++Field) {
9129     QualType FieldType = Context.getBaseElementType(Field->getType());
9130     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9131       if (CXXMethodDecl *MoveAssign =
9132               LookupMovingAssignment(FieldClassDecl,
9133                                      FieldType.getCVRQualifiers(),
9134                                      false, 0))
9135         ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
9136     }
9137   }
9138 
9139   return ExceptSpec;
9140 }
9141 
9142 /// Determine whether the class type has any direct or indirect virtual base
9143 /// classes which have a non-trivial move assignment operator.
9144 static bool
9145 hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
9146   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9147                                           BaseEnd = ClassDecl->vbases_end();
9148        Base != BaseEnd; ++Base) {
9149     CXXRecordDecl *BaseClass =
9150         cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9151 
9152     // Try to declare the move assignment. If it would be deleted, then the
9153     // class does not have a non-trivial move assignment.
9154     if (BaseClass->needsImplicitMoveAssignment())
9155       S.DeclareImplicitMoveAssignment(BaseClass);
9156 
9157     if (BaseClass->hasNonTrivialMoveAssignment())
9158       return true;
9159   }
9160 
9161   return false;
9162 }
9163 
9164 /// Determine whether the given type either has a move constructor or is
9165 /// trivially copyable.
9166 static bool
9167 hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
9168   Type = S.Context.getBaseElementType(Type);
9169 
9170   // FIXME: Technically, non-trivially-copyable non-class types, such as
9171   // reference types, are supposed to return false here, but that appears
9172   // to be a standard defect.
9173   CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
9174   if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
9175     return true;
9176 
9177   if (Type.isTriviallyCopyableType(S.Context))
9178     return true;
9179 
9180   if (IsConstructor) {
9181     // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
9182     // give the right answer.
9183     if (ClassDecl->needsImplicitMoveConstructor())
9184       S.DeclareImplicitMoveConstructor(ClassDecl);
9185     return ClassDecl->hasMoveConstructor();
9186   }
9187 
9188   // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
9189   // give the right answer.
9190   if (ClassDecl->needsImplicitMoveAssignment())
9191     S.DeclareImplicitMoveAssignment(ClassDecl);
9192   return ClassDecl->hasMoveAssignment();
9193 }
9194 
9195 /// Determine whether all non-static data members and direct or virtual bases
9196 /// of class \p ClassDecl have either a move operation, or are trivially
9197 /// copyable.
9198 static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
9199                                             bool IsConstructor) {
9200   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9201                                           BaseEnd = ClassDecl->bases_end();
9202        Base != BaseEnd; ++Base) {
9203     if (Base->isVirtual())
9204       continue;
9205 
9206     if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9207       return false;
9208   }
9209 
9210   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9211                                           BaseEnd = ClassDecl->vbases_end();
9212        Base != BaseEnd; ++Base) {
9213     if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9214       return false;
9215   }
9216 
9217   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9218                                      FieldEnd = ClassDecl->field_end();
9219        Field != FieldEnd; ++Field) {
9220     if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
9221       return false;
9222   }
9223 
9224   return true;
9225 }
9226 
9227 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
9228   // C++11 [class.copy]p20:
9229   //   If the definition of a class X does not explicitly declare a move
9230   //   assignment operator, one will be implicitly declared as defaulted
9231   //   if and only if:
9232   //
9233   //   - [first 4 bullets]
9234   assert(ClassDecl->needsImplicitMoveAssignment());
9235 
9236   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9237   if (DSM.isAlreadyBeingDeclared())
9238     return 0;
9239 
9240   // [Checked after we build the declaration]
9241   //   - the move assignment operator would not be implicitly defined as
9242   //     deleted,
9243 
9244   // [DR1402]:
9245   //   - X has no direct or indirect virtual base class with a non-trivial
9246   //     move assignment operator, and
9247   //   - each of X's non-static data members and direct or virtual base classes
9248   //     has a type that either has a move assignment operator or is trivially
9249   //     copyable.
9250   if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
9251       !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
9252     ClassDecl->setFailedImplicitMoveAssignment();
9253     return 0;
9254   }
9255 
9256   // Note: The following rules are largely analoguous to the move
9257   // constructor rules.
9258 
9259   QualType ArgType = Context.getTypeDeclType(ClassDecl);
9260   QualType RetType = Context.getLValueReferenceType(ArgType);
9261   ArgType = Context.getRValueReferenceType(ArgType);
9262 
9263   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9264                                                      CXXMoveAssignment,
9265                                                      false);
9266 
9267   //   An implicitly-declared move assignment operator is an inline public
9268   //   member of its class.
9269   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9270   SourceLocation ClassLoc = ClassDecl->getLocation();
9271   DeclarationNameInfo NameInfo(Name, ClassLoc);
9272   CXXMethodDecl *MoveAssignment =
9273       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9274                             /*TInfo=*/0, /*StorageClass=*/SC_None,
9275                             /*isInline=*/true, Constexpr, SourceLocation());
9276   MoveAssignment->setAccess(AS_public);
9277   MoveAssignment->setDefaulted();
9278   MoveAssignment->setImplicit();
9279 
9280   // Build an exception specification pointing back at this member.
9281   FunctionProtoType::ExtProtoInfo EPI;
9282   EPI.ExceptionSpecType = EST_Unevaluated;
9283   EPI.ExceptionSpecDecl = MoveAssignment;
9284   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
9285 
9286   // Add the parameter to the operator.
9287   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9288                                                ClassLoc, ClassLoc, /*Id=*/0,
9289                                                ArgType, /*TInfo=*/0,
9290                                                SC_None, 0);
9291   MoveAssignment->setParams(FromParam);
9292 
9293   AddOverriddenMethods(ClassDecl, MoveAssignment);
9294 
9295   MoveAssignment->setTrivial(
9296     ClassDecl->needsOverloadResolutionForMoveAssignment()
9297       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9298       : ClassDecl->hasTrivialMoveAssignment());
9299 
9300   // C++0x [class.copy]p9:
9301   //   If the definition of a class X does not explicitly declare a move
9302   //   assignment operator, one will be implicitly declared as defaulted if and
9303   //   only if:
9304   //   [...]
9305   //   - the move assignment operator would not be implicitly defined as
9306   //     deleted.
9307   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
9308     // Cache this result so that we don't try to generate this over and over
9309     // on every lookup, leaking memory and wasting time.
9310     ClassDecl->setFailedImplicitMoveAssignment();
9311     return 0;
9312   }
9313 
9314   // Note that we have added this copy-assignment operator.
9315   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9316 
9317   if (Scope *S = getScopeForContext(ClassDecl))
9318     PushOnScopeChains(MoveAssignment, S, false);
9319   ClassDecl->addDecl(MoveAssignment);
9320 
9321   return MoveAssignment;
9322 }
9323 
9324 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9325                                         CXXMethodDecl *MoveAssignOperator) {
9326   assert((MoveAssignOperator->isDefaulted() &&
9327           MoveAssignOperator->isOverloadedOperator() &&
9328           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
9329           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9330           !MoveAssignOperator->isDeleted()) &&
9331          "DefineImplicitMoveAssignment called for wrong function");
9332 
9333   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9334 
9335   if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9336     MoveAssignOperator->setInvalidDecl();
9337     return;
9338   }
9339 
9340   MoveAssignOperator->setUsed();
9341 
9342   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
9343   DiagnosticErrorTrap Trap(Diags);
9344 
9345   // C++0x [class.copy]p28:
9346   //   The implicitly-defined or move assignment operator for a non-union class
9347   //   X performs memberwise move assignment of its subobjects. The direct base
9348   //   classes of X are assigned first, in the order of their declaration in the
9349   //   base-specifier-list, and then the immediate non-static data members of X
9350   //   are assigned, in the order in which they were declared in the class
9351   //   definition.
9352 
9353   // The statements that form the synthesized function body.
9354   SmallVector<Stmt*, 8> Statements;
9355 
9356   // The parameter for the "other" object, which we are move from.
9357   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9358   QualType OtherRefType = Other->getType()->
9359       getAs<RValueReferenceType>()->getPointeeType();
9360   assert(!OtherRefType.getQualifiers() &&
9361          "Bad argument type of defaulted move assignment");
9362 
9363   // Our location for everything implicitly-generated.
9364   SourceLocation Loc = MoveAssignOperator->getLocation();
9365 
9366   // Construct a reference to the "other" object. We'll be using this
9367   // throughout the generated ASTs.
9368   Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
9369   assert(OtherRef && "Reference to parameter cannot fail!");
9370   // Cast to rvalue.
9371   OtherRef = CastForMoving(*this, OtherRef);
9372 
9373   // Construct the "this" pointer. We'll be using this throughout the generated
9374   // ASTs.
9375   Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
9376   assert(This && "Reference to this cannot fail!");
9377 
9378   // Assign base classes.
9379   bool Invalid = false;
9380   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9381        E = ClassDecl->bases_end(); Base != E; ++Base) {
9382     // Form the assignment:
9383     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9384     QualType BaseType = Base->getType().getUnqualifiedType();
9385     if (!BaseType->isRecordType()) {
9386       Invalid = true;
9387       continue;
9388     }
9389 
9390     CXXCastPath BasePath;
9391     BasePath.push_back(Base);
9392 
9393     // Construct the "from" expression, which is an implicit cast to the
9394     // appropriately-qualified base type.
9395     Expr *From = OtherRef;
9396     From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
9397                              VK_XValue, &BasePath).take();
9398 
9399     // Dereference "this".
9400     ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9401 
9402     // Implicitly cast "this" to the appropriately-qualified base type.
9403     To = ImpCastExprToType(To.take(),
9404                            Context.getCVRQualifiedType(BaseType,
9405                                      MoveAssignOperator->getTypeQualifiers()),
9406                            CK_UncheckedDerivedToBase,
9407                            VK_LValue, &BasePath);
9408 
9409     // Build the move.
9410     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
9411                                             To.get(), From,
9412                                             /*CopyingBaseSubobject=*/true,
9413                                             /*Copying=*/false);
9414     if (Move.isInvalid()) {
9415       Diag(CurrentLocation, diag::note_member_synthesized_at)
9416         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9417       MoveAssignOperator->setInvalidDecl();
9418       return;
9419     }
9420 
9421     // Success! Record the move.
9422     Statements.push_back(Move.takeAs<Expr>());
9423   }
9424 
9425   // Assign non-static members.
9426   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9427                                   FieldEnd = ClassDecl->field_end();
9428        Field != FieldEnd; ++Field) {
9429     if (Field->isUnnamedBitfield())
9430       continue;
9431 
9432     if (Field->isInvalidDecl()) {
9433       Invalid = true;
9434       continue;
9435     }
9436 
9437     // Check for members of reference type; we can't move those.
9438     if (Field->getType()->isReferenceType()) {
9439       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9440         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9441       Diag(Field->getLocation(), diag::note_declared_at);
9442       Diag(CurrentLocation, diag::note_member_synthesized_at)
9443         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9444       Invalid = true;
9445       continue;
9446     }
9447 
9448     // Check for members of const-qualified, non-class type.
9449     QualType BaseType = Context.getBaseElementType(Field->getType());
9450     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9451       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9452         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9453       Diag(Field->getLocation(), diag::note_declared_at);
9454       Diag(CurrentLocation, diag::note_member_synthesized_at)
9455         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9456       Invalid = true;
9457       continue;
9458     }
9459 
9460     // Suppress assigning zero-width bitfields.
9461     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9462       continue;
9463 
9464     QualType FieldType = Field->getType().getNonReferenceType();
9465     if (FieldType->isIncompleteArrayType()) {
9466       assert(ClassDecl->hasFlexibleArrayMember() &&
9467              "Incomplete array type is not valid");
9468       continue;
9469     }
9470 
9471     // Build references to the field in the object we're copying from and to.
9472     CXXScopeSpec SS; // Intentionally empty
9473     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9474                               LookupMemberName);
9475     MemberLookup.addDecl(*Field);
9476     MemberLookup.resolveKind();
9477     ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
9478                                                Loc, /*IsArrow=*/false,
9479                                                SS, SourceLocation(), 0,
9480                                                MemberLookup, 0);
9481     ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
9482                                              Loc, /*IsArrow=*/true,
9483                                              SS, SourceLocation(), 0,
9484                                              MemberLookup, 0);
9485     assert(!From.isInvalid() && "Implicit field reference cannot fail");
9486     assert(!To.isInvalid() && "Implicit field reference cannot fail");
9487 
9488     assert(!From.get()->isLValue() && // could be xvalue or prvalue
9489         "Member reference with rvalue base must be rvalue except for reference "
9490         "members, which aren't allowed for move assignment.");
9491 
9492     // Build the move of this field.
9493     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
9494                                             To.get(), From.get(),
9495                                             /*CopyingBaseSubobject=*/false,
9496                                             /*Copying=*/false);
9497     if (Move.isInvalid()) {
9498       Diag(CurrentLocation, diag::note_member_synthesized_at)
9499         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9500       MoveAssignOperator->setInvalidDecl();
9501       return;
9502     }
9503 
9504     // Success! Record the copy.
9505     Statements.push_back(Move.takeAs<Stmt>());
9506   }
9507 
9508   if (!Invalid) {
9509     // Add a "return *this;"
9510     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9511 
9512     StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9513     if (Return.isInvalid())
9514       Invalid = true;
9515     else {
9516       Statements.push_back(Return.takeAs<Stmt>());
9517 
9518       if (Trap.hasErrorOccurred()) {
9519         Diag(CurrentLocation, diag::note_member_synthesized_at)
9520           << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9521         Invalid = true;
9522       }
9523     }
9524   }
9525 
9526   if (Invalid) {
9527     MoveAssignOperator->setInvalidDecl();
9528     return;
9529   }
9530 
9531   StmtResult Body;
9532   {
9533     CompoundScopeRAII CompoundScope(*this);
9534     Body = ActOnCompoundStmt(Loc, Loc, Statements,
9535                              /*isStmtExpr=*/false);
9536     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9537   }
9538   MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9539 
9540   if (ASTMutationListener *L = getASTMutationListener()) {
9541     L->CompletedImplicitDefinition(MoveAssignOperator);
9542   }
9543 }
9544 
9545 Sema::ImplicitExceptionSpecification
9546 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9547   CXXRecordDecl *ClassDecl = MD->getParent();
9548 
9549   ImplicitExceptionSpecification ExceptSpec(*this);
9550   if (ClassDecl->isInvalidDecl())
9551     return ExceptSpec;
9552 
9553   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9554   assert(T->getNumArgs() >= 1 && "not a copy ctor");
9555   unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9556 
9557   // C++ [except.spec]p14:
9558   //   An implicitly declared special member function (Clause 12) shall have an
9559   //   exception-specification. [...]
9560   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9561                                        BaseEnd = ClassDecl->bases_end();
9562        Base != BaseEnd;
9563        ++Base) {
9564     // Virtual bases are handled below.
9565     if (Base->isVirtual())
9566       continue;
9567 
9568     CXXRecordDecl *BaseClassDecl
9569       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9570     if (CXXConstructorDecl *CopyConstructor =
9571           LookupCopyingConstructor(BaseClassDecl, Quals))
9572       ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
9573   }
9574   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9575                                        BaseEnd = ClassDecl->vbases_end();
9576        Base != BaseEnd;
9577        ++Base) {
9578     CXXRecordDecl *BaseClassDecl
9579       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9580     if (CXXConstructorDecl *CopyConstructor =
9581           LookupCopyingConstructor(BaseClassDecl, Quals))
9582       ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
9583   }
9584   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9585                                   FieldEnd = ClassDecl->field_end();
9586        Field != FieldEnd;
9587        ++Field) {
9588     QualType FieldType = Context.getBaseElementType(Field->getType());
9589     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9590       if (CXXConstructorDecl *CopyConstructor =
9591               LookupCopyingConstructor(FieldClassDecl,
9592                                        Quals | FieldType.getCVRQualifiers()))
9593       ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
9594     }
9595   }
9596 
9597   return ExceptSpec;
9598 }
9599 
9600 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9601                                                     CXXRecordDecl *ClassDecl) {
9602   // C++ [class.copy]p4:
9603   //   If the class definition does not explicitly declare a copy
9604   //   constructor, one is declared implicitly.
9605   assert(ClassDecl->needsImplicitCopyConstructor());
9606 
9607   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9608   if (DSM.isAlreadyBeingDeclared())
9609     return 0;
9610 
9611   QualType ClassType = Context.getTypeDeclType(ClassDecl);
9612   QualType ArgType = ClassType;
9613   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
9614   if (Const)
9615     ArgType = ArgType.withConst();
9616   ArgType = Context.getLValueReferenceType(ArgType);
9617 
9618   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9619                                                      CXXCopyConstructor,
9620                                                      Const);
9621 
9622   DeclarationName Name
9623     = Context.DeclarationNames.getCXXConstructorName(
9624                                            Context.getCanonicalType(ClassType));
9625   SourceLocation ClassLoc = ClassDecl->getLocation();
9626   DeclarationNameInfo NameInfo(Name, ClassLoc);
9627 
9628   //   An implicitly-declared copy constructor is an inline public
9629   //   member of its class.
9630   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
9631       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
9632       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
9633       Constexpr);
9634   CopyConstructor->setAccess(AS_public);
9635   CopyConstructor->setDefaulted();
9636 
9637   // Build an exception specification pointing back at this member.
9638   FunctionProtoType::ExtProtoInfo EPI;
9639   EPI.ExceptionSpecType = EST_Unevaluated;
9640   EPI.ExceptionSpecDecl = CopyConstructor;
9641   CopyConstructor->setType(
9642       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
9643 
9644   // Add the parameter to the constructor.
9645   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
9646                                                ClassLoc, ClassLoc,
9647                                                /*IdentifierInfo=*/0,
9648                                                ArgType, /*TInfo=*/0,
9649                                                SC_None, 0);
9650   CopyConstructor->setParams(FromParam);
9651 
9652   CopyConstructor->setTrivial(
9653     ClassDecl->needsOverloadResolutionForCopyConstructor()
9654       ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9655       : ClassDecl->hasTrivialCopyConstructor());
9656 
9657   // C++11 [class.copy]p8:
9658   //   ... If the class definition does not explicitly declare a copy
9659   //   constructor, there is no user-declared move constructor, and there is no
9660   //   user-declared move assignment operator, a copy constructor is implicitly
9661   //   declared as defaulted.
9662   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
9663     SetDeclDeleted(CopyConstructor, ClassLoc);
9664 
9665   // Note that we have declared this constructor.
9666   ++ASTContext::NumImplicitCopyConstructorsDeclared;
9667 
9668   if (Scope *S = getScopeForContext(ClassDecl))
9669     PushOnScopeChains(CopyConstructor, S, false);
9670   ClassDecl->addDecl(CopyConstructor);
9671 
9672   return CopyConstructor;
9673 }
9674 
9675 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
9676                                    CXXConstructorDecl *CopyConstructor) {
9677   assert((CopyConstructor->isDefaulted() &&
9678           CopyConstructor->isCopyConstructor() &&
9679           !CopyConstructor->doesThisDeclarationHaveABody() &&
9680           !CopyConstructor->isDeleted()) &&
9681          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
9682 
9683   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
9684   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
9685 
9686   // C++11 [class.copy]p7:
9687   //   The [definition of an implicitly declared copy constructro] is
9688   //   deprecated if the class has a user-declared copy assignment operator
9689   //   or a user-declared destructor.
9690   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
9691     diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
9692 
9693   SynthesizedFunctionScope Scope(*this, CopyConstructor);
9694   DiagnosticErrorTrap Trap(Diags);
9695 
9696   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
9697       Trap.hasErrorOccurred()) {
9698     Diag(CurrentLocation, diag::note_member_synthesized_at)
9699       << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
9700     CopyConstructor->setInvalidDecl();
9701   }  else {
9702     Sema::CompoundScopeRAII CompoundScope(*this);
9703     CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9704                                                CopyConstructor->getLocation(),
9705                                                MultiStmtArg(),
9706                                                /*isStmtExpr=*/false)
9707                                                               .takeAs<Stmt>());
9708     CopyConstructor->setImplicitlyDefined(true);
9709   }
9710 
9711   CopyConstructor->setUsed();
9712   if (ASTMutationListener *L = getASTMutationListener()) {
9713     L->CompletedImplicitDefinition(CopyConstructor);
9714   }
9715 }
9716 
9717 Sema::ImplicitExceptionSpecification
9718 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9719   CXXRecordDecl *ClassDecl = MD->getParent();
9720 
9721   // C++ [except.spec]p14:
9722   //   An implicitly declared special member function (Clause 12) shall have an
9723   //   exception-specification. [...]
9724   ImplicitExceptionSpecification ExceptSpec(*this);
9725   if (ClassDecl->isInvalidDecl())
9726     return ExceptSpec;
9727 
9728   // Direct base-class constructors.
9729   for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9730                                        BEnd = ClassDecl->bases_end();
9731        B != BEnd; ++B) {
9732     if (B->isVirtual()) // Handled below.
9733       continue;
9734 
9735     if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9736       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
9737       CXXConstructorDecl *Constructor =
9738           LookupMovingConstructor(BaseClassDecl, 0);
9739       // If this is a deleted function, add it anyway. This might be conformant
9740       // with the standard. This might not. I'm not sure. It might not matter.
9741       if (Constructor)
9742         ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
9743     }
9744   }
9745 
9746   // Virtual base-class constructors.
9747   for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9748                                        BEnd = ClassDecl->vbases_end();
9749        B != BEnd; ++B) {
9750     if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9751       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
9752       CXXConstructorDecl *Constructor =
9753           LookupMovingConstructor(BaseClassDecl, 0);
9754       // If this is a deleted function, add it anyway. This might be conformant
9755       // with the standard. This might not. I'm not sure. It might not matter.
9756       if (Constructor)
9757         ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
9758     }
9759   }
9760 
9761   // Field constructors.
9762   for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9763                                FEnd = ClassDecl->field_end();
9764        F != FEnd; ++F) {
9765     QualType FieldType = Context.getBaseElementType(F->getType());
9766     if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9767       CXXConstructorDecl *Constructor =
9768           LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
9769       // If this is a deleted function, add it anyway. This might be conformant
9770       // with the standard. This might not. I'm not sure. It might not matter.
9771       // In particular, the problem is that this function never gets called. It
9772       // might just be ill-formed because this function attempts to refer to
9773       // a deleted function here.
9774       if (Constructor)
9775         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
9776     }
9777   }
9778 
9779   return ExceptSpec;
9780 }
9781 
9782 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9783                                                     CXXRecordDecl *ClassDecl) {
9784   // C++11 [class.copy]p9:
9785   //   If the definition of a class X does not explicitly declare a move
9786   //   constructor, one will be implicitly declared as defaulted if and only if:
9787   //
9788   //   - [first 4 bullets]
9789   assert(ClassDecl->needsImplicitMoveConstructor());
9790 
9791   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9792   if (DSM.isAlreadyBeingDeclared())
9793     return 0;
9794 
9795   // [Checked after we build the declaration]
9796   //   - the move assignment operator would not be implicitly defined as
9797   //     deleted,
9798 
9799   // [DR1402]:
9800   //   - each of X's non-static data members and direct or virtual base classes
9801   //     has a type that either has a move constructor or is trivially copyable.
9802   if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9803     ClassDecl->setFailedImplicitMoveConstructor();
9804     return 0;
9805   }
9806 
9807   QualType ClassType = Context.getTypeDeclType(ClassDecl);
9808   QualType ArgType = Context.getRValueReferenceType(ClassType);
9809 
9810   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9811                                                      CXXMoveConstructor,
9812                                                      false);
9813 
9814   DeclarationName Name
9815     = Context.DeclarationNames.getCXXConstructorName(
9816                                            Context.getCanonicalType(ClassType));
9817   SourceLocation ClassLoc = ClassDecl->getLocation();
9818   DeclarationNameInfo NameInfo(Name, ClassLoc);
9819 
9820   // C++11 [class.copy]p11:
9821   //   An implicitly-declared copy/move constructor is an inline public
9822   //   member of its class.
9823   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
9824       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
9825       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
9826       Constexpr);
9827   MoveConstructor->setAccess(AS_public);
9828   MoveConstructor->setDefaulted();
9829 
9830   // Build an exception specification pointing back at this member.
9831   FunctionProtoType::ExtProtoInfo EPI;
9832   EPI.ExceptionSpecType = EST_Unevaluated;
9833   EPI.ExceptionSpecDecl = MoveConstructor;
9834   MoveConstructor->setType(
9835       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
9836 
9837   // Add the parameter to the constructor.
9838   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9839                                                ClassLoc, ClassLoc,
9840                                                /*IdentifierInfo=*/0,
9841                                                ArgType, /*TInfo=*/0,
9842                                                SC_None, 0);
9843   MoveConstructor->setParams(FromParam);
9844 
9845   MoveConstructor->setTrivial(
9846     ClassDecl->needsOverloadResolutionForMoveConstructor()
9847       ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9848       : ClassDecl->hasTrivialMoveConstructor());
9849 
9850   // C++0x [class.copy]p9:
9851   //   If the definition of a class X does not explicitly declare a move
9852   //   constructor, one will be implicitly declared as defaulted if and only if:
9853   //   [...]
9854   //   - the move constructor would not be implicitly defined as deleted.
9855   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
9856     // Cache this result so that we don't try to generate this over and over
9857     // on every lookup, leaking memory and wasting time.
9858     ClassDecl->setFailedImplicitMoveConstructor();
9859     return 0;
9860   }
9861 
9862   // Note that we have declared this constructor.
9863   ++ASTContext::NumImplicitMoveConstructorsDeclared;
9864 
9865   if (Scope *S = getScopeForContext(ClassDecl))
9866     PushOnScopeChains(MoveConstructor, S, false);
9867   ClassDecl->addDecl(MoveConstructor);
9868 
9869   return MoveConstructor;
9870 }
9871 
9872 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9873                                    CXXConstructorDecl *MoveConstructor) {
9874   assert((MoveConstructor->isDefaulted() &&
9875           MoveConstructor->isMoveConstructor() &&
9876           !MoveConstructor->doesThisDeclarationHaveABody() &&
9877           !MoveConstructor->isDeleted()) &&
9878          "DefineImplicitMoveConstructor - call it for implicit move ctor");
9879 
9880   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9881   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9882 
9883   SynthesizedFunctionScope Scope(*this, MoveConstructor);
9884   DiagnosticErrorTrap Trap(Diags);
9885 
9886   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
9887       Trap.hasErrorOccurred()) {
9888     Diag(CurrentLocation, diag::note_member_synthesized_at)
9889       << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9890     MoveConstructor->setInvalidDecl();
9891   }  else {
9892     Sema::CompoundScopeRAII CompoundScope(*this);
9893     MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9894                                                MoveConstructor->getLocation(),
9895                                                MultiStmtArg(),
9896                                                /*isStmtExpr=*/false)
9897                                                               .takeAs<Stmt>());
9898     MoveConstructor->setImplicitlyDefined(true);
9899   }
9900 
9901   MoveConstructor->setUsed();
9902 
9903   if (ASTMutationListener *L = getASTMutationListener()) {
9904     L->CompletedImplicitDefinition(MoveConstructor);
9905   }
9906 }
9907 
9908 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9909   return FD->isDeleted() &&
9910          (FD->isDefaulted() || FD->isImplicit()) &&
9911          isa<CXXMethodDecl>(FD);
9912 }
9913 
9914 /// \brief Mark the call operator of the given lambda closure type as "used".
9915 static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9916   CXXMethodDecl *CallOperator
9917     = cast<CXXMethodDecl>(
9918         Lambda->lookup(
9919           S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
9920   CallOperator->setReferenced();
9921   CallOperator->setUsed();
9922 }
9923 
9924 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9925        SourceLocation CurrentLocation,
9926        CXXConversionDecl *Conv)
9927 {
9928   CXXRecordDecl *Lambda = Conv->getParent();
9929 
9930   // Make sure that the lambda call operator is marked used.
9931   markLambdaCallOperatorUsed(*this, Lambda);
9932 
9933   Conv->setUsed();
9934 
9935   SynthesizedFunctionScope Scope(*this, Conv);
9936   DiagnosticErrorTrap Trap(Diags);
9937 
9938   // Return the address of the __invoke function.
9939   DeclarationName InvokeName = &Context.Idents.get("__invoke");
9940   CXXMethodDecl *Invoke
9941     = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
9942   Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9943                                        VK_LValue, Conv->getLocation()).take();
9944   assert(FunctionRef && "Can't refer to __invoke function?");
9945   Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
9946   Conv->setBody(new (Context) CompoundStmt(Context, Return,
9947                                            Conv->getLocation(),
9948                                            Conv->getLocation()));
9949 
9950   // Fill in the __invoke function with a dummy implementation. IR generation
9951   // will fill in the actual details.
9952   Invoke->setUsed();
9953   Invoke->setReferenced();
9954   Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
9955 
9956   if (ASTMutationListener *L = getASTMutationListener()) {
9957     L->CompletedImplicitDefinition(Conv);
9958     L->CompletedImplicitDefinition(Invoke);
9959   }
9960 }
9961 
9962 void Sema::DefineImplicitLambdaToBlockPointerConversion(
9963        SourceLocation CurrentLocation,
9964        CXXConversionDecl *Conv)
9965 {
9966   Conv->setUsed();
9967 
9968   SynthesizedFunctionScope Scope(*this, Conv);
9969   DiagnosticErrorTrap Trap(Diags);
9970 
9971   // Copy-initialize the lambda object as needed to capture it.
9972   Expr *This = ActOnCXXThis(CurrentLocation).take();
9973   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
9974 
9975   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9976                                                         Conv->getLocation(),
9977                                                         Conv, DerefThis);
9978 
9979   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9980   // behavior.  Note that only the general conversion function does this
9981   // (since it's unusable otherwise); in the case where we inline the
9982   // block literal, it has block literal lifetime semantics.
9983   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
9984     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9985                                           CK_CopyAndAutoreleaseBlockObject,
9986                                           BuildBlock.get(), 0, VK_RValue);
9987 
9988   if (BuildBlock.isInvalid()) {
9989     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9990     Conv->setInvalidDecl();
9991     return;
9992   }
9993 
9994   // Create the return statement that returns the block from the conversion
9995   // function.
9996   StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
9997   if (Return.isInvalid()) {
9998     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9999     Conv->setInvalidDecl();
10000     return;
10001   }
10002 
10003   // Set the body of the conversion function.
10004   Stmt *ReturnS = Return.take();
10005   Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
10006                                            Conv->getLocation(),
10007                                            Conv->getLocation()));
10008 
10009   // We're done; notify the mutation listener, if any.
10010   if (ASTMutationListener *L = getASTMutationListener()) {
10011     L->CompletedImplicitDefinition(Conv);
10012   }
10013 }
10014 
10015 /// \brief Determine whether the given list arguments contains exactly one
10016 /// "real" (non-default) argument.
10017 static bool hasOneRealArgument(MultiExprArg Args) {
10018   switch (Args.size()) {
10019   case 0:
10020     return false;
10021 
10022   default:
10023     if (!Args[1]->isDefaultArgument())
10024       return false;
10025 
10026     // fall through
10027   case 1:
10028     return !Args[0]->isDefaultArgument();
10029   }
10030 
10031   return false;
10032 }
10033 
10034 ExprResult
10035 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10036                             CXXConstructorDecl *Constructor,
10037                             MultiExprArg ExprArgs,
10038                             bool HadMultipleCandidates,
10039                             bool IsListInitialization,
10040                             bool RequiresZeroInit,
10041                             unsigned ConstructKind,
10042                             SourceRange ParenRange) {
10043   bool Elidable = false;
10044 
10045   // C++0x [class.copy]p34:
10046   //   When certain criteria are met, an implementation is allowed to
10047   //   omit the copy/move construction of a class object, even if the
10048   //   copy/move constructor and/or destructor for the object have
10049   //   side effects. [...]
10050   //     - when a temporary class object that has not been bound to a
10051   //       reference (12.2) would be copied/moved to a class object
10052   //       with the same cv-unqualified type, the copy/move operation
10053   //       can be omitted by constructing the temporary object
10054   //       directly into the target of the omitted copy/move
10055   if (ConstructKind == CXXConstructExpr::CK_Complete &&
10056       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
10057     Expr *SubExpr = ExprArgs[0];
10058     Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
10059   }
10060 
10061   return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
10062                                Elidable, ExprArgs, HadMultipleCandidates,
10063                                IsListInitialization, RequiresZeroInit,
10064                                ConstructKind, ParenRange);
10065 }
10066 
10067 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
10068 /// including handling of its default argument expressions.
10069 ExprResult
10070 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10071                             CXXConstructorDecl *Constructor, bool Elidable,
10072                             MultiExprArg ExprArgs,
10073                             bool HadMultipleCandidates,
10074                             bool IsListInitialization,
10075                             bool RequiresZeroInit,
10076                             unsigned ConstructKind,
10077                             SourceRange ParenRange) {
10078   MarkFunctionReferenced(ConstructLoc, Constructor);
10079   return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
10080                                         Constructor, Elidable, ExprArgs,
10081                                         HadMultipleCandidates,
10082                                         IsListInitialization, RequiresZeroInit,
10083               static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10084                                         ParenRange));
10085 }
10086 
10087 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
10088   if (VD->isInvalidDecl()) return;
10089 
10090   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
10091   if (ClassDecl->isInvalidDecl()) return;
10092   if (ClassDecl->hasIrrelevantDestructor()) return;
10093   if (ClassDecl->isDependentContext()) return;
10094 
10095   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10096   MarkFunctionReferenced(VD->getLocation(), Destructor);
10097   CheckDestructorAccess(VD->getLocation(), Destructor,
10098                         PDiag(diag::err_access_dtor_var)
10099                         << VD->getDeclName()
10100                         << VD->getType());
10101   DiagnoseUseOfDecl(Destructor, VD->getLocation());
10102 
10103   if (!VD->hasGlobalStorage()) return;
10104 
10105   // Emit warning for non-trivial dtor in global scope (a real global,
10106   // class-static, function-static).
10107   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10108 
10109   // TODO: this should be re-enabled for static locals by !CXAAtExit
10110   if (!VD->isStaticLocal())
10111     Diag(VD->getLocation(), diag::warn_global_destructor);
10112 }
10113 
10114 /// \brief Given a constructor and the set of arguments provided for the
10115 /// constructor, convert the arguments and add any required default arguments
10116 /// to form a proper call to this constructor.
10117 ///
10118 /// \returns true if an error occurred, false otherwise.
10119 bool
10120 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10121                               MultiExprArg ArgsPtr,
10122                               SourceLocation Loc,
10123                               SmallVectorImpl<Expr*> &ConvertedArgs,
10124                               bool AllowExplicit,
10125                               bool IsListInitialization) {
10126   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10127   unsigned NumArgs = ArgsPtr.size();
10128   Expr **Args = ArgsPtr.data();
10129 
10130   const FunctionProtoType *Proto
10131     = Constructor->getType()->getAs<FunctionProtoType>();
10132   assert(Proto && "Constructor without a prototype?");
10133   unsigned NumArgsInProto = Proto->getNumArgs();
10134 
10135   // If too few arguments are available, we'll fill in the rest with defaults.
10136   if (NumArgs < NumArgsInProto)
10137     ConvertedArgs.reserve(NumArgsInProto);
10138   else
10139     ConvertedArgs.reserve(NumArgs);
10140 
10141   VariadicCallType CallType =
10142     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
10143   SmallVector<Expr *, 8> AllArgs;
10144   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
10145                                         Proto, 0,
10146                                         llvm::makeArrayRef(Args, NumArgs),
10147                                         AllArgs,
10148                                         CallType, AllowExplicit,
10149                                         IsListInitialization);
10150   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
10151 
10152   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
10153 
10154   CheckConstructorCall(Constructor,
10155                        llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10156                                                         AllArgs.size()),
10157                        Proto, Loc);
10158 
10159   return Invalid;
10160 }
10161 
10162 static inline bool
10163 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10164                                        const FunctionDecl *FnDecl) {
10165   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
10166   if (isa<NamespaceDecl>(DC)) {
10167     return SemaRef.Diag(FnDecl->getLocation(),
10168                         diag::err_operator_new_delete_declared_in_namespace)
10169       << FnDecl->getDeclName();
10170   }
10171 
10172   if (isa<TranslationUnitDecl>(DC) &&
10173       FnDecl->getStorageClass() == SC_Static) {
10174     return SemaRef.Diag(FnDecl->getLocation(),
10175                         diag::err_operator_new_delete_declared_static)
10176       << FnDecl->getDeclName();
10177   }
10178 
10179   return false;
10180 }
10181 
10182 static inline bool
10183 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10184                             CanQualType ExpectedResultType,
10185                             CanQualType ExpectedFirstParamType,
10186                             unsigned DependentParamTypeDiag,
10187                             unsigned InvalidParamTypeDiag) {
10188   QualType ResultType =
10189     FnDecl->getType()->getAs<FunctionType>()->getResultType();
10190 
10191   // Check that the result type is not dependent.
10192   if (ResultType->isDependentType())
10193     return SemaRef.Diag(FnDecl->getLocation(),
10194                         diag::err_operator_new_delete_dependent_result_type)
10195     << FnDecl->getDeclName() << ExpectedResultType;
10196 
10197   // Check that the result type is what we expect.
10198   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10199     return SemaRef.Diag(FnDecl->getLocation(),
10200                         diag::err_operator_new_delete_invalid_result_type)
10201     << FnDecl->getDeclName() << ExpectedResultType;
10202 
10203   // A function template must have at least 2 parameters.
10204   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10205     return SemaRef.Diag(FnDecl->getLocation(),
10206                       diag::err_operator_new_delete_template_too_few_parameters)
10207         << FnDecl->getDeclName();
10208 
10209   // The function decl must have at least 1 parameter.
10210   if (FnDecl->getNumParams() == 0)
10211     return SemaRef.Diag(FnDecl->getLocation(),
10212                         diag::err_operator_new_delete_too_few_parameters)
10213       << FnDecl->getDeclName();
10214 
10215   // Check the first parameter type is not dependent.
10216   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10217   if (FirstParamType->isDependentType())
10218     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10219       << FnDecl->getDeclName() << ExpectedFirstParamType;
10220 
10221   // Check that the first parameter type is what we expect.
10222   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
10223       ExpectedFirstParamType)
10224     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10225     << FnDecl->getDeclName() << ExpectedFirstParamType;
10226 
10227   return false;
10228 }
10229 
10230 static bool
10231 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
10232   // C++ [basic.stc.dynamic.allocation]p1:
10233   //   A program is ill-formed if an allocation function is declared in a
10234   //   namespace scope other than global scope or declared static in global
10235   //   scope.
10236   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10237     return true;
10238 
10239   CanQualType SizeTy =
10240     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10241 
10242   // C++ [basic.stc.dynamic.allocation]p1:
10243   //  The return type shall be void*. The first parameter shall have type
10244   //  std::size_t.
10245   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10246                                   SizeTy,
10247                                   diag::err_operator_new_dependent_param_type,
10248                                   diag::err_operator_new_param_type))
10249     return true;
10250 
10251   // C++ [basic.stc.dynamic.allocation]p1:
10252   //  The first parameter shall not have an associated default argument.
10253   if (FnDecl->getParamDecl(0)->hasDefaultArg())
10254     return SemaRef.Diag(FnDecl->getLocation(),
10255                         diag::err_operator_new_default_arg)
10256       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10257 
10258   return false;
10259 }
10260 
10261 static bool
10262 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
10263   // C++ [basic.stc.dynamic.deallocation]p1:
10264   //   A program is ill-formed if deallocation functions are declared in a
10265   //   namespace scope other than global scope or declared static in global
10266   //   scope.
10267   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10268     return true;
10269 
10270   // C++ [basic.stc.dynamic.deallocation]p2:
10271   //   Each deallocation function shall return void and its first parameter
10272   //   shall be void*.
10273   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10274                                   SemaRef.Context.VoidPtrTy,
10275                                  diag::err_operator_delete_dependent_param_type,
10276                                  diag::err_operator_delete_param_type))
10277     return true;
10278 
10279   return false;
10280 }
10281 
10282 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
10283 /// of this overloaded operator is well-formed. If so, returns false;
10284 /// otherwise, emits appropriate diagnostics and returns true.
10285 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
10286   assert(FnDecl && FnDecl->isOverloadedOperator() &&
10287          "Expected an overloaded operator declaration");
10288 
10289   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10290 
10291   // C++ [over.oper]p5:
10292   //   The allocation and deallocation functions, operator new,
10293   //   operator new[], operator delete and operator delete[], are
10294   //   described completely in 3.7.3. The attributes and restrictions
10295   //   found in the rest of this subclause do not apply to them unless
10296   //   explicitly stated in 3.7.3.
10297   if (Op == OO_Delete || Op == OO_Array_Delete)
10298     return CheckOperatorDeleteDeclaration(*this, FnDecl);
10299 
10300   if (Op == OO_New || Op == OO_Array_New)
10301     return CheckOperatorNewDeclaration(*this, FnDecl);
10302 
10303   // C++ [over.oper]p6:
10304   //   An operator function shall either be a non-static member
10305   //   function or be a non-member function and have at least one
10306   //   parameter whose type is a class, a reference to a class, an
10307   //   enumeration, or a reference to an enumeration.
10308   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10309     if (MethodDecl->isStatic())
10310       return Diag(FnDecl->getLocation(),
10311                   diag::err_operator_overload_static) << FnDecl->getDeclName();
10312   } else {
10313     bool ClassOrEnumParam = false;
10314     for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10315                                    ParamEnd = FnDecl->param_end();
10316          Param != ParamEnd; ++Param) {
10317       QualType ParamType = (*Param)->getType().getNonReferenceType();
10318       if (ParamType->isDependentType() || ParamType->isRecordType() ||
10319           ParamType->isEnumeralType()) {
10320         ClassOrEnumParam = true;
10321         break;
10322       }
10323     }
10324 
10325     if (!ClassOrEnumParam)
10326       return Diag(FnDecl->getLocation(),
10327                   diag::err_operator_overload_needs_class_or_enum)
10328         << FnDecl->getDeclName();
10329   }
10330 
10331   // C++ [over.oper]p8:
10332   //   An operator function cannot have default arguments (8.3.6),
10333   //   except where explicitly stated below.
10334   //
10335   // Only the function-call operator allows default arguments
10336   // (C++ [over.call]p1).
10337   if (Op != OO_Call) {
10338     for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10339          Param != FnDecl->param_end(); ++Param) {
10340       if ((*Param)->hasDefaultArg())
10341         return Diag((*Param)->getLocation(),
10342                     diag::err_operator_overload_default_arg)
10343           << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
10344     }
10345   }
10346 
10347   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10348     { false, false, false }
10349 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10350     , { Unary, Binary, MemberOnly }
10351 #include "clang/Basic/OperatorKinds.def"
10352   };
10353 
10354   bool CanBeUnaryOperator = OperatorUses[Op][0];
10355   bool CanBeBinaryOperator = OperatorUses[Op][1];
10356   bool MustBeMemberOperator = OperatorUses[Op][2];
10357 
10358   // C++ [over.oper]p8:
10359   //   [...] Operator functions cannot have more or fewer parameters
10360   //   than the number required for the corresponding operator, as
10361   //   described in the rest of this subclause.
10362   unsigned NumParams = FnDecl->getNumParams()
10363                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
10364   if (Op != OO_Call &&
10365       ((NumParams == 1 && !CanBeUnaryOperator) ||
10366        (NumParams == 2 && !CanBeBinaryOperator) ||
10367        (NumParams < 1) || (NumParams > 2))) {
10368     // We have the wrong number of parameters.
10369     unsigned ErrorKind;
10370     if (CanBeUnaryOperator && CanBeBinaryOperator) {
10371       ErrorKind = 2;  // 2 -> unary or binary.
10372     } else if (CanBeUnaryOperator) {
10373       ErrorKind = 0;  // 0 -> unary
10374     } else {
10375       assert(CanBeBinaryOperator &&
10376              "All non-call overloaded operators are unary or binary!");
10377       ErrorKind = 1;  // 1 -> binary
10378     }
10379 
10380     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
10381       << FnDecl->getDeclName() << NumParams << ErrorKind;
10382   }
10383 
10384   // Overloaded operators other than operator() cannot be variadic.
10385   if (Op != OO_Call &&
10386       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
10387     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
10388       << FnDecl->getDeclName();
10389   }
10390 
10391   // Some operators must be non-static member functions.
10392   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10393     return Diag(FnDecl->getLocation(),
10394                 diag::err_operator_overload_must_be_member)
10395       << FnDecl->getDeclName();
10396   }
10397 
10398   // C++ [over.inc]p1:
10399   //   The user-defined function called operator++ implements the
10400   //   prefix and postfix ++ operator. If this function is a member
10401   //   function with no parameters, or a non-member function with one
10402   //   parameter of class or enumeration type, it defines the prefix
10403   //   increment operator ++ for objects of that type. If the function
10404   //   is a member function with one parameter (which shall be of type
10405   //   int) or a non-member function with two parameters (the second
10406   //   of which shall be of type int), it defines the postfix
10407   //   increment operator ++ for objects of that type.
10408   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10409     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10410     bool ParamIsInt = false;
10411     if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
10412       ParamIsInt = BT->getKind() == BuiltinType::Int;
10413 
10414     if (!ParamIsInt)
10415       return Diag(LastParam->getLocation(),
10416                   diag::err_operator_overload_post_incdec_must_be_int)
10417         << LastParam->getType() << (Op == OO_MinusMinus);
10418   }
10419 
10420   return false;
10421 }
10422 
10423 /// CheckLiteralOperatorDeclaration - Check whether the declaration
10424 /// of this literal operator function is well-formed. If so, returns
10425 /// false; otherwise, emits appropriate diagnostics and returns true.
10426 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
10427   if (isa<CXXMethodDecl>(FnDecl)) {
10428     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10429       << FnDecl->getDeclName();
10430     return true;
10431   }
10432 
10433   if (FnDecl->isExternC()) {
10434     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10435     return true;
10436   }
10437 
10438   bool Valid = false;
10439 
10440   // This might be the definition of a literal operator template.
10441   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10442   // This might be a specialization of a literal operator template.
10443   if (!TpDecl)
10444     TpDecl = FnDecl->getPrimaryTemplate();
10445 
10446   // template <char...> type operator "" name() is the only valid template
10447   // signature, and the only valid signature with no parameters.
10448   if (TpDecl) {
10449     if (FnDecl->param_size() == 0) {
10450       // Must have only one template parameter
10451       TemplateParameterList *Params = TpDecl->getTemplateParameters();
10452       if (Params->size() == 1) {
10453         NonTypeTemplateParmDecl *PmDecl =
10454           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
10455 
10456         // The template parameter must be a char parameter pack.
10457         if (PmDecl && PmDecl->isTemplateParameterPack() &&
10458             Context.hasSameType(PmDecl->getType(), Context.CharTy))
10459           Valid = true;
10460       }
10461     }
10462   } else if (FnDecl->param_size()) {
10463     // Check the first parameter
10464     FunctionDecl::param_iterator Param = FnDecl->param_begin();
10465 
10466     QualType T = (*Param)->getType().getUnqualifiedType();
10467 
10468     // unsigned long long int, long double, and any character type are allowed
10469     // as the only parameters.
10470     if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10471         Context.hasSameType(T, Context.LongDoubleTy) ||
10472         Context.hasSameType(T, Context.CharTy) ||
10473         Context.hasSameType(T, Context.WideCharTy) ||
10474         Context.hasSameType(T, Context.Char16Ty) ||
10475         Context.hasSameType(T, Context.Char32Ty)) {
10476       if (++Param == FnDecl->param_end())
10477         Valid = true;
10478       goto FinishedParams;
10479     }
10480 
10481     // Otherwise it must be a pointer to const; let's strip those qualifiers.
10482     const PointerType *PT = T->getAs<PointerType>();
10483     if (!PT)
10484       goto FinishedParams;
10485     T = PT->getPointeeType();
10486     if (!T.isConstQualified() || T.isVolatileQualified())
10487       goto FinishedParams;
10488     T = T.getUnqualifiedType();
10489 
10490     // Move on to the second parameter;
10491     ++Param;
10492 
10493     // If there is no second parameter, the first must be a const char *
10494     if (Param == FnDecl->param_end()) {
10495       if (Context.hasSameType(T, Context.CharTy))
10496         Valid = true;
10497       goto FinishedParams;
10498     }
10499 
10500     // const char *, const wchar_t*, const char16_t*, and const char32_t*
10501     // are allowed as the first parameter to a two-parameter function
10502     if (!(Context.hasSameType(T, Context.CharTy) ||
10503           Context.hasSameType(T, Context.WideCharTy) ||
10504           Context.hasSameType(T, Context.Char16Ty) ||
10505           Context.hasSameType(T, Context.Char32Ty)))
10506       goto FinishedParams;
10507 
10508     // The second and final parameter must be an std::size_t
10509     T = (*Param)->getType().getUnqualifiedType();
10510     if (Context.hasSameType(T, Context.getSizeType()) &&
10511         ++Param == FnDecl->param_end())
10512       Valid = true;
10513   }
10514 
10515   // FIXME: This diagnostic is absolutely terrible.
10516 FinishedParams:
10517   if (!Valid) {
10518     Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10519       << FnDecl->getDeclName();
10520     return true;
10521   }
10522 
10523   // A parameter-declaration-clause containing a default argument is not
10524   // equivalent to any of the permitted forms.
10525   for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10526                                     ParamEnd = FnDecl->param_end();
10527        Param != ParamEnd; ++Param) {
10528     if ((*Param)->hasDefaultArg()) {
10529       Diag((*Param)->getDefaultArgRange().getBegin(),
10530            diag::err_literal_operator_default_argument)
10531         << (*Param)->getDefaultArgRange();
10532       break;
10533     }
10534   }
10535 
10536   StringRef LiteralName
10537     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10538   if (LiteralName[0] != '_') {
10539     // C++11 [usrlit.suffix]p1:
10540     //   Literal suffix identifiers that do not start with an underscore
10541     //   are reserved for future standardization.
10542     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
10543   }
10544 
10545   return false;
10546 }
10547 
10548 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10549 /// linkage specification, including the language and (if present)
10550 /// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10551 /// the location of the language string literal, which is provided
10552 /// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10553 /// the '{' brace. Otherwise, this linkage specification does not
10554 /// have any braces.
10555 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10556                                            SourceLocation LangLoc,
10557                                            StringRef Lang,
10558                                            SourceLocation LBraceLoc) {
10559   LinkageSpecDecl::LanguageIDs Language;
10560   if (Lang == "\"C\"")
10561     Language = LinkageSpecDecl::lang_c;
10562   else if (Lang == "\"C++\"")
10563     Language = LinkageSpecDecl::lang_cxx;
10564   else {
10565     Diag(LangLoc, diag::err_bad_language);
10566     return 0;
10567   }
10568 
10569   // FIXME: Add all the various semantics of linkage specifications
10570 
10571   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
10572                                                ExternLoc, LangLoc, Language,
10573                                                LBraceLoc.isValid());
10574   CurContext->addDecl(D);
10575   PushDeclContext(S, D);
10576   return D;
10577 }
10578 
10579 /// ActOnFinishLinkageSpecification - Complete the definition of
10580 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
10581 /// valid, it's the position of the closing '}' brace in a linkage
10582 /// specification that uses braces.
10583 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
10584                                             Decl *LinkageSpec,
10585                                             SourceLocation RBraceLoc) {
10586   if (LinkageSpec) {
10587     if (RBraceLoc.isValid()) {
10588       LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10589       LSDecl->setRBraceLoc(RBraceLoc);
10590     }
10591     PopDeclContext();
10592   }
10593   return LinkageSpec;
10594 }
10595 
10596 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10597                                   AttributeList *AttrList,
10598                                   SourceLocation SemiLoc) {
10599   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10600   // Attribute declarations appertain to empty declaration so we handle
10601   // them here.
10602   if (AttrList)
10603     ProcessDeclAttributeList(S, ED, AttrList);
10604 
10605   CurContext->addDecl(ED);
10606   return ED;
10607 }
10608 
10609 /// \brief Perform semantic analysis for the variable declaration that
10610 /// occurs within a C++ catch clause, returning the newly-created
10611 /// variable.
10612 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
10613                                          TypeSourceInfo *TInfo,
10614                                          SourceLocation StartLoc,
10615                                          SourceLocation Loc,
10616                                          IdentifierInfo *Name) {
10617   bool Invalid = false;
10618   QualType ExDeclType = TInfo->getType();
10619 
10620   // Arrays and functions decay.
10621   if (ExDeclType->isArrayType())
10622     ExDeclType = Context.getArrayDecayedType(ExDeclType);
10623   else if (ExDeclType->isFunctionType())
10624     ExDeclType = Context.getPointerType(ExDeclType);
10625 
10626   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10627   // The exception-declaration shall not denote a pointer or reference to an
10628   // incomplete type, other than [cv] void*.
10629   // N2844 forbids rvalue references.
10630   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
10631     Diag(Loc, diag::err_catch_rvalue_ref);
10632     Invalid = true;
10633   }
10634 
10635   QualType BaseType = ExDeclType;
10636   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
10637   unsigned DK = diag::err_catch_incomplete;
10638   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
10639     BaseType = Ptr->getPointeeType();
10640     Mode = 1;
10641     DK = diag::err_catch_incomplete_ptr;
10642   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
10643     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
10644     BaseType = Ref->getPointeeType();
10645     Mode = 2;
10646     DK = diag::err_catch_incomplete_ref;
10647   }
10648   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
10649       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
10650     Invalid = true;
10651 
10652   if (!Invalid && !ExDeclType->isDependentType() &&
10653       RequireNonAbstractType(Loc, ExDeclType,
10654                              diag::err_abstract_type_in_decl,
10655                              AbstractVariableType))
10656     Invalid = true;
10657 
10658   // Only the non-fragile NeXT runtime currently supports C++ catches
10659   // of ObjC types, and no runtime supports catching ObjC types by value.
10660   if (!Invalid && getLangOpts().ObjC1) {
10661     QualType T = ExDeclType;
10662     if (const ReferenceType *RT = T->getAs<ReferenceType>())
10663       T = RT->getPointeeType();
10664 
10665     if (T->isObjCObjectType()) {
10666       Diag(Loc, diag::err_objc_object_catch);
10667       Invalid = true;
10668     } else if (T->isObjCObjectPointerType()) {
10669       // FIXME: should this be a test for macosx-fragile specifically?
10670       if (getLangOpts().ObjCRuntime.isFragile())
10671         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
10672     }
10673   }
10674 
10675   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
10676                                     ExDeclType, TInfo, SC_None);
10677   ExDecl->setExceptionVariable(true);
10678 
10679   // In ARC, infer 'retaining' for variables of retainable type.
10680   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
10681     Invalid = true;
10682 
10683   if (!Invalid && !ExDeclType->isDependentType()) {
10684     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
10685       // Insulate this from anything else we might currently be parsing.
10686       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10687 
10688       // C++ [except.handle]p16:
10689       //   The object declared in an exception-declaration or, if the
10690       //   exception-declaration does not specify a name, a temporary (12.2) is
10691       //   copy-initialized (8.5) from the exception object. [...]
10692       //   The object is destroyed when the handler exits, after the destruction
10693       //   of any automatic objects initialized within the handler.
10694       //
10695       // We just pretend to initialize the object with itself, then make sure
10696       // it can be destroyed later.
10697       QualType initType = ExDeclType;
10698 
10699       InitializedEntity entity =
10700         InitializedEntity::InitializeVariable(ExDecl);
10701       InitializationKind initKind =
10702         InitializationKind::CreateCopy(Loc, SourceLocation());
10703 
10704       Expr *opaqueValue =
10705         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
10706       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
10707       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
10708       if (result.isInvalid())
10709         Invalid = true;
10710       else {
10711         // If the constructor used was non-trivial, set this as the
10712         // "initializer".
10713         CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10714         if (!construct->getConstructor()->isTrivial()) {
10715           Expr *init = MaybeCreateExprWithCleanups(construct);
10716           ExDecl->setInit(init);
10717         }
10718 
10719         // And make sure it's destructable.
10720         FinalizeVarWithDestructor(ExDecl, recordType);
10721       }
10722     }
10723   }
10724 
10725   if (Invalid)
10726     ExDecl->setInvalidDecl();
10727 
10728   return ExDecl;
10729 }
10730 
10731 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10732 /// handler.
10733 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
10734   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10735   bool Invalid = D.isInvalidType();
10736 
10737   // Check for unexpanded parameter packs.
10738   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10739                                       UPPC_ExceptionType)) {
10740     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10741                                              D.getIdentifierLoc());
10742     Invalid = true;
10743   }
10744 
10745   IdentifierInfo *II = D.getIdentifier();
10746   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
10747                                              LookupOrdinaryName,
10748                                              ForRedeclaration)) {
10749     // The scope should be freshly made just for us. There is just no way
10750     // it contains any previous declaration.
10751     assert(!S->isDeclScope(PrevDecl));
10752     if (PrevDecl->isTemplateParameter()) {
10753       // Maybe we will complain about the shadowed template parameter.
10754       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
10755       PrevDecl = 0;
10756     }
10757   }
10758 
10759   if (D.getCXXScopeSpec().isSet() && !Invalid) {
10760     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10761       << D.getCXXScopeSpec().getRange();
10762     Invalid = true;
10763   }
10764 
10765   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
10766                                               D.getLocStart(),
10767                                               D.getIdentifierLoc(),
10768                                               D.getIdentifier());
10769   if (Invalid)
10770     ExDecl->setInvalidDecl();
10771 
10772   // Add the exception declaration into this scope.
10773   if (II)
10774     PushOnScopeChains(ExDecl, S);
10775   else
10776     CurContext->addDecl(ExDecl);
10777 
10778   ProcessDeclAttributes(S, ExDecl, D);
10779   return ExDecl;
10780 }
10781 
10782 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10783                                          Expr *AssertExpr,
10784                                          Expr *AssertMessageExpr,
10785                                          SourceLocation RParenLoc) {
10786   StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
10787 
10788   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10789     return 0;
10790 
10791   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10792                                       AssertMessage, RParenLoc, false);
10793 }
10794 
10795 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10796                                          Expr *AssertExpr,
10797                                          StringLiteral *AssertMessage,
10798                                          SourceLocation RParenLoc,
10799                                          bool Failed) {
10800   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10801       !Failed) {
10802     // In a static_assert-declaration, the constant-expression shall be a
10803     // constant expression that can be contextually converted to bool.
10804     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10805     if (Converted.isInvalid())
10806       Failed = true;
10807 
10808     llvm::APSInt Cond;
10809     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
10810           diag::err_static_assert_expression_is_not_constant,
10811           /*AllowFold=*/false).isInvalid())
10812       Failed = true;
10813 
10814     if (!Failed && !Cond) {
10815       SmallString<256> MsgBuffer;
10816       llvm::raw_svector_ostream Msg(MsgBuffer);
10817       AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
10818       Diag(StaticAssertLoc, diag::err_static_assert_failed)
10819         << Msg.str() << AssertExpr->getSourceRange();
10820       Failed = true;
10821     }
10822   }
10823 
10824   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
10825                                         AssertExpr, AssertMessage, RParenLoc,
10826                                         Failed);
10827 
10828   CurContext->addDecl(Decl);
10829   return Decl;
10830 }
10831 
10832 /// \brief Perform semantic analysis of the given friend type declaration.
10833 ///
10834 /// \returns A friend declaration that.
10835 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
10836                                       SourceLocation FriendLoc,
10837                                       TypeSourceInfo *TSInfo) {
10838   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10839 
10840   QualType T = TSInfo->getType();
10841   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
10842 
10843   // C++03 [class.friend]p2:
10844   //   An elaborated-type-specifier shall be used in a friend declaration
10845   //   for a class.*
10846   //
10847   //   * The class-key of the elaborated-type-specifier is required.
10848   if (!ActiveTemplateInstantiations.empty()) {
10849     // Do not complain about the form of friend template types during
10850     // template instantiation; we will already have complained when the
10851     // template was declared.
10852   } else {
10853     if (!T->isElaboratedTypeSpecifier()) {
10854       // If we evaluated the type to a record type, suggest putting
10855       // a tag in front.
10856       if (const RecordType *RT = T->getAs<RecordType>()) {
10857         RecordDecl *RD = RT->getDecl();
10858 
10859         std::string InsertionText = std::string(" ") + RD->getKindName();
10860 
10861         Diag(TypeRange.getBegin(),
10862              getLangOpts().CPlusPlus11 ?
10863                diag::warn_cxx98_compat_unelaborated_friend_type :
10864                diag::ext_unelaborated_friend_type)
10865           << (unsigned) RD->getTagKind()
10866           << T
10867           << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10868                                         InsertionText);
10869       } else {
10870         Diag(FriendLoc,
10871              getLangOpts().CPlusPlus11 ?
10872                diag::warn_cxx98_compat_nonclass_type_friend :
10873                diag::ext_nonclass_type_friend)
10874           << T
10875           << TypeRange;
10876       }
10877     } else if (T->getAs<EnumType>()) {
10878       Diag(FriendLoc,
10879            getLangOpts().CPlusPlus11 ?
10880              diag::warn_cxx98_compat_enum_friend :
10881              diag::ext_enum_friend)
10882         << T
10883         << TypeRange;
10884     }
10885 
10886     // C++11 [class.friend]p3:
10887     //   A friend declaration that does not declare a function shall have one
10888     //   of the following forms:
10889     //     friend elaborated-type-specifier ;
10890     //     friend simple-type-specifier ;
10891     //     friend typename-specifier ;
10892     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
10893       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10894   }
10895 
10896   //   If the type specifier in a friend declaration designates a (possibly
10897   //   cv-qualified) class type, that class is declared as a friend; otherwise,
10898   //   the friend declaration is ignored.
10899   return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
10900 }
10901 
10902 /// Handle a friend tag declaration where the scope specifier was
10903 /// templated.
10904 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10905                                     unsigned TagSpec, SourceLocation TagLoc,
10906                                     CXXScopeSpec &SS,
10907                                     IdentifierInfo *Name,
10908                                     SourceLocation NameLoc,
10909                                     AttributeList *Attr,
10910                                     MultiTemplateParamsArg TempParamLists) {
10911   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10912 
10913   bool isExplicitSpecialization = false;
10914   bool Invalid = false;
10915 
10916   if (TemplateParameterList *TemplateParams
10917         = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
10918                                                   TempParamLists.data(),
10919                                                   TempParamLists.size(),
10920                                                   /*friend*/ true,
10921                                                   isExplicitSpecialization,
10922                                                   Invalid)) {
10923     if (TemplateParams->size() > 0) {
10924       // This is a declaration of a class template.
10925       if (Invalid)
10926         return 0;
10927 
10928       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10929                                 SS, Name, NameLoc, Attr,
10930                                 TemplateParams, AS_public,
10931                                 /*ModulePrivateLoc=*/SourceLocation(),
10932                                 TempParamLists.size() - 1,
10933                                 TempParamLists.data()).take();
10934     } else {
10935       // The "template<>" header is extraneous.
10936       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10937         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10938       isExplicitSpecialization = true;
10939     }
10940   }
10941 
10942   if (Invalid) return 0;
10943 
10944   bool isAllExplicitSpecializations = true;
10945   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
10946     if (TempParamLists[I]->size()) {
10947       isAllExplicitSpecializations = false;
10948       break;
10949     }
10950   }
10951 
10952   // FIXME: don't ignore attributes.
10953 
10954   // If it's explicit specializations all the way down, just forget
10955   // about the template header and build an appropriate non-templated
10956   // friend.  TODO: for source fidelity, remember the headers.
10957   if (isAllExplicitSpecializations) {
10958     if (SS.isEmpty()) {
10959       bool Owned = false;
10960       bool IsDependent = false;
10961       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10962                       Attr, AS_public,
10963                       /*ModulePrivateLoc=*/SourceLocation(),
10964                       MultiTemplateParamsArg(), Owned, IsDependent,
10965                       /*ScopedEnumKWLoc=*/SourceLocation(),
10966                       /*ScopedEnumUsesClassTag=*/false,
10967                       /*UnderlyingType=*/TypeResult());
10968     }
10969 
10970     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10971     ElaboratedTypeKeyword Keyword
10972       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10973     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
10974                                    *Name, NameLoc);
10975     if (T.isNull())
10976       return 0;
10977 
10978     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10979     if (isa<DependentNameType>(T)) {
10980       DependentNameTypeLoc TL =
10981           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
10982       TL.setElaboratedKeywordLoc(TagLoc);
10983       TL.setQualifierLoc(QualifierLoc);
10984       TL.setNameLoc(NameLoc);
10985     } else {
10986       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
10987       TL.setElaboratedKeywordLoc(TagLoc);
10988       TL.setQualifierLoc(QualifierLoc);
10989       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
10990     }
10991 
10992     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10993                                             TSI, FriendLoc, TempParamLists);
10994     Friend->setAccess(AS_public);
10995     CurContext->addDecl(Friend);
10996     return Friend;
10997   }
10998 
10999   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11000 
11001 
11002 
11003   // Handle the case of a templated-scope friend class.  e.g.
11004   //   template <class T> class A<T>::B;
11005   // FIXME: we don't support these right now.
11006   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11007   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11008   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11009   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
11010   TL.setElaboratedKeywordLoc(TagLoc);
11011   TL.setQualifierLoc(SS.getWithLocInContext(Context));
11012   TL.setNameLoc(NameLoc);
11013 
11014   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
11015                                           TSI, FriendLoc, TempParamLists);
11016   Friend->setAccess(AS_public);
11017   Friend->setUnsupportedFriend(true);
11018   CurContext->addDecl(Friend);
11019   return Friend;
11020 }
11021 
11022 
11023 /// Handle a friend type declaration.  This works in tandem with
11024 /// ActOnTag.
11025 ///
11026 /// Notes on friend class templates:
11027 ///
11028 /// We generally treat friend class declarations as if they were
11029 /// declaring a class.  So, for example, the elaborated type specifier
11030 /// in a friend declaration is required to obey the restrictions of a
11031 /// class-head (i.e. no typedefs in the scope chain), template
11032 /// parameters are required to match up with simple template-ids, &c.
11033 /// However, unlike when declaring a template specialization, it's
11034 /// okay to refer to a template specialization without an empty
11035 /// template parameter declaration, e.g.
11036 ///   friend class A<T>::B<unsigned>;
11037 /// We permit this as a special case; if there are any template
11038 /// parameters present at all, require proper matching, i.e.
11039 ///   template <> template \<class T> friend class A<int>::B;
11040 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
11041                                 MultiTemplateParamsArg TempParams) {
11042   SourceLocation Loc = DS.getLocStart();
11043 
11044   assert(DS.isFriendSpecified());
11045   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11046 
11047   // Try to convert the decl specifier to a type.  This works for
11048   // friend templates because ActOnTag never produces a ClassTemplateDecl
11049   // for a TUK_Friend.
11050   Declarator TheDeclarator(DS, Declarator::MemberContext);
11051   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11052   QualType T = TSI->getType();
11053   if (TheDeclarator.isInvalidType())
11054     return 0;
11055 
11056   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11057     return 0;
11058 
11059   // This is definitely an error in C++98.  It's probably meant to
11060   // be forbidden in C++0x, too, but the specification is just
11061   // poorly written.
11062   //
11063   // The problem is with declarations like the following:
11064   //   template <T> friend A<T>::foo;
11065   // where deciding whether a class C is a friend or not now hinges
11066   // on whether there exists an instantiation of A that causes
11067   // 'foo' to equal C.  There are restrictions on class-heads
11068   // (which we declare (by fiat) elaborated friend declarations to
11069   // be) that makes this tractable.
11070   //
11071   // FIXME: handle "template <> friend class A<T>;", which
11072   // is possibly well-formed?  Who even knows?
11073   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
11074     Diag(Loc, diag::err_tagless_friend_type_template)
11075       << DS.getSourceRange();
11076     return 0;
11077   }
11078 
11079   // C++98 [class.friend]p1: A friend of a class is a function
11080   //   or class that is not a member of the class . . .
11081   // This is fixed in DR77, which just barely didn't make the C++03
11082   // deadline.  It's also a very silly restriction that seriously
11083   // affects inner classes and which nobody else seems to implement;
11084   // thus we never diagnose it, not even in -pedantic.
11085   //
11086   // But note that we could warn about it: it's always useless to
11087   // friend one of your own members (it's not, however, worthless to
11088   // friend a member of an arbitrary specialization of your template).
11089 
11090   Decl *D;
11091   if (unsigned NumTempParamLists = TempParams.size())
11092     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
11093                                    NumTempParamLists,
11094                                    TempParams.data(),
11095                                    TSI,
11096                                    DS.getFriendSpecLoc());
11097   else
11098     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
11099 
11100   if (!D)
11101     return 0;
11102 
11103   D->setAccess(AS_public);
11104   CurContext->addDecl(D);
11105 
11106   return D;
11107 }
11108 
11109 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11110                                         MultiTemplateParamsArg TemplateParams) {
11111   const DeclSpec &DS = D.getDeclSpec();
11112 
11113   assert(DS.isFriendSpecified());
11114   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11115 
11116   SourceLocation Loc = D.getIdentifierLoc();
11117   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11118 
11119   // C++ [class.friend]p1
11120   //   A friend of a class is a function or class....
11121   // Note that this sees through typedefs, which is intended.
11122   // It *doesn't* see through dependent types, which is correct
11123   // according to [temp.arg.type]p3:
11124   //   If a declaration acquires a function type through a
11125   //   type dependent on a template-parameter and this causes
11126   //   a declaration that does not use the syntactic form of a
11127   //   function declarator to have a function type, the program
11128   //   is ill-formed.
11129   if (!TInfo->getType()->isFunctionType()) {
11130     Diag(Loc, diag::err_unexpected_friend);
11131 
11132     // It might be worthwhile to try to recover by creating an
11133     // appropriate declaration.
11134     return 0;
11135   }
11136 
11137   // C++ [namespace.memdef]p3
11138   //  - If a friend declaration in a non-local class first declares a
11139   //    class or function, the friend class or function is a member
11140   //    of the innermost enclosing namespace.
11141   //  - The name of the friend is not found by simple name lookup
11142   //    until a matching declaration is provided in that namespace
11143   //    scope (either before or after the class declaration granting
11144   //    friendship).
11145   //  - If a friend function is called, its name may be found by the
11146   //    name lookup that considers functions from namespaces and
11147   //    classes associated with the types of the function arguments.
11148   //  - When looking for a prior declaration of a class or a function
11149   //    declared as a friend, scopes outside the innermost enclosing
11150   //    namespace scope are not considered.
11151 
11152   CXXScopeSpec &SS = D.getCXXScopeSpec();
11153   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11154   DeclarationName Name = NameInfo.getName();
11155   assert(Name);
11156 
11157   // Check for unexpanded parameter packs.
11158   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11159       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11160       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11161     return 0;
11162 
11163   // The context we found the declaration in, or in which we should
11164   // create the declaration.
11165   DeclContext *DC;
11166   Scope *DCScope = S;
11167   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
11168                         ForRedeclaration);
11169 
11170   // FIXME: there are different rules in local classes
11171 
11172   // There are four cases here.
11173   //   - There's no scope specifier, in which case we just go to the
11174   //     appropriate scope and look for a function or function template
11175   //     there as appropriate.
11176   // Recover from invalid scope qualifiers as if they just weren't there.
11177   if (SS.isInvalid() || !SS.isSet()) {
11178     // C++0x [namespace.memdef]p3:
11179     //   If the name in a friend declaration is neither qualified nor
11180     //   a template-id and the declaration is a function or an
11181     //   elaborated-type-specifier, the lookup to determine whether
11182     //   the entity has been previously declared shall not consider
11183     //   any scopes outside the innermost enclosing namespace.
11184     // C++0x [class.friend]p11:
11185     //   If a friend declaration appears in a local class and the name
11186     //   specified is an unqualified name, a prior declaration is
11187     //   looked up without considering scopes that are outside the
11188     //   innermost enclosing non-class scope. For a friend function
11189     //   declaration, if there is no prior declaration, the program is
11190     //   ill-formed.
11191     bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
11192     bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
11193 
11194     // Find the appropriate context according to the above.
11195     DC = CurContext;
11196 
11197     // Skip class contexts.  If someone can cite chapter and verse
11198     // for this behavior, that would be nice --- it's what GCC and
11199     // EDG do, and it seems like a reasonable intent, but the spec
11200     // really only says that checks for unqualified existing
11201     // declarations should stop at the nearest enclosing namespace,
11202     // not that they should only consider the nearest enclosing
11203     // namespace.
11204     while (DC->isRecord())
11205       DC = DC->getParent();
11206 
11207     DeclContext *LookupDC = DC;
11208     while (LookupDC->isTransparentContext())
11209       LookupDC = LookupDC->getParent();
11210 
11211     while (true) {
11212       LookupQualifiedName(Previous, LookupDC);
11213 
11214       // TODO: decide what we think about using declarations.
11215       if (isLocal)
11216         break;
11217 
11218       if (!Previous.empty()) {
11219         DC = LookupDC;
11220         break;
11221       }
11222 
11223       if (isTemplateId) {
11224         if (isa<TranslationUnitDecl>(LookupDC)) break;
11225       } else {
11226         if (LookupDC->isFileContext()) break;
11227       }
11228       LookupDC = LookupDC->getParent();
11229     }
11230 
11231     DCScope = getScopeForDeclContext(S, DC);
11232 
11233     // C++ [class.friend]p6:
11234     //   A function can be defined in a friend declaration of a class if and
11235     //   only if the class is a non-local class (9.8), the function name is
11236     //   unqualified, and the function has namespace scope.
11237     if (isLocal && D.isFunctionDefinition()) {
11238       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11239     }
11240 
11241   //   - There's a non-dependent scope specifier, in which case we
11242   //     compute it and do a previous lookup there for a function
11243   //     or function template.
11244   } else if (!SS.getScopeRep()->isDependent()) {
11245     DC = computeDeclContext(SS);
11246     if (!DC) return 0;
11247 
11248     if (RequireCompleteDeclContext(SS, DC)) return 0;
11249 
11250     LookupQualifiedName(Previous, DC);
11251 
11252     // Ignore things found implicitly in the wrong scope.
11253     // TODO: better diagnostics for this case.  Suggesting the right
11254     // qualified scope would be nice...
11255     LookupResult::Filter F = Previous.makeFilter();
11256     while (F.hasNext()) {
11257       NamedDecl *D = F.next();
11258       if (!DC->InEnclosingNamespaceSetOf(
11259               D->getDeclContext()->getRedeclContext()))
11260         F.erase();
11261     }
11262     F.done();
11263 
11264     if (Previous.empty()) {
11265       D.setInvalidType();
11266       Diag(Loc, diag::err_qualified_friend_not_found)
11267           << Name << TInfo->getType();
11268       return 0;
11269     }
11270 
11271     // C++ [class.friend]p1: A friend of a class is a function or
11272     //   class that is not a member of the class . . .
11273     if (DC->Equals(CurContext))
11274       Diag(DS.getFriendSpecLoc(),
11275            getLangOpts().CPlusPlus11 ?
11276              diag::warn_cxx98_compat_friend_is_member :
11277              diag::err_friend_is_member);
11278 
11279     if (D.isFunctionDefinition()) {
11280       // C++ [class.friend]p6:
11281       //   A function can be defined in a friend declaration of a class if and
11282       //   only if the class is a non-local class (9.8), the function name is
11283       //   unqualified, and the function has namespace scope.
11284       SemaDiagnosticBuilder DB
11285         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11286 
11287       DB << SS.getScopeRep();
11288       if (DC->isFileContext())
11289         DB << FixItHint::CreateRemoval(SS.getRange());
11290       SS.clear();
11291     }
11292 
11293   //   - There's a scope specifier that does not match any template
11294   //     parameter lists, in which case we use some arbitrary context,
11295   //     create a method or method template, and wait for instantiation.
11296   //   - There's a scope specifier that does match some template
11297   //     parameter lists, which we don't handle right now.
11298   } else {
11299     if (D.isFunctionDefinition()) {
11300       // C++ [class.friend]p6:
11301       //   A function can be defined in a friend declaration of a class if and
11302       //   only if the class is a non-local class (9.8), the function name is
11303       //   unqualified, and the function has namespace scope.
11304       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11305         << SS.getScopeRep();
11306     }
11307 
11308     DC = CurContext;
11309     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
11310   }
11311 
11312   if (!DC->isRecord()) {
11313     // This implies that it has to be an operator or function.
11314     if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11315         D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11316         D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
11317       Diag(Loc, diag::err_introducing_special_friend) <<
11318         (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11319          D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
11320       return 0;
11321     }
11322   }
11323 
11324   // FIXME: This is an egregious hack to cope with cases where the scope stack
11325   // does not contain the declaration context, i.e., in an out-of-line
11326   // definition of a class.
11327   Scope FakeDCScope(S, Scope::DeclScope, Diags);
11328   if (!DCScope) {
11329     FakeDCScope.setEntity(DC);
11330     DCScope = &FakeDCScope;
11331   }
11332 
11333   bool AddToScope = true;
11334   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
11335                                           TemplateParams, AddToScope);
11336   if (!ND) return 0;
11337 
11338   assert(ND->getDeclContext() == DC);
11339   assert(ND->getLexicalDeclContext() == CurContext);
11340 
11341   // Add the function declaration to the appropriate lookup tables,
11342   // adjusting the redeclarations list as necessary.  We don't
11343   // want to do this yet if the friending class is dependent.
11344   //
11345   // Also update the scope-based lookup if the target context's
11346   // lookup context is in lexical scope.
11347   if (!CurContext->isDependentContext()) {
11348     DC = DC->getRedeclContext();
11349     DC->makeDeclVisibleInContext(ND);
11350     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11351       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
11352   }
11353 
11354   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
11355                                        D.getIdentifierLoc(), ND,
11356                                        DS.getFriendSpecLoc());
11357   FrD->setAccess(AS_public);
11358   CurContext->addDecl(FrD);
11359 
11360   if (ND->isInvalidDecl()) {
11361     FrD->setInvalidDecl();
11362   } else {
11363     if (DC->isRecord()) CheckFriendAccess(ND);
11364 
11365     FunctionDecl *FD;
11366     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11367       FD = FTD->getTemplatedDecl();
11368     else
11369       FD = cast<FunctionDecl>(ND);
11370 
11371     // Mark templated-scope function declarations as unsupported.
11372     if (FD->getNumTemplateParameterLists())
11373       FrD->setUnsupportedFriend(true);
11374   }
11375 
11376   return ND;
11377 }
11378 
11379 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11380   AdjustDeclIfTemplate(Dcl);
11381 
11382   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
11383   if (!Fn) {
11384     Diag(DelLoc, diag::err_deleted_non_function);
11385     return;
11386   }
11387 
11388   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
11389     // Don't consider the implicit declaration we generate for explicit
11390     // specializations. FIXME: Do not generate these implicit declarations.
11391     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11392         || Prev->getPreviousDecl()) && !Prev->isDefined()) {
11393       Diag(DelLoc, diag::err_deleted_decl_not_first);
11394       Diag(Prev->getLocation(), diag::note_previous_declaration);
11395     }
11396     // If the declaration wasn't the first, we delete the function anyway for
11397     // recovery.
11398     Fn = Fn->getCanonicalDecl();
11399   }
11400 
11401   if (Fn->isDeleted())
11402     return;
11403 
11404   // See if we're deleting a function which is already known to override a
11405   // non-deleted virtual function.
11406   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11407     bool IssuedDiagnostic = false;
11408     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11409                                         E = MD->end_overridden_methods();
11410          I != E; ++I) {
11411       if (!(*MD->begin_overridden_methods())->isDeleted()) {
11412         if (!IssuedDiagnostic) {
11413           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11414           IssuedDiagnostic = true;
11415         }
11416         Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11417       }
11418     }
11419   }
11420 
11421   Fn->setDeletedAsWritten();
11422 }
11423 
11424 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
11425   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
11426 
11427   if (MD) {
11428     if (MD->getParent()->isDependentType()) {
11429       MD->setDefaulted();
11430       MD->setExplicitlyDefaulted();
11431       return;
11432     }
11433 
11434     CXXSpecialMember Member = getSpecialMember(MD);
11435     if (Member == CXXInvalid) {
11436       Diag(DefaultLoc, diag::err_default_special_members);
11437       return;
11438     }
11439 
11440     MD->setDefaulted();
11441     MD->setExplicitlyDefaulted();
11442 
11443     // If this definition appears within the record, do the checking when
11444     // the record is complete.
11445     const FunctionDecl *Primary = MD;
11446     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
11447       // Find the uninstantiated declaration that actually had the '= default'
11448       // on it.
11449       Pattern->isDefined(Primary);
11450 
11451     // If the method was defaulted on its first declaration, we will have
11452     // already performed the checking in CheckCompletedCXXClass. Such a
11453     // declaration doesn't trigger an implicit definition.
11454     if (Primary == Primary->getCanonicalDecl())
11455       return;
11456 
11457     CheckExplicitlyDefaultedSpecialMember(MD);
11458 
11459     // The exception specification is needed because we are defining the
11460     // function.
11461     ResolveExceptionSpec(DefaultLoc,
11462                          MD->getType()->castAs<FunctionProtoType>());
11463 
11464     switch (Member) {
11465     case CXXDefaultConstructor: {
11466       CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
11467       if (!CD->isInvalidDecl())
11468         DefineImplicitDefaultConstructor(DefaultLoc, CD);
11469       break;
11470     }
11471 
11472     case CXXCopyConstructor: {
11473       CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
11474       if (!CD->isInvalidDecl())
11475         DefineImplicitCopyConstructor(DefaultLoc, CD);
11476       break;
11477     }
11478 
11479     case CXXCopyAssignment: {
11480       if (!MD->isInvalidDecl())
11481         DefineImplicitCopyAssignment(DefaultLoc, MD);
11482       break;
11483     }
11484 
11485     case CXXDestructor: {
11486       CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
11487       if (!DD->isInvalidDecl())
11488         DefineImplicitDestructor(DefaultLoc, DD);
11489       break;
11490     }
11491 
11492     case CXXMoveConstructor: {
11493       CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
11494       if (!CD->isInvalidDecl())
11495         DefineImplicitMoveConstructor(DefaultLoc, CD);
11496       break;
11497     }
11498 
11499     case CXXMoveAssignment: {
11500       if (!MD->isInvalidDecl())
11501         DefineImplicitMoveAssignment(DefaultLoc, MD);
11502       break;
11503     }
11504 
11505     case CXXInvalid:
11506       llvm_unreachable("Invalid special member.");
11507     }
11508   } else {
11509     Diag(DefaultLoc, diag::err_default_special_members);
11510   }
11511 }
11512 
11513 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
11514   for (Stmt::child_range CI = S->children(); CI; ++CI) {
11515     Stmt *SubStmt = *CI;
11516     if (!SubStmt)
11517       continue;
11518     if (isa<ReturnStmt>(SubStmt))
11519       Self.Diag(SubStmt->getLocStart(),
11520            diag::err_return_in_constructor_handler);
11521     if (!isa<Expr>(SubStmt))
11522       SearchForReturnInStmt(Self, SubStmt);
11523   }
11524 }
11525 
11526 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11527   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11528     CXXCatchStmt *Handler = TryBlock->getHandler(I);
11529     SearchForReturnInStmt(*this, Handler);
11530   }
11531 }
11532 
11533 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
11534                                              const CXXMethodDecl *Old) {
11535   const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11536   const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11537 
11538   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11539 
11540   // If the calling conventions match, everything is fine
11541   if (NewCC == OldCC)
11542     return false;
11543 
11544   // If either of the calling conventions are set to "default", we need to pick
11545   // something more sensible based on the target. This supports code where the
11546   // one method explicitly sets thiscall, and another has no explicit calling
11547   // convention.
11548   CallingConv Default =
11549     Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
11550   if (NewCC == CC_Default)
11551     NewCC = Default;
11552   if (OldCC == CC_Default)
11553     OldCC = Default;
11554 
11555   // If the calling conventions still don't match, then report the error
11556   if (NewCC != OldCC) {
11557     Diag(New->getLocation(),
11558          diag::err_conflicting_overriding_cc_attributes)
11559       << New->getDeclName() << New->getType() << Old->getType();
11560     Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11561     return true;
11562   }
11563 
11564   return false;
11565 }
11566 
11567 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
11568                                              const CXXMethodDecl *Old) {
11569   QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11570   QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
11571 
11572   if (Context.hasSameType(NewTy, OldTy) ||
11573       NewTy->isDependentType() || OldTy->isDependentType())
11574     return false;
11575 
11576   // Check if the return types are covariant
11577   QualType NewClassTy, OldClassTy;
11578 
11579   /// Both types must be pointers or references to classes.
11580   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11581     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
11582       NewClassTy = NewPT->getPointeeType();
11583       OldClassTy = OldPT->getPointeeType();
11584     }
11585   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11586     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11587       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11588         NewClassTy = NewRT->getPointeeType();
11589         OldClassTy = OldRT->getPointeeType();
11590       }
11591     }
11592   }
11593 
11594   // The return types aren't either both pointers or references to a class type.
11595   if (NewClassTy.isNull()) {
11596     Diag(New->getLocation(),
11597          diag::err_different_return_type_for_overriding_virtual_function)
11598       << New->getDeclName() << NewTy << OldTy;
11599     Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11600 
11601     return true;
11602   }
11603 
11604   // C++ [class.virtual]p6:
11605   //   If the return type of D::f differs from the return type of B::f, the
11606   //   class type in the return type of D::f shall be complete at the point of
11607   //   declaration of D::f or shall be the class type D.
11608   if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11609     if (!RT->isBeingDefined() &&
11610         RequireCompleteType(New->getLocation(), NewClassTy,
11611                             diag::err_covariant_return_incomplete,
11612                             New->getDeclName()))
11613     return true;
11614   }
11615 
11616   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
11617     // Check if the new class derives from the old class.
11618     if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11619       Diag(New->getLocation(),
11620            diag::err_covariant_return_not_derived)
11621       << New->getDeclName() << NewTy << OldTy;
11622       Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11623       return true;
11624     }
11625 
11626     // Check if we the conversion from derived to base is valid.
11627     if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
11628                     diag::err_covariant_return_inaccessible_base,
11629                     diag::err_covariant_return_ambiguous_derived_to_base_conv,
11630                     // FIXME: Should this point to the return type?
11631                     New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
11632       // FIXME: this note won't trigger for delayed access control
11633       // diagnostics, and it's impossible to get an undelayed error
11634       // here from access control during the original parse because
11635       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
11636       Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11637       return true;
11638     }
11639   }
11640 
11641   // The qualifiers of the return types must be the same.
11642   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
11643     Diag(New->getLocation(),
11644          diag::err_covariant_return_type_different_qualifications)
11645     << New->getDeclName() << NewTy << OldTy;
11646     Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11647     return true;
11648   };
11649 
11650 
11651   // The new class type must have the same or less qualifiers as the old type.
11652   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11653     Diag(New->getLocation(),
11654          diag::err_covariant_return_type_class_type_more_qualified)
11655     << New->getDeclName() << NewTy << OldTy;
11656     Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11657     return true;
11658   };
11659 
11660   return false;
11661 }
11662 
11663 /// \brief Mark the given method pure.
11664 ///
11665 /// \param Method the method to be marked pure.
11666 ///
11667 /// \param InitRange the source range that covers the "0" initializer.
11668 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
11669   SourceLocation EndLoc = InitRange.getEnd();
11670   if (EndLoc.isValid())
11671     Method->setRangeEnd(EndLoc);
11672 
11673   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11674     Method->setPure();
11675     return false;
11676   }
11677 
11678   if (!Method->isInvalidDecl())
11679     Diag(Method->getLocation(), diag::err_non_virtual_pure)
11680       << Method->getDeclName() << InitRange;
11681   return true;
11682 }
11683 
11684 /// \brief Determine whether the given declaration is a static data member.
11685 static bool isStaticDataMember(Decl *D) {
11686   VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11687   if (!Var)
11688     return false;
11689 
11690   return Var->isStaticDataMember();
11691 }
11692 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11693 /// an initializer for the out-of-line declaration 'Dcl'.  The scope
11694 /// is a fresh scope pushed for just this purpose.
11695 ///
11696 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11697 /// static data member of class X, names should be looked up in the scope of
11698 /// class X.
11699 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
11700   // If there is no declaration, there was an error parsing it.
11701   if (D == 0 || D->isInvalidDecl()) return;
11702 
11703   // We should only get called for declarations with scope specifiers, like:
11704   //   int foo::bar;
11705   assert(D->isOutOfLine());
11706   EnterDeclaratorContext(S, D->getDeclContext());
11707 
11708   // If we are parsing the initializer for a static data member, push a
11709   // new expression evaluation context that is associated with this static
11710   // data member.
11711   if (isStaticDataMember(D))
11712     PushExpressionEvaluationContext(PotentiallyEvaluated, D);
11713 }
11714 
11715 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
11716 /// initializer for the out-of-line declaration 'D'.
11717 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
11718   // If there is no declaration, there was an error parsing it.
11719   if (D == 0 || D->isInvalidDecl()) return;
11720 
11721   if (isStaticDataMember(D))
11722     PopExpressionEvaluationContext();
11723 
11724   assert(D->isOutOfLine());
11725   ExitDeclaratorContext(S);
11726 }
11727 
11728 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11729 /// C++ if/switch/while/for statement.
11730 /// e.g: "if (int x = f()) {...}"
11731 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
11732   // C++ 6.4p2:
11733   // The declarator shall not specify a function or an array.
11734   // The type-specifier-seq shall not contain typedef and shall not declare a
11735   // new class or enumeration.
11736   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11737          "Parser allowed 'typedef' as storage class of condition decl.");
11738 
11739   Decl *Dcl = ActOnDeclarator(S, D);
11740   if (!Dcl)
11741     return true;
11742 
11743   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11744     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
11745       << D.getSourceRange();
11746     return true;
11747   }
11748 
11749   return Dcl;
11750 }
11751 
11752 void Sema::LoadExternalVTableUses() {
11753   if (!ExternalSource)
11754     return;
11755 
11756   SmallVector<ExternalVTableUse, 4> VTables;
11757   ExternalSource->ReadUsedVTables(VTables);
11758   SmallVector<VTableUse, 4> NewUses;
11759   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11760     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11761       = VTablesUsed.find(VTables[I].Record);
11762     // Even if a definition wasn't required before, it may be required now.
11763     if (Pos != VTablesUsed.end()) {
11764       if (!Pos->second && VTables[I].DefinitionRequired)
11765         Pos->second = true;
11766       continue;
11767     }
11768 
11769     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11770     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11771   }
11772 
11773   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11774 }
11775 
11776 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11777                           bool DefinitionRequired) {
11778   // Ignore any vtable uses in unevaluated operands or for classes that do
11779   // not have a vtable.
11780   if (!Class->isDynamicClass() || Class->isDependentContext() ||
11781       CurContext->isDependentContext() || isUnevaluatedContext())
11782     return;
11783 
11784   // Try to insert this class into the map.
11785   LoadExternalVTableUses();
11786   Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11787   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11788     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11789   if (!Pos.second) {
11790     // If we already had an entry, check to see if we are promoting this vtable
11791     // to required a definition. If so, we need to reappend to the VTableUses
11792     // list, since we may have already processed the first entry.
11793     if (DefinitionRequired && !Pos.first->second) {
11794       Pos.first->second = true;
11795     } else {
11796       // Otherwise, we can early exit.
11797       return;
11798     }
11799   }
11800 
11801   // Local classes need to have their virtual members marked
11802   // immediately. For all other classes, we mark their virtual members
11803   // at the end of the translation unit.
11804   if (Class->isLocalClass())
11805     MarkVirtualMembersReferenced(Loc, Class);
11806   else
11807     VTableUses.push_back(std::make_pair(Class, Loc));
11808 }
11809 
11810 bool Sema::DefineUsedVTables() {
11811   LoadExternalVTableUses();
11812   if (VTableUses.empty())
11813     return false;
11814 
11815   // Note: The VTableUses vector could grow as a result of marking
11816   // the members of a class as "used", so we check the size each
11817   // time through the loop and prefer indices (which are stable) to
11818   // iterators (which are not).
11819   bool DefinedAnything = false;
11820   for (unsigned I = 0; I != VTableUses.size(); ++I) {
11821     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
11822     if (!Class)
11823       continue;
11824 
11825     SourceLocation Loc = VTableUses[I].second;
11826 
11827     bool DefineVTable = true;
11828 
11829     // If this class has a key function, but that key function is
11830     // defined in another translation unit, we don't need to emit the
11831     // vtable even though we're using it.
11832     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
11833     if (KeyFunction && !KeyFunction->hasBody()) {
11834       switch (KeyFunction->getTemplateSpecializationKind()) {
11835       case TSK_Undeclared:
11836       case TSK_ExplicitSpecialization:
11837       case TSK_ExplicitInstantiationDeclaration:
11838         // The key function is in another translation unit.
11839         DefineVTable = false;
11840         break;
11841 
11842       case TSK_ExplicitInstantiationDefinition:
11843       case TSK_ImplicitInstantiation:
11844         // We will be instantiating the key function.
11845         break;
11846       }
11847     } else if (!KeyFunction) {
11848       // If we have a class with no key function that is the subject
11849       // of an explicit instantiation declaration, suppress the
11850       // vtable; it will live with the explicit instantiation
11851       // definition.
11852       bool IsExplicitInstantiationDeclaration
11853         = Class->getTemplateSpecializationKind()
11854                                       == TSK_ExplicitInstantiationDeclaration;
11855       for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11856                                  REnd = Class->redecls_end();
11857            R != REnd; ++R) {
11858         TemplateSpecializationKind TSK
11859           = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11860         if (TSK == TSK_ExplicitInstantiationDeclaration)
11861           IsExplicitInstantiationDeclaration = true;
11862         else if (TSK == TSK_ExplicitInstantiationDefinition) {
11863           IsExplicitInstantiationDeclaration = false;
11864           break;
11865         }
11866       }
11867 
11868       if (IsExplicitInstantiationDeclaration)
11869         DefineVTable = false;
11870     }
11871 
11872     // The exception specifications for all virtual members may be needed even
11873     // if we are not providing an authoritative form of the vtable in this TU.
11874     // We may choose to emit it available_externally anyway.
11875     if (!DefineVTable) {
11876       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11877       continue;
11878     }
11879 
11880     // Mark all of the virtual members of this class as referenced, so
11881     // that we can build a vtable. Then, tell the AST consumer that a
11882     // vtable for this class is required.
11883     DefinedAnything = true;
11884     MarkVirtualMembersReferenced(Loc, Class);
11885     CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11886     Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11887 
11888     // Optionally warn if we're emitting a weak vtable.
11889     if (Class->isExternallyVisible() &&
11890         Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
11891       const FunctionDecl *KeyFunctionDef = 0;
11892       if (!KeyFunction ||
11893           (KeyFunction->hasBody(KeyFunctionDef) &&
11894            KeyFunctionDef->isInlined()))
11895         Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11896              TSK_ExplicitInstantiationDefinition
11897              ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11898           << Class;
11899     }
11900   }
11901   VTableUses.clear();
11902 
11903   return DefinedAnything;
11904 }
11905 
11906 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
11907                                                  const CXXRecordDecl *RD) {
11908   for (CXXRecordDecl::method_iterator I = RD->method_begin(),
11909                                       E = RD->method_end(); I != E; ++I)
11910     if ((*I)->isVirtual() && !(*I)->isPure())
11911       ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
11912 }
11913 
11914 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
11915                                         const CXXRecordDecl *RD) {
11916   // Mark all functions which will appear in RD's vtable as used.
11917   CXXFinalOverriderMap FinalOverriders;
11918   RD->getFinalOverriders(FinalOverriders);
11919   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
11920                                             E = FinalOverriders.end();
11921        I != E; ++I) {
11922     for (OverridingMethods::const_iterator OI = I->second.begin(),
11923                                            OE = I->second.end();
11924          OI != OE; ++OI) {
11925       assert(OI->second.size() > 0 && "no final overrider");
11926       CXXMethodDecl *Overrider = OI->second.front().Method;
11927 
11928       // C++ [basic.def.odr]p2:
11929       //   [...] A virtual member function is used if it is not pure. [...]
11930       if (!Overrider->isPure())
11931         MarkFunctionReferenced(Loc, Overrider);
11932     }
11933   }
11934 
11935   // Only classes that have virtual bases need a VTT.
11936   if (RD->getNumVBases() == 0)
11937     return;
11938 
11939   for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11940            e = RD->bases_end(); i != e; ++i) {
11941     const CXXRecordDecl *Base =
11942         cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
11943     if (Base->getNumVBases() == 0)
11944       continue;
11945     MarkVirtualMembersReferenced(Loc, Base);
11946   }
11947 }
11948 
11949 /// SetIvarInitializers - This routine builds initialization ASTs for the
11950 /// Objective-C implementation whose ivars need be initialized.
11951 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
11952   if (!getLangOpts().CPlusPlus)
11953     return;
11954   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
11955     SmallVector<ObjCIvarDecl*, 8> ivars;
11956     CollectIvarsToConstructOrDestruct(OID, ivars);
11957     if (ivars.empty())
11958       return;
11959     SmallVector<CXXCtorInitializer*, 32> AllToInit;
11960     for (unsigned i = 0; i < ivars.size(); i++) {
11961       FieldDecl *Field = ivars[i];
11962       if (Field->isInvalidDecl())
11963         continue;
11964 
11965       CXXCtorInitializer *Member;
11966       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
11967       InitializationKind InitKind =
11968         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
11969 
11970       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
11971       ExprResult MemberInit =
11972         InitSeq.Perform(*this, InitEntity, InitKind, None);
11973       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
11974       // Note, MemberInit could actually come back empty if no initialization
11975       // is required (e.g., because it would call a trivial default constructor)
11976       if (!MemberInit.get() || MemberInit.isInvalid())
11977         continue;
11978 
11979       Member =
11980         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
11981                                          SourceLocation(),
11982                                          MemberInit.takeAs<Expr>(),
11983                                          SourceLocation());
11984       AllToInit.push_back(Member);
11985 
11986       // Be sure that the destructor is accessible and is marked as referenced.
11987       if (const RecordType *RecordTy
11988                   = Context.getBaseElementType(Field->getType())
11989                                                         ->getAs<RecordType>()) {
11990                     CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
11991         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
11992           MarkFunctionReferenced(Field->getLocation(), Destructor);
11993           CheckDestructorAccess(Field->getLocation(), Destructor,
11994                             PDiag(diag::err_access_dtor_ivar)
11995                               << Context.getBaseElementType(Field->getType()));
11996         }
11997       }
11998     }
11999     ObjCImplementation->setIvarInitializers(Context,
12000                                             AllToInit.data(), AllToInit.size());
12001   }
12002 }
12003 
12004 static
12005 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12006                            llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12007                            llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12008                            llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12009                            Sema &S) {
12010   llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
12011                                                    CE = Current.end();
12012   if (Ctor->isInvalidDecl())
12013     return;
12014 
12015   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12016 
12017   // Target may not be determinable yet, for instance if this is a dependent
12018   // call in an uninstantiated template.
12019   if (Target) {
12020     const FunctionDecl *FNTarget = 0;
12021     (void)Target->hasBody(FNTarget);
12022     Target = const_cast<CXXConstructorDecl*>(
12023       cast_or_null<CXXConstructorDecl>(FNTarget));
12024   }
12025 
12026   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12027                      // Avoid dereferencing a null pointer here.
12028                      *TCanonical = Target ? Target->getCanonicalDecl() : 0;
12029 
12030   if (!Current.insert(Canonical))
12031     return;
12032 
12033   // We know that beyond here, we aren't chaining into a cycle.
12034   if (!Target || !Target->isDelegatingConstructor() ||
12035       Target->isInvalidDecl() || Valid.count(TCanonical)) {
12036     for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
12037       Valid.insert(*CI);
12038     Current.clear();
12039   // We've hit a cycle.
12040   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12041              Current.count(TCanonical)) {
12042     // If we haven't diagnosed this cycle yet, do so now.
12043     if (!Invalid.count(TCanonical)) {
12044       S.Diag((*Ctor->init_begin())->getSourceLocation(),
12045              diag::warn_delegating_ctor_cycle)
12046         << Ctor;
12047 
12048       // Don't add a note for a function delegating directly to itself.
12049       if (TCanonical != Canonical)
12050         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12051 
12052       CXXConstructorDecl *C = Target;
12053       while (C->getCanonicalDecl() != Canonical) {
12054         const FunctionDecl *FNTarget = 0;
12055         (void)C->getTargetConstructor()->hasBody(FNTarget);
12056         assert(FNTarget && "Ctor cycle through bodiless function");
12057 
12058         C = const_cast<CXXConstructorDecl*>(
12059           cast<CXXConstructorDecl>(FNTarget));
12060         S.Diag(C->getLocation(), diag::note_which_delegates_to);
12061       }
12062     }
12063 
12064     for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
12065       Invalid.insert(*CI);
12066     Current.clear();
12067   } else {
12068     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12069   }
12070 }
12071 
12072 
12073 void Sema::CheckDelegatingCtorCycles() {
12074   llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12075 
12076   llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
12077                                                    CE = Current.end();
12078 
12079   for (DelegatingCtorDeclsType::iterator
12080          I = DelegatingCtorDecls.begin(ExternalSource),
12081          E = DelegatingCtorDecls.end();
12082        I != E; ++I)
12083     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
12084 
12085   for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
12086     (*CI)->setInvalidDecl();
12087 }
12088 
12089 namespace {
12090   /// \brief AST visitor that finds references to the 'this' expression.
12091   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12092     Sema &S;
12093 
12094   public:
12095     explicit FindCXXThisExpr(Sema &S) : S(S) { }
12096 
12097     bool VisitCXXThisExpr(CXXThisExpr *E) {
12098       S.Diag(E->getLocation(), diag::err_this_static_member_func)
12099         << E->isImplicit();
12100       return false;
12101     }
12102   };
12103 }
12104 
12105 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12106   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12107   if (!TSInfo)
12108     return false;
12109 
12110   TypeLoc TL = TSInfo->getTypeLoc();
12111   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
12112   if (!ProtoTL)
12113     return false;
12114 
12115   // C++11 [expr.prim.general]p3:
12116   //   [The expression this] shall not appear before the optional
12117   //   cv-qualifier-seq and it shall not appear within the declaration of a
12118   //   static member function (although its type and value category are defined
12119   //   within a static member function as they are within a non-static member
12120   //   function). [ Note: this is because declaration matching does not occur
12121   //  until the complete declarator is known. - end note ]
12122   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
12123   FindCXXThisExpr Finder(*this);
12124 
12125   // If the return type came after the cv-qualifier-seq, check it now.
12126   if (Proto->hasTrailingReturn() &&
12127       !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
12128     return true;
12129 
12130   // Check the exception specification.
12131   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12132     return true;
12133 
12134   return checkThisInStaticMemberFunctionAttributes(Method);
12135 }
12136 
12137 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12138   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12139   if (!TSInfo)
12140     return false;
12141 
12142   TypeLoc TL = TSInfo->getTypeLoc();
12143   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
12144   if (!ProtoTL)
12145     return false;
12146 
12147   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
12148   FindCXXThisExpr Finder(*this);
12149 
12150   switch (Proto->getExceptionSpecType()) {
12151   case EST_Uninstantiated:
12152   case EST_Unevaluated:
12153   case EST_BasicNoexcept:
12154   case EST_DynamicNone:
12155   case EST_MSAny:
12156   case EST_None:
12157     break;
12158 
12159   case EST_ComputedNoexcept:
12160     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12161       return true;
12162 
12163   case EST_Dynamic:
12164     for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
12165          EEnd = Proto->exception_end();
12166          E != EEnd; ++E) {
12167       if (!Finder.TraverseType(*E))
12168         return true;
12169     }
12170     break;
12171   }
12172 
12173   return false;
12174 }
12175 
12176 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12177   FindCXXThisExpr Finder(*this);
12178 
12179   // Check attributes.
12180   for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
12181        A != AEnd; ++A) {
12182     // FIXME: This should be emitted by tblgen.
12183     Expr *Arg = 0;
12184     ArrayRef<Expr *> Args;
12185     if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
12186       Arg = G->getArg();
12187     else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
12188       Arg = G->getArg();
12189     else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
12190       Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12191     else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
12192       Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12193     else if (ExclusiveLockFunctionAttr *ELF
12194                = dyn_cast<ExclusiveLockFunctionAttr>(*A))
12195       Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
12196     else if (SharedLockFunctionAttr *SLF
12197                = dyn_cast<SharedLockFunctionAttr>(*A))
12198       Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
12199     else if (ExclusiveTrylockFunctionAttr *ETLF
12200                = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
12201       Arg = ETLF->getSuccessValue();
12202       Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12203     } else if (SharedTrylockFunctionAttr *STLF
12204                  = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
12205       Arg = STLF->getSuccessValue();
12206       Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12207     } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
12208       Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
12209     else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
12210       Arg = LR->getArg();
12211     else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
12212       Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12213     else if (ExclusiveLocksRequiredAttr *ELR
12214                = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
12215       Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
12216     else if (SharedLocksRequiredAttr *SLR
12217                = dyn_cast<SharedLocksRequiredAttr>(*A))
12218       Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
12219 
12220     if (Arg && !Finder.TraverseStmt(Arg))
12221       return true;
12222 
12223     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12224       if (!Finder.TraverseStmt(Args[I]))
12225         return true;
12226     }
12227   }
12228 
12229   return false;
12230 }
12231 
12232 void
12233 Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12234                                   ArrayRef<ParsedType> DynamicExceptions,
12235                                   ArrayRef<SourceRange> DynamicExceptionRanges,
12236                                   Expr *NoexceptExpr,
12237                                   SmallVectorImpl<QualType> &Exceptions,
12238                                   FunctionProtoType::ExtProtoInfo &EPI) {
12239   Exceptions.clear();
12240   EPI.ExceptionSpecType = EST;
12241   if (EST == EST_Dynamic) {
12242     Exceptions.reserve(DynamicExceptions.size());
12243     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12244       // FIXME: Preserve type source info.
12245       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12246 
12247       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12248       collectUnexpandedParameterPacks(ET, Unexpanded);
12249       if (!Unexpanded.empty()) {
12250         DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12251                                          UPPC_ExceptionType,
12252                                          Unexpanded);
12253         continue;
12254       }
12255 
12256       // Check that the type is valid for an exception spec, and
12257       // drop it if not.
12258       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12259         Exceptions.push_back(ET);
12260     }
12261     EPI.NumExceptions = Exceptions.size();
12262     EPI.Exceptions = Exceptions.data();
12263     return;
12264   }
12265 
12266   if (EST == EST_ComputedNoexcept) {
12267     // If an error occurred, there's no expression here.
12268     if (NoexceptExpr) {
12269       assert((NoexceptExpr->isTypeDependent() ||
12270               NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12271               Context.BoolTy) &&
12272              "Parser should have made sure that the expression is boolean");
12273       if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12274         EPI.ExceptionSpecType = EST_BasicNoexcept;
12275         return;
12276       }
12277 
12278       if (!NoexceptExpr->isValueDependent())
12279         NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
12280                          diag::err_noexcept_needs_constant_expression,
12281                          /*AllowFold*/ false).take();
12282       EPI.NoexceptExpr = NoexceptExpr;
12283     }
12284     return;
12285   }
12286 }
12287 
12288 /// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12289 Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12290   // Implicitly declared functions (e.g. copy constructors) are
12291   // __host__ __device__
12292   if (D->isImplicit())
12293     return CFT_HostDevice;
12294 
12295   if (D->hasAttr<CUDAGlobalAttr>())
12296     return CFT_Global;
12297 
12298   if (D->hasAttr<CUDADeviceAttr>()) {
12299     if (D->hasAttr<CUDAHostAttr>())
12300       return CFT_HostDevice;
12301     else
12302       return CFT_Device;
12303   }
12304 
12305   return CFT_Host;
12306 }
12307 
12308 bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12309                            CUDAFunctionTarget CalleeTarget) {
12310   // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12311   // Callable from the device only."
12312   if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12313     return true;
12314 
12315   // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12316   // Callable from the host only."
12317   // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12318   // Callable from the host only."
12319   if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12320       (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12321     return true;
12322 
12323   if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12324     return true;
12325 
12326   return false;
12327 }
12328 
12329 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12330 ///
12331 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12332                                        SourceLocation DeclStart,
12333                                        Declarator &D, Expr *BitWidth,
12334                                        InClassInitStyle InitStyle,
12335                                        AccessSpecifier AS,
12336                                        AttributeList *MSPropertyAttr) {
12337   IdentifierInfo *II = D.getIdentifier();
12338   if (!II) {
12339     Diag(DeclStart, diag::err_anonymous_property);
12340     return NULL;
12341   }
12342   SourceLocation Loc = D.getIdentifierLoc();
12343 
12344   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12345   QualType T = TInfo->getType();
12346   if (getLangOpts().CPlusPlus) {
12347     CheckExtraCXXDefaultArguments(D);
12348 
12349     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12350                                         UPPC_DataMemberType)) {
12351       D.setInvalidType();
12352       T = Context.IntTy;
12353       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12354     }
12355   }
12356 
12357   DiagnoseFunctionSpecifiers(D.getDeclSpec());
12358 
12359   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12360     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12361          diag::err_invalid_thread)
12362       << DeclSpec::getSpecifierName(TSCS);
12363 
12364   // Check to see if this name was declared as a member previously
12365   NamedDecl *PrevDecl = 0;
12366   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12367   LookupName(Previous, S);
12368   switch (Previous.getResultKind()) {
12369   case LookupResult::Found:
12370   case LookupResult::FoundUnresolvedValue:
12371     PrevDecl = Previous.getAsSingle<NamedDecl>();
12372     break;
12373 
12374   case LookupResult::FoundOverloaded:
12375     PrevDecl = Previous.getRepresentativeDecl();
12376     break;
12377 
12378   case LookupResult::NotFound:
12379   case LookupResult::NotFoundInCurrentInstantiation:
12380   case LookupResult::Ambiguous:
12381     break;
12382   }
12383 
12384   if (PrevDecl && PrevDecl->isTemplateParameter()) {
12385     // Maybe we will complain about the shadowed template parameter.
12386     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12387     // Just pretend that we didn't see the previous declaration.
12388     PrevDecl = 0;
12389   }
12390 
12391   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12392     PrevDecl = 0;
12393 
12394   SourceLocation TSSL = D.getLocStart();
12395   MSPropertyDecl *NewPD;
12396   const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12397   NewPD = new (Context) MSPropertyDecl(Record, Loc,
12398                                        II, T, TInfo, TSSL,
12399                                        Data.GetterId, Data.SetterId);
12400   ProcessDeclAttributes(TUScope, NewPD, D);
12401   NewPD->setAccess(AS);
12402 
12403   if (NewPD->isInvalidDecl())
12404     Record->setInvalidDecl();
12405 
12406   if (D.getDeclSpec().isModulePrivateSpecified())
12407     NewPD->setModulePrivate();
12408 
12409   if (NewPD->isInvalidDecl() && PrevDecl) {
12410     // Don't introduce NewFD into scope; there's already something
12411     // with the same name in the same scope.
12412   } else if (II) {
12413     PushOnScopeChains(NewPD, S);
12414   } else
12415     Record->addDecl(NewPD);
12416 
12417   return NewPD;
12418 }
12419