1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for C++ declarations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/DeclVisitor.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/RecordLayout.h"
25 #include "clang/AST/RecursiveASTVisitor.h"
26 #include "clang/AST/StmtVisitor.h"
27 #include "clang/AST/TypeLoc.h"
28 #include "clang/AST/TypeOrdering.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/LiteralSupport.h"
32 #include "clang/Lex/Preprocessor.h"
33 #include "clang/Sema/CXXFieldCollector.h"
34 #include "clang/Sema/DeclSpec.h"
35 #include "clang/Sema/Initialization.h"
36 #include "clang/Sema/Lookup.h"
37 #include "clang/Sema/ParsedTemplate.h"
38 #include "clang/Sema/Scope.h"
39 #include "clang/Sema/ScopeInfo.h"
40 #include "llvm/ADT/STLExtras.h"
41 #include "llvm/ADT/SmallString.h"
42 #include <map>
43 #include <set>
44 
45 using namespace clang;
46 
47 //===----------------------------------------------------------------------===//
48 // CheckDefaultArgumentVisitor
49 //===----------------------------------------------------------------------===//
50 
51 namespace {
52   /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
53   /// the default argument of a parameter to determine whether it
54   /// contains any ill-formed subexpressions. For example, this will
55   /// diagnose the use of local variables or parameters within the
56   /// default argument expression.
57   class CheckDefaultArgumentVisitor
58     : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
59     Expr *DefaultArg;
60     Sema *S;
61 
62   public:
63     CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
64       : DefaultArg(defarg), S(s) {}
65 
66     bool VisitExpr(Expr *Node);
67     bool VisitDeclRefExpr(DeclRefExpr *DRE);
68     bool VisitCXXThisExpr(CXXThisExpr *ThisE);
69     bool VisitLambdaExpr(LambdaExpr *Lambda);
70     bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
71   };
72 
73   /// VisitExpr - Visit all of the children of this expression.
74   bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
75     bool IsInvalid = false;
76     for (Stmt::child_range I = Node->children(); I; ++I)
77       IsInvalid |= Visit(*I);
78     return IsInvalid;
79   }
80 
81   /// VisitDeclRefExpr - Visit a reference to a declaration, to
82   /// determine whether this declaration can be used in the default
83   /// argument expression.
84   bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
85     NamedDecl *Decl = DRE->getDecl();
86     if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
87       // C++ [dcl.fct.default]p9
88       //   Default arguments are evaluated each time the function is
89       //   called. The order of evaluation of function arguments is
90       //   unspecified. Consequently, parameters of a function shall not
91       //   be used in default argument expressions, even if they are not
92       //   evaluated. Parameters of a function declared before a default
93       //   argument expression are in scope and can hide namespace and
94       //   class member names.
95       return S->Diag(DRE->getLocStart(),
96                      diag::err_param_default_argument_references_param)
97          << Param->getDeclName() << DefaultArg->getSourceRange();
98     } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
99       // C++ [dcl.fct.default]p7
100       //   Local variables shall not be used in default argument
101       //   expressions.
102       if (VDecl->isLocalVarDecl())
103         return S->Diag(DRE->getLocStart(),
104                        diag::err_param_default_argument_references_local)
105           << VDecl->getDeclName() << DefaultArg->getSourceRange();
106     }
107 
108     return false;
109   }
110 
111   /// VisitCXXThisExpr - Visit a C++ "this" expression.
112   bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
113     // C++ [dcl.fct.default]p8:
114     //   The keyword this shall not be used in a default argument of a
115     //   member function.
116     return S->Diag(ThisE->getLocStart(),
117                    diag::err_param_default_argument_references_this)
118                << ThisE->getSourceRange();
119   }
120 
121   bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
122     bool Invalid = false;
123     for (PseudoObjectExpr::semantics_iterator
124            i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
125       Expr *E = *i;
126 
127       // Look through bindings.
128       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
129         E = OVE->getSourceExpr();
130         assert(E && "pseudo-object binding without source expression?");
131       }
132 
133       Invalid |= Visit(E);
134     }
135     return Invalid;
136   }
137 
138   bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
139     // C++11 [expr.lambda.prim]p13:
140     //   A lambda-expression appearing in a default argument shall not
141     //   implicitly or explicitly capture any entity.
142     if (Lambda->capture_begin() == Lambda->capture_end())
143       return false;
144 
145     return S->Diag(Lambda->getLocStart(),
146                    diag::err_lambda_capture_default_arg);
147   }
148 }
149 
150 void
151 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
152                                                  const CXXMethodDecl *Method) {
153   // If we have an MSAny spec already, don't bother.
154   if (!Method || ComputedEST == EST_MSAny)
155     return;
156 
157   const FunctionProtoType *Proto
158     = Method->getType()->getAs<FunctionProtoType>();
159   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
160   if (!Proto)
161     return;
162 
163   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
164 
165   // If this function can throw any exceptions, make a note of that.
166   if (EST == EST_MSAny || EST == EST_None) {
167     ClearExceptions();
168     ComputedEST = EST;
169     return;
170   }
171 
172   // FIXME: If the call to this decl is using any of its default arguments, we
173   // need to search them for potentially-throwing calls.
174 
175   // If this function has a basic noexcept, it doesn't affect the outcome.
176   if (EST == EST_BasicNoexcept)
177     return;
178 
179   // If we have a throw-all spec at this point, ignore the function.
180   if (ComputedEST == EST_None)
181     return;
182 
183   // If we're still at noexcept(true) and there's a nothrow() callee,
184   // change to that specification.
185   if (EST == EST_DynamicNone) {
186     if (ComputedEST == EST_BasicNoexcept)
187       ComputedEST = EST_DynamicNone;
188     return;
189   }
190 
191   // Check out noexcept specs.
192   if (EST == EST_ComputedNoexcept) {
193     FunctionProtoType::NoexceptResult NR =
194         Proto->getNoexceptSpec(Self->Context);
195     assert(NR != FunctionProtoType::NR_NoNoexcept &&
196            "Must have noexcept result for EST_ComputedNoexcept.");
197     assert(NR != FunctionProtoType::NR_Dependent &&
198            "Should not generate implicit declarations for dependent cases, "
199            "and don't know how to handle them anyway.");
200 
201     // noexcept(false) -> no spec on the new function
202     if (NR == FunctionProtoType::NR_Throw) {
203       ClearExceptions();
204       ComputedEST = EST_None;
205     }
206     // noexcept(true) won't change anything either.
207     return;
208   }
209 
210   assert(EST == EST_Dynamic && "EST case not considered earlier.");
211   assert(ComputedEST != EST_None &&
212          "Shouldn't collect exceptions when throw-all is guaranteed.");
213   ComputedEST = EST_Dynamic;
214   // Record the exceptions in this function's exception specification.
215   for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
216                                           EEnd = Proto->exception_end();
217        E != EEnd; ++E)
218     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
219       Exceptions.push_back(*E);
220 }
221 
222 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
223   if (!E || ComputedEST == EST_MSAny)
224     return;
225 
226   // FIXME:
227   //
228   // C++0x [except.spec]p14:
229   //   [An] implicit exception-specification specifies the type-id T if and
230   // only if T is allowed by the exception-specification of a function directly
231   // invoked by f's implicit definition; f shall allow all exceptions if any
232   // function it directly invokes allows all exceptions, and f shall allow no
233   // exceptions if every function it directly invokes allows no exceptions.
234   //
235   // Note in particular that if an implicit exception-specification is generated
236   // for a function containing a throw-expression, that specification can still
237   // be noexcept(true).
238   //
239   // Note also that 'directly invoked' is not defined in the standard, and there
240   // is no indication that we should only consider potentially-evaluated calls.
241   //
242   // Ultimately we should implement the intent of the standard: the exception
243   // specification should be the set of exceptions which can be thrown by the
244   // implicit definition. For now, we assume that any non-nothrow expression can
245   // throw any exception.
246 
247   if (Self->canThrow(E))
248     ComputedEST = EST_None;
249 }
250 
251 bool
252 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
253                               SourceLocation EqualLoc) {
254   if (RequireCompleteType(Param->getLocation(), Param->getType(),
255                           diag::err_typecheck_decl_incomplete_type)) {
256     Param->setInvalidDecl();
257     return true;
258   }
259 
260   // C++ [dcl.fct.default]p5
261   //   A default argument expression is implicitly converted (clause
262   //   4) to the parameter type. The default argument expression has
263   //   the same semantic constraints as the initializer expression in
264   //   a declaration of a variable of the parameter type, using the
265   //   copy-initialization semantics (8.5).
266   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
267                                                                     Param);
268   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
269                                                            EqualLoc);
270   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
271   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
272   if (Result.isInvalid())
273     return true;
274   Arg = Result.takeAs<Expr>();
275 
276   CheckCompletedExpr(Arg, EqualLoc);
277   Arg = MaybeCreateExprWithCleanups(Arg);
278 
279   // Okay: add the default argument to the parameter
280   Param->setDefaultArg(Arg);
281 
282   // We have already instantiated this parameter; provide each of the
283   // instantiations with the uninstantiated default argument.
284   UnparsedDefaultArgInstantiationsMap::iterator InstPos
285     = UnparsedDefaultArgInstantiations.find(Param);
286   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
287     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
288       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
289 
290     // We're done tracking this parameter's instantiations.
291     UnparsedDefaultArgInstantiations.erase(InstPos);
292   }
293 
294   return false;
295 }
296 
297 /// ActOnParamDefaultArgument - Check whether the default argument
298 /// provided for a function parameter is well-formed. If so, attach it
299 /// to the parameter declaration.
300 void
301 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
302                                 Expr *DefaultArg) {
303   if (!param || !DefaultArg)
304     return;
305 
306   ParmVarDecl *Param = cast<ParmVarDecl>(param);
307   UnparsedDefaultArgLocs.erase(Param);
308 
309   // Default arguments are only permitted in C++
310   if (!getLangOpts().CPlusPlus) {
311     Diag(EqualLoc, diag::err_param_default_argument)
312       << DefaultArg->getSourceRange();
313     Param->setInvalidDecl();
314     return;
315   }
316 
317   // Check for unexpanded parameter packs.
318   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
319     Param->setInvalidDecl();
320     return;
321   }
322 
323   // Check that the default argument is well-formed
324   CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
325   if (DefaultArgChecker.Visit(DefaultArg)) {
326     Param->setInvalidDecl();
327     return;
328   }
329 
330   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
331 }
332 
333 /// ActOnParamUnparsedDefaultArgument - We've seen a default
334 /// argument for a function parameter, but we can't parse it yet
335 /// because we're inside a class definition. Note that this default
336 /// argument will be parsed later.
337 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
338                                              SourceLocation EqualLoc,
339                                              SourceLocation ArgLoc) {
340   if (!param)
341     return;
342 
343   ParmVarDecl *Param = cast<ParmVarDecl>(param);
344   Param->setUnparsedDefaultArg();
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   Param->setInvalidDecl();
356   UnparsedDefaultArgLocs.erase(Param);
357 }
358 
359 /// CheckExtraCXXDefaultArguments - Check for any extra default
360 /// arguments in the declarator, which is not a function declaration
361 /// or definition and therefore is not permitted to have default
362 /// arguments. This routine should be invoked for every declarator
363 /// that is not a function declaration or definition.
364 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
365   // C++ [dcl.fct.default]p3
366   //   A default argument expression shall be specified only in the
367   //   parameter-declaration-clause of a function declaration or in a
368   //   template-parameter (14.1). It shall not be specified for a
369   //   parameter pack. If it is specified in a
370   //   parameter-declaration-clause, it shall not occur within a
371   //   declarator or abstract-declarator of a parameter-declaration.
372   bool MightBeFunction = D.isFunctionDeclarationContext();
373   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
374     DeclaratorChunk &chunk = D.getTypeObject(i);
375     if (chunk.Kind == DeclaratorChunk::Function) {
376       if (MightBeFunction) {
377         // This is a function declaration. It can have default arguments, but
378         // keep looking in case its return type is a function type with default
379         // arguments.
380         MightBeFunction = false;
381         continue;
382       }
383       for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
384         ParmVarDecl *Param =
385           cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
386         if (Param->hasUnparsedDefaultArg()) {
387           CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
388           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
389             << SourceRange((*Toks)[1].getLocation(),
390                            Toks->back().getLocation());
391           delete Toks;
392           chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
393         } else if (Param->getDefaultArg()) {
394           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
395             << Param->getDefaultArg()->getSourceRange();
396           Param->setDefaultArg(0);
397         }
398       }
399     } else if (chunk.Kind != DeclaratorChunk::Paren) {
400       MightBeFunction = false;
401     }
402   }
403 }
404 
405 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
406   for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
407     const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
408     if (!PVD->hasDefaultArg())
409       return false;
410     if (!PVD->hasInheritedDefaultArg())
411       return true;
412   }
413   return false;
414 }
415 
416 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
417 /// function, once we already know that they have the same
418 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
419 /// error, false otherwise.
420 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
421                                 Scope *S) {
422   bool Invalid = false;
423 
424   // C++ [dcl.fct.default]p4:
425   //   For non-template functions, default arguments can be added in
426   //   later declarations of a function in the same
427   //   scope. Declarations in different scopes have completely
428   //   distinct sets of default arguments. That is, declarations in
429   //   inner scopes do not acquire default arguments from
430   //   declarations in outer scopes, and vice versa. In a given
431   //   function declaration, all parameters subsequent to a
432   //   parameter with a default argument shall have default
433   //   arguments supplied in this or previous declarations. A
434   //   default argument shall not be redefined by a later
435   //   declaration (not even to the same value).
436   //
437   // C++ [dcl.fct.default]p6:
438   //   Except for member functions of class templates, the default arguments
439   //   in a member function definition that appears outside of the class
440   //   definition are added to the set of default arguments provided by the
441   //   member function declaration in the class definition.
442   for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
443     ParmVarDecl *OldParam = Old->getParamDecl(p);
444     ParmVarDecl *NewParam = New->getParamDecl(p);
445 
446     bool OldParamHasDfl = OldParam->hasDefaultArg();
447     bool NewParamHasDfl = NewParam->hasDefaultArg();
448 
449     NamedDecl *ND = Old;
450 
451     // The declaration context corresponding to the scope is the semantic
452     // parent, unless this is a local function declaration, in which case
453     // it is that surrounding function.
454     DeclContext *ScopeDC = New->getLexicalDeclContext();
455     if (!ScopeDC->isFunctionOrMethod())
456       ScopeDC = New->getDeclContext();
457     if (S && !isDeclInScope(ND, ScopeDC, S) &&
458         !New->getDeclContext()->isRecord())
459       // Ignore default parameters of old decl if they are not in
460       // the same scope and this is not an out-of-line definition of
461       // a member function.
462       OldParamHasDfl = false;
463 
464     if (OldParamHasDfl && NewParamHasDfl) {
465 
466       unsigned DiagDefaultParamID =
467         diag::err_param_default_argument_redefinition;
468 
469       // MSVC accepts that default parameters be redefined for member functions
470       // of template class. The new default parameter's value is ignored.
471       Invalid = true;
472       if (getLangOpts().MicrosoftExt) {
473         CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
474         if (MD && MD->getParent()->getDescribedClassTemplate()) {
475           // Merge the old default argument into the new parameter.
476           NewParam->setHasInheritedDefaultArg();
477           if (OldParam->hasUninstantiatedDefaultArg())
478             NewParam->setUninstantiatedDefaultArg(
479                                       OldParam->getUninstantiatedDefaultArg());
480           else
481             NewParam->setDefaultArg(OldParam->getInit());
482           DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
483           Invalid = false;
484         }
485       }
486 
487       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
488       // hint here. Alternatively, we could walk the type-source information
489       // for NewParam to find the last source location in the type... but it
490       // isn't worth the effort right now. This is the kind of test case that
491       // is hard to get right:
492       //   int f(int);
493       //   void g(int (*fp)(int) = f);
494       //   void g(int (*fp)(int) = &f);
495       Diag(NewParam->getLocation(), DiagDefaultParamID)
496         << NewParam->getDefaultArgRange();
497 
498       // Look for the function declaration where the default argument was
499       // actually written, which may be a declaration prior to Old.
500       for (FunctionDecl *Older = Old->getPreviousDecl();
501            Older; Older = Older->getPreviousDecl()) {
502         if (!Older->getParamDecl(p)->hasDefaultArg())
503           break;
504 
505         OldParam = Older->getParamDecl(p);
506       }
507 
508       Diag(OldParam->getLocation(), diag::note_previous_definition)
509         << OldParam->getDefaultArgRange();
510     } else if (OldParamHasDfl) {
511       // Merge the old default argument into the new parameter.
512       // It's important to use getInit() here;  getDefaultArg()
513       // strips off any top-level ExprWithCleanups.
514       NewParam->setHasInheritedDefaultArg();
515       if (OldParam->hasUninstantiatedDefaultArg())
516         NewParam->setUninstantiatedDefaultArg(
517                                       OldParam->getUninstantiatedDefaultArg());
518       else
519         NewParam->setDefaultArg(OldParam->getInit());
520     } else if (NewParamHasDfl) {
521       if (New->getDescribedFunctionTemplate()) {
522         // Paragraph 4, quoted above, only applies to non-template functions.
523         Diag(NewParam->getLocation(),
524              diag::err_param_default_argument_template_redecl)
525           << NewParam->getDefaultArgRange();
526         Diag(Old->getLocation(), diag::note_template_prev_declaration)
527           << false;
528       } else if (New->getTemplateSpecializationKind()
529                    != TSK_ImplicitInstantiation &&
530                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
531         // C++ [temp.expr.spec]p21:
532         //   Default function arguments shall not be specified in a declaration
533         //   or a definition for one of the following explicit specializations:
534         //     - the explicit specialization of a function template;
535         //     - the explicit specialization of a member function template;
536         //     - the explicit specialization of a member function of a class
537         //       template where the class template specialization to which the
538         //       member function specialization belongs is implicitly
539         //       instantiated.
540         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
541           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
542           << New->getDeclName()
543           << NewParam->getDefaultArgRange();
544       } else if (New->getDeclContext()->isDependentContext()) {
545         // C++ [dcl.fct.default]p6 (DR217):
546         //   Default arguments for a member function of a class template shall
547         //   be specified on the initial declaration of the member function
548         //   within the class template.
549         //
550         // Reading the tea leaves a bit in DR217 and its reference to DR205
551         // leads me to the conclusion that one cannot add default function
552         // arguments for an out-of-line definition of a member function of a
553         // dependent type.
554         int WhichKind = 2;
555         if (CXXRecordDecl *Record
556               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
557           if (Record->getDescribedClassTemplate())
558             WhichKind = 0;
559           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
560             WhichKind = 1;
561           else
562             WhichKind = 2;
563         }
564 
565         Diag(NewParam->getLocation(),
566              diag::err_param_default_argument_member_template_redecl)
567           << WhichKind
568           << NewParam->getDefaultArgRange();
569       }
570     }
571   }
572 
573   // DR1344: If a default argument is added outside a class definition and that
574   // default argument makes the function a special member function, the program
575   // is ill-formed. This can only happen for constructors.
576   if (isa<CXXConstructorDecl>(New) &&
577       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
578     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
579                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
580     if (NewSM != OldSM) {
581       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
582       assert(NewParam->hasDefaultArg());
583       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
584         << NewParam->getDefaultArgRange() << NewSM;
585       Diag(Old->getLocation(), diag::note_previous_declaration);
586     }
587   }
588 
589   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
590   // template has a constexpr specifier then all its declarations shall
591   // contain the constexpr specifier.
592   if (New->isConstexpr() != Old->isConstexpr()) {
593     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
594       << New << New->isConstexpr();
595     Diag(Old->getLocation(), diag::note_previous_declaration);
596     Invalid = true;
597   }
598 
599   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
600   // argument expression, that declaration shall be a definition and shall be
601   // the only declaration of the function or function template in the
602   // translation unit.
603   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
604       functionDeclHasDefaultArgument(Old)) {
605     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
606     Diag(Old->getLocation(), diag::note_previous_declaration);
607     Invalid = true;
608   }
609 
610   if (CheckEquivalentExceptionSpec(Old, New))
611     Invalid = true;
612 
613   return Invalid;
614 }
615 
616 /// \brief Merge the exception specifications of two variable declarations.
617 ///
618 /// This is called when there's a redeclaration of a VarDecl. The function
619 /// checks if the redeclaration might have an exception specification and
620 /// validates compatibility and merges the specs if necessary.
621 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
622   // Shortcut if exceptions are disabled.
623   if (!getLangOpts().CXXExceptions)
624     return;
625 
626   assert(Context.hasSameType(New->getType(), Old->getType()) &&
627          "Should only be called if types are otherwise the same.");
628 
629   QualType NewType = New->getType();
630   QualType OldType = Old->getType();
631 
632   // We're only interested in pointers and references to functions, as well
633   // as pointers to member functions.
634   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
635     NewType = R->getPointeeType();
636     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
637   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
638     NewType = P->getPointeeType();
639     OldType = OldType->getAs<PointerType>()->getPointeeType();
640   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
641     NewType = M->getPointeeType();
642     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
643   }
644 
645   if (!NewType->isFunctionProtoType())
646     return;
647 
648   // There's lots of special cases for functions. For function pointers, system
649   // libraries are hopefully not as broken so that we don't need these
650   // workarounds.
651   if (CheckEquivalentExceptionSpec(
652         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
653         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
654     New->setInvalidDecl();
655   }
656 }
657 
658 /// CheckCXXDefaultArguments - Verify that the default arguments for a
659 /// function declaration are well-formed according to C++
660 /// [dcl.fct.default].
661 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
662   unsigned NumParams = FD->getNumParams();
663   unsigned p;
664 
665   // Find first parameter with a default argument
666   for (p = 0; p < NumParams; ++p) {
667     ParmVarDecl *Param = FD->getParamDecl(p);
668     if (Param->hasDefaultArg())
669       break;
670   }
671 
672   // C++ [dcl.fct.default]p4:
673   //   In a given function declaration, all parameters
674   //   subsequent to a parameter with a default argument shall
675   //   have default arguments supplied in this or previous
676   //   declarations. A default argument shall not be redefined
677   //   by a later declaration (not even to the same value).
678   unsigned LastMissingDefaultArg = 0;
679   for (; p < NumParams; ++p) {
680     ParmVarDecl *Param = FD->getParamDecl(p);
681     if (!Param->hasDefaultArg()) {
682       if (Param->isInvalidDecl())
683         /* We already complained about this parameter. */;
684       else if (Param->getIdentifier())
685         Diag(Param->getLocation(),
686              diag::err_param_default_argument_missing_name)
687           << Param->getIdentifier();
688       else
689         Diag(Param->getLocation(),
690              diag::err_param_default_argument_missing);
691 
692       LastMissingDefaultArg = p;
693     }
694   }
695 
696   if (LastMissingDefaultArg > 0) {
697     // Some default arguments were missing. Clear out all of the
698     // default arguments up to (and including) the last missing
699     // default argument, so that we leave the function parameters
700     // in a semantically valid state.
701     for (p = 0; p <= LastMissingDefaultArg; ++p) {
702       ParmVarDecl *Param = FD->getParamDecl(p);
703       if (Param->hasDefaultArg()) {
704         Param->setDefaultArg(0);
705       }
706     }
707   }
708 }
709 
710 // CheckConstexprParameterTypes - Check whether a function's parameter types
711 // are all literal types. If so, return true. If not, produce a suitable
712 // diagnostic and return false.
713 static bool CheckConstexprParameterTypes(Sema &SemaRef,
714                                          const FunctionDecl *FD) {
715   unsigned ArgIndex = 0;
716   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
717   for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
718        e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
719     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
720     SourceLocation ParamLoc = PD->getLocation();
721     if (!(*i)->isDependentType() &&
722         SemaRef.RequireLiteralType(ParamLoc, *i,
723                                    diag::err_constexpr_non_literal_param,
724                                    ArgIndex+1, PD->getSourceRange(),
725                                    isa<CXXConstructorDecl>(FD)))
726       return false;
727   }
728   return true;
729 }
730 
731 /// \brief Get diagnostic %select index for tag kind for
732 /// record diagnostic message.
733 /// WARNING: Indexes apply to particular diagnostics only!
734 ///
735 /// \returns diagnostic %select index.
736 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
737   switch (Tag) {
738   case TTK_Struct: return 0;
739   case TTK_Interface: return 1;
740   case TTK_Class:  return 2;
741   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
742   }
743 }
744 
745 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
746 // the requirements of a constexpr function definition or a constexpr
747 // constructor definition. If so, return true. If not, produce appropriate
748 // diagnostics and return false.
749 //
750 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
751 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
752   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
753   if (MD && MD->isInstance()) {
754     // C++11 [dcl.constexpr]p4:
755     //  The definition of a constexpr constructor shall satisfy the following
756     //  constraints:
757     //  - the class shall not have any virtual base classes;
758     const CXXRecordDecl *RD = MD->getParent();
759     if (RD->getNumVBases()) {
760       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
761         << isa<CXXConstructorDecl>(NewFD)
762         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
763       for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
764              E = RD->vbases_end(); I != E; ++I)
765         Diag(I->getLocStart(),
766              diag::note_constexpr_virtual_base_here) << I->getSourceRange();
767       return false;
768     }
769   }
770 
771   if (!isa<CXXConstructorDecl>(NewFD)) {
772     // C++11 [dcl.constexpr]p3:
773     //  The definition of a constexpr function shall satisfy the following
774     //  constraints:
775     // - it shall not be virtual;
776     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
777     if (Method && Method->isVirtual()) {
778       Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
779 
780       // If it's not obvious why this function is virtual, find an overridden
781       // function which uses the 'virtual' keyword.
782       const CXXMethodDecl *WrittenVirtual = Method;
783       while (!WrittenVirtual->isVirtualAsWritten())
784         WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
785       if (WrittenVirtual != Method)
786         Diag(WrittenVirtual->getLocation(),
787              diag::note_overridden_virtual_function);
788       return false;
789     }
790 
791     // - its return type shall be a literal type;
792     QualType RT = NewFD->getResultType();
793     if (!RT->isDependentType() &&
794         RequireLiteralType(NewFD->getLocation(), RT,
795                            diag::err_constexpr_non_literal_return))
796       return false;
797   }
798 
799   // - each of its parameter types shall be a literal type;
800   if (!CheckConstexprParameterTypes(*this, NewFD))
801     return false;
802 
803   return true;
804 }
805 
806 /// Check the given declaration statement is legal within a constexpr function
807 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
808 ///
809 /// \return true if the body is OK (maybe only as an extension), false if we
810 ///         have diagnosed a problem.
811 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
812                                    DeclStmt *DS, SourceLocation &Cxx1yLoc) {
813   // C++11 [dcl.constexpr]p3 and p4:
814   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
815   //  contain only
816   for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
817          DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
818     switch ((*DclIt)->getKind()) {
819     case Decl::StaticAssert:
820     case Decl::Using:
821     case Decl::UsingShadow:
822     case Decl::UsingDirective:
823     case Decl::UnresolvedUsingTypename:
824     case Decl::UnresolvedUsingValue:
825       //   - static_assert-declarations
826       //   - using-declarations,
827       //   - using-directives,
828       continue;
829 
830     case Decl::Typedef:
831     case Decl::TypeAlias: {
832       //   - typedef declarations and alias-declarations that do not define
833       //     classes or enumerations,
834       TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
835       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
836         // Don't allow variably-modified types in constexpr functions.
837         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
838         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
839           << TL.getSourceRange() << TL.getType()
840           << isa<CXXConstructorDecl>(Dcl);
841         return false;
842       }
843       continue;
844     }
845 
846     case Decl::Enum:
847     case Decl::CXXRecord:
848       // C++1y allows types to be defined, not just declared.
849       if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition())
850         SemaRef.Diag(DS->getLocStart(),
851                      SemaRef.getLangOpts().CPlusPlus1y
852                        ? diag::warn_cxx11_compat_constexpr_type_definition
853                        : diag::ext_constexpr_type_definition)
854           << isa<CXXConstructorDecl>(Dcl);
855       continue;
856 
857     case Decl::EnumConstant:
858     case Decl::IndirectField:
859     case Decl::ParmVar:
860       // These can only appear with other declarations which are banned in
861       // C++11 and permitted in C++1y, so ignore them.
862       continue;
863 
864     case Decl::Var: {
865       // C++1y [dcl.constexpr]p3 allows anything except:
866       //   a definition of a variable of non-literal type or of static or
867       //   thread storage duration or for which no initialization is performed.
868       VarDecl *VD = cast<VarDecl>(*DclIt);
869       if (VD->isThisDeclarationADefinition()) {
870         if (VD->isStaticLocal()) {
871           SemaRef.Diag(VD->getLocation(),
872                        diag::err_constexpr_local_var_static)
873             << isa<CXXConstructorDecl>(Dcl)
874             << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
875           return false;
876         }
877         if (!VD->getType()->isDependentType() &&
878             SemaRef.RequireLiteralType(
879               VD->getLocation(), VD->getType(),
880               diag::err_constexpr_local_var_non_literal_type,
881               isa<CXXConstructorDecl>(Dcl)))
882           return false;
883         if (!VD->hasInit() && !VD->isCXXForRangeDecl()) {
884           SemaRef.Diag(VD->getLocation(),
885                        diag::err_constexpr_local_var_no_init)
886             << isa<CXXConstructorDecl>(Dcl);
887           return false;
888         }
889       }
890       SemaRef.Diag(VD->getLocation(),
891                    SemaRef.getLangOpts().CPlusPlus1y
892                     ? diag::warn_cxx11_compat_constexpr_local_var
893                     : diag::ext_constexpr_local_var)
894         << isa<CXXConstructorDecl>(Dcl);
895       continue;
896     }
897 
898     case Decl::NamespaceAlias:
899     case Decl::Function:
900       // These are disallowed in C++11 and permitted in C++1y. Allow them
901       // everywhere as an extension.
902       if (!Cxx1yLoc.isValid())
903         Cxx1yLoc = DS->getLocStart();
904       continue;
905 
906     default:
907       SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
908         << isa<CXXConstructorDecl>(Dcl);
909       return false;
910     }
911   }
912 
913   return true;
914 }
915 
916 /// Check that the given field is initialized within a constexpr constructor.
917 ///
918 /// \param Dcl The constexpr constructor being checked.
919 /// \param Field The field being checked. This may be a member of an anonymous
920 ///        struct or union nested within the class being checked.
921 /// \param Inits All declarations, including anonymous struct/union members and
922 ///        indirect members, for which any initialization was provided.
923 /// \param Diagnosed Set to true if an error is produced.
924 static void CheckConstexprCtorInitializer(Sema &SemaRef,
925                                           const FunctionDecl *Dcl,
926                                           FieldDecl *Field,
927                                           llvm::SmallSet<Decl*, 16> &Inits,
928                                           bool &Diagnosed) {
929   if (Field->isInvalidDecl())
930     return;
931 
932   if (Field->isUnnamedBitfield())
933     return;
934 
935   if (Field->isAnonymousStructOrUnion() &&
936       Field->getType()->getAsCXXRecordDecl()->isEmpty())
937     return;
938 
939   if (!Inits.count(Field)) {
940     if (!Diagnosed) {
941       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
942       Diagnosed = true;
943     }
944     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
945   } else if (Field->isAnonymousStructOrUnion()) {
946     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
947     for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
948          I != E; ++I)
949       // If an anonymous union contains an anonymous struct of which any member
950       // is initialized, all members must be initialized.
951       if (!RD->isUnion() || Inits.count(*I))
952         CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
953   }
954 }
955 
956 /// Check the provided statement is allowed in a constexpr function
957 /// definition.
958 static bool
959 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
960                            SmallVectorImpl<SourceLocation> &ReturnStmts,
961                            SourceLocation &Cxx1yLoc) {
962   // - its function-body shall be [...] a compound-statement that contains only
963   switch (S->getStmtClass()) {
964   case Stmt::NullStmtClass:
965     //   - null statements,
966     return true;
967 
968   case Stmt::DeclStmtClass:
969     //   - static_assert-declarations
970     //   - using-declarations,
971     //   - using-directives,
972     //   - typedef declarations and alias-declarations that do not define
973     //     classes or enumerations,
974     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
975       return false;
976     return true;
977 
978   case Stmt::ReturnStmtClass:
979     //   - and exactly one return statement;
980     if (isa<CXXConstructorDecl>(Dcl)) {
981       // C++1y allows return statements in constexpr constructors.
982       if (!Cxx1yLoc.isValid())
983         Cxx1yLoc = S->getLocStart();
984       return true;
985     }
986 
987     ReturnStmts.push_back(S->getLocStart());
988     return true;
989 
990   case Stmt::CompoundStmtClass: {
991     // C++1y allows compound-statements.
992     if (!Cxx1yLoc.isValid())
993       Cxx1yLoc = S->getLocStart();
994 
995     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
996     for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(),
997            BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) {
998       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts,
999                                       Cxx1yLoc))
1000         return false;
1001     }
1002     return true;
1003   }
1004 
1005   case Stmt::AttributedStmtClass:
1006     if (!Cxx1yLoc.isValid())
1007       Cxx1yLoc = S->getLocStart();
1008     return true;
1009 
1010   case Stmt::IfStmtClass: {
1011     // C++1y allows if-statements.
1012     if (!Cxx1yLoc.isValid())
1013       Cxx1yLoc = S->getLocStart();
1014 
1015     IfStmt *If = cast<IfStmt>(S);
1016     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1017                                     Cxx1yLoc))
1018       return false;
1019     if (If->getElse() &&
1020         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1021                                     Cxx1yLoc))
1022       return false;
1023     return true;
1024   }
1025 
1026   case Stmt::WhileStmtClass:
1027   case Stmt::DoStmtClass:
1028   case Stmt::ForStmtClass:
1029   case Stmt::CXXForRangeStmtClass:
1030   case Stmt::ContinueStmtClass:
1031     // C++1y allows all of these. We don't allow them as extensions in C++11,
1032     // because they don't make sense without variable mutation.
1033     if (!SemaRef.getLangOpts().CPlusPlus1y)
1034       break;
1035     if (!Cxx1yLoc.isValid())
1036       Cxx1yLoc = S->getLocStart();
1037     for (Stmt::child_range Children = S->children(); Children; ++Children)
1038       if (*Children &&
1039           !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1040                                       Cxx1yLoc))
1041         return false;
1042     return true;
1043 
1044   case Stmt::SwitchStmtClass:
1045   case Stmt::CaseStmtClass:
1046   case Stmt::DefaultStmtClass:
1047   case Stmt::BreakStmtClass:
1048     // C++1y allows switch-statements, and since they don't need variable
1049     // mutation, we can reasonably allow them in C++11 as an extension.
1050     if (!Cxx1yLoc.isValid())
1051       Cxx1yLoc = S->getLocStart();
1052     for (Stmt::child_range Children = S->children(); Children; ++Children)
1053       if (*Children &&
1054           !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1055                                       Cxx1yLoc))
1056         return false;
1057     return true;
1058 
1059   default:
1060     if (!isa<Expr>(S))
1061       break;
1062 
1063     // C++1y allows expression-statements.
1064     if (!Cxx1yLoc.isValid())
1065       Cxx1yLoc = S->getLocStart();
1066     return true;
1067   }
1068 
1069   SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1070     << isa<CXXConstructorDecl>(Dcl);
1071   return false;
1072 }
1073 
1074 /// Check the body for the given constexpr function declaration only contains
1075 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1076 ///
1077 /// \return true if the body is OK, false if we have diagnosed a problem.
1078 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1079   if (isa<CXXTryStmt>(Body)) {
1080     // C++11 [dcl.constexpr]p3:
1081     //  The definition of a constexpr function shall satisfy the following
1082     //  constraints: [...]
1083     // - its function-body shall be = delete, = default, or a
1084     //   compound-statement
1085     //
1086     // C++11 [dcl.constexpr]p4:
1087     //  In the definition of a constexpr constructor, [...]
1088     // - its function-body shall not be a function-try-block;
1089     Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1090       << isa<CXXConstructorDecl>(Dcl);
1091     return false;
1092   }
1093 
1094   SmallVector<SourceLocation, 4> ReturnStmts;
1095 
1096   // - its function-body shall be [...] a compound-statement that contains only
1097   //   [... list of cases ...]
1098   CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1099   SourceLocation Cxx1yLoc;
1100   for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
1101          BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
1102     if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc))
1103       return false;
1104   }
1105 
1106   if (Cxx1yLoc.isValid())
1107     Diag(Cxx1yLoc,
1108          getLangOpts().CPlusPlus1y
1109            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1110            : diag::ext_constexpr_body_invalid_stmt)
1111       << isa<CXXConstructorDecl>(Dcl);
1112 
1113   if (const CXXConstructorDecl *Constructor
1114         = dyn_cast<CXXConstructorDecl>(Dcl)) {
1115     const CXXRecordDecl *RD = Constructor->getParent();
1116     // DR1359:
1117     // - every non-variant non-static data member and base class sub-object
1118     //   shall be initialized;
1119     // - if the class is a non-empty union, or for each non-empty anonymous
1120     //   union member of a non-union class, exactly one non-static data member
1121     //   shall be initialized;
1122     if (RD->isUnion()) {
1123       if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
1124         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1125         return false;
1126       }
1127     } else if (!Constructor->isDependentContext() &&
1128                !Constructor->isDelegatingConstructor()) {
1129       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1130 
1131       // Skip detailed checking if we have enough initializers, and we would
1132       // allow at most one initializer per member.
1133       bool AnyAnonStructUnionMembers = false;
1134       unsigned Fields = 0;
1135       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1136            E = RD->field_end(); I != E; ++I, ++Fields) {
1137         if (I->isAnonymousStructOrUnion()) {
1138           AnyAnonStructUnionMembers = true;
1139           break;
1140         }
1141       }
1142       if (AnyAnonStructUnionMembers ||
1143           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1144         // Check initialization of non-static data members. Base classes are
1145         // always initialized so do not need to be checked. Dependent bases
1146         // might not have initializers in the member initializer list.
1147         llvm::SmallSet<Decl*, 16> Inits;
1148         for (CXXConstructorDecl::init_const_iterator
1149                I = Constructor->init_begin(), E = Constructor->init_end();
1150              I != E; ++I) {
1151           if (FieldDecl *FD = (*I)->getMember())
1152             Inits.insert(FD);
1153           else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
1154             Inits.insert(ID->chain_begin(), ID->chain_end());
1155         }
1156 
1157         bool Diagnosed = false;
1158         for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1159              E = RD->field_end(); I != E; ++I)
1160           CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
1161         if (Diagnosed)
1162           return false;
1163       }
1164     }
1165   } else {
1166     if (ReturnStmts.empty()) {
1167       // C++1y doesn't require constexpr functions to contain a 'return'
1168       // statement. We still do, unless the return type is void, because
1169       // otherwise if there's no return statement, the function cannot
1170       // be used in a core constant expression.
1171       bool OK = getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType();
1172       Diag(Dcl->getLocation(),
1173            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1174               : diag::err_constexpr_body_no_return);
1175       return OK;
1176     }
1177     if (ReturnStmts.size() > 1) {
1178       Diag(ReturnStmts.back(),
1179            getLangOpts().CPlusPlus1y
1180              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1181              : diag::ext_constexpr_body_multiple_return);
1182       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1183         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
1184     }
1185   }
1186 
1187   // C++11 [dcl.constexpr]p5:
1188   //   if no function argument values exist such that the function invocation
1189   //   substitution would produce a constant expression, the program is
1190   //   ill-formed; no diagnostic required.
1191   // C++11 [dcl.constexpr]p3:
1192   //   - every constructor call and implicit conversion used in initializing the
1193   //     return value shall be one of those allowed in a constant expression.
1194   // C++11 [dcl.constexpr]p4:
1195   //   - every constructor involved in initializing non-static data members and
1196   //     base class sub-objects shall be a constexpr constructor.
1197   SmallVector<PartialDiagnosticAt, 8> Diags;
1198   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
1199     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
1200       << isa<CXXConstructorDecl>(Dcl);
1201     for (size_t I = 0, N = Diags.size(); I != N; ++I)
1202       Diag(Diags[I].first, Diags[I].second);
1203     // Don't return false here: we allow this for compatibility in
1204     // system headers.
1205   }
1206 
1207   return true;
1208 }
1209 
1210 /// isCurrentClassName - Determine whether the identifier II is the
1211 /// name of the class type currently being defined. In the case of
1212 /// nested classes, this will only return true if II is the name of
1213 /// the innermost class.
1214 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1215                               const CXXScopeSpec *SS) {
1216   assert(getLangOpts().CPlusPlus && "No class names in C!");
1217 
1218   CXXRecordDecl *CurDecl;
1219   if (SS && SS->isSet() && !SS->isInvalid()) {
1220     DeclContext *DC = computeDeclContext(*SS, true);
1221     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1222   } else
1223     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1224 
1225   if (CurDecl && CurDecl->getIdentifier())
1226     return &II == CurDecl->getIdentifier();
1227   return false;
1228 }
1229 
1230 /// \brief Determine whether the identifier II is a typo for the name of
1231 /// the class type currently being defined. If so, update it to the identifier
1232 /// that should have been used.
1233 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1234   assert(getLangOpts().CPlusPlus && "No class names in C!");
1235 
1236   if (!getLangOpts().SpellChecking)
1237     return false;
1238 
1239   CXXRecordDecl *CurDecl;
1240   if (SS && SS->isSet() && !SS->isInvalid()) {
1241     DeclContext *DC = computeDeclContext(*SS, true);
1242     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1243   } else
1244     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1245 
1246   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1247       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1248           < II->getLength()) {
1249     II = CurDecl->getIdentifier();
1250     return true;
1251   }
1252 
1253   return false;
1254 }
1255 
1256 /// \brief Determine whether the given class is a base class of the given
1257 /// class, including looking at dependent bases.
1258 static bool findCircularInheritance(const CXXRecordDecl *Class,
1259                                     const CXXRecordDecl *Current) {
1260   SmallVector<const CXXRecordDecl*, 8> Queue;
1261 
1262   Class = Class->getCanonicalDecl();
1263   while (true) {
1264     for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1265                                                   E = Current->bases_end();
1266          I != E; ++I) {
1267       CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1268       if (!Base)
1269         continue;
1270 
1271       Base = Base->getDefinition();
1272       if (!Base)
1273         continue;
1274 
1275       if (Base->getCanonicalDecl() == Class)
1276         return true;
1277 
1278       Queue.push_back(Base);
1279     }
1280 
1281     if (Queue.empty())
1282       return false;
1283 
1284     Current = Queue.pop_back_val();
1285   }
1286 
1287   return false;
1288 }
1289 
1290 /// \brief Check the validity of a C++ base class specifier.
1291 ///
1292 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1293 /// and returns NULL otherwise.
1294 CXXBaseSpecifier *
1295 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1296                          SourceRange SpecifierRange,
1297                          bool Virtual, AccessSpecifier Access,
1298                          TypeSourceInfo *TInfo,
1299                          SourceLocation EllipsisLoc) {
1300   QualType BaseType = TInfo->getType();
1301 
1302   // C++ [class.union]p1:
1303   //   A union shall not have base classes.
1304   if (Class->isUnion()) {
1305     Diag(Class->getLocation(), diag::err_base_clause_on_union)
1306       << SpecifierRange;
1307     return 0;
1308   }
1309 
1310   if (EllipsisLoc.isValid() &&
1311       !TInfo->getType()->containsUnexpandedParameterPack()) {
1312     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1313       << TInfo->getTypeLoc().getSourceRange();
1314     EllipsisLoc = SourceLocation();
1315   }
1316 
1317   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1318 
1319   if (BaseType->isDependentType()) {
1320     // Make sure that we don't have circular inheritance among our dependent
1321     // bases. For non-dependent bases, the check for completeness below handles
1322     // this.
1323     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1324       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1325           ((BaseDecl = BaseDecl->getDefinition()) &&
1326            findCircularInheritance(Class, BaseDecl))) {
1327         Diag(BaseLoc, diag::err_circular_inheritance)
1328           << BaseType << Context.getTypeDeclType(Class);
1329 
1330         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1331           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1332             << BaseType;
1333 
1334         return 0;
1335       }
1336     }
1337 
1338     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1339                                           Class->getTagKind() == TTK_Class,
1340                                           Access, TInfo, EllipsisLoc);
1341   }
1342 
1343   // Base specifiers must be record types.
1344   if (!BaseType->isRecordType()) {
1345     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1346     return 0;
1347   }
1348 
1349   // C++ [class.union]p1:
1350   //   A union shall not be used as a base class.
1351   if (BaseType->isUnionType()) {
1352     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1353     return 0;
1354   }
1355 
1356   // C++ [class.derived]p2:
1357   //   The class-name in a base-specifier shall not be an incompletely
1358   //   defined class.
1359   if (RequireCompleteType(BaseLoc, BaseType,
1360                           diag::err_incomplete_base_class, SpecifierRange)) {
1361     Class->setInvalidDecl();
1362     return 0;
1363   }
1364 
1365   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1366   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1367   assert(BaseDecl && "Record type has no declaration");
1368   BaseDecl = BaseDecl->getDefinition();
1369   assert(BaseDecl && "Base type is not incomplete, but has no definition");
1370   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1371   assert(CXXBaseDecl && "Base type is not a C++ type");
1372 
1373   // A class which contains a flexible array member is not suitable for use as a
1374   // base class:
1375   //   - If the layout determines that a base comes before another base,
1376   //     the flexible array member would index into the subsequent base.
1377   //   - If the layout determines that base comes before the derived class,
1378   //     the flexible array member would index into the derived class.
1379   if (CXXBaseDecl->hasFlexibleArrayMember()) {
1380     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1381       << CXXBaseDecl->getDeclName();
1382     return 0;
1383   }
1384 
1385   // C++ [class]p3:
1386   //   If a class is marked final and it appears as a base-type-specifier in
1387   //   base-clause, the program is ill-formed.
1388   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
1389     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1390       << CXXBaseDecl->getDeclName()
1391       << FA->isSpelledAsSealed();
1392     Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1393       << CXXBaseDecl->getDeclName();
1394     return 0;
1395   }
1396 
1397   if (BaseDecl->isInvalidDecl())
1398     Class->setInvalidDecl();
1399 
1400   // Create the base specifier.
1401   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1402                                         Class->getTagKind() == TTK_Class,
1403                                         Access, TInfo, EllipsisLoc);
1404 }
1405 
1406 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1407 /// one entry in the base class list of a class specifier, for
1408 /// example:
1409 ///    class foo : public bar, virtual private baz {
1410 /// 'public bar' and 'virtual private baz' are each base-specifiers.
1411 BaseResult
1412 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1413                          ParsedAttributes &Attributes,
1414                          bool Virtual, AccessSpecifier Access,
1415                          ParsedType basetype, SourceLocation BaseLoc,
1416                          SourceLocation EllipsisLoc) {
1417   if (!classdecl)
1418     return true;
1419 
1420   AdjustDeclIfTemplate(classdecl);
1421   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1422   if (!Class)
1423     return true;
1424 
1425   // We do not support any C++11 attributes on base-specifiers yet.
1426   // Diagnose any attributes we see.
1427   if (!Attributes.empty()) {
1428     for (AttributeList *Attr = Attributes.getList(); Attr;
1429          Attr = Attr->getNext()) {
1430       if (Attr->isInvalid() ||
1431           Attr->getKind() == AttributeList::IgnoredAttribute)
1432         continue;
1433       Diag(Attr->getLoc(),
1434            Attr->getKind() == AttributeList::UnknownAttribute
1435              ? diag::warn_unknown_attribute_ignored
1436              : diag::err_base_specifier_attribute)
1437         << Attr->getName();
1438     }
1439   }
1440 
1441   TypeSourceInfo *TInfo = 0;
1442   GetTypeFromParser(basetype, &TInfo);
1443 
1444   if (EllipsisLoc.isInvalid() &&
1445       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1446                                       UPPC_BaseType))
1447     return true;
1448 
1449   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1450                                                       Virtual, Access, TInfo,
1451                                                       EllipsisLoc))
1452     return BaseSpec;
1453   else
1454     Class->setInvalidDecl();
1455 
1456   return true;
1457 }
1458 
1459 /// \brief Performs the actual work of attaching the given base class
1460 /// specifiers to a C++ class.
1461 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1462                                 unsigned NumBases) {
1463  if (NumBases == 0)
1464     return false;
1465 
1466   // Used to keep track of which base types we have already seen, so
1467   // that we can properly diagnose redundant direct base types. Note
1468   // that the key is always the unqualified canonical type of the base
1469   // class.
1470   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1471 
1472   // Copy non-redundant base specifiers into permanent storage.
1473   unsigned NumGoodBases = 0;
1474   bool Invalid = false;
1475   for (unsigned idx = 0; idx < NumBases; ++idx) {
1476     QualType NewBaseType
1477       = Context.getCanonicalType(Bases[idx]->getType());
1478     NewBaseType = NewBaseType.getLocalUnqualifiedType();
1479 
1480     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1481     if (KnownBase) {
1482       // C++ [class.mi]p3:
1483       //   A class shall not be specified as a direct base class of a
1484       //   derived class more than once.
1485       Diag(Bases[idx]->getLocStart(),
1486            diag::err_duplicate_base_class)
1487         << KnownBase->getType()
1488         << Bases[idx]->getSourceRange();
1489 
1490       // Delete the duplicate base class specifier; we're going to
1491       // overwrite its pointer later.
1492       Context.Deallocate(Bases[idx]);
1493 
1494       Invalid = true;
1495     } else {
1496       // Okay, add this new base class.
1497       KnownBase = Bases[idx];
1498       Bases[NumGoodBases++] = Bases[idx];
1499       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1500         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1501         if (Class->isInterface() &&
1502               (!RD->isInterface() ||
1503                KnownBase->getAccessSpecifier() != AS_public)) {
1504           // The Microsoft extension __interface does not permit bases that
1505           // are not themselves public interfaces.
1506           Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1507             << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1508             << RD->getSourceRange();
1509           Invalid = true;
1510         }
1511         if (RD->hasAttr<WeakAttr>())
1512           Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1513       }
1514     }
1515   }
1516 
1517   // Attach the remaining base class specifiers to the derived class.
1518   Class->setBases(Bases, NumGoodBases);
1519 
1520   // Delete the remaining (good) base class specifiers, since their
1521   // data has been copied into the CXXRecordDecl.
1522   for (unsigned idx = 0; idx < NumGoodBases; ++idx)
1523     Context.Deallocate(Bases[idx]);
1524 
1525   return Invalid;
1526 }
1527 
1528 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
1529 /// class, after checking whether there are any duplicate base
1530 /// classes.
1531 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
1532                                unsigned NumBases) {
1533   if (!ClassDecl || !Bases || !NumBases)
1534     return;
1535 
1536   AdjustDeclIfTemplate(ClassDecl);
1537   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
1538 }
1539 
1540 /// \brief Determine whether the type \p Derived is a C++ class that is
1541 /// derived from the type \p Base.
1542 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1543   if (!getLangOpts().CPlusPlus)
1544     return false;
1545 
1546   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1547   if (!DerivedRD)
1548     return false;
1549 
1550   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1551   if (!BaseRD)
1552     return false;
1553 
1554   // If either the base or the derived type is invalid, don't try to
1555   // check whether one is derived from the other.
1556   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1557     return false;
1558 
1559   // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
1560   return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
1561 }
1562 
1563 /// \brief Determine whether the type \p Derived is a C++ class that is
1564 /// derived from the type \p Base.
1565 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1566   if (!getLangOpts().CPlusPlus)
1567     return false;
1568 
1569   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1570   if (!DerivedRD)
1571     return false;
1572 
1573   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1574   if (!BaseRD)
1575     return false;
1576 
1577   return DerivedRD->isDerivedFrom(BaseRD, Paths);
1578 }
1579 
1580 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1581                               CXXCastPath &BasePathArray) {
1582   assert(BasePathArray.empty() && "Base path array must be empty!");
1583   assert(Paths.isRecordingPaths() && "Must record paths!");
1584 
1585   const CXXBasePath &Path = Paths.front();
1586 
1587   // We first go backward and check if we have a virtual base.
1588   // FIXME: It would be better if CXXBasePath had the base specifier for
1589   // the nearest virtual base.
1590   unsigned Start = 0;
1591   for (unsigned I = Path.size(); I != 0; --I) {
1592     if (Path[I - 1].Base->isVirtual()) {
1593       Start = I - 1;
1594       break;
1595     }
1596   }
1597 
1598   // Now add all bases.
1599   for (unsigned I = Start, E = Path.size(); I != E; ++I)
1600     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1601 }
1602 
1603 /// \brief Determine whether the given base path includes a virtual
1604 /// base class.
1605 bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1606   for (CXXCastPath::const_iterator B = BasePath.begin(),
1607                                 BEnd = BasePath.end();
1608        B != BEnd; ++B)
1609     if ((*B)->isVirtual())
1610       return true;
1611 
1612   return false;
1613 }
1614 
1615 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1616 /// conversion (where Derived and Base are class types) is
1617 /// well-formed, meaning that the conversion is unambiguous (and
1618 /// that all of the base classes are accessible). Returns true
1619 /// and emits a diagnostic if the code is ill-formed, returns false
1620 /// otherwise. Loc is the location where this routine should point to
1621 /// if there is an error, and Range is the source range to highlight
1622 /// if there is an error.
1623 bool
1624 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1625                                    unsigned InaccessibleBaseID,
1626                                    unsigned AmbigiousBaseConvID,
1627                                    SourceLocation Loc, SourceRange Range,
1628                                    DeclarationName Name,
1629                                    CXXCastPath *BasePath) {
1630   // First, determine whether the path from Derived to Base is
1631   // ambiguous. This is slightly more expensive than checking whether
1632   // the Derived to Base conversion exists, because here we need to
1633   // explore multiple paths to determine if there is an ambiguity.
1634   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1635                      /*DetectVirtual=*/false);
1636   bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1637   assert(DerivationOkay &&
1638          "Can only be used with a derived-to-base conversion");
1639   (void)DerivationOkay;
1640 
1641   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1642     if (InaccessibleBaseID) {
1643       // Check that the base class can be accessed.
1644       switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1645                                    InaccessibleBaseID)) {
1646         case AR_inaccessible:
1647           return true;
1648         case AR_accessible:
1649         case AR_dependent:
1650         case AR_delayed:
1651           break;
1652       }
1653     }
1654 
1655     // Build a base path if necessary.
1656     if (BasePath)
1657       BuildBasePathArray(Paths, *BasePath);
1658     return false;
1659   }
1660 
1661   if (AmbigiousBaseConvID) {
1662     // We know that the derived-to-base conversion is ambiguous, and
1663     // we're going to produce a diagnostic. Perform the derived-to-base
1664     // search just one more time to compute all of the possible paths so
1665     // that we can print them out. This is more expensive than any of
1666     // the previous derived-to-base checks we've done, but at this point
1667     // performance isn't as much of an issue.
1668     Paths.clear();
1669     Paths.setRecordingPaths(true);
1670     bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1671     assert(StillOkay && "Can only be used with a derived-to-base conversion");
1672     (void)StillOkay;
1673 
1674     // Build up a textual representation of the ambiguous paths, e.g.,
1675     // D -> B -> A, that will be used to illustrate the ambiguous
1676     // conversions in the diagnostic. We only print one of the paths
1677     // to each base class subobject.
1678     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1679 
1680     Diag(Loc, AmbigiousBaseConvID)
1681     << Derived << Base << PathDisplayStr << Range << Name;
1682   }
1683   return true;
1684 }
1685 
1686 bool
1687 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1688                                    SourceLocation Loc, SourceRange Range,
1689                                    CXXCastPath *BasePath,
1690                                    bool IgnoreAccess) {
1691   return CheckDerivedToBaseConversion(Derived, Base,
1692                                       IgnoreAccess ? 0
1693                                        : diag::err_upcast_to_inaccessible_base,
1694                                       diag::err_ambiguous_derived_to_base_conv,
1695                                       Loc, Range, DeclarationName(),
1696                                       BasePath);
1697 }
1698 
1699 
1700 /// @brief Builds a string representing ambiguous paths from a
1701 /// specific derived class to different subobjects of the same base
1702 /// class.
1703 ///
1704 /// This function builds a string that can be used in error messages
1705 /// to show the different paths that one can take through the
1706 /// inheritance hierarchy to go from the derived class to different
1707 /// subobjects of a base class. The result looks something like this:
1708 /// @code
1709 /// struct D -> struct B -> struct A
1710 /// struct D -> struct C -> struct A
1711 /// @endcode
1712 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1713   std::string PathDisplayStr;
1714   std::set<unsigned> DisplayedPaths;
1715   for (CXXBasePaths::paths_iterator Path = Paths.begin();
1716        Path != Paths.end(); ++Path) {
1717     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1718       // We haven't displayed a path to this particular base
1719       // class subobject yet.
1720       PathDisplayStr += "\n    ";
1721       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1722       for (CXXBasePath::const_iterator Element = Path->begin();
1723            Element != Path->end(); ++Element)
1724         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1725     }
1726   }
1727 
1728   return PathDisplayStr;
1729 }
1730 
1731 //===----------------------------------------------------------------------===//
1732 // C++ class member Handling
1733 //===----------------------------------------------------------------------===//
1734 
1735 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1736 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1737                                 SourceLocation ASLoc,
1738                                 SourceLocation ColonLoc,
1739                                 AttributeList *Attrs) {
1740   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1741   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1742                                                   ASLoc, ColonLoc);
1743   CurContext->addHiddenDecl(ASDecl);
1744   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1745 }
1746 
1747 /// CheckOverrideControl - Check C++11 override control semantics.
1748 void Sema::CheckOverrideControl(NamedDecl *D) {
1749   if (D->isInvalidDecl())
1750     return;
1751 
1752   // We only care about "override" and "final" declarations.
1753   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1754     return;
1755 
1756   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1757 
1758   // We can't check dependent instance methods.
1759   if (MD && MD->isInstance() &&
1760       (MD->getParent()->hasAnyDependentBases() ||
1761        MD->getType()->isDependentType()))
1762     return;
1763 
1764   if (MD && !MD->isVirtual()) {
1765     // If we have a non-virtual method, check if if hides a virtual method.
1766     // (In that case, it's most likely the method has the wrong type.)
1767     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1768     FindHiddenVirtualMethods(MD, OverloadedMethods);
1769 
1770     if (!OverloadedMethods.empty()) {
1771       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1772         Diag(OA->getLocation(),
1773              diag::override_keyword_hides_virtual_member_function)
1774           << "override" << (OverloadedMethods.size() > 1);
1775       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1776         Diag(FA->getLocation(),
1777              diag::override_keyword_hides_virtual_member_function)
1778           << (FA->isSpelledAsSealed() ? "sealed" : "final")
1779           << (OverloadedMethods.size() > 1);
1780       }
1781       NoteHiddenVirtualMethods(MD, OverloadedMethods);
1782       MD->setInvalidDecl();
1783       return;
1784     }
1785     // Fall through into the general case diagnostic.
1786     // FIXME: We might want to attempt typo correction here.
1787   }
1788 
1789   if (!MD || !MD->isVirtual()) {
1790     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1791       Diag(OA->getLocation(),
1792            diag::override_keyword_only_allowed_on_virtual_member_functions)
1793         << "override" << FixItHint::CreateRemoval(OA->getLocation());
1794       D->dropAttr<OverrideAttr>();
1795     }
1796     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1797       Diag(FA->getLocation(),
1798            diag::override_keyword_only_allowed_on_virtual_member_functions)
1799         << (FA->isSpelledAsSealed() ? "sealed" : "final")
1800         << FixItHint::CreateRemoval(FA->getLocation());
1801       D->dropAttr<FinalAttr>();
1802     }
1803     return;
1804   }
1805 
1806   // C++11 [class.virtual]p5:
1807   //   If a virtual function is marked with the virt-specifier override and
1808   //   does not override a member function of a base class, the program is
1809   //   ill-formed.
1810   bool HasOverriddenMethods =
1811     MD->begin_overridden_methods() != MD->end_overridden_methods();
1812   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1813     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1814       << MD->getDeclName();
1815 }
1816 
1817 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1818 /// function overrides a virtual member function marked 'final', according to
1819 /// C++11 [class.virtual]p4.
1820 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1821                                                   const CXXMethodDecl *Old) {
1822   FinalAttr *FA = Old->getAttr<FinalAttr>();
1823   if (!FA)
1824     return false;
1825 
1826   Diag(New->getLocation(), diag::err_final_function_overridden)
1827     << New->getDeclName()
1828     << FA->isSpelledAsSealed();
1829   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1830   return true;
1831 }
1832 
1833 static bool InitializationHasSideEffects(const FieldDecl &FD) {
1834   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1835   // FIXME: Destruction of ObjC lifetime types has side-effects.
1836   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1837     return !RD->isCompleteDefinition() ||
1838            !RD->hasTrivialDefaultConstructor() ||
1839            !RD->hasTrivialDestructor();
1840   return false;
1841 }
1842 
1843 static AttributeList *getMSPropertyAttr(AttributeList *list) {
1844   for (AttributeList* it = list; it != 0; it = it->getNext())
1845     if (it->isDeclspecPropertyAttribute())
1846       return it;
1847   return 0;
1848 }
1849 
1850 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1851 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1852 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
1853 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1854 /// present (but parsing it has been deferred).
1855 NamedDecl *
1856 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1857                                MultiTemplateParamsArg TemplateParameterLists,
1858                                Expr *BW, const VirtSpecifiers &VS,
1859                                InClassInitStyle InitStyle) {
1860   const DeclSpec &DS = D.getDeclSpec();
1861   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1862   DeclarationName Name = NameInfo.getName();
1863   SourceLocation Loc = NameInfo.getLoc();
1864 
1865   // For anonymous bitfields, the location should point to the type.
1866   if (Loc.isInvalid())
1867     Loc = D.getLocStart();
1868 
1869   Expr *BitWidth = static_cast<Expr*>(BW);
1870 
1871   assert(isa<CXXRecordDecl>(CurContext));
1872   assert(!DS.isFriendSpecified());
1873 
1874   bool isFunc = D.isDeclarationOfFunction();
1875 
1876   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1877     // The Microsoft extension __interface only permits public member functions
1878     // and prohibits constructors, destructors, operators, non-public member
1879     // functions, static methods and data members.
1880     unsigned InvalidDecl;
1881     bool ShowDeclName = true;
1882     if (!isFunc)
1883       InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1884     else if (AS != AS_public)
1885       InvalidDecl = 2;
1886     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1887       InvalidDecl = 3;
1888     else switch (Name.getNameKind()) {
1889       case DeclarationName::CXXConstructorName:
1890         InvalidDecl = 4;
1891         ShowDeclName = false;
1892         break;
1893 
1894       case DeclarationName::CXXDestructorName:
1895         InvalidDecl = 5;
1896         ShowDeclName = false;
1897         break;
1898 
1899       case DeclarationName::CXXOperatorName:
1900       case DeclarationName::CXXConversionFunctionName:
1901         InvalidDecl = 6;
1902         break;
1903 
1904       default:
1905         InvalidDecl = 0;
1906         break;
1907     }
1908 
1909     if (InvalidDecl) {
1910       if (ShowDeclName)
1911         Diag(Loc, diag::err_invalid_member_in_interface)
1912           << (InvalidDecl-1) << Name;
1913       else
1914         Diag(Loc, diag::err_invalid_member_in_interface)
1915           << (InvalidDecl-1) << "";
1916       return 0;
1917     }
1918   }
1919 
1920   // C++ 9.2p6: A member shall not be declared to have automatic storage
1921   // duration (auto, register) or with the extern storage-class-specifier.
1922   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1923   // data members and cannot be applied to names declared const or static,
1924   // and cannot be applied to reference members.
1925   switch (DS.getStorageClassSpec()) {
1926   case DeclSpec::SCS_unspecified:
1927   case DeclSpec::SCS_typedef:
1928   case DeclSpec::SCS_static:
1929     break;
1930   case DeclSpec::SCS_mutable:
1931     if (isFunc) {
1932       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
1933 
1934       // FIXME: It would be nicer if the keyword was ignored only for this
1935       // declarator. Otherwise we could get follow-up errors.
1936       D.getMutableDeclSpec().ClearStorageClassSpecs();
1937     }
1938     break;
1939   default:
1940     Diag(DS.getStorageClassSpecLoc(),
1941          diag::err_storageclass_invalid_for_member);
1942     D.getMutableDeclSpec().ClearStorageClassSpecs();
1943     break;
1944   }
1945 
1946   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1947                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
1948                       !isFunc);
1949 
1950   if (DS.isConstexprSpecified() && isInstField) {
1951     SemaDiagnosticBuilder B =
1952         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1953     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1954     if (InitStyle == ICIS_NoInit) {
1955       B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1956       D.getMutableDeclSpec().ClearConstexprSpec();
1957       const char *PrevSpec;
1958       unsigned DiagID;
1959       bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1960                                          PrevSpec, DiagID, getLangOpts());
1961       (void)Failed;
1962       assert(!Failed && "Making a constexpr member const shouldn't fail");
1963     } else {
1964       B << 1;
1965       const char *PrevSpec;
1966       unsigned DiagID;
1967       if (D.getMutableDeclSpec().SetStorageClassSpec(
1968           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
1969         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
1970                "This is the only DeclSpec that should fail to be applied");
1971         B << 1;
1972       } else {
1973         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1974         isInstField = false;
1975       }
1976     }
1977   }
1978 
1979   NamedDecl *Member;
1980   if (isInstField) {
1981     CXXScopeSpec &SS = D.getCXXScopeSpec();
1982 
1983     // Data members must have identifiers for names.
1984     if (!Name.isIdentifier()) {
1985       Diag(Loc, diag::err_bad_variable_name)
1986         << Name;
1987       return 0;
1988     }
1989 
1990     IdentifierInfo *II = Name.getAsIdentifierInfo();
1991 
1992     // Member field could not be with "template" keyword.
1993     // So TemplateParameterLists should be empty in this case.
1994     if (TemplateParameterLists.size()) {
1995       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
1996       if (TemplateParams->size()) {
1997         // There is no such thing as a member field template.
1998         Diag(D.getIdentifierLoc(), diag::err_template_member)
1999             << II
2000             << SourceRange(TemplateParams->getTemplateLoc(),
2001                 TemplateParams->getRAngleLoc());
2002       } else {
2003         // There is an extraneous 'template<>' for this member.
2004         Diag(TemplateParams->getTemplateLoc(),
2005             diag::err_template_member_noparams)
2006             << II
2007             << SourceRange(TemplateParams->getTemplateLoc(),
2008                 TemplateParams->getRAngleLoc());
2009       }
2010       return 0;
2011     }
2012 
2013     if (SS.isSet() && !SS.isInvalid()) {
2014       // The user provided a superfluous scope specifier inside a class
2015       // definition:
2016       //
2017       // class X {
2018       //   int X::member;
2019       // };
2020       if (DeclContext *DC = computeDeclContext(SS, false))
2021         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
2022       else
2023         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2024           << Name << SS.getRange();
2025 
2026       SS.clear();
2027     }
2028 
2029     AttributeList *MSPropertyAttr =
2030       getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
2031     if (MSPropertyAttr) {
2032       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2033                                 BitWidth, InitStyle, AS, MSPropertyAttr);
2034       if (!Member)
2035         return 0;
2036       isInstField = false;
2037     } else {
2038       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2039                                 BitWidth, InitStyle, AS);
2040       assert(Member && "HandleField never returns null");
2041     }
2042   } else {
2043     assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2044 
2045     Member = HandleDeclarator(S, D, TemplateParameterLists);
2046     if (!Member)
2047       return 0;
2048 
2049     // Non-instance-fields can't have a bitfield.
2050     if (BitWidth) {
2051       if (Member->isInvalidDecl()) {
2052         // don't emit another diagnostic.
2053       } else if (isa<VarDecl>(Member)) {
2054         // C++ 9.6p3: A bit-field shall not be a static member.
2055         // "static member 'A' cannot be a bit-field"
2056         Diag(Loc, diag::err_static_not_bitfield)
2057           << Name << BitWidth->getSourceRange();
2058       } else if (isa<TypedefDecl>(Member)) {
2059         // "typedef member 'x' cannot be a bit-field"
2060         Diag(Loc, diag::err_typedef_not_bitfield)
2061           << Name << BitWidth->getSourceRange();
2062       } else {
2063         // A function typedef ("typedef int f(); f a;").
2064         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2065         Diag(Loc, diag::err_not_integral_type_bitfield)
2066           << Name << cast<ValueDecl>(Member)->getType()
2067           << BitWidth->getSourceRange();
2068       }
2069 
2070       BitWidth = 0;
2071       Member->setInvalidDecl();
2072     }
2073 
2074     Member->setAccess(AS);
2075 
2076     // If we have declared a member function template or static data member
2077     // template, set the access of the templated declaration as well.
2078     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2079       FunTmpl->getTemplatedDecl()->setAccess(AS);
2080     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2081       VarTmpl->getTemplatedDecl()->setAccess(AS);
2082   }
2083 
2084   if (VS.isOverrideSpecified())
2085     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
2086   if (VS.isFinalSpecified())
2087     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2088                                             VS.isFinalSpelledSealed()));
2089 
2090   if (VS.getLastLocation().isValid()) {
2091     // Update the end location of a method that has a virt-specifiers.
2092     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2093       MD->setRangeEnd(VS.getLastLocation());
2094   }
2095 
2096   CheckOverrideControl(Member);
2097 
2098   assert((Name || isInstField) && "No identifier for non-field ?");
2099 
2100   if (isInstField) {
2101     FieldDecl *FD = cast<FieldDecl>(Member);
2102     FieldCollector->Add(FD);
2103 
2104     if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2105                                  FD->getLocation())
2106           != DiagnosticsEngine::Ignored) {
2107       // Remember all explicit private FieldDecls that have a name, no side
2108       // effects and are not part of a dependent type declaration.
2109       if (!FD->isImplicit() && FD->getDeclName() &&
2110           FD->getAccess() == AS_private &&
2111           !FD->hasAttr<UnusedAttr>() &&
2112           !FD->getParent()->isDependentContext() &&
2113           !InitializationHasSideEffects(*FD))
2114         UnusedPrivateFields.insert(FD);
2115     }
2116   }
2117 
2118   return Member;
2119 }
2120 
2121 namespace {
2122   class UninitializedFieldVisitor
2123       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2124     Sema &S;
2125     // List of Decls to generate a warning on.  Also remove Decls that become
2126     // initialized.
2127     llvm::SmallPtrSet<ValueDecl*, 4> &Decls;
2128     // If non-null, add a note to the warning pointing back to the constructor.
2129     const CXXConstructorDecl *Constructor;
2130   public:
2131     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2132     UninitializedFieldVisitor(Sema &S,
2133                               llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
2134                               const CXXConstructorDecl *Constructor)
2135       : Inherited(S.Context), S(S), Decls(Decls),
2136         Constructor(Constructor) { }
2137 
2138     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) {
2139       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2140         return;
2141 
2142       // FieldME is the inner-most MemberExpr that is not an anonymous struct
2143       // or union.
2144       MemberExpr *FieldME = ME;
2145 
2146       Expr *Base = ME;
2147       while (isa<MemberExpr>(Base)) {
2148         ME = cast<MemberExpr>(Base);
2149 
2150         if (isa<VarDecl>(ME->getMemberDecl()))
2151           return;
2152 
2153         if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2154           if (!FD->isAnonymousStructOrUnion())
2155             FieldME = ME;
2156 
2157         Base = ME->getBase();
2158       }
2159 
2160       if (!isa<CXXThisExpr>(Base))
2161         return;
2162 
2163       ValueDecl* FoundVD = FieldME->getMemberDecl();
2164 
2165       if (!Decls.count(FoundVD))
2166         return;
2167 
2168       const bool IsReference = FoundVD->getType()->isReferenceType();
2169 
2170       // Prevent double warnings on use of unbounded references.
2171       if (IsReference != CheckReferenceOnly)
2172         return;
2173 
2174       unsigned diag = IsReference
2175           ? diag::warn_reference_field_is_uninit
2176           : diag::warn_field_is_uninit;
2177       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2178       if (Constructor)
2179         S.Diag(Constructor->getLocation(),
2180                diag::note_uninit_in_this_constructor)
2181           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2182 
2183     }
2184 
2185     void HandleValue(Expr *E) {
2186       E = E->IgnoreParens();
2187 
2188       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2189         HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
2190         return;
2191       }
2192 
2193       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2194         HandleValue(CO->getTrueExpr());
2195         HandleValue(CO->getFalseExpr());
2196         return;
2197       }
2198 
2199       if (BinaryConditionalOperator *BCO =
2200               dyn_cast<BinaryConditionalOperator>(E)) {
2201         HandleValue(BCO->getCommon());
2202         HandleValue(BCO->getFalseExpr());
2203         return;
2204       }
2205 
2206       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2207         switch (BO->getOpcode()) {
2208         default:
2209           return;
2210         case(BO_PtrMemD):
2211         case(BO_PtrMemI):
2212           HandleValue(BO->getLHS());
2213           return;
2214         case(BO_Comma):
2215           HandleValue(BO->getRHS());
2216           return;
2217         }
2218       }
2219     }
2220 
2221     void VisitMemberExpr(MemberExpr *ME) {
2222       // All uses of unbounded reference fields will warn.
2223       HandleMemberExpr(ME, true /*CheckReferenceOnly*/);
2224 
2225       Inherited::VisitMemberExpr(ME);
2226     }
2227 
2228     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2229       if (E->getCastKind() == CK_LValueToRValue)
2230         HandleValue(E->getSubExpr());
2231 
2232       Inherited::VisitImplicitCastExpr(E);
2233     }
2234 
2235     void VisitCXXConstructExpr(CXXConstructExpr *E) {
2236       if (E->getConstructor()->isCopyConstructor())
2237         if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0)))
2238           if (ICE->getCastKind() == CK_NoOp)
2239             if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr()))
2240               HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
2241 
2242       Inherited::VisitCXXConstructExpr(E);
2243     }
2244 
2245     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2246       Expr *Callee = E->getCallee();
2247       if (isa<MemberExpr>(Callee))
2248         HandleValue(Callee);
2249 
2250       Inherited::VisitCXXMemberCallExpr(E);
2251     }
2252 
2253     void VisitBinaryOperator(BinaryOperator *E) {
2254       // If a field assignment is detected, remove the field from the
2255       // uninitiailized field set.
2256       if (E->getOpcode() == BO_Assign)
2257         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2258           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2259             if (!FD->getType()->isReferenceType())
2260               Decls.erase(FD);
2261 
2262       Inherited::VisitBinaryOperator(E);
2263     }
2264   };
2265   static void CheckInitExprContainsUninitializedFields(
2266       Sema &S, Expr *E, llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
2267       const CXXConstructorDecl *Constructor) {
2268     if (Decls.size() == 0)
2269       return;
2270 
2271     if (!E)
2272       return;
2273 
2274     if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(E)) {
2275       E = Default->getExpr();
2276       if (!E)
2277         return;
2278       // In class initializers will point to the constructor.
2279       UninitializedFieldVisitor(S, Decls, Constructor).Visit(E);
2280     } else {
2281       UninitializedFieldVisitor(S, Decls, 0).Visit(E);
2282     }
2283   }
2284 
2285   // Diagnose value-uses of fields to initialize themselves, e.g.
2286   //   foo(foo)
2287   // where foo is not also a parameter to the constructor.
2288   // Also diagnose across field uninitialized use such as
2289   //   x(y), y(x)
2290   // TODO: implement -Wuninitialized and fold this into that framework.
2291   static void DiagnoseUninitializedFields(
2292       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2293 
2294     if (SemaRef.getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit,
2295                                                     Constructor->getLocation())
2296         == DiagnosticsEngine::Ignored) {
2297       return;
2298     }
2299 
2300     if (Constructor->isInvalidDecl())
2301       return;
2302 
2303     const CXXRecordDecl *RD = Constructor->getParent();
2304 
2305     // Holds fields that are uninitialized.
2306     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2307 
2308     // At the beginning, all fields are uninitialized.
2309     for (DeclContext::decl_iterator I = RD->decls_begin(), E = RD->decls_end();
2310          I != E; ++I) {
2311       if (FieldDecl *FD = dyn_cast<FieldDecl>(*I)) {
2312         UninitializedFields.insert(FD);
2313       } else if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I)) {
2314         UninitializedFields.insert(IFD->getAnonField());
2315       }
2316     }
2317 
2318     for (CXXConstructorDecl::init_const_iterator FieldInit =
2319              Constructor->init_begin(),
2320              FieldInitEnd = Constructor->init_end();
2321          FieldInit != FieldInitEnd; ++FieldInit) {
2322 
2323       Expr *InitExpr = (*FieldInit)->getInit();
2324 
2325       CheckInitExprContainsUninitializedFields(
2326           SemaRef, InitExpr, UninitializedFields, Constructor);
2327 
2328       if (FieldDecl *Field = (*FieldInit)->getAnyMember())
2329         UninitializedFields.erase(Field);
2330     }
2331   }
2332 } // namespace
2333 
2334 /// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
2335 /// in-class initializer for a non-static C++ class member, and after
2336 /// instantiating an in-class initializer in a class template. Such actions
2337 /// are deferred until the class is complete.
2338 void
2339 Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
2340                                        Expr *InitExpr) {
2341   FieldDecl *FD = cast<FieldDecl>(D);
2342   assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2343          "must set init style when field is created");
2344 
2345   if (!InitExpr) {
2346     FD->setInvalidDecl();
2347     FD->removeInClassInitializer();
2348     return;
2349   }
2350 
2351   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2352     FD->setInvalidDecl();
2353     FD->removeInClassInitializer();
2354     return;
2355   }
2356 
2357   ExprResult Init = InitExpr;
2358   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
2359     InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
2360     InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
2361         ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
2362         : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
2363     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2364     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
2365     if (Init.isInvalid()) {
2366       FD->setInvalidDecl();
2367       return;
2368     }
2369   }
2370 
2371   // C++11 [class.base.init]p7:
2372   //   The initialization of each base and member constitutes a
2373   //   full-expression.
2374   Init = ActOnFinishFullExpr(Init.take(), InitLoc);
2375   if (Init.isInvalid()) {
2376     FD->setInvalidDecl();
2377     return;
2378   }
2379 
2380   InitExpr = Init.release();
2381 
2382   FD->setInClassInitializer(InitExpr);
2383 }
2384 
2385 /// \brief Find the direct and/or virtual base specifiers that
2386 /// correspond to the given base type, for use in base initialization
2387 /// within a constructor.
2388 static bool FindBaseInitializer(Sema &SemaRef,
2389                                 CXXRecordDecl *ClassDecl,
2390                                 QualType BaseType,
2391                                 const CXXBaseSpecifier *&DirectBaseSpec,
2392                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
2393   // First, check for a direct base class.
2394   DirectBaseSpec = 0;
2395   for (CXXRecordDecl::base_class_const_iterator Base
2396          = ClassDecl->bases_begin();
2397        Base != ClassDecl->bases_end(); ++Base) {
2398     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2399       // We found a direct base of this type. That's what we're
2400       // initializing.
2401       DirectBaseSpec = &*Base;
2402       break;
2403     }
2404   }
2405 
2406   // Check for a virtual base class.
2407   // FIXME: We might be able to short-circuit this if we know in advance that
2408   // there are no virtual bases.
2409   VirtualBaseSpec = 0;
2410   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2411     // We haven't found a base yet; search the class hierarchy for a
2412     // virtual base class.
2413     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2414                        /*DetectVirtual=*/false);
2415     if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2416                               BaseType, Paths)) {
2417       for (CXXBasePaths::paths_iterator Path = Paths.begin();
2418            Path != Paths.end(); ++Path) {
2419         if (Path->back().Base->isVirtual()) {
2420           VirtualBaseSpec = Path->back().Base;
2421           break;
2422         }
2423       }
2424     }
2425   }
2426 
2427   return DirectBaseSpec || VirtualBaseSpec;
2428 }
2429 
2430 /// \brief Handle a C++ member initializer using braced-init-list syntax.
2431 MemInitResult
2432 Sema::ActOnMemInitializer(Decl *ConstructorD,
2433                           Scope *S,
2434                           CXXScopeSpec &SS,
2435                           IdentifierInfo *MemberOrBase,
2436                           ParsedType TemplateTypeTy,
2437                           const DeclSpec &DS,
2438                           SourceLocation IdLoc,
2439                           Expr *InitList,
2440                           SourceLocation EllipsisLoc) {
2441   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2442                              DS, IdLoc, InitList,
2443                              EllipsisLoc);
2444 }
2445 
2446 /// \brief Handle a C++ member initializer using parentheses syntax.
2447 MemInitResult
2448 Sema::ActOnMemInitializer(Decl *ConstructorD,
2449                           Scope *S,
2450                           CXXScopeSpec &SS,
2451                           IdentifierInfo *MemberOrBase,
2452                           ParsedType TemplateTypeTy,
2453                           const DeclSpec &DS,
2454                           SourceLocation IdLoc,
2455                           SourceLocation LParenLoc,
2456                           ArrayRef<Expr *> Args,
2457                           SourceLocation RParenLoc,
2458                           SourceLocation EllipsisLoc) {
2459   Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2460                                            Args, RParenLoc);
2461   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2462                              DS, IdLoc, List, EllipsisLoc);
2463 }
2464 
2465 namespace {
2466 
2467 // Callback to only accept typo corrections that can be a valid C++ member
2468 // intializer: either a non-static field member or a base class.
2469 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2470 public:
2471   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2472       : ClassDecl(ClassDecl) {}
2473 
2474   bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE {
2475     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2476       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2477         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2478       return isa<TypeDecl>(ND);
2479     }
2480     return false;
2481   }
2482 
2483 private:
2484   CXXRecordDecl *ClassDecl;
2485 };
2486 
2487 }
2488 
2489 /// \brief Handle a C++ member initializer.
2490 MemInitResult
2491 Sema::BuildMemInitializer(Decl *ConstructorD,
2492                           Scope *S,
2493                           CXXScopeSpec &SS,
2494                           IdentifierInfo *MemberOrBase,
2495                           ParsedType TemplateTypeTy,
2496                           const DeclSpec &DS,
2497                           SourceLocation IdLoc,
2498                           Expr *Init,
2499                           SourceLocation EllipsisLoc) {
2500   if (!ConstructorD)
2501     return true;
2502 
2503   AdjustDeclIfTemplate(ConstructorD);
2504 
2505   CXXConstructorDecl *Constructor
2506     = dyn_cast<CXXConstructorDecl>(ConstructorD);
2507   if (!Constructor) {
2508     // The user wrote a constructor initializer on a function that is
2509     // not a C++ constructor. Ignore the error for now, because we may
2510     // have more member initializers coming; we'll diagnose it just
2511     // once in ActOnMemInitializers.
2512     return true;
2513   }
2514 
2515   CXXRecordDecl *ClassDecl = Constructor->getParent();
2516 
2517   // C++ [class.base.init]p2:
2518   //   Names in a mem-initializer-id are looked up in the scope of the
2519   //   constructor's class and, if not found in that scope, are looked
2520   //   up in the scope containing the constructor's definition.
2521   //   [Note: if the constructor's class contains a member with the
2522   //   same name as a direct or virtual base class of the class, a
2523   //   mem-initializer-id naming the member or base class and composed
2524   //   of a single identifier refers to the class member. A
2525   //   mem-initializer-id for the hidden base class may be specified
2526   //   using a qualified name. ]
2527   if (!SS.getScopeRep() && !TemplateTypeTy) {
2528     // Look for a member, first.
2529     DeclContext::lookup_result Result
2530       = ClassDecl->lookup(MemberOrBase);
2531     if (!Result.empty()) {
2532       ValueDecl *Member;
2533       if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2534           (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
2535         if (EllipsisLoc.isValid())
2536           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
2537             << MemberOrBase
2538             << SourceRange(IdLoc, Init->getSourceRange().getEnd());
2539 
2540         return BuildMemberInitializer(Member, Init, IdLoc);
2541       }
2542     }
2543   }
2544   // It didn't name a member, so see if it names a class.
2545   QualType BaseType;
2546   TypeSourceInfo *TInfo = 0;
2547 
2548   if (TemplateTypeTy) {
2549     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
2550   } else if (DS.getTypeSpecType() == TST_decltype) {
2551     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
2552   } else {
2553     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2554     LookupParsedName(R, S, &SS);
2555 
2556     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2557     if (!TyD) {
2558       if (R.isAmbiguous()) return true;
2559 
2560       // We don't want access-control diagnostics here.
2561       R.suppressDiagnostics();
2562 
2563       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2564         bool NotUnknownSpecialization = false;
2565         DeclContext *DC = computeDeclContext(SS, false);
2566         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2567           NotUnknownSpecialization = !Record->hasAnyDependentBases();
2568 
2569         if (!NotUnknownSpecialization) {
2570           // When the scope specifier can refer to a member of an unknown
2571           // specialization, we take it as a type name.
2572           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2573                                        SS.getWithLocInContext(Context),
2574                                        *MemberOrBase, IdLoc);
2575           if (BaseType.isNull())
2576             return true;
2577 
2578           R.clear();
2579           R.setLookupName(MemberOrBase);
2580         }
2581       }
2582 
2583       // If no results were found, try to correct typos.
2584       TypoCorrection Corr;
2585       MemInitializerValidatorCCC Validator(ClassDecl);
2586       if (R.empty() && BaseType.isNull() &&
2587           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2588                               Validator, ClassDecl))) {
2589         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
2590           // We have found a non-static data member with a similar
2591           // name to what was typed; complain and initialize that
2592           // member.
2593           diagnoseTypo(Corr,
2594                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
2595                          << MemberOrBase << true);
2596           return BuildMemberInitializer(Member, Init, IdLoc);
2597         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
2598           const CXXBaseSpecifier *DirectBaseSpec;
2599           const CXXBaseSpecifier *VirtualBaseSpec;
2600           if (FindBaseInitializer(*this, ClassDecl,
2601                                   Context.getTypeDeclType(Type),
2602                                   DirectBaseSpec, VirtualBaseSpec)) {
2603             // We have found a direct or virtual base class with a
2604             // similar name to what was typed; complain and initialize
2605             // that base class.
2606             diagnoseTypo(Corr,
2607                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
2608                            << MemberOrBase << false,
2609                          PDiag() /*Suppress note, we provide our own.*/);
2610 
2611             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2612                                                               : VirtualBaseSpec;
2613             Diag(BaseSpec->getLocStart(),
2614                  diag::note_base_class_specified_here)
2615               << BaseSpec->getType()
2616               << BaseSpec->getSourceRange();
2617 
2618             TyD = Type;
2619           }
2620         }
2621       }
2622 
2623       if (!TyD && BaseType.isNull()) {
2624         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
2625           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
2626         return true;
2627       }
2628     }
2629 
2630     if (BaseType.isNull()) {
2631       BaseType = Context.getTypeDeclType(TyD);
2632       if (SS.isSet()) {
2633         NestedNameSpecifier *Qualifier =
2634           static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2635 
2636         // FIXME: preserve source range information
2637         BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
2638       }
2639     }
2640   }
2641 
2642   if (!TInfo)
2643     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
2644 
2645   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
2646 }
2647 
2648 /// Checks a member initializer expression for cases where reference (or
2649 /// pointer) members are bound to by-value parameters (or their addresses).
2650 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2651                                                Expr *Init,
2652                                                SourceLocation IdLoc) {
2653   QualType MemberTy = Member->getType();
2654 
2655   // We only handle pointers and references currently.
2656   // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2657   if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2658     return;
2659 
2660   const bool IsPointer = MemberTy->isPointerType();
2661   if (IsPointer) {
2662     if (const UnaryOperator *Op
2663           = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2664       // The only case we're worried about with pointers requires taking the
2665       // address.
2666       if (Op->getOpcode() != UO_AddrOf)
2667         return;
2668 
2669       Init = Op->getSubExpr();
2670     } else {
2671       // We only handle address-of expression initializers for pointers.
2672       return;
2673     }
2674   }
2675 
2676   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2677     // We only warn when referring to a non-reference parameter declaration.
2678     const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2679     if (!Parameter || Parameter->getType()->isReferenceType())
2680       return;
2681 
2682     S.Diag(Init->getExprLoc(),
2683            IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2684                      : diag::warn_bind_ref_member_to_parameter)
2685       << Member << Parameter << Init->getSourceRange();
2686   } else {
2687     // Other initializers are fine.
2688     return;
2689   }
2690 
2691   S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2692     << (unsigned)IsPointer;
2693 }
2694 
2695 MemInitResult
2696 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
2697                              SourceLocation IdLoc) {
2698   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2699   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2700   assert((DirectMember || IndirectMember) &&
2701          "Member must be a FieldDecl or IndirectFieldDecl");
2702 
2703   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2704     return true;
2705 
2706   if (Member->isInvalidDecl())
2707     return true;
2708 
2709   MultiExprArg Args;
2710   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2711     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2712   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2713     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
2714   } else {
2715     // Template instantiation doesn't reconstruct ParenListExprs for us.
2716     Args = Init;
2717   }
2718 
2719   SourceRange InitRange = Init->getSourceRange();
2720 
2721   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
2722     // Can't check initialization for a member of dependent type or when
2723     // any of the arguments are type-dependent expressions.
2724     DiscardCleanupsInEvaluationContext();
2725   } else {
2726     bool InitList = false;
2727     if (isa<InitListExpr>(Init)) {
2728       InitList = true;
2729       Args = Init;
2730     }
2731 
2732     // Initialize the member.
2733     InitializedEntity MemberEntity =
2734       DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2735                    : InitializedEntity::InitializeMember(IndirectMember, 0);
2736     InitializationKind Kind =
2737       InitList ? InitializationKind::CreateDirectList(IdLoc)
2738                : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2739                                                   InitRange.getEnd());
2740 
2741     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2742     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
2743     if (MemberInit.isInvalid())
2744       return true;
2745 
2746     CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2747 
2748     // C++11 [class.base.init]p7:
2749     //   The initialization of each base and member constitutes a
2750     //   full-expression.
2751     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
2752     if (MemberInit.isInvalid())
2753       return true;
2754 
2755     Init = MemberInit.get();
2756   }
2757 
2758   if (DirectMember) {
2759     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2760                                             InitRange.getBegin(), Init,
2761                                             InitRange.getEnd());
2762   } else {
2763     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2764                                             InitRange.getBegin(), Init,
2765                                             InitRange.getEnd());
2766   }
2767 }
2768 
2769 MemInitResult
2770 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
2771                                  CXXRecordDecl *ClassDecl) {
2772   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
2773   if (!LangOpts.CPlusPlus11)
2774     return Diag(NameLoc, diag::err_delegating_ctor)
2775       << TInfo->getTypeLoc().getLocalSourceRange();
2776   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
2777 
2778   bool InitList = true;
2779   MultiExprArg Args = Init;
2780   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2781     InitList = false;
2782     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2783   }
2784 
2785   SourceRange InitRange = Init->getSourceRange();
2786   // Initialize the object.
2787   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2788                                      QualType(ClassDecl->getTypeForDecl(), 0));
2789   InitializationKind Kind =
2790     InitList ? InitializationKind::CreateDirectList(NameLoc)
2791              : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2792                                                 InitRange.getEnd());
2793   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
2794   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2795                                               Args, 0);
2796   if (DelegationInit.isInvalid())
2797     return true;
2798 
2799   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2800          "Delegating constructor with no target?");
2801 
2802   // C++11 [class.base.init]p7:
2803   //   The initialization of each base and member constitutes a
2804   //   full-expression.
2805   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2806                                        InitRange.getBegin());
2807   if (DelegationInit.isInvalid())
2808     return true;
2809 
2810   // If we are in a dependent context, template instantiation will
2811   // perform this type-checking again. Just save the arguments that we
2812   // received in a ParenListExpr.
2813   // FIXME: This isn't quite ideal, since our ASTs don't capture all
2814   // of the information that we have about the base
2815   // initializer. However, deconstructing the ASTs is a dicey process,
2816   // and this approach is far more likely to get the corner cases right.
2817   if (CurContext->isDependentContext())
2818     DelegationInit = Owned(Init);
2819 
2820   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
2821                                           DelegationInit.takeAs<Expr>(),
2822                                           InitRange.getEnd());
2823 }
2824 
2825 MemInitResult
2826 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
2827                            Expr *Init, CXXRecordDecl *ClassDecl,
2828                            SourceLocation EllipsisLoc) {
2829   SourceLocation BaseLoc
2830     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
2831 
2832   if (!BaseType->isDependentType() && !BaseType->isRecordType())
2833     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2834              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2835 
2836   // C++ [class.base.init]p2:
2837   //   [...] Unless the mem-initializer-id names a nonstatic data
2838   //   member of the constructor's class or a direct or virtual base
2839   //   of that class, the mem-initializer is ill-formed. A
2840   //   mem-initializer-list can initialize a base class using any
2841   //   name that denotes that base class type.
2842   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
2843 
2844   SourceRange InitRange = Init->getSourceRange();
2845   if (EllipsisLoc.isValid()) {
2846     // This is a pack expansion.
2847     if (!BaseType->containsUnexpandedParameterPack())  {
2848       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2849         << SourceRange(BaseLoc, InitRange.getEnd());
2850 
2851       EllipsisLoc = SourceLocation();
2852     }
2853   } else {
2854     // Check for any unexpanded parameter packs.
2855     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2856       return true;
2857 
2858     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2859       return true;
2860   }
2861 
2862   // Check for direct and virtual base classes.
2863   const CXXBaseSpecifier *DirectBaseSpec = 0;
2864   const CXXBaseSpecifier *VirtualBaseSpec = 0;
2865   if (!Dependent) {
2866     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2867                                        BaseType))
2868       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
2869 
2870     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2871                         VirtualBaseSpec);
2872 
2873     // C++ [base.class.init]p2:
2874     // Unless the mem-initializer-id names a nonstatic data member of the
2875     // constructor's class or a direct or virtual base of that class, the
2876     // mem-initializer is ill-formed.
2877     if (!DirectBaseSpec && !VirtualBaseSpec) {
2878       // If the class has any dependent bases, then it's possible that
2879       // one of those types will resolve to the same type as
2880       // BaseType. Therefore, just treat this as a dependent base
2881       // class initialization.  FIXME: Should we try to check the
2882       // initialization anyway? It seems odd.
2883       if (ClassDecl->hasAnyDependentBases())
2884         Dependent = true;
2885       else
2886         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2887           << BaseType << Context.getTypeDeclType(ClassDecl)
2888           << BaseTInfo->getTypeLoc().getLocalSourceRange();
2889     }
2890   }
2891 
2892   if (Dependent) {
2893     DiscardCleanupsInEvaluationContext();
2894 
2895     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2896                                             /*IsVirtual=*/false,
2897                                             InitRange.getBegin(), Init,
2898                                             InitRange.getEnd(), EllipsisLoc);
2899   }
2900 
2901   // C++ [base.class.init]p2:
2902   //   If a mem-initializer-id is ambiguous because it designates both
2903   //   a direct non-virtual base class and an inherited virtual base
2904   //   class, the mem-initializer is ill-formed.
2905   if (DirectBaseSpec && VirtualBaseSpec)
2906     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
2907       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2908 
2909   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
2910   if (!BaseSpec)
2911     BaseSpec = VirtualBaseSpec;
2912 
2913   // Initialize the base.
2914   bool InitList = true;
2915   MultiExprArg Args = Init;
2916   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2917     InitList = false;
2918     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2919   }
2920 
2921   InitializedEntity BaseEntity =
2922     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2923   InitializationKind Kind =
2924     InitList ? InitializationKind::CreateDirectList(BaseLoc)
2925              : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2926                                                 InitRange.getEnd());
2927   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2928   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
2929   if (BaseInit.isInvalid())
2930     return true;
2931 
2932   // C++11 [class.base.init]p7:
2933   //   The initialization of each base and member constitutes a
2934   //   full-expression.
2935   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
2936   if (BaseInit.isInvalid())
2937     return true;
2938 
2939   // If we are in a dependent context, template instantiation will
2940   // perform this type-checking again. Just save the arguments that we
2941   // received in a ParenListExpr.
2942   // FIXME: This isn't quite ideal, since our ASTs don't capture all
2943   // of the information that we have about the base
2944   // initializer. However, deconstructing the ASTs is a dicey process,
2945   // and this approach is far more likely to get the corner cases right.
2946   if (CurContext->isDependentContext())
2947     BaseInit = Owned(Init);
2948 
2949   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2950                                           BaseSpec->isVirtual(),
2951                                           InitRange.getBegin(),
2952                                           BaseInit.takeAs<Expr>(),
2953                                           InitRange.getEnd(), EllipsisLoc);
2954 }
2955 
2956 // Create a static_cast\<T&&>(expr).
2957 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2958   if (T.isNull()) T = E->getType();
2959   QualType TargetType = SemaRef.BuildReferenceType(
2960       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
2961   SourceLocation ExprLoc = E->getLocStart();
2962   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2963       TargetType, ExprLoc);
2964 
2965   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2966                                    SourceRange(ExprLoc, ExprLoc),
2967                                    E->getSourceRange()).take();
2968 }
2969 
2970 /// ImplicitInitializerKind - How an implicit base or member initializer should
2971 /// initialize its base or member.
2972 enum ImplicitInitializerKind {
2973   IIK_Default,
2974   IIK_Copy,
2975   IIK_Move,
2976   IIK_Inherit
2977 };
2978 
2979 static bool
2980 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2981                              ImplicitInitializerKind ImplicitInitKind,
2982                              CXXBaseSpecifier *BaseSpec,
2983                              bool IsInheritedVirtualBase,
2984                              CXXCtorInitializer *&CXXBaseInit) {
2985   InitializedEntity InitEntity
2986     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2987                                         IsInheritedVirtualBase);
2988 
2989   ExprResult BaseInit;
2990 
2991   switch (ImplicitInitKind) {
2992   case IIK_Inherit: {
2993     const CXXRecordDecl *Inherited =
2994         Constructor->getInheritedConstructor()->getParent();
2995     const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2996     if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2997       // C++11 [class.inhctor]p8:
2998       //   Each expression in the expression-list is of the form
2999       //   static_cast<T&&>(p), where p is the name of the corresponding
3000       //   constructor parameter and T is the declared type of p.
3001       SmallVector<Expr*, 16> Args;
3002       for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3003         ParmVarDecl *PD = Constructor->getParamDecl(I);
3004         ExprResult ArgExpr =
3005             SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3006                                      VK_LValue, SourceLocation());
3007         if (ArgExpr.isInvalid())
3008           return true;
3009         Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
3010       }
3011 
3012       InitializationKind InitKind = InitializationKind::CreateDirect(
3013           Constructor->getLocation(), SourceLocation(), SourceLocation());
3014       InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
3015       BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3016       break;
3017     }
3018   }
3019   // Fall through.
3020   case IIK_Default: {
3021     InitializationKind InitKind
3022       = InitializationKind::CreateDefault(Constructor->getLocation());
3023     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3024     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3025     break;
3026   }
3027 
3028   case IIK_Move:
3029   case IIK_Copy: {
3030     bool Moving = ImplicitInitKind == IIK_Move;
3031     ParmVarDecl *Param = Constructor->getParamDecl(0);
3032     QualType ParamType = Param->getType().getNonReferenceType();
3033 
3034     Expr *CopyCtorArg =
3035       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3036                           SourceLocation(), Param, false,
3037                           Constructor->getLocation(), ParamType,
3038                           VK_LValue, 0);
3039 
3040     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3041 
3042     // Cast to the base class to avoid ambiguities.
3043     QualType ArgTy =
3044       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3045                                        ParamType.getQualifiers());
3046 
3047     if (Moving) {
3048       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3049     }
3050 
3051     CXXCastPath BasePath;
3052     BasePath.push_back(BaseSpec);
3053     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3054                                             CK_UncheckedDerivedToBase,
3055                                             Moving ? VK_XValue : VK_LValue,
3056                                             &BasePath).take();
3057 
3058     InitializationKind InitKind
3059       = InitializationKind::CreateDirect(Constructor->getLocation(),
3060                                          SourceLocation(), SourceLocation());
3061     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3062     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
3063     break;
3064   }
3065   }
3066 
3067   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
3068   if (BaseInit.isInvalid())
3069     return true;
3070 
3071   CXXBaseInit =
3072     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3073                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3074                                                         SourceLocation()),
3075                                              BaseSpec->isVirtual(),
3076                                              SourceLocation(),
3077                                              BaseInit.takeAs<Expr>(),
3078                                              SourceLocation(),
3079                                              SourceLocation());
3080 
3081   return false;
3082 }
3083 
3084 static bool RefersToRValueRef(Expr *MemRef) {
3085   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3086   return Referenced->getType()->isRValueReferenceType();
3087 }
3088 
3089 static bool
3090 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3091                                ImplicitInitializerKind ImplicitInitKind,
3092                                FieldDecl *Field, IndirectFieldDecl *Indirect,
3093                                CXXCtorInitializer *&CXXMemberInit) {
3094   if (Field->isInvalidDecl())
3095     return true;
3096 
3097   SourceLocation Loc = Constructor->getLocation();
3098 
3099   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3100     bool Moving = ImplicitInitKind == IIK_Move;
3101     ParmVarDecl *Param = Constructor->getParamDecl(0);
3102     QualType ParamType = Param->getType().getNonReferenceType();
3103 
3104     // Suppress copying zero-width bitfields.
3105     if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3106       return false;
3107 
3108     Expr *MemberExprBase =
3109       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3110                           SourceLocation(), Param, false,
3111                           Loc, ParamType, VK_LValue, 0);
3112 
3113     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3114 
3115     if (Moving) {
3116       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3117     }
3118 
3119     // Build a reference to this field within the parameter.
3120     CXXScopeSpec SS;
3121     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3122                               Sema::LookupMemberName);
3123     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3124                                   : cast<ValueDecl>(Field), AS_public);
3125     MemberLookup.resolveKind();
3126     ExprResult CtorArg
3127       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
3128                                          ParamType, Loc,
3129                                          /*IsArrow=*/false,
3130                                          SS,
3131                                          /*TemplateKWLoc=*/SourceLocation(),
3132                                          /*FirstQualifierInScope=*/0,
3133                                          MemberLookup,
3134                                          /*TemplateArgs=*/0);
3135     if (CtorArg.isInvalid())
3136       return true;
3137 
3138     // C++11 [class.copy]p15:
3139     //   - if a member m has rvalue reference type T&&, it is direct-initialized
3140     //     with static_cast<T&&>(x.m);
3141     if (RefersToRValueRef(CtorArg.get())) {
3142       CtorArg = CastForMoving(SemaRef, CtorArg.take());
3143     }
3144 
3145     // When the field we are copying is an array, create index variables for
3146     // each dimension of the array. We use these index variables to subscript
3147     // the source array, and other clients (e.g., CodeGen) will perform the
3148     // necessary iteration with these index variables.
3149     SmallVector<VarDecl *, 4> IndexVariables;
3150     QualType BaseType = Field->getType();
3151     QualType SizeType = SemaRef.Context.getSizeType();
3152     bool InitializingArray = false;
3153     while (const ConstantArrayType *Array
3154                           = SemaRef.Context.getAsConstantArrayType(BaseType)) {
3155       InitializingArray = true;
3156       // Create the iteration variable for this array index.
3157       IdentifierInfo *IterationVarName = 0;
3158       {
3159         SmallString<8> Str;
3160         llvm::raw_svector_ostream OS(Str);
3161         OS << "__i" << IndexVariables.size();
3162         IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3163       }
3164       VarDecl *IterationVar
3165         = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
3166                           IterationVarName, SizeType,
3167                         SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
3168                           SC_None);
3169       IndexVariables.push_back(IterationVar);
3170 
3171       // Create a reference to the iteration variable.
3172       ExprResult IterationVarRef
3173         = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
3174       assert(!IterationVarRef.isInvalid() &&
3175              "Reference to invented variable cannot fail!");
3176       IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3177       assert(!IterationVarRef.isInvalid() &&
3178              "Conversion of invented variable cannot fail!");
3179 
3180       // Subscript the array with this iteration variable.
3181       CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
3182                                                         IterationVarRef.take(),
3183                                                         Loc);
3184       if (CtorArg.isInvalid())
3185         return true;
3186 
3187       BaseType = Array->getElementType();
3188     }
3189 
3190     // The array subscript expression is an lvalue, which is wrong for moving.
3191     if (Moving && InitializingArray)
3192       CtorArg = CastForMoving(SemaRef, CtorArg.take());
3193 
3194     // Construct the entity that we will be initializing. For an array, this
3195     // will be first element in the array, which may require several levels
3196     // of array-subscript entities.
3197     SmallVector<InitializedEntity, 4> Entities;
3198     Entities.reserve(1 + IndexVariables.size());
3199     if (Indirect)
3200       Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3201     else
3202       Entities.push_back(InitializedEntity::InitializeMember(Field));
3203     for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3204       Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3205                                                               0,
3206                                                               Entities.back()));
3207 
3208     // Direct-initialize to use the copy constructor.
3209     InitializationKind InitKind =
3210       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3211 
3212     Expr *CtorArgE = CtorArg.takeAs<Expr>();
3213     InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
3214 
3215     ExprResult MemberInit
3216       = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
3217                         MultiExprArg(&CtorArgE, 1));
3218     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3219     if (MemberInit.isInvalid())
3220       return true;
3221 
3222     if (Indirect) {
3223       assert(IndexVariables.size() == 0 &&
3224              "Indirect field improperly initialized");
3225       CXXMemberInit
3226         = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3227                                                    Loc, Loc,
3228                                                    MemberInit.takeAs<Expr>(),
3229                                                    Loc);
3230     } else
3231       CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3232                                                  Loc, MemberInit.takeAs<Expr>(),
3233                                                  Loc,
3234                                                  IndexVariables.data(),
3235                                                  IndexVariables.size());
3236     return false;
3237   }
3238 
3239   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3240          "Unhandled implicit init kind!");
3241 
3242   QualType FieldBaseElementType =
3243     SemaRef.Context.getBaseElementType(Field->getType());
3244 
3245   if (FieldBaseElementType->isRecordType()) {
3246     InitializedEntity InitEntity
3247       = Indirect? InitializedEntity::InitializeMember(Indirect)
3248                 : InitializedEntity::InitializeMember(Field);
3249     InitializationKind InitKind =
3250       InitializationKind::CreateDefault(Loc);
3251 
3252     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3253     ExprResult MemberInit =
3254       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3255 
3256     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3257     if (MemberInit.isInvalid())
3258       return true;
3259 
3260     if (Indirect)
3261       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3262                                                                Indirect, Loc,
3263                                                                Loc,
3264                                                                MemberInit.get(),
3265                                                                Loc);
3266     else
3267       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3268                                                                Field, Loc, Loc,
3269                                                                MemberInit.get(),
3270                                                                Loc);
3271     return false;
3272   }
3273 
3274   if (!Field->getParent()->isUnion()) {
3275     if (FieldBaseElementType->isReferenceType()) {
3276       SemaRef.Diag(Constructor->getLocation(),
3277                    diag::err_uninitialized_member_in_ctor)
3278       << (int)Constructor->isImplicit()
3279       << SemaRef.Context.getTagDeclType(Constructor->getParent())
3280       << 0 << Field->getDeclName();
3281       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3282       return true;
3283     }
3284 
3285     if (FieldBaseElementType.isConstQualified()) {
3286       SemaRef.Diag(Constructor->getLocation(),
3287                    diag::err_uninitialized_member_in_ctor)
3288       << (int)Constructor->isImplicit()
3289       << SemaRef.Context.getTagDeclType(Constructor->getParent())
3290       << 1 << Field->getDeclName();
3291       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3292       return true;
3293     }
3294   }
3295 
3296   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
3297       FieldBaseElementType->isObjCRetainableType() &&
3298       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3299       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
3300     // ARC:
3301     //   Default-initialize Objective-C pointers to NULL.
3302     CXXMemberInit
3303       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3304                                                  Loc, Loc,
3305                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3306                                                  Loc);
3307     return false;
3308   }
3309 
3310   // Nothing to initialize.
3311   CXXMemberInit = 0;
3312   return false;
3313 }
3314 
3315 namespace {
3316 struct BaseAndFieldInfo {
3317   Sema &S;
3318   CXXConstructorDecl *Ctor;
3319   bool AnyErrorsInInits;
3320   ImplicitInitializerKind IIK;
3321   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
3322   SmallVector<CXXCtorInitializer*, 8> AllToInit;
3323 
3324   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3325     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
3326     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3327     if (Generated && Ctor->isCopyConstructor())
3328       IIK = IIK_Copy;
3329     else if (Generated && Ctor->isMoveConstructor())
3330       IIK = IIK_Move;
3331     else if (Ctor->getInheritedConstructor())
3332       IIK = IIK_Inherit;
3333     else
3334       IIK = IIK_Default;
3335   }
3336 
3337   bool isImplicitCopyOrMove() const {
3338     switch (IIK) {
3339     case IIK_Copy:
3340     case IIK_Move:
3341       return true;
3342 
3343     case IIK_Default:
3344     case IIK_Inherit:
3345       return false;
3346     }
3347 
3348     llvm_unreachable("Invalid ImplicitInitializerKind!");
3349   }
3350 
3351   bool addFieldInitializer(CXXCtorInitializer *Init) {
3352     AllToInit.push_back(Init);
3353 
3354     // Check whether this initializer makes the field "used".
3355     if (Init->getInit()->HasSideEffects(S.Context))
3356       S.UnusedPrivateFields.remove(Init->getAnyMember());
3357 
3358     return false;
3359   }
3360 };
3361 }
3362 
3363 /// \brief Determine whether the given indirect field declaration is somewhere
3364 /// within an anonymous union.
3365 static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3366   for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3367                                       CEnd = F->chain_end();
3368        C != CEnd; ++C)
3369     if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3370       if (Record->isUnion())
3371         return true;
3372 
3373   return false;
3374 }
3375 
3376 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
3377 /// array type.
3378 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3379   if (T->isIncompleteArrayType())
3380     return true;
3381 
3382   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3383     if (!ArrayT->getSize())
3384       return true;
3385 
3386     T = ArrayT->getElementType();
3387   }
3388 
3389   return false;
3390 }
3391 
3392 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
3393                                     FieldDecl *Field,
3394                                     IndirectFieldDecl *Indirect = 0) {
3395   if (Field->isInvalidDecl())
3396     return false;
3397 
3398   // Overwhelmingly common case: we have a direct initializer for this field.
3399   if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3400     return Info.addFieldInitializer(Init);
3401 
3402   // C++11 [class.base.init]p8: if the entity is a non-static data member that
3403   // has a brace-or-equal-initializer, the entity is initialized as specified
3404   // in [dcl.init].
3405   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
3406     Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3407                                            Info.Ctor->getLocation(), Field);
3408     CXXCtorInitializer *Init;
3409     if (Indirect)
3410       Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3411                                                       SourceLocation(),
3412                                                       SourceLocation(), DIE,
3413                                                       SourceLocation());
3414     else
3415       Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3416                                                       SourceLocation(),
3417                                                       SourceLocation(), DIE,
3418                                                       SourceLocation());
3419     return Info.addFieldInitializer(Init);
3420   }
3421 
3422   // Don't build an implicit initializer for union members if none was
3423   // explicitly specified.
3424   if (Field->getParent()->isUnion() ||
3425       (Indirect && isWithinAnonymousUnion(Indirect)))
3426     return false;
3427 
3428   // Don't initialize incomplete or zero-length arrays.
3429   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3430     return false;
3431 
3432   // Don't try to build an implicit initializer if there were semantic
3433   // errors in any of the initializers (and therefore we might be
3434   // missing some that the user actually wrote).
3435   if (Info.AnyErrorsInInits)
3436     return false;
3437 
3438   CXXCtorInitializer *Init = 0;
3439   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3440                                      Indirect, Init))
3441     return true;
3442 
3443   if (!Init)
3444     return false;
3445 
3446   return Info.addFieldInitializer(Init);
3447 }
3448 
3449 bool
3450 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3451                                CXXCtorInitializer *Initializer) {
3452   assert(Initializer->isDelegatingInitializer());
3453   Constructor->setNumCtorInitializers(1);
3454   CXXCtorInitializer **initializer =
3455     new (Context) CXXCtorInitializer*[1];
3456   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3457   Constructor->setCtorInitializers(initializer);
3458 
3459   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
3460     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
3461     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3462   }
3463 
3464   DelegatingCtorDecls.push_back(Constructor);
3465 
3466   return false;
3467 }
3468 
3469 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3470                                ArrayRef<CXXCtorInitializer *> Initializers) {
3471   if (Constructor->isDependentContext()) {
3472     // Just store the initializers as written, they will be checked during
3473     // instantiation.
3474     if (!Initializers.empty()) {
3475       Constructor->setNumCtorInitializers(Initializers.size());
3476       CXXCtorInitializer **baseOrMemberInitializers =
3477         new (Context) CXXCtorInitializer*[Initializers.size()];
3478       memcpy(baseOrMemberInitializers, Initializers.data(),
3479              Initializers.size() * sizeof(CXXCtorInitializer*));
3480       Constructor->setCtorInitializers(baseOrMemberInitializers);
3481     }
3482 
3483     // Let template instantiation know whether we had errors.
3484     if (AnyErrors)
3485       Constructor->setInvalidDecl();
3486 
3487     return false;
3488   }
3489 
3490   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
3491 
3492   // We need to build the initializer AST according to order of construction
3493   // and not what user specified in the Initializers list.
3494   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
3495   if (!ClassDecl)
3496     return true;
3497 
3498   bool HadError = false;
3499 
3500   for (unsigned i = 0; i < Initializers.size(); i++) {
3501     CXXCtorInitializer *Member = Initializers[i];
3502 
3503     if (Member->isBaseInitializer())
3504       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
3505     else
3506       Info.AllBaseFields[Member->getAnyMember()] = Member;
3507   }
3508 
3509   // Keep track of the direct virtual bases.
3510   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3511   for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3512        E = ClassDecl->bases_end(); I != E; ++I) {
3513     if (I->isVirtual())
3514       DirectVBases.insert(I);
3515   }
3516 
3517   // Push virtual bases before others.
3518   for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3519        E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3520 
3521     if (CXXCtorInitializer *Value
3522         = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3523       // [class.base.init]p7, per DR257:
3524       //   A mem-initializer where the mem-initializer-id names a virtual base
3525       //   class is ignored during execution of a constructor of any class that
3526       //   is not the most derived class.
3527       if (ClassDecl->isAbstract()) {
3528         // FIXME: Provide a fixit to remove the base specifier. This requires
3529         // tracking the location of the associated comma for a base specifier.
3530         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3531           << VBase->getType() << ClassDecl;
3532         DiagnoseAbstractType(ClassDecl);
3533       }
3534 
3535       Info.AllToInit.push_back(Value);
3536     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3537       // [class.base.init]p8, per DR257:
3538       //   If a given [...] base class is not named by a mem-initializer-id
3539       //   [...] and the entity is not a virtual base class of an abstract
3540       //   class, then [...] the entity is default-initialized.
3541       bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
3542       CXXCtorInitializer *CXXBaseInit;
3543       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3544                                        VBase, IsInheritedVirtualBase,
3545                                        CXXBaseInit)) {
3546         HadError = true;
3547         continue;
3548       }
3549 
3550       Info.AllToInit.push_back(CXXBaseInit);
3551     }
3552   }
3553 
3554   // Non-virtual bases.
3555   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3556        E = ClassDecl->bases_end(); Base != E; ++Base) {
3557     // Virtuals are in the virtual base list and already constructed.
3558     if (Base->isVirtual())
3559       continue;
3560 
3561     if (CXXCtorInitializer *Value
3562           = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3563       Info.AllToInit.push_back(Value);
3564     } else if (!AnyErrors) {
3565       CXXCtorInitializer *CXXBaseInit;
3566       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3567                                        Base, /*IsInheritedVirtualBase=*/false,
3568                                        CXXBaseInit)) {
3569         HadError = true;
3570         continue;
3571       }
3572 
3573       Info.AllToInit.push_back(CXXBaseInit);
3574     }
3575   }
3576 
3577   // Fields.
3578   for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3579                                MemEnd = ClassDecl->decls_end();
3580        Mem != MemEnd; ++Mem) {
3581     if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
3582       // C++ [class.bit]p2:
3583       //   A declaration for a bit-field that omits the identifier declares an
3584       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
3585       //   initialized.
3586       if (F->isUnnamedBitfield())
3587         continue;
3588 
3589       // If we're not generating the implicit copy/move constructor, then we'll
3590       // handle anonymous struct/union fields based on their individual
3591       // indirect fields.
3592       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
3593         continue;
3594 
3595       if (CollectFieldInitializer(*this, Info, F))
3596         HadError = true;
3597       continue;
3598     }
3599 
3600     // Beyond this point, we only consider default initialization.
3601     if (Info.isImplicitCopyOrMove())
3602       continue;
3603 
3604     if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3605       if (F->getType()->isIncompleteArrayType()) {
3606         assert(ClassDecl->hasFlexibleArrayMember() &&
3607                "Incomplete array type is not valid");
3608         continue;
3609       }
3610 
3611       // Initialize each field of an anonymous struct individually.
3612       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3613         HadError = true;
3614 
3615       continue;
3616     }
3617   }
3618 
3619   unsigned NumInitializers = Info.AllToInit.size();
3620   if (NumInitializers > 0) {
3621     Constructor->setNumCtorInitializers(NumInitializers);
3622     CXXCtorInitializer **baseOrMemberInitializers =
3623       new (Context) CXXCtorInitializer*[NumInitializers];
3624     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
3625            NumInitializers * sizeof(CXXCtorInitializer*));
3626     Constructor->setCtorInitializers(baseOrMemberInitializers);
3627 
3628     // Constructors implicitly reference the base and member
3629     // destructors.
3630     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3631                                            Constructor->getParent());
3632   }
3633 
3634   return HadError;
3635 }
3636 
3637 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
3638   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
3639     const RecordDecl *RD = RT->getDecl();
3640     if (RD->isAnonymousStructOrUnion()) {
3641       for (RecordDecl::field_iterator Field = RD->field_begin(),
3642           E = RD->field_end(); Field != E; ++Field)
3643         PopulateKeysForFields(*Field, IdealInits);
3644       return;
3645     }
3646   }
3647   IdealInits.push_back(Field);
3648 }
3649 
3650 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3651   return Context.getCanonicalType(BaseType).getTypePtr();
3652 }
3653 
3654 static const void *GetKeyForMember(ASTContext &Context,
3655                                    CXXCtorInitializer *Member) {
3656   if (!Member->isAnyMemberInitializer())
3657     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
3658 
3659   return Member->getAnyMember();
3660 }
3661 
3662 static void DiagnoseBaseOrMemInitializerOrder(
3663     Sema &SemaRef, const CXXConstructorDecl *Constructor,
3664     ArrayRef<CXXCtorInitializer *> Inits) {
3665   if (Constructor->getDeclContext()->isDependentContext())
3666     return;
3667 
3668   // Don't check initializers order unless the warning is enabled at the
3669   // location of at least one initializer.
3670   bool ShouldCheckOrder = false;
3671   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3672     CXXCtorInitializer *Init = Inits[InitIndex];
3673     if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3674                                          Init->getSourceLocation())
3675           != DiagnosticsEngine::Ignored) {
3676       ShouldCheckOrder = true;
3677       break;
3678     }
3679   }
3680   if (!ShouldCheckOrder)
3681     return;
3682 
3683   // Build the list of bases and members in the order that they'll
3684   // actually be initialized.  The explicit initializers should be in
3685   // this same order but may be missing things.
3686   SmallVector<const void*, 32> IdealInitKeys;
3687 
3688   const CXXRecordDecl *ClassDecl = Constructor->getParent();
3689 
3690   // 1. Virtual bases.
3691   for (CXXRecordDecl::base_class_const_iterator VBase =
3692        ClassDecl->vbases_begin(),
3693        E = ClassDecl->vbases_end(); VBase != E; ++VBase)
3694     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
3695 
3696   // 2. Non-virtual bases.
3697   for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
3698        E = ClassDecl->bases_end(); Base != E; ++Base) {
3699     if (Base->isVirtual())
3700       continue;
3701     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
3702   }
3703 
3704   // 3. Direct fields.
3705   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3706        E = ClassDecl->field_end(); Field != E; ++Field) {
3707     if (Field->isUnnamedBitfield())
3708       continue;
3709 
3710     PopulateKeysForFields(*Field, IdealInitKeys);
3711   }
3712 
3713   unsigned NumIdealInits = IdealInitKeys.size();
3714   unsigned IdealIndex = 0;
3715 
3716   CXXCtorInitializer *PrevInit = 0;
3717   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3718     CXXCtorInitializer *Init = Inits[InitIndex];
3719     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
3720 
3721     // Scan forward to try to find this initializer in the idealized
3722     // initializers list.
3723     for (; IdealIndex != NumIdealInits; ++IdealIndex)
3724       if (InitKey == IdealInitKeys[IdealIndex])
3725         break;
3726 
3727     // If we didn't find this initializer, it must be because we
3728     // scanned past it on a previous iteration.  That can only
3729     // happen if we're out of order;  emit a warning.
3730     if (IdealIndex == NumIdealInits && PrevInit) {
3731       Sema::SemaDiagnosticBuilder D =
3732         SemaRef.Diag(PrevInit->getSourceLocation(),
3733                      diag::warn_initializer_out_of_order);
3734 
3735       if (PrevInit->isAnyMemberInitializer())
3736         D << 0 << PrevInit->getAnyMember()->getDeclName();
3737       else
3738         D << 1 << PrevInit->getTypeSourceInfo()->getType();
3739 
3740       if (Init->isAnyMemberInitializer())
3741         D << 0 << Init->getAnyMember()->getDeclName();
3742       else
3743         D << 1 << Init->getTypeSourceInfo()->getType();
3744 
3745       // Move back to the initializer's location in the ideal list.
3746       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3747         if (InitKey == IdealInitKeys[IdealIndex])
3748           break;
3749 
3750       assert(IdealIndex != NumIdealInits &&
3751              "initializer not found in initializer list");
3752     }
3753 
3754     PrevInit = Init;
3755   }
3756 }
3757 
3758 namespace {
3759 bool CheckRedundantInit(Sema &S,
3760                         CXXCtorInitializer *Init,
3761                         CXXCtorInitializer *&PrevInit) {
3762   if (!PrevInit) {
3763     PrevInit = Init;
3764     return false;
3765   }
3766 
3767   if (FieldDecl *Field = Init->getAnyMember())
3768     S.Diag(Init->getSourceLocation(),
3769            diag::err_multiple_mem_initialization)
3770       << Field->getDeclName()
3771       << Init->getSourceRange();
3772   else {
3773     const Type *BaseClass = Init->getBaseClass();
3774     assert(BaseClass && "neither field nor base");
3775     S.Diag(Init->getSourceLocation(),
3776            diag::err_multiple_base_initialization)
3777       << QualType(BaseClass, 0)
3778       << Init->getSourceRange();
3779   }
3780   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3781     << 0 << PrevInit->getSourceRange();
3782 
3783   return true;
3784 }
3785 
3786 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
3787 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3788 
3789 bool CheckRedundantUnionInit(Sema &S,
3790                              CXXCtorInitializer *Init,
3791                              RedundantUnionMap &Unions) {
3792   FieldDecl *Field = Init->getAnyMember();
3793   RecordDecl *Parent = Field->getParent();
3794   NamedDecl *Child = Field;
3795 
3796   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
3797     if (Parent->isUnion()) {
3798       UnionEntry &En = Unions[Parent];
3799       if (En.first && En.first != Child) {
3800         S.Diag(Init->getSourceLocation(),
3801                diag::err_multiple_mem_union_initialization)
3802           << Field->getDeclName()
3803           << Init->getSourceRange();
3804         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3805           << 0 << En.second->getSourceRange();
3806         return true;
3807       }
3808       if (!En.first) {
3809         En.first = Child;
3810         En.second = Init;
3811       }
3812       if (!Parent->isAnonymousStructOrUnion())
3813         return false;
3814     }
3815 
3816     Child = Parent;
3817     Parent = cast<RecordDecl>(Parent->getDeclContext());
3818   }
3819 
3820   return false;
3821 }
3822 }
3823 
3824 /// ActOnMemInitializers - Handle the member initializers for a constructor.
3825 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
3826                                 SourceLocation ColonLoc,
3827                                 ArrayRef<CXXCtorInitializer*> MemInits,
3828                                 bool AnyErrors) {
3829   if (!ConstructorDecl)
3830     return;
3831 
3832   AdjustDeclIfTemplate(ConstructorDecl);
3833 
3834   CXXConstructorDecl *Constructor
3835     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
3836 
3837   if (!Constructor) {
3838     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3839     return;
3840   }
3841 
3842   // Mapping for the duplicate initializers check.
3843   // For member initializers, this is keyed with a FieldDecl*.
3844   // For base initializers, this is keyed with a Type*.
3845   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
3846 
3847   // Mapping for the inconsistent anonymous-union initializers check.
3848   RedundantUnionMap MemberUnions;
3849 
3850   bool HadError = false;
3851   for (unsigned i = 0; i < MemInits.size(); i++) {
3852     CXXCtorInitializer *Init = MemInits[i];
3853 
3854     // Set the source order index.
3855     Init->setSourceOrder(i);
3856 
3857     if (Init->isAnyMemberInitializer()) {
3858       FieldDecl *Field = Init->getAnyMember();
3859       if (CheckRedundantInit(*this, Init, Members[Field]) ||
3860           CheckRedundantUnionInit(*this, Init, MemberUnions))
3861         HadError = true;
3862     } else if (Init->isBaseInitializer()) {
3863       const void *Key =
3864           GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3865       if (CheckRedundantInit(*this, Init, Members[Key]))
3866         HadError = true;
3867     } else {
3868       assert(Init->isDelegatingInitializer());
3869       // This must be the only initializer
3870       if (MemInits.size() != 1) {
3871         Diag(Init->getSourceLocation(),
3872              diag::err_delegating_initializer_alone)
3873           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
3874         // We will treat this as being the only initializer.
3875       }
3876       SetDelegatingInitializer(Constructor, MemInits[i]);
3877       // Return immediately as the initializer is set.
3878       return;
3879     }
3880   }
3881 
3882   if (HadError)
3883     return;
3884 
3885   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
3886 
3887   SetCtorInitializers(Constructor, AnyErrors, MemInits);
3888 
3889   DiagnoseUninitializedFields(*this, Constructor);
3890 }
3891 
3892 void
3893 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3894                                              CXXRecordDecl *ClassDecl) {
3895   // Ignore dependent contexts. Also ignore unions, since their members never
3896   // have destructors implicitly called.
3897   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
3898     return;
3899 
3900   // FIXME: all the access-control diagnostics are positioned on the
3901   // field/base declaration.  That's probably good; that said, the
3902   // user might reasonably want to know why the destructor is being
3903   // emitted, and we currently don't say.
3904 
3905   // Non-static data members.
3906   for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3907        E = ClassDecl->field_end(); I != E; ++I) {
3908     FieldDecl *Field = *I;
3909     if (Field->isInvalidDecl())
3910       continue;
3911 
3912     // Don't destroy incomplete or zero-length arrays.
3913     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3914       continue;
3915 
3916     QualType FieldType = Context.getBaseElementType(Field->getType());
3917 
3918     const RecordType* RT = FieldType->getAs<RecordType>();
3919     if (!RT)
3920       continue;
3921 
3922     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3923     if (FieldClassDecl->isInvalidDecl())
3924       continue;
3925     if (FieldClassDecl->hasIrrelevantDestructor())
3926       continue;
3927     // The destructor for an implicit anonymous union member is never invoked.
3928     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3929       continue;
3930 
3931     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
3932     assert(Dtor && "No dtor found for FieldClassDecl!");
3933     CheckDestructorAccess(Field->getLocation(), Dtor,
3934                           PDiag(diag::err_access_dtor_field)
3935                             << Field->getDeclName()
3936                             << FieldType);
3937 
3938     MarkFunctionReferenced(Location, Dtor);
3939     DiagnoseUseOfDecl(Dtor, Location);
3940   }
3941 
3942   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3943 
3944   // Bases.
3945   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3946        E = ClassDecl->bases_end(); Base != E; ++Base) {
3947     // Bases are always records in a well-formed non-dependent class.
3948     const RecordType *RT = Base->getType()->getAs<RecordType>();
3949 
3950     // Remember direct virtual bases.
3951     if (Base->isVirtual())
3952       DirectVirtualBases.insert(RT);
3953 
3954     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3955     // If our base class is invalid, we probably can't get its dtor anyway.
3956     if (BaseClassDecl->isInvalidDecl())
3957       continue;
3958     if (BaseClassDecl->hasIrrelevantDestructor())
3959       continue;
3960 
3961     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3962     assert(Dtor && "No dtor found for BaseClassDecl!");
3963 
3964     // FIXME: caret should be on the start of the class name
3965     CheckDestructorAccess(Base->getLocStart(), Dtor,
3966                           PDiag(diag::err_access_dtor_base)
3967                             << Base->getType()
3968                             << Base->getSourceRange(),
3969                           Context.getTypeDeclType(ClassDecl));
3970 
3971     MarkFunctionReferenced(Location, Dtor);
3972     DiagnoseUseOfDecl(Dtor, Location);
3973   }
3974 
3975   // Virtual bases.
3976   for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3977        E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3978 
3979     // Bases are always records in a well-formed non-dependent class.
3980     const RecordType *RT = VBase->getType()->castAs<RecordType>();
3981 
3982     // Ignore direct virtual bases.
3983     if (DirectVirtualBases.count(RT))
3984       continue;
3985 
3986     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3987     // If our base class is invalid, we probably can't get its dtor anyway.
3988     if (BaseClassDecl->isInvalidDecl())
3989       continue;
3990     if (BaseClassDecl->hasIrrelevantDestructor())
3991       continue;
3992 
3993     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3994     assert(Dtor && "No dtor found for BaseClassDecl!");
3995     if (CheckDestructorAccess(
3996             ClassDecl->getLocation(), Dtor,
3997             PDiag(diag::err_access_dtor_vbase)
3998                 << Context.getTypeDeclType(ClassDecl) << VBase->getType(),
3999             Context.getTypeDeclType(ClassDecl)) ==
4000         AR_accessible) {
4001       CheckDerivedToBaseConversion(
4002           Context.getTypeDeclType(ClassDecl), VBase->getType(),
4003           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4004           SourceRange(), DeclarationName(), 0);
4005     }
4006 
4007     MarkFunctionReferenced(Location, Dtor);
4008     DiagnoseUseOfDecl(Dtor, Location);
4009   }
4010 }
4011 
4012 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
4013   if (!CDtorDecl)
4014     return;
4015 
4016   if (CXXConstructorDecl *Constructor
4017       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
4018     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
4019     DiagnoseUninitializedFields(*this, Constructor);
4020   }
4021 }
4022 
4023 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4024                                   unsigned DiagID, AbstractDiagSelID SelID) {
4025   class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4026     unsigned DiagID;
4027     AbstractDiagSelID SelID;
4028 
4029   public:
4030     NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4031       : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
4032 
4033     void diagnose(Sema &S, SourceLocation Loc, QualType T) LLVM_OVERRIDE {
4034       if (Suppressed) return;
4035       if (SelID == -1)
4036         S.Diag(Loc, DiagID) << T;
4037       else
4038         S.Diag(Loc, DiagID) << SelID << T;
4039     }
4040   } Diagnoser(DiagID, SelID);
4041 
4042   return RequireNonAbstractType(Loc, T, Diagnoser);
4043 }
4044 
4045 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4046                                   TypeDiagnoser &Diagnoser) {
4047   if (!getLangOpts().CPlusPlus)
4048     return false;
4049 
4050   if (const ArrayType *AT = Context.getAsArrayType(T))
4051     return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4052 
4053   if (const PointerType *PT = T->getAs<PointerType>()) {
4054     // Find the innermost pointer type.
4055     while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
4056       PT = T;
4057 
4058     if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
4059       return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4060   }
4061 
4062   const RecordType *RT = T->getAs<RecordType>();
4063   if (!RT)
4064     return false;
4065 
4066   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4067 
4068   // We can't answer whether something is abstract until it has a
4069   // definition.  If it's currently being defined, we'll walk back
4070   // over all the declarations when we have a full definition.
4071   const CXXRecordDecl *Def = RD->getDefinition();
4072   if (!Def || Def->isBeingDefined())
4073     return false;
4074 
4075   if (!RD->isAbstract())
4076     return false;
4077 
4078   Diagnoser.diagnose(*this, Loc, T);
4079   DiagnoseAbstractType(RD);
4080 
4081   return true;
4082 }
4083 
4084 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4085   // Check if we've already emitted the list of pure virtual functions
4086   // for this class.
4087   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
4088     return;
4089 
4090   // If the diagnostic is suppressed, don't emit the notes. We're only
4091   // going to emit them once, so try to attach them to a diagnostic we're
4092   // actually going to show.
4093   if (Diags.isLastDiagnosticIgnored())
4094     return;
4095 
4096   CXXFinalOverriderMap FinalOverriders;
4097   RD->getFinalOverriders(FinalOverriders);
4098 
4099   // Keep a set of seen pure methods so we won't diagnose the same method
4100   // more than once.
4101   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4102 
4103   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4104                                    MEnd = FinalOverriders.end();
4105        M != MEnd;
4106        ++M) {
4107     for (OverridingMethods::iterator SO = M->second.begin(),
4108                                   SOEnd = M->second.end();
4109          SO != SOEnd; ++SO) {
4110       // C++ [class.abstract]p4:
4111       //   A class is abstract if it contains or inherits at least one
4112       //   pure virtual function for which the final overrider is pure
4113       //   virtual.
4114 
4115       //
4116       if (SO->second.size() != 1)
4117         continue;
4118 
4119       if (!SO->second.front().Method->isPure())
4120         continue;
4121 
4122       if (!SeenPureMethods.insert(SO->second.front().Method))
4123         continue;
4124 
4125       Diag(SO->second.front().Method->getLocation(),
4126            diag::note_pure_virtual_function)
4127         << SO->second.front().Method->getDeclName() << RD->getDeclName();
4128     }
4129   }
4130 
4131   if (!PureVirtualClassDiagSet)
4132     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4133   PureVirtualClassDiagSet->insert(RD);
4134 }
4135 
4136 namespace {
4137 struct AbstractUsageInfo {
4138   Sema &S;
4139   CXXRecordDecl *Record;
4140   CanQualType AbstractType;
4141   bool Invalid;
4142 
4143   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4144     : S(S), Record(Record),
4145       AbstractType(S.Context.getCanonicalType(
4146                    S.Context.getTypeDeclType(Record))),
4147       Invalid(false) {}
4148 
4149   void DiagnoseAbstractType() {
4150     if (Invalid) return;
4151     S.DiagnoseAbstractType(Record);
4152     Invalid = true;
4153   }
4154 
4155   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4156 };
4157 
4158 struct CheckAbstractUsage {
4159   AbstractUsageInfo &Info;
4160   const NamedDecl *Ctx;
4161 
4162   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4163     : Info(Info), Ctx(Ctx) {}
4164 
4165   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4166     switch (TL.getTypeLocClass()) {
4167 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4168 #define TYPELOC(CLASS, PARENT) \
4169     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
4170 #include "clang/AST/TypeLocNodes.def"
4171     }
4172   }
4173 
4174   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4175     Visit(TL.getResultLoc(), Sema::AbstractReturnType);
4176     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4177       if (!TL.getArg(I))
4178         continue;
4179 
4180       TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
4181       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
4182     }
4183   }
4184 
4185   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4186     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4187   }
4188 
4189   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4190     // Visit the type parameters from a permissive context.
4191     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4192       TemplateArgumentLoc TAL = TL.getArgLoc(I);
4193       if (TAL.getArgument().getKind() == TemplateArgument::Type)
4194         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4195           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4196       // TODO: other template argument types?
4197     }
4198   }
4199 
4200   // Visit pointee types from a permissive context.
4201 #define CheckPolymorphic(Type) \
4202   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4203     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4204   }
4205   CheckPolymorphic(PointerTypeLoc)
4206   CheckPolymorphic(ReferenceTypeLoc)
4207   CheckPolymorphic(MemberPointerTypeLoc)
4208   CheckPolymorphic(BlockPointerTypeLoc)
4209   CheckPolymorphic(AtomicTypeLoc)
4210 
4211   /// Handle all the types we haven't given a more specific
4212   /// implementation for above.
4213   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4214     // Every other kind of type that we haven't called out already
4215     // that has an inner type is either (1) sugar or (2) contains that
4216     // inner type in some way as a subobject.
4217     if (TypeLoc Next = TL.getNextTypeLoc())
4218       return Visit(Next, Sel);
4219 
4220     // If there's no inner type and we're in a permissive context,
4221     // don't diagnose.
4222     if (Sel == Sema::AbstractNone) return;
4223 
4224     // Check whether the type matches the abstract type.
4225     QualType T = TL.getType();
4226     if (T->isArrayType()) {
4227       Sel = Sema::AbstractArrayType;
4228       T = Info.S.Context.getBaseElementType(T);
4229     }
4230     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4231     if (CT != Info.AbstractType) return;
4232 
4233     // It matched; do some magic.
4234     if (Sel == Sema::AbstractArrayType) {
4235       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4236         << T << TL.getSourceRange();
4237     } else {
4238       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4239         << Sel << T << TL.getSourceRange();
4240     }
4241     Info.DiagnoseAbstractType();
4242   }
4243 };
4244 
4245 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4246                                   Sema::AbstractDiagSelID Sel) {
4247   CheckAbstractUsage(*this, D).Visit(TL, Sel);
4248 }
4249 
4250 }
4251 
4252 /// Check for invalid uses of an abstract type in a method declaration.
4253 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4254                                     CXXMethodDecl *MD) {
4255   // No need to do the check on definitions, which require that
4256   // the return/param types be complete.
4257   if (MD->doesThisDeclarationHaveABody())
4258     return;
4259 
4260   // For safety's sake, just ignore it if we don't have type source
4261   // information.  This should never happen for non-implicit methods,
4262   // but...
4263   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4264     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4265 }
4266 
4267 /// Check for invalid uses of an abstract type within a class definition.
4268 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4269                                     CXXRecordDecl *RD) {
4270   for (CXXRecordDecl::decl_iterator
4271          I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
4272     Decl *D = *I;
4273     if (D->isImplicit()) continue;
4274 
4275     // Methods and method templates.
4276     if (isa<CXXMethodDecl>(D)) {
4277       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4278     } else if (isa<FunctionTemplateDecl>(D)) {
4279       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4280       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4281 
4282     // Fields and static variables.
4283     } else if (isa<FieldDecl>(D)) {
4284       FieldDecl *FD = cast<FieldDecl>(D);
4285       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4286         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4287     } else if (isa<VarDecl>(D)) {
4288       VarDecl *VD = cast<VarDecl>(D);
4289       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4290         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4291 
4292     // Nested classes and class templates.
4293     } else if (isa<CXXRecordDecl>(D)) {
4294       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4295     } else if (isa<ClassTemplateDecl>(D)) {
4296       CheckAbstractClassUsage(Info,
4297                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4298     }
4299   }
4300 }
4301 
4302 /// \brief Perform semantic checks on a class definition that has been
4303 /// completing, introducing implicitly-declared members, checking for
4304 /// abstract types, etc.
4305 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
4306   if (!Record)
4307     return;
4308 
4309   if (Record->isAbstract() && !Record->isInvalidDecl()) {
4310     AbstractUsageInfo Info(*this, Record);
4311     CheckAbstractClassUsage(Info, Record);
4312   }
4313 
4314   // If this is not an aggregate type and has no user-declared constructor,
4315   // complain about any non-static data members of reference or const scalar
4316   // type, since they will never get initializers.
4317   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
4318       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4319       !Record->isLambda()) {
4320     bool Complained = false;
4321     for (RecordDecl::field_iterator F = Record->field_begin(),
4322                                  FEnd = Record->field_end();
4323          F != FEnd; ++F) {
4324       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
4325         continue;
4326 
4327       if (F->getType()->isReferenceType() ||
4328           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
4329         if (!Complained) {
4330           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4331             << Record->getTagKind() << Record;
4332           Complained = true;
4333         }
4334 
4335         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4336           << F->getType()->isReferenceType()
4337           << F->getDeclName();
4338       }
4339     }
4340   }
4341 
4342   if (Record->isDynamicClass() && !Record->isDependentType())
4343     DynamicClasses.push_back(Record);
4344 
4345   if (Record->getIdentifier()) {
4346     // C++ [class.mem]p13:
4347     //   If T is the name of a class, then each of the following shall have a
4348     //   name different from T:
4349     //     - every member of every anonymous union that is a member of class T.
4350     //
4351     // C++ [class.mem]p14:
4352     //   In addition, if class T has a user-declared constructor (12.1), every
4353     //   non-static data member of class T shall have a name different from T.
4354     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4355     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4356          ++I) {
4357       NamedDecl *D = *I;
4358       if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4359           isa<IndirectFieldDecl>(D)) {
4360         Diag(D->getLocation(), diag::err_member_name_of_class)
4361           << D->getDeclName();
4362         break;
4363       }
4364     }
4365   }
4366 
4367   // Warn if the class has virtual methods but non-virtual public destructor.
4368   if (Record->isPolymorphic() && !Record->isDependentType()) {
4369     CXXDestructorDecl *dtor = Record->getDestructor();
4370     if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
4371       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4372            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4373   }
4374 
4375   if (Record->isAbstract()) {
4376     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4377       Diag(Record->getLocation(), diag::warn_abstract_final_class)
4378         << FA->isSpelledAsSealed();
4379       DiagnoseAbstractType(Record);
4380     }
4381   }
4382 
4383   if (!Record->isDependentType()) {
4384     for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4385                                      MEnd = Record->method_end();
4386          M != MEnd; ++M) {
4387       // See if a method overloads virtual methods in a base
4388       // class without overriding any.
4389       if (!M->isStatic())
4390         DiagnoseHiddenVirtualMethods(*M);
4391 
4392       // Check whether the explicitly-defaulted special members are valid.
4393       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4394         CheckExplicitlyDefaultedSpecialMember(*M);
4395 
4396       // For an explicitly defaulted or deleted special member, we defer
4397       // determining triviality until the class is complete. That time is now!
4398       if (!M->isImplicit() && !M->isUserProvided()) {
4399         CXXSpecialMember CSM = getSpecialMember(*M);
4400         if (CSM != CXXInvalid) {
4401           M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4402 
4403           // Inform the class that we've finished declaring this member.
4404           Record->finishedDefaultedOrDeletedMember(*M);
4405         }
4406       }
4407     }
4408   }
4409 
4410   // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4411   // function that is not a constructor declares that member function to be
4412   // const. [...] The class of which that function is a member shall be
4413   // a literal type.
4414   //
4415   // If the class has virtual bases, any constexpr members will already have
4416   // been diagnosed by the checks performed on the member declaration, so
4417   // suppress this (less useful) diagnostic.
4418   //
4419   // We delay this until we know whether an explicitly-defaulted (or deleted)
4420   // destructor for the class is trivial.
4421   if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
4422       !Record->isLiteral() && !Record->getNumVBases()) {
4423     for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4424                                      MEnd = Record->method_end();
4425          M != MEnd; ++M) {
4426       if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4427         switch (Record->getTemplateSpecializationKind()) {
4428         case TSK_ImplicitInstantiation:
4429         case TSK_ExplicitInstantiationDeclaration:
4430         case TSK_ExplicitInstantiationDefinition:
4431           // If a template instantiates to a non-literal type, but its members
4432           // instantiate to constexpr functions, the template is technically
4433           // ill-formed, but we allow it for sanity.
4434           continue;
4435 
4436         case TSK_Undeclared:
4437         case TSK_ExplicitSpecialization:
4438           RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4439                              diag::err_constexpr_method_non_literal);
4440           break;
4441         }
4442 
4443         // Only produce one error per class.
4444         break;
4445       }
4446     }
4447   }
4448 
4449   // Check to see if we're trying to lay out a struct using the ms_struct
4450   // attribute that is dynamic.
4451   if (Record->isMsStruct(Context) && Record->isDynamicClass()) {
4452     Diag(Record->getLocation(), diag::warn_pragma_ms_struct_failed);
4453     Record->dropAttr<MsStructAttr>();
4454   }
4455 
4456   // Declare inheriting constructors. We do this eagerly here because:
4457   // - The standard requires an eager diagnostic for conflicting inheriting
4458   //   constructors from different classes.
4459   // - The lazy declaration of the other implicit constructors is so as to not
4460   //   waste space and performance on classes that are not meant to be
4461   //   instantiated (e.g. meta-functions). This doesn't apply to classes that
4462   //   have inheriting constructors.
4463   DeclareInheritingConstructors(Record);
4464 }
4465 
4466 /// Is the special member function which would be selected to perform the
4467 /// specified operation on the specified class type a constexpr constructor?
4468 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4469                                      Sema::CXXSpecialMember CSM,
4470                                      bool ConstArg) {
4471   Sema::SpecialMemberOverloadResult *SMOR =
4472       S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4473                             false, false, false, false);
4474   if (!SMOR || !SMOR->getMethod())
4475     // A constructor we wouldn't select can't be "involved in initializing"
4476     // anything.
4477     return true;
4478   return SMOR->getMethod()->isConstexpr();
4479 }
4480 
4481 /// Determine whether the specified special member function would be constexpr
4482 /// if it were implicitly defined.
4483 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4484                                               Sema::CXXSpecialMember CSM,
4485                                               bool ConstArg) {
4486   if (!S.getLangOpts().CPlusPlus11)
4487     return false;
4488 
4489   // C++11 [dcl.constexpr]p4:
4490   // In the definition of a constexpr constructor [...]
4491   bool Ctor = true;
4492   switch (CSM) {
4493   case Sema::CXXDefaultConstructor:
4494     // Since default constructor lookup is essentially trivial (and cannot
4495     // involve, for instance, template instantiation), we compute whether a
4496     // defaulted default constructor is constexpr directly within CXXRecordDecl.
4497     //
4498     // This is important for performance; we need to know whether the default
4499     // constructor is constexpr to determine whether the type is a literal type.
4500     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4501 
4502   case Sema::CXXCopyConstructor:
4503   case Sema::CXXMoveConstructor:
4504     // For copy or move constructors, we need to perform overload resolution.
4505     break;
4506 
4507   case Sema::CXXCopyAssignment:
4508   case Sema::CXXMoveAssignment:
4509     if (!S.getLangOpts().CPlusPlus1y)
4510       return false;
4511     // In C++1y, we need to perform overload resolution.
4512     Ctor = false;
4513     break;
4514 
4515   case Sema::CXXDestructor:
4516   case Sema::CXXInvalid:
4517     return false;
4518   }
4519 
4520   //   -- if the class is a non-empty union, or for each non-empty anonymous
4521   //      union member of a non-union class, exactly one non-static data member
4522   //      shall be initialized; [DR1359]
4523   //
4524   // If we squint, this is guaranteed, since exactly one non-static data member
4525   // will be initialized (if the constructor isn't deleted), we just don't know
4526   // which one.
4527   if (Ctor && ClassDecl->isUnion())
4528     return true;
4529 
4530   //   -- the class shall not have any virtual base classes;
4531   if (Ctor && ClassDecl->getNumVBases())
4532     return false;
4533 
4534   // C++1y [class.copy]p26:
4535   //   -- [the class] is a literal type, and
4536   if (!Ctor && !ClassDecl->isLiteral())
4537     return false;
4538 
4539   //   -- every constructor involved in initializing [...] base class
4540   //      sub-objects shall be a constexpr constructor;
4541   //   -- the assignment operator selected to copy/move each direct base
4542   //      class is a constexpr function, and
4543   for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4544                                        BEnd = ClassDecl->bases_end();
4545        B != BEnd; ++B) {
4546     const RecordType *BaseType = B->getType()->getAs<RecordType>();
4547     if (!BaseType) continue;
4548 
4549     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4550     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4551       return false;
4552   }
4553 
4554   //   -- every constructor involved in initializing non-static data members
4555   //      [...] shall be a constexpr constructor;
4556   //   -- every non-static data member and base class sub-object shall be
4557   //      initialized
4558   //   -- for each non-stastic data member of X that is of class type (or array
4559   //      thereof), the assignment operator selected to copy/move that member is
4560   //      a constexpr function
4561   for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4562                                FEnd = ClassDecl->field_end();
4563        F != FEnd; ++F) {
4564     if (F->isInvalidDecl())
4565       continue;
4566     if (const RecordType *RecordTy =
4567             S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4568       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4569       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4570         return false;
4571     }
4572   }
4573 
4574   // All OK, it's constexpr!
4575   return true;
4576 }
4577 
4578 static Sema::ImplicitExceptionSpecification
4579 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4580   switch (S.getSpecialMember(MD)) {
4581   case Sema::CXXDefaultConstructor:
4582     return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4583   case Sema::CXXCopyConstructor:
4584     return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4585   case Sema::CXXCopyAssignment:
4586     return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4587   case Sema::CXXMoveConstructor:
4588     return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4589   case Sema::CXXMoveAssignment:
4590     return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4591   case Sema::CXXDestructor:
4592     return S.ComputeDefaultedDtorExceptionSpec(MD);
4593   case Sema::CXXInvalid:
4594     break;
4595   }
4596   assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4597          "only special members have implicit exception specs");
4598   return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
4599 }
4600 
4601 static void
4602 updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4603                     const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4604   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4605   ExceptSpec.getEPI(EPI);
4606   FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4607                                         FPT->getArgTypes(), EPI));
4608 }
4609 
4610 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4611                                                             CXXMethodDecl *MD) {
4612   FunctionProtoType::ExtProtoInfo EPI;
4613 
4614   // Build an exception specification pointing back at this member.
4615   EPI.ExceptionSpecType = EST_Unevaluated;
4616   EPI.ExceptionSpecDecl = MD;
4617 
4618   // Set the calling convention to the default for C++ instance methods.
4619   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4620       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4621                                             /*IsCXXMethod=*/true));
4622   return EPI;
4623 }
4624 
4625 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4626   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4627   if (FPT->getExceptionSpecType() != EST_Unevaluated)
4628     return;
4629 
4630   // Evaluate the exception specification.
4631   ImplicitExceptionSpecification ExceptSpec =
4632       computeImplicitExceptionSpec(*this, Loc, MD);
4633 
4634   // Update the type of the special member to use it.
4635   updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4636 
4637   // A user-provided destructor can be defined outside the class. When that
4638   // happens, be sure to update the exception specification on both
4639   // declarations.
4640   const FunctionProtoType *CanonicalFPT =
4641     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4642   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4643     updateExceptionSpec(*this, MD->getCanonicalDecl(),
4644                         CanonicalFPT, ExceptSpec);
4645 }
4646 
4647 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4648   CXXRecordDecl *RD = MD->getParent();
4649   CXXSpecialMember CSM = getSpecialMember(MD);
4650 
4651   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4652          "not an explicitly-defaulted special member");
4653 
4654   // Whether this was the first-declared instance of the constructor.
4655   // This affects whether we implicitly add an exception spec and constexpr.
4656   bool First = MD == MD->getCanonicalDecl();
4657 
4658   bool HadError = false;
4659 
4660   // C++11 [dcl.fct.def.default]p1:
4661   //   A function that is explicitly defaulted shall
4662   //     -- be a special member function (checked elsewhere),
4663   //     -- have the same type (except for ref-qualifiers, and except that a
4664   //        copy operation can take a non-const reference) as an implicit
4665   //        declaration, and
4666   //     -- not have default arguments.
4667   unsigned ExpectedParams = 1;
4668   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4669     ExpectedParams = 0;
4670   if (MD->getNumParams() != ExpectedParams) {
4671     // This also checks for default arguments: a copy or move constructor with a
4672     // default argument is classified as a default constructor, and assignment
4673     // operations and destructors can't have default arguments.
4674     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4675       << CSM << MD->getSourceRange();
4676     HadError = true;
4677   } else if (MD->isVariadic()) {
4678     Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4679       << CSM << MD->getSourceRange();
4680     HadError = true;
4681   }
4682 
4683   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
4684 
4685   bool CanHaveConstParam = false;
4686   if (CSM == CXXCopyConstructor)
4687     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
4688   else if (CSM == CXXCopyAssignment)
4689     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
4690 
4691   QualType ReturnType = Context.VoidTy;
4692   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4693     // Check for return type matching.
4694     ReturnType = Type->getResultType();
4695     QualType ExpectedReturnType =
4696         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4697     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4698       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4699         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4700       HadError = true;
4701     }
4702 
4703     // A defaulted special member cannot have cv-qualifiers.
4704     if (Type->getTypeQuals()) {
4705       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4706         << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
4707       HadError = true;
4708     }
4709   }
4710 
4711   // Check for parameter type matching.
4712   QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
4713   bool HasConstParam = false;
4714   if (ExpectedParams && ArgType->isReferenceType()) {
4715     // Argument must be reference to possibly-const T.
4716     QualType ReferentType = ArgType->getPointeeType();
4717     HasConstParam = ReferentType.isConstQualified();
4718 
4719     if (ReferentType.isVolatileQualified()) {
4720       Diag(MD->getLocation(),
4721            diag::err_defaulted_special_member_volatile_param) << CSM;
4722       HadError = true;
4723     }
4724 
4725     if (HasConstParam && !CanHaveConstParam) {
4726       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4727         Diag(MD->getLocation(),
4728              diag::err_defaulted_special_member_copy_const_param)
4729           << (CSM == CXXCopyAssignment);
4730         // FIXME: Explain why this special member can't be const.
4731       } else {
4732         Diag(MD->getLocation(),
4733              diag::err_defaulted_special_member_move_const_param)
4734           << (CSM == CXXMoveAssignment);
4735       }
4736       HadError = true;
4737     }
4738   } else if (ExpectedParams) {
4739     // A copy assignment operator can take its argument by value, but a
4740     // defaulted one cannot.
4741     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
4742     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
4743     HadError = true;
4744   }
4745 
4746   // C++11 [dcl.fct.def.default]p2:
4747   //   An explicitly-defaulted function may be declared constexpr only if it
4748   //   would have been implicitly declared as constexpr,
4749   // Do not apply this rule to members of class templates, since core issue 1358
4750   // makes such functions always instantiate to constexpr functions. For
4751   // functions which cannot be constexpr (for non-constructors in C++11 and for
4752   // destructors in C++1y), this is checked elsewhere.
4753   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4754                                                      HasConstParam);
4755   if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4756                                  : isa<CXXConstructorDecl>(MD)) &&
4757       MD->isConstexpr() && !Constexpr &&
4758       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4759     Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
4760     // FIXME: Explain why the special member can't be constexpr.
4761     HadError = true;
4762   }
4763 
4764   //   and may have an explicit exception-specification only if it is compatible
4765   //   with the exception-specification on the implicit declaration.
4766   if (Type->hasExceptionSpec()) {
4767     // Delay the check if this is the first declaration of the special member,
4768     // since we may not have parsed some necessary in-class initializers yet.
4769     if (First) {
4770       // If the exception specification needs to be instantiated, do so now,
4771       // before we clobber it with an EST_Unevaluated specification below.
4772       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4773         InstantiateExceptionSpec(MD->getLocStart(), MD);
4774         Type = MD->getType()->getAs<FunctionProtoType>();
4775       }
4776       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
4777     } else
4778       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4779   }
4780 
4781   //   If a function is explicitly defaulted on its first declaration,
4782   if (First) {
4783     //  -- it is implicitly considered to be constexpr if the implicit
4784     //     definition would be,
4785     MD->setConstexpr(Constexpr);
4786 
4787     //  -- it is implicitly considered to have the same exception-specification
4788     //     as if it had been implicitly declared,
4789     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4790     EPI.ExceptionSpecType = EST_Unevaluated;
4791     EPI.ExceptionSpecDecl = MD;
4792     MD->setType(Context.getFunctionType(ReturnType,
4793                                         ArrayRef<QualType>(&ArgType,
4794                                                            ExpectedParams),
4795                                         EPI));
4796   }
4797 
4798   if (ShouldDeleteSpecialMember(MD, CSM)) {
4799     if (First) {
4800       SetDeclDeleted(MD, MD->getLocation());
4801     } else {
4802       // C++11 [dcl.fct.def.default]p4:
4803       //   [For a] user-provided explicitly-defaulted function [...] if such a
4804       //   function is implicitly defined as deleted, the program is ill-formed.
4805       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4806       HadError = true;
4807     }
4808   }
4809 
4810   if (HadError)
4811     MD->setInvalidDecl();
4812 }
4813 
4814 /// Check whether the exception specification provided for an
4815 /// explicitly-defaulted special member matches the exception specification
4816 /// that would have been generated for an implicit special member, per
4817 /// C++11 [dcl.fct.def.default]p2.
4818 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4819     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4820   // Compute the implicit exception specification.
4821   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4822                                                        /*IsCXXMethod=*/true);
4823   FunctionProtoType::ExtProtoInfo EPI(CC);
4824   computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4825   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
4826     Context.getFunctionType(Context.VoidTy, None, EPI));
4827 
4828   // Ensure that it matches.
4829   CheckEquivalentExceptionSpec(
4830     PDiag(diag::err_incorrect_defaulted_exception_spec)
4831       << getSpecialMember(MD), PDiag(),
4832     ImplicitType, SourceLocation(),
4833     SpecifiedType, MD->getLocation());
4834 }
4835 
4836 void Sema::CheckDelayedMemberExceptionSpecs() {
4837   SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
4838               2> Checks;
4839   SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
4840 
4841   std::swap(Checks, DelayedDestructorExceptionSpecChecks);
4842   std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
4843 
4844   // Perform any deferred checking of exception specifications for virtual
4845   // destructors.
4846   for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
4847     const CXXDestructorDecl *Dtor = Checks[i].first;
4848     assert(!Dtor->getParent()->isDependentType() &&
4849            "Should not ever add destructors of templates into the list.");
4850     CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
4851   }
4852 
4853   // Check that any explicitly-defaulted methods have exception specifications
4854   // compatible with their implicit exception specifications.
4855   for (unsigned I = 0, N = Specs.size(); I != N; ++I)
4856     CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
4857                                                 Specs[I].second);
4858 }
4859 
4860 namespace {
4861 struct SpecialMemberDeletionInfo {
4862   Sema &S;
4863   CXXMethodDecl *MD;
4864   Sema::CXXSpecialMember CSM;
4865   bool Diagnose;
4866 
4867   // Properties of the special member, computed for convenience.
4868   bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4869   SourceLocation Loc;
4870 
4871   bool AllFieldsAreConst;
4872 
4873   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
4874                             Sema::CXXSpecialMember CSM, bool Diagnose)
4875     : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
4876       IsConstructor(false), IsAssignment(false), IsMove(false),
4877       ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4878       AllFieldsAreConst(true) {
4879     switch (CSM) {
4880       case Sema::CXXDefaultConstructor:
4881       case Sema::CXXCopyConstructor:
4882         IsConstructor = true;
4883         break;
4884       case Sema::CXXMoveConstructor:
4885         IsConstructor = true;
4886         IsMove = true;
4887         break;
4888       case Sema::CXXCopyAssignment:
4889         IsAssignment = true;
4890         break;
4891       case Sema::CXXMoveAssignment:
4892         IsAssignment = true;
4893         IsMove = true;
4894         break;
4895       case Sema::CXXDestructor:
4896         break;
4897       case Sema::CXXInvalid:
4898         llvm_unreachable("invalid special member kind");
4899     }
4900 
4901     if (MD->getNumParams()) {
4902       ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4903       VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4904     }
4905   }
4906 
4907   bool inUnion() const { return MD->getParent()->isUnion(); }
4908 
4909   /// Look up the corresponding special member in the given class.
4910   Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4911                                               unsigned Quals) {
4912     unsigned TQ = MD->getTypeQualifiers();
4913     // cv-qualifiers on class members don't affect default ctor / dtor calls.
4914     if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4915       Quals = 0;
4916     // cv-qualifiers on class members affect the type of both '*this' and the
4917     // argument for an assignment.
4918     if (IsAssignment)
4919       TQ |= Quals;
4920     return S.LookupSpecialMember(Class, CSM,
4921                                  ConstArg || (Quals & Qualifiers::Const),
4922                                  VolatileArg || (Quals & Qualifiers::Volatile),
4923                                  MD->getRefQualifier() == RQ_RValue,
4924                                  TQ & Qualifiers::Const,
4925                                  TQ & Qualifiers::Volatile);
4926   }
4927 
4928   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
4929 
4930   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
4931   bool shouldDeleteForField(FieldDecl *FD);
4932   bool shouldDeleteForAllConstMembers();
4933 
4934   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4935                                      unsigned Quals);
4936   bool shouldDeleteForSubobjectCall(Subobject Subobj,
4937                                     Sema::SpecialMemberOverloadResult *SMOR,
4938                                     bool IsDtorCallInCtor);
4939 
4940   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
4941 };
4942 }
4943 
4944 /// Is the given special member inaccessible when used on the given
4945 /// sub-object.
4946 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4947                                              CXXMethodDecl *target) {
4948   /// If we're operating on a base class, the object type is the
4949   /// type of this special member.
4950   QualType objectTy;
4951   AccessSpecifier access = target->getAccess();
4952   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4953     objectTy = S.Context.getTypeDeclType(MD->getParent());
4954     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4955 
4956   // If we're operating on a field, the object type is the type of the field.
4957   } else {
4958     objectTy = S.Context.getTypeDeclType(target->getParent());
4959   }
4960 
4961   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4962 }
4963 
4964 /// Check whether we should delete a special member due to the implicit
4965 /// definition containing a call to a special member of a subobject.
4966 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4967     Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4968     bool IsDtorCallInCtor) {
4969   CXXMethodDecl *Decl = SMOR->getMethod();
4970   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4971 
4972   int DiagKind = -1;
4973 
4974   if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4975     DiagKind = !Decl ? 0 : 1;
4976   else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4977     DiagKind = 2;
4978   else if (!isAccessible(Subobj, Decl))
4979     DiagKind = 3;
4980   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4981            !Decl->isTrivial()) {
4982     // A member of a union must have a trivial corresponding special member.
4983     // As a weird special case, a destructor call from a union's constructor
4984     // must be accessible and non-deleted, but need not be trivial. Such a
4985     // destructor is never actually called, but is semantically checked as
4986     // if it were.
4987     DiagKind = 4;
4988   }
4989 
4990   if (DiagKind == -1)
4991     return false;
4992 
4993   if (Diagnose) {
4994     if (Field) {
4995       S.Diag(Field->getLocation(),
4996              diag::note_deleted_special_member_class_subobject)
4997         << CSM << MD->getParent() << /*IsField*/true
4998         << Field << DiagKind << IsDtorCallInCtor;
4999     } else {
5000       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5001       S.Diag(Base->getLocStart(),
5002              diag::note_deleted_special_member_class_subobject)
5003         << CSM << MD->getParent() << /*IsField*/false
5004         << Base->getType() << DiagKind << IsDtorCallInCtor;
5005     }
5006 
5007     if (DiagKind == 1)
5008       S.NoteDeletedFunction(Decl);
5009     // FIXME: Explain inaccessibility if DiagKind == 3.
5010   }
5011 
5012   return true;
5013 }
5014 
5015 /// Check whether we should delete a special member function due to having a
5016 /// direct or virtual base class or non-static data member of class type M.
5017 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
5018     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
5019   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5020 
5021   // C++11 [class.ctor]p5:
5022   // -- any direct or virtual base class, or non-static data member with no
5023   //    brace-or-equal-initializer, has class type M (or array thereof) and
5024   //    either M has no default constructor or overload resolution as applied
5025   //    to M's default constructor results in an ambiguity or in a function
5026   //    that is deleted or inaccessible
5027   // C++11 [class.copy]p11, C++11 [class.copy]p23:
5028   // -- a direct or virtual base class B that cannot be copied/moved because
5029   //    overload resolution, as applied to B's corresponding special member,
5030   //    results in an ambiguity or a function that is deleted or inaccessible
5031   //    from the defaulted special member
5032   // C++11 [class.dtor]p5:
5033   // -- any direct or virtual base class [...] has a type with a destructor
5034   //    that is deleted or inaccessible
5035   if (!(CSM == Sema::CXXDefaultConstructor &&
5036         Field && Field->hasInClassInitializer()) &&
5037       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
5038     return true;
5039 
5040   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5041   // -- any direct or virtual base class or non-static data member has a
5042   //    type with a destructor that is deleted or inaccessible
5043   if (IsConstructor) {
5044     Sema::SpecialMemberOverloadResult *SMOR =
5045         S.LookupSpecialMember(Class, Sema::CXXDestructor,
5046                               false, false, false, false, false);
5047     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5048       return true;
5049   }
5050 
5051   return false;
5052 }
5053 
5054 /// Check whether we should delete a special member function due to the class
5055 /// having a particular direct or virtual base class.
5056 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
5057   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
5058   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
5059 }
5060 
5061 /// Check whether we should delete a special member function due to the class
5062 /// having a particular non-static data member.
5063 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5064   QualType FieldType = S.Context.getBaseElementType(FD->getType());
5065   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5066 
5067   if (CSM == Sema::CXXDefaultConstructor) {
5068     // For a default constructor, all references must be initialized in-class
5069     // and, if a union, it must have a non-const member.
5070     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5071       if (Diagnose)
5072         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5073           << MD->getParent() << FD << FieldType << /*Reference*/0;
5074       return true;
5075     }
5076     // C++11 [class.ctor]p5: any non-variant non-static data member of
5077     // const-qualified type (or array thereof) with no
5078     // brace-or-equal-initializer does not have a user-provided default
5079     // constructor.
5080     if (!inUnion() && FieldType.isConstQualified() &&
5081         !FD->hasInClassInitializer() &&
5082         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5083       if (Diagnose)
5084         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5085           << MD->getParent() << FD << FD->getType() << /*Const*/1;
5086       return true;
5087     }
5088 
5089     if (inUnion() && !FieldType.isConstQualified())
5090       AllFieldsAreConst = false;
5091   } else if (CSM == Sema::CXXCopyConstructor) {
5092     // For a copy constructor, data members must not be of rvalue reference
5093     // type.
5094     if (FieldType->isRValueReferenceType()) {
5095       if (Diagnose)
5096         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5097           << MD->getParent() << FD << FieldType;
5098       return true;
5099     }
5100   } else if (IsAssignment) {
5101     // For an assignment operator, data members must not be of reference type.
5102     if (FieldType->isReferenceType()) {
5103       if (Diagnose)
5104         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5105           << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
5106       return true;
5107     }
5108     if (!FieldRecord && FieldType.isConstQualified()) {
5109       // C++11 [class.copy]p23:
5110       // -- a non-static data member of const non-class type (or array thereof)
5111       if (Diagnose)
5112         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5113           << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
5114       return true;
5115     }
5116   }
5117 
5118   if (FieldRecord) {
5119     // Some additional restrictions exist on the variant members.
5120     if (!inUnion() && FieldRecord->isUnion() &&
5121         FieldRecord->isAnonymousStructOrUnion()) {
5122       bool AllVariantFieldsAreConst = true;
5123 
5124       // FIXME: Handle anonymous unions declared within anonymous unions.
5125       for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
5126                                          UE = FieldRecord->field_end();
5127            UI != UE; ++UI) {
5128         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
5129 
5130         if (!UnionFieldType.isConstQualified())
5131           AllVariantFieldsAreConst = false;
5132 
5133         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5134         if (UnionFieldRecord &&
5135             shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
5136                                           UnionFieldType.getCVRQualifiers()))
5137           return true;
5138       }
5139 
5140       // At least one member in each anonymous union must be non-const
5141       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
5142           FieldRecord->field_begin() != FieldRecord->field_end()) {
5143         if (Diagnose)
5144           S.Diag(FieldRecord->getLocation(),
5145                  diag::note_deleted_default_ctor_all_const)
5146             << MD->getParent() << /*anonymous union*/1;
5147         return true;
5148       }
5149 
5150       // Don't check the implicit member of the anonymous union type.
5151       // This is technically non-conformant, but sanity demands it.
5152       return false;
5153     }
5154 
5155     if (shouldDeleteForClassSubobject(FieldRecord, FD,
5156                                       FieldType.getCVRQualifiers()))
5157       return true;
5158   }
5159 
5160   return false;
5161 }
5162 
5163 /// C++11 [class.ctor] p5:
5164 ///   A defaulted default constructor for a class X is defined as deleted if
5165 /// X is a union and all of its variant members are of const-qualified type.
5166 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
5167   // This is a silly definition, because it gives an empty union a deleted
5168   // default constructor. Don't do that.
5169   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5170       (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
5171     if (Diagnose)
5172       S.Diag(MD->getParent()->getLocation(),
5173              diag::note_deleted_default_ctor_all_const)
5174         << MD->getParent() << /*not anonymous union*/0;
5175     return true;
5176   }
5177   return false;
5178 }
5179 
5180 /// Determine whether a defaulted special member function should be defined as
5181 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5182 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
5183 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5184                                      bool Diagnose) {
5185   if (MD->isInvalidDecl())
5186     return false;
5187   CXXRecordDecl *RD = MD->getParent();
5188   assert(!RD->isDependentType() && "do deletion after instantiation");
5189   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
5190     return false;
5191 
5192   // C++11 [expr.lambda.prim]p19:
5193   //   The closure type associated with a lambda-expression has a
5194   //   deleted (8.4.3) default constructor and a deleted copy
5195   //   assignment operator.
5196   if (RD->isLambda() &&
5197       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5198     if (Diagnose)
5199       Diag(RD->getLocation(), diag::note_lambda_decl);
5200     return true;
5201   }
5202 
5203   // For an anonymous struct or union, the copy and assignment special members
5204   // will never be used, so skip the check. For an anonymous union declared at
5205   // namespace scope, the constructor and destructor are used.
5206   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5207       RD->isAnonymousStructOrUnion())
5208     return false;
5209 
5210   // C++11 [class.copy]p7, p18:
5211   //   If the class definition declares a move constructor or move assignment
5212   //   operator, an implicitly declared copy constructor or copy assignment
5213   //   operator is defined as deleted.
5214   if (MD->isImplicit() &&
5215       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5216     CXXMethodDecl *UserDeclaredMove = 0;
5217 
5218     // In Microsoft mode, a user-declared move only causes the deletion of the
5219     // corresponding copy operation, not both copy operations.
5220     if (RD->hasUserDeclaredMoveConstructor() &&
5221         (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
5222       if (!Diagnose) return true;
5223 
5224       // Find any user-declared move constructor.
5225       for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
5226                                         E = RD->ctor_end(); I != E; ++I) {
5227         if (I->isMoveConstructor()) {
5228           UserDeclaredMove = *I;
5229           break;
5230         }
5231       }
5232       assert(UserDeclaredMove);
5233     } else if (RD->hasUserDeclaredMoveAssignment() &&
5234                (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
5235       if (!Diagnose) return true;
5236 
5237       // Find any user-declared move assignment operator.
5238       for (CXXRecordDecl::method_iterator I = RD->method_begin(),
5239                                           E = RD->method_end(); I != E; ++I) {
5240         if (I->isMoveAssignmentOperator()) {
5241           UserDeclaredMove = *I;
5242           break;
5243         }
5244       }
5245       assert(UserDeclaredMove);
5246     }
5247 
5248     if (UserDeclaredMove) {
5249       Diag(UserDeclaredMove->getLocation(),
5250            diag::note_deleted_copy_user_declared_move)
5251         << (CSM == CXXCopyAssignment) << RD
5252         << UserDeclaredMove->isMoveAssignmentOperator();
5253       return true;
5254     }
5255   }
5256 
5257   // Do access control from the special member function
5258   ContextRAII MethodContext(*this, MD);
5259 
5260   // C++11 [class.dtor]p5:
5261   // -- for a virtual destructor, lookup of the non-array deallocation function
5262   //    results in an ambiguity or in a function that is deleted or inaccessible
5263   if (CSM == CXXDestructor && MD->isVirtual()) {
5264     FunctionDecl *OperatorDelete = 0;
5265     DeclarationName Name =
5266       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5267     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
5268                                  OperatorDelete, false)) {
5269       if (Diagnose)
5270         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
5271       return true;
5272     }
5273   }
5274 
5275   SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
5276 
5277   for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5278                                           BE = RD->bases_end(); BI != BE; ++BI)
5279     if (!BI->isVirtual() &&
5280         SMI.shouldDeleteForBase(BI))
5281       return true;
5282 
5283   // Per DR1611, do not consider virtual bases of constructors of abstract
5284   // classes, since we are not going to construct them.
5285   if (!RD->isAbstract() || !SMI.IsConstructor) {
5286     for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
5287                                             BE = RD->vbases_end();
5288          BI != BE; ++BI)
5289       if (SMI.shouldDeleteForBase(BI))
5290         return true;
5291   }
5292 
5293   for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5294                                      FE = RD->field_end(); FI != FE; ++FI)
5295     if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
5296         SMI.shouldDeleteForField(*FI))
5297       return true;
5298 
5299   if (SMI.shouldDeleteForAllConstMembers())
5300     return true;
5301 
5302   return false;
5303 }
5304 
5305 /// Perform lookup for a special member of the specified kind, and determine
5306 /// whether it is trivial. If the triviality can be determined without the
5307 /// lookup, skip it. This is intended for use when determining whether a
5308 /// special member of a containing object is trivial, and thus does not ever
5309 /// perform overload resolution for default constructors.
5310 ///
5311 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5312 /// member that was most likely to be intended to be trivial, if any.
5313 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5314                                      Sema::CXXSpecialMember CSM, unsigned Quals,
5315                                      CXXMethodDecl **Selected) {
5316   if (Selected)
5317     *Selected = 0;
5318 
5319   switch (CSM) {
5320   case Sema::CXXInvalid:
5321     llvm_unreachable("not a special member");
5322 
5323   case Sema::CXXDefaultConstructor:
5324     // C++11 [class.ctor]p5:
5325     //   A default constructor is trivial if:
5326     //    - all the [direct subobjects] have trivial default constructors
5327     //
5328     // Note, no overload resolution is performed in this case.
5329     if (RD->hasTrivialDefaultConstructor())
5330       return true;
5331 
5332     if (Selected) {
5333       // If there's a default constructor which could have been trivial, dig it
5334       // out. Otherwise, if there's any user-provided default constructor, point
5335       // to that as an example of why there's not a trivial one.
5336       CXXConstructorDecl *DefCtor = 0;
5337       if (RD->needsImplicitDefaultConstructor())
5338         S.DeclareImplicitDefaultConstructor(RD);
5339       for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
5340                                         CE = RD->ctor_end(); CI != CE; ++CI) {
5341         if (!CI->isDefaultConstructor())
5342           continue;
5343         DefCtor = *CI;
5344         if (!DefCtor->isUserProvided())
5345           break;
5346       }
5347 
5348       *Selected = DefCtor;
5349     }
5350 
5351     return false;
5352 
5353   case Sema::CXXDestructor:
5354     // C++11 [class.dtor]p5:
5355     //   A destructor is trivial if:
5356     //    - all the direct [subobjects] have trivial destructors
5357     if (RD->hasTrivialDestructor())
5358       return true;
5359 
5360     if (Selected) {
5361       if (RD->needsImplicitDestructor())
5362         S.DeclareImplicitDestructor(RD);
5363       *Selected = RD->getDestructor();
5364     }
5365 
5366     return false;
5367 
5368   case Sema::CXXCopyConstructor:
5369     // C++11 [class.copy]p12:
5370     //   A copy constructor is trivial if:
5371     //    - the constructor selected to copy each direct [subobject] is trivial
5372     if (RD->hasTrivialCopyConstructor()) {
5373       if (Quals == Qualifiers::Const)
5374         // We must either select the trivial copy constructor or reach an
5375         // ambiguity; no need to actually perform overload resolution.
5376         return true;
5377     } else if (!Selected) {
5378       return false;
5379     }
5380     // In C++98, we are not supposed to perform overload resolution here, but we
5381     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5382     // cases like B as having a non-trivial copy constructor:
5383     //   struct A { template<typename T> A(T&); };
5384     //   struct B { mutable A a; };
5385     goto NeedOverloadResolution;
5386 
5387   case Sema::CXXCopyAssignment:
5388     // C++11 [class.copy]p25:
5389     //   A copy assignment operator is trivial if:
5390     //    - the assignment operator selected to copy each direct [subobject] is
5391     //      trivial
5392     if (RD->hasTrivialCopyAssignment()) {
5393       if (Quals == Qualifiers::Const)
5394         return true;
5395     } else if (!Selected) {
5396       return false;
5397     }
5398     // In C++98, we are not supposed to perform overload resolution here, but we
5399     // treat that as a language defect.
5400     goto NeedOverloadResolution;
5401 
5402   case Sema::CXXMoveConstructor:
5403   case Sema::CXXMoveAssignment:
5404   NeedOverloadResolution:
5405     Sema::SpecialMemberOverloadResult *SMOR =
5406       S.LookupSpecialMember(RD, CSM,
5407                             Quals & Qualifiers::Const,
5408                             Quals & Qualifiers::Volatile,
5409                             /*RValueThis*/false, /*ConstThis*/false,
5410                             /*VolatileThis*/false);
5411 
5412     // The standard doesn't describe how to behave if the lookup is ambiguous.
5413     // We treat it as not making the member non-trivial, just like the standard
5414     // mandates for the default constructor. This should rarely matter, because
5415     // the member will also be deleted.
5416     if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5417       return true;
5418 
5419     if (!SMOR->getMethod()) {
5420       assert(SMOR->getKind() ==
5421              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5422       return false;
5423     }
5424 
5425     // We deliberately don't check if we found a deleted special member. We're
5426     // not supposed to!
5427     if (Selected)
5428       *Selected = SMOR->getMethod();
5429     return SMOR->getMethod()->isTrivial();
5430   }
5431 
5432   llvm_unreachable("unknown special method kind");
5433 }
5434 
5435 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
5436   for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5437        CI != CE; ++CI)
5438     if (!CI->isImplicit())
5439       return *CI;
5440 
5441   // Look for constructor templates.
5442   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5443   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5444     if (CXXConstructorDecl *CD =
5445           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5446       return CD;
5447   }
5448 
5449   return 0;
5450 }
5451 
5452 /// The kind of subobject we are checking for triviality. The values of this
5453 /// enumeration are used in diagnostics.
5454 enum TrivialSubobjectKind {
5455   /// The subobject is a base class.
5456   TSK_BaseClass,
5457   /// The subobject is a non-static data member.
5458   TSK_Field,
5459   /// The object is actually the complete object.
5460   TSK_CompleteObject
5461 };
5462 
5463 /// Check whether the special member selected for a given type would be trivial.
5464 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5465                                       QualType SubType,
5466                                       Sema::CXXSpecialMember CSM,
5467                                       TrivialSubobjectKind Kind,
5468                                       bool Diagnose) {
5469   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5470   if (!SubRD)
5471     return true;
5472 
5473   CXXMethodDecl *Selected;
5474   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5475                                Diagnose ? &Selected : 0))
5476     return true;
5477 
5478   if (Diagnose) {
5479     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5480       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5481         << Kind << SubType.getUnqualifiedType();
5482       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5483         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5484     } else if (!Selected)
5485       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5486         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5487     else if (Selected->isUserProvided()) {
5488       if (Kind == TSK_CompleteObject)
5489         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5490           << Kind << SubType.getUnqualifiedType() << CSM;
5491       else {
5492         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5493           << Kind << SubType.getUnqualifiedType() << CSM;
5494         S.Diag(Selected->getLocation(), diag::note_declared_at);
5495       }
5496     } else {
5497       if (Kind != TSK_CompleteObject)
5498         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5499           << Kind << SubType.getUnqualifiedType() << CSM;
5500 
5501       // Explain why the defaulted or deleted special member isn't trivial.
5502       S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5503     }
5504   }
5505 
5506   return false;
5507 }
5508 
5509 /// Check whether the members of a class type allow a special member to be
5510 /// trivial.
5511 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5512                                      Sema::CXXSpecialMember CSM,
5513                                      bool ConstArg, bool Diagnose) {
5514   for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5515                                      FE = RD->field_end(); FI != FE; ++FI) {
5516     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5517       continue;
5518 
5519     QualType FieldType = S.Context.getBaseElementType(FI->getType());
5520 
5521     // Pretend anonymous struct or union members are members of this class.
5522     if (FI->isAnonymousStructOrUnion()) {
5523       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5524                                     CSM, ConstArg, Diagnose))
5525         return false;
5526       continue;
5527     }
5528 
5529     // C++11 [class.ctor]p5:
5530     //   A default constructor is trivial if [...]
5531     //    -- no non-static data member of its class has a
5532     //       brace-or-equal-initializer
5533     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5534       if (Diagnose)
5535         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5536       return false;
5537     }
5538 
5539     // Objective C ARC 4.3.5:
5540     //   [...] nontrivally ownership-qualified types are [...] not trivially
5541     //   default constructible, copy constructible, move constructible, copy
5542     //   assignable, move assignable, or destructible [...]
5543     if (S.getLangOpts().ObjCAutoRefCount &&
5544         FieldType.hasNonTrivialObjCLifetime()) {
5545       if (Diagnose)
5546         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5547           << RD << FieldType.getObjCLifetime();
5548       return false;
5549     }
5550 
5551     if (ConstArg && !FI->isMutable())
5552       FieldType.addConst();
5553     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5554                                    TSK_Field, Diagnose))
5555       return false;
5556   }
5557 
5558   return true;
5559 }
5560 
5561 /// Diagnose why the specified class does not have a trivial special member of
5562 /// the given kind.
5563 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5564   QualType Ty = Context.getRecordType(RD);
5565   if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5566     Ty.addConst();
5567 
5568   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5569                             TSK_CompleteObject, /*Diagnose*/true);
5570 }
5571 
5572 /// Determine whether a defaulted or deleted special member function is trivial,
5573 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5574 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5575 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5576                                   bool Diagnose) {
5577   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5578 
5579   CXXRecordDecl *RD = MD->getParent();
5580 
5581   bool ConstArg = false;
5582 
5583   // C++11 [class.copy]p12, p25: [DR1593]
5584   //   A [special member] is trivial if [...] its parameter-type-list is
5585   //   equivalent to the parameter-type-list of an implicit declaration [...]
5586   switch (CSM) {
5587   case CXXDefaultConstructor:
5588   case CXXDestructor:
5589     // Trivial default constructors and destructors cannot have parameters.
5590     break;
5591 
5592   case CXXCopyConstructor:
5593   case CXXCopyAssignment: {
5594     // Trivial copy operations always have const, non-volatile parameter types.
5595     ConstArg = true;
5596     const ParmVarDecl *Param0 = MD->getParamDecl(0);
5597     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5598     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5599       if (Diagnose)
5600         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5601           << Param0->getSourceRange() << Param0->getType()
5602           << Context.getLValueReferenceType(
5603                Context.getRecordType(RD).withConst());
5604       return false;
5605     }
5606     break;
5607   }
5608 
5609   case CXXMoveConstructor:
5610   case CXXMoveAssignment: {
5611     // Trivial move operations always have non-cv-qualified parameters.
5612     const ParmVarDecl *Param0 = MD->getParamDecl(0);
5613     const RValueReferenceType *RT =
5614       Param0->getType()->getAs<RValueReferenceType>();
5615     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5616       if (Diagnose)
5617         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5618           << Param0->getSourceRange() << Param0->getType()
5619           << Context.getRValueReferenceType(Context.getRecordType(RD));
5620       return false;
5621     }
5622     break;
5623   }
5624 
5625   case CXXInvalid:
5626     llvm_unreachable("not a special member");
5627   }
5628 
5629   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5630     if (Diagnose)
5631       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5632            diag::note_nontrivial_default_arg)
5633         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5634     return false;
5635   }
5636   if (MD->isVariadic()) {
5637     if (Diagnose)
5638       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5639     return false;
5640   }
5641 
5642   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5643   //   A copy/move [constructor or assignment operator] is trivial if
5644   //    -- the [member] selected to copy/move each direct base class subobject
5645   //       is trivial
5646   //
5647   // C++11 [class.copy]p12, C++11 [class.copy]p25:
5648   //   A [default constructor or destructor] is trivial if
5649   //    -- all the direct base classes have trivial [default constructors or
5650   //       destructors]
5651   for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5652                                           BE = RD->bases_end(); BI != BE; ++BI)
5653     if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5654                                    ConstArg ? BI->getType().withConst()
5655                                             : BI->getType(),
5656                                    CSM, TSK_BaseClass, Diagnose))
5657       return false;
5658 
5659   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5660   //   A copy/move [constructor or assignment operator] for a class X is
5661   //   trivial if
5662   //    -- for each non-static data member of X that is of class type (or array
5663   //       thereof), the constructor selected to copy/move that member is
5664   //       trivial
5665   //
5666   // C++11 [class.copy]p12, C++11 [class.copy]p25:
5667   //   A [default constructor or destructor] is trivial if
5668   //    -- for all of the non-static data members of its class that are of class
5669   //       type (or array thereof), each such class has a trivial [default
5670   //       constructor or destructor]
5671   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5672     return false;
5673 
5674   // C++11 [class.dtor]p5:
5675   //   A destructor is trivial if [...]
5676   //    -- the destructor is not virtual
5677   if (CSM == CXXDestructor && MD->isVirtual()) {
5678     if (Diagnose)
5679       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5680     return false;
5681   }
5682 
5683   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5684   //   A [special member] for class X is trivial if [...]
5685   //    -- class X has no virtual functions and no virtual base classes
5686   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5687     if (!Diagnose)
5688       return false;
5689 
5690     if (RD->getNumVBases()) {
5691       // Check for virtual bases. We already know that the corresponding
5692       // member in all bases is trivial, so vbases must all be direct.
5693       CXXBaseSpecifier &BS = *RD->vbases_begin();
5694       assert(BS.isVirtual());
5695       Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5696       return false;
5697     }
5698 
5699     // Must have a virtual method.
5700     for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5701                                         ME = RD->method_end(); MI != ME; ++MI) {
5702       if (MI->isVirtual()) {
5703         SourceLocation MLoc = MI->getLocStart();
5704         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5705         return false;
5706       }
5707     }
5708 
5709     llvm_unreachable("dynamic class with no vbases and no virtual functions");
5710   }
5711 
5712   // Looks like it's trivial!
5713   return true;
5714 }
5715 
5716 /// \brief Data used with FindHiddenVirtualMethod
5717 namespace {
5718   struct FindHiddenVirtualMethodData {
5719     Sema *S;
5720     CXXMethodDecl *Method;
5721     llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
5722     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5723   };
5724 }
5725 
5726 /// \brief Check whether any most overriden method from MD in Methods
5727 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5728                    const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5729   if (MD->size_overridden_methods() == 0)
5730     return Methods.count(MD->getCanonicalDecl());
5731   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5732                                       E = MD->end_overridden_methods();
5733        I != E; ++I)
5734     if (CheckMostOverridenMethods(*I, Methods))
5735       return true;
5736   return false;
5737 }
5738 
5739 /// \brief Member lookup function that determines whether a given C++
5740 /// method overloads virtual methods in a base class without overriding any,
5741 /// to be used with CXXRecordDecl::lookupInBases().
5742 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5743                                     CXXBasePath &Path,
5744                                     void *UserData) {
5745   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5746 
5747   FindHiddenVirtualMethodData &Data
5748     = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5749 
5750   DeclarationName Name = Data.Method->getDeclName();
5751   assert(Name.getNameKind() == DeclarationName::Identifier);
5752 
5753   bool foundSameNameMethod = false;
5754   SmallVector<CXXMethodDecl *, 8> overloadedMethods;
5755   for (Path.Decls = BaseRecord->lookup(Name);
5756        !Path.Decls.empty();
5757        Path.Decls = Path.Decls.slice(1)) {
5758     NamedDecl *D = Path.Decls.front();
5759     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5760       MD = MD->getCanonicalDecl();
5761       foundSameNameMethod = true;
5762       // Interested only in hidden virtual methods.
5763       if (!MD->isVirtual())
5764         continue;
5765       // If the method we are checking overrides a method from its base
5766       // don't warn about the other overloaded methods.
5767       if (!Data.S->IsOverload(Data.Method, MD, false))
5768         return true;
5769       // Collect the overload only if its hidden.
5770       if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
5771         overloadedMethods.push_back(MD);
5772     }
5773   }
5774 
5775   if (foundSameNameMethod)
5776     Data.OverloadedMethods.append(overloadedMethods.begin(),
5777                                    overloadedMethods.end());
5778   return foundSameNameMethod;
5779 }
5780 
5781 /// \brief Add the most overriden methods from MD to Methods
5782 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5783                          llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5784   if (MD->size_overridden_methods() == 0)
5785     Methods.insert(MD->getCanonicalDecl());
5786   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5787                                       E = MD->end_overridden_methods();
5788        I != E; ++I)
5789     AddMostOverridenMethods(*I, Methods);
5790 }
5791 
5792 /// \brief Check if a method overloads virtual methods in a base class without
5793 /// overriding any.
5794 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
5795                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
5796   if (!MD->getDeclName().isIdentifier())
5797     return;
5798 
5799   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5800                      /*bool RecordPaths=*/false,
5801                      /*bool DetectVirtual=*/false);
5802   FindHiddenVirtualMethodData Data;
5803   Data.Method = MD;
5804   Data.S = this;
5805 
5806   // Keep the base methods that were overriden or introduced in the subclass
5807   // by 'using' in a set. A base method not in this set is hidden.
5808   CXXRecordDecl *DC = MD->getParent();
5809   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5810   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5811     NamedDecl *ND = *I;
5812     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
5813       ND = shad->getTargetDecl();
5814     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5815       AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
5816   }
5817 
5818   if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
5819     OverloadedMethods = Data.OverloadedMethods;
5820 }
5821 
5822 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
5823                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
5824   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
5825     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
5826     PartialDiagnostic PD = PDiag(
5827          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5828     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5829     Diag(overloadedMD->getLocation(), PD);
5830   }
5831 }
5832 
5833 /// \brief Diagnose methods which overload virtual methods in a base class
5834 /// without overriding any.
5835 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
5836   if (MD->isInvalidDecl())
5837     return;
5838 
5839   if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
5840                                MD->getLocation()) == DiagnosticsEngine::Ignored)
5841     return;
5842 
5843   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5844   FindHiddenVirtualMethods(MD, OverloadedMethods);
5845   if (!OverloadedMethods.empty()) {
5846     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5847       << MD << (OverloadedMethods.size() > 1);
5848 
5849     NoteHiddenVirtualMethods(MD, OverloadedMethods);
5850   }
5851 }
5852 
5853 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5854                                              Decl *TagDecl,
5855                                              SourceLocation LBrac,
5856                                              SourceLocation RBrac,
5857                                              AttributeList *AttrList) {
5858   if (!TagDecl)
5859     return;
5860 
5861   AdjustDeclIfTemplate(TagDecl);
5862 
5863   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5864     if (l->getKind() != AttributeList::AT_Visibility)
5865       continue;
5866     l->setInvalid();
5867     Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5868       l->getName();
5869   }
5870 
5871   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
5872               // strict aliasing violation!
5873               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
5874               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
5875 
5876   CheckCompletedCXXClass(
5877                         dyn_cast_or_null<CXXRecordDecl>(TagDecl));
5878 }
5879 
5880 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5881 /// special functions, such as the default constructor, copy
5882 /// constructor, or destructor, to the given C++ class (C++
5883 /// [special]p1).  This routine can only be executed just before the
5884 /// definition of the class is complete.
5885 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
5886   if (!ClassDecl->hasUserDeclaredConstructor())
5887     ++ASTContext::NumImplicitDefaultConstructors;
5888 
5889   if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
5890     ++ASTContext::NumImplicitCopyConstructors;
5891 
5892     // If the properties or semantics of the copy constructor couldn't be
5893     // determined while the class was being declared, force a declaration
5894     // of it now.
5895     if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5896       DeclareImplicitCopyConstructor(ClassDecl);
5897   }
5898 
5899   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
5900     ++ASTContext::NumImplicitMoveConstructors;
5901 
5902     if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5903       DeclareImplicitMoveConstructor(ClassDecl);
5904   }
5905 
5906   if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5907     ++ASTContext::NumImplicitCopyAssignmentOperators;
5908 
5909     // If we have a dynamic class, then the copy assignment operator may be
5910     // virtual, so we have to declare it immediately. This ensures that, e.g.,
5911     // it shows up in the right place in the vtable and that we diagnose
5912     // problems with the implicit exception specification.
5913     if (ClassDecl->isDynamicClass() ||
5914         ClassDecl->needsOverloadResolutionForCopyAssignment())
5915       DeclareImplicitCopyAssignment(ClassDecl);
5916   }
5917 
5918   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
5919     ++ASTContext::NumImplicitMoveAssignmentOperators;
5920 
5921     // Likewise for the move assignment operator.
5922     if (ClassDecl->isDynamicClass() ||
5923         ClassDecl->needsOverloadResolutionForMoveAssignment())
5924       DeclareImplicitMoveAssignment(ClassDecl);
5925   }
5926 
5927   if (!ClassDecl->hasUserDeclaredDestructor()) {
5928     ++ASTContext::NumImplicitDestructors;
5929 
5930     // If we have a dynamic class, then the destructor may be virtual, so we
5931     // have to declare the destructor immediately. This ensures that, e.g., it
5932     // shows up in the right place in the vtable and that we diagnose problems
5933     // with the implicit exception specification.
5934     if (ClassDecl->isDynamicClass() ||
5935         ClassDecl->needsOverloadResolutionForDestructor())
5936       DeclareImplicitDestructor(ClassDecl);
5937   }
5938 }
5939 
5940 void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5941   if (!D)
5942     return;
5943 
5944   int NumParamList = D->getNumTemplateParameterLists();
5945   for (int i = 0; i < NumParamList; i++) {
5946     TemplateParameterList* Params = D->getTemplateParameterList(i);
5947     for (TemplateParameterList::iterator Param = Params->begin(),
5948                                       ParamEnd = Params->end();
5949           Param != ParamEnd; ++Param) {
5950       NamedDecl *Named = cast<NamedDecl>(*Param);
5951       if (Named->getDeclName()) {
5952         S->AddDecl(Named);
5953         IdResolver.AddDecl(Named);
5954       }
5955     }
5956   }
5957 }
5958 
5959 void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
5960   if (!D)
5961     return;
5962 
5963   TemplateParameterList *Params = 0;
5964   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5965     Params = Template->getTemplateParameters();
5966   else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5967            = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5968     Params = PartialSpec->getTemplateParameters();
5969   else
5970     return;
5971 
5972   for (TemplateParameterList::iterator Param = Params->begin(),
5973                                     ParamEnd = Params->end();
5974        Param != ParamEnd; ++Param) {
5975     NamedDecl *Named = cast<NamedDecl>(*Param);
5976     if (Named->getDeclName()) {
5977       S->AddDecl(Named);
5978       IdResolver.AddDecl(Named);
5979     }
5980   }
5981 }
5982 
5983 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
5984   if (!RecordD) return;
5985   AdjustDeclIfTemplate(RecordD);
5986   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
5987   PushDeclContext(S, Record);
5988 }
5989 
5990 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
5991   if (!RecordD) return;
5992   PopDeclContext();
5993 }
5994 
5995 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
5996 /// parsing a top-level (non-nested) C++ class, and we are now
5997 /// parsing those parts of the given Method declaration that could
5998 /// not be parsed earlier (C++ [class.mem]p2), such as default
5999 /// arguments. This action should enter the scope of the given
6000 /// Method declaration as if we had just parsed the qualified method
6001 /// name. However, it should not bring the parameters into scope;
6002 /// that will be performed by ActOnDelayedCXXMethodParameter.
6003 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6004 }
6005 
6006 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
6007 /// C++ method declaration. We're (re-)introducing the given
6008 /// function parameter into scope for use in parsing later parts of
6009 /// the method declaration. For example, we could see an
6010 /// ActOnParamDefaultArgument event for this parameter.
6011 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
6012   if (!ParamD)
6013     return;
6014 
6015   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
6016 
6017   // If this parameter has an unparsed default argument, clear it out
6018   // to make way for the parsed default argument.
6019   if (Param->hasUnparsedDefaultArg())
6020     Param->setDefaultArg(0);
6021 
6022   S->AddDecl(Param);
6023   if (Param->getDeclName())
6024     IdResolver.AddDecl(Param);
6025 }
6026 
6027 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6028 /// processing the delayed method declaration for Method. The method
6029 /// declaration is now considered finished. There may be a separate
6030 /// ActOnStartOfFunctionDef action later (not necessarily
6031 /// immediately!) for this method, if it was also defined inside the
6032 /// class body.
6033 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6034   if (!MethodD)
6035     return;
6036 
6037   AdjustDeclIfTemplate(MethodD);
6038 
6039   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
6040 
6041   // Now that we have our default arguments, check the constructor
6042   // again. It could produce additional diagnostics or affect whether
6043   // the class has implicitly-declared destructors, among other
6044   // things.
6045   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6046     CheckConstructor(Constructor);
6047 
6048   // Check the default arguments, which we may have added.
6049   if (!Method->isInvalidDecl())
6050     CheckCXXDefaultArguments(Method);
6051 }
6052 
6053 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
6054 /// the well-formedness of the constructor declarator @p D with type @p
6055 /// R. If there are any errors in the declarator, this routine will
6056 /// emit diagnostics and set the invalid bit to true.  In any case, the type
6057 /// will be updated to reflect a well-formed type for the constructor and
6058 /// returned.
6059 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
6060                                           StorageClass &SC) {
6061   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6062 
6063   // C++ [class.ctor]p3:
6064   //   A constructor shall not be virtual (10.3) or static (9.4). A
6065   //   constructor can be invoked for a const, volatile or const
6066   //   volatile object. A constructor shall not be declared const,
6067   //   volatile, or const volatile (9.3.2).
6068   if (isVirtual) {
6069     if (!D.isInvalidType())
6070       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6071         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6072         << SourceRange(D.getIdentifierLoc());
6073     D.setInvalidType();
6074   }
6075   if (SC == SC_Static) {
6076     if (!D.isInvalidType())
6077       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6078         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6079         << SourceRange(D.getIdentifierLoc());
6080     D.setInvalidType();
6081     SC = SC_None;
6082   }
6083 
6084   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6085   if (FTI.TypeQuals != 0) {
6086     if (FTI.TypeQuals & Qualifiers::Const)
6087       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6088         << "const" << SourceRange(D.getIdentifierLoc());
6089     if (FTI.TypeQuals & Qualifiers::Volatile)
6090       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6091         << "volatile" << SourceRange(D.getIdentifierLoc());
6092     if (FTI.TypeQuals & Qualifiers::Restrict)
6093       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6094         << "restrict" << SourceRange(D.getIdentifierLoc());
6095     D.setInvalidType();
6096   }
6097 
6098   // C++0x [class.ctor]p4:
6099   //   A constructor shall not be declared with a ref-qualifier.
6100   if (FTI.hasRefQualifier()) {
6101     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6102       << FTI.RefQualifierIsLValueRef
6103       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6104     D.setInvalidType();
6105   }
6106 
6107   // Rebuild the function type "R" without any type qualifiers (in
6108   // case any of the errors above fired) and with "void" as the
6109   // return type, since constructors don't have return types.
6110   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6111   if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
6112     return R;
6113 
6114   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6115   EPI.TypeQuals = 0;
6116   EPI.RefQualifier = RQ_None;
6117 
6118   return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
6119 }
6120 
6121 /// CheckConstructor - Checks a fully-formed constructor for
6122 /// well-formedness, issuing any diagnostics required. Returns true if
6123 /// the constructor declarator is invalid.
6124 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
6125   CXXRecordDecl *ClassDecl
6126     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6127   if (!ClassDecl)
6128     return Constructor->setInvalidDecl();
6129 
6130   // C++ [class.copy]p3:
6131   //   A declaration of a constructor for a class X is ill-formed if
6132   //   its first parameter is of type (optionally cv-qualified) X and
6133   //   either there are no other parameters or else all other
6134   //   parameters have default arguments.
6135   if (!Constructor->isInvalidDecl() &&
6136       ((Constructor->getNumParams() == 1) ||
6137        (Constructor->getNumParams() > 1 &&
6138         Constructor->getParamDecl(1)->hasDefaultArg())) &&
6139       Constructor->getTemplateSpecializationKind()
6140                                               != TSK_ImplicitInstantiation) {
6141     QualType ParamType = Constructor->getParamDecl(0)->getType();
6142     QualType ClassTy = Context.getTagDeclType(ClassDecl);
6143     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
6144       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
6145       const char *ConstRef
6146         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6147                                                         : " const &";
6148       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
6149         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
6150 
6151       // FIXME: Rather that making the constructor invalid, we should endeavor
6152       // to fix the type.
6153       Constructor->setInvalidDecl();
6154     }
6155   }
6156 }
6157 
6158 /// CheckDestructor - Checks a fully-formed destructor definition for
6159 /// well-formedness, issuing any diagnostics required.  Returns true
6160 /// on error.
6161 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
6162   CXXRecordDecl *RD = Destructor->getParent();
6163 
6164   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
6165     SourceLocation Loc;
6166 
6167     if (!Destructor->isImplicit())
6168       Loc = Destructor->getLocation();
6169     else
6170       Loc = RD->getLocation();
6171 
6172     // If we have a virtual destructor, look up the deallocation function
6173     FunctionDecl *OperatorDelete = 0;
6174     DeclarationName Name =
6175     Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6176     if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
6177       return true;
6178 
6179     MarkFunctionReferenced(Loc, OperatorDelete);
6180 
6181     Destructor->setOperatorDelete(OperatorDelete);
6182   }
6183 
6184   return false;
6185 }
6186 
6187 static inline bool
6188 FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
6189   return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
6190           FTI.ArgInfo[0].Param &&
6191           cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
6192 }
6193 
6194 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6195 /// the well-formednes of the destructor declarator @p D with type @p
6196 /// R. If there are any errors in the declarator, this routine will
6197 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
6198 /// will be updated to reflect a well-formed type for the destructor and
6199 /// returned.
6200 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
6201                                          StorageClass& SC) {
6202   // C++ [class.dtor]p1:
6203   //   [...] A typedef-name that names a class is a class-name
6204   //   (7.1.3); however, a typedef-name that names a class shall not
6205   //   be used as the identifier in the declarator for a destructor
6206   //   declaration.
6207   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
6208   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
6209     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6210       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
6211   else if (const TemplateSpecializationType *TST =
6212              DeclaratorType->getAs<TemplateSpecializationType>())
6213     if (TST->isTypeAlias())
6214       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6215         << DeclaratorType << 1;
6216 
6217   // C++ [class.dtor]p2:
6218   //   A destructor is used to destroy objects of its class type. A
6219   //   destructor takes no parameters, and no return type can be
6220   //   specified for it (not even void). The address of a destructor
6221   //   shall not be taken. A destructor shall not be static. A
6222   //   destructor can be invoked for a const, volatile or const
6223   //   volatile object. A destructor shall not be declared const,
6224   //   volatile or const volatile (9.3.2).
6225   if (SC == SC_Static) {
6226     if (!D.isInvalidType())
6227       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6228         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6229         << SourceRange(D.getIdentifierLoc())
6230         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6231 
6232     SC = SC_None;
6233   }
6234   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
6235     // Destructors don't have return types, but the parser will
6236     // happily parse something like:
6237     //
6238     //   class X {
6239     //     float ~X();
6240     //   };
6241     //
6242     // The return type will be eliminated later.
6243     Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6244       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6245       << SourceRange(D.getIdentifierLoc());
6246   }
6247 
6248   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6249   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
6250     if (FTI.TypeQuals & Qualifiers::Const)
6251       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6252         << "const" << SourceRange(D.getIdentifierLoc());
6253     if (FTI.TypeQuals & Qualifiers::Volatile)
6254       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6255         << "volatile" << SourceRange(D.getIdentifierLoc());
6256     if (FTI.TypeQuals & Qualifiers::Restrict)
6257       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6258         << "restrict" << SourceRange(D.getIdentifierLoc());
6259     D.setInvalidType();
6260   }
6261 
6262   // C++0x [class.dtor]p2:
6263   //   A destructor shall not be declared with a ref-qualifier.
6264   if (FTI.hasRefQualifier()) {
6265     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6266       << FTI.RefQualifierIsLValueRef
6267       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6268     D.setInvalidType();
6269   }
6270 
6271   // Make sure we don't have any parameters.
6272   if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
6273     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6274 
6275     // Delete the parameters.
6276     FTI.freeArgs();
6277     D.setInvalidType();
6278   }
6279 
6280   // Make sure the destructor isn't variadic.
6281   if (FTI.isVariadic) {
6282     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
6283     D.setInvalidType();
6284   }
6285 
6286   // Rebuild the function type "R" without any type qualifiers or
6287   // parameters (in case any of the errors above fired) and with
6288   // "void" as the return type, since destructors don't have return
6289   // types.
6290   if (!D.isInvalidType())
6291     return R;
6292 
6293   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6294   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6295   EPI.Variadic = false;
6296   EPI.TypeQuals = 0;
6297   EPI.RefQualifier = RQ_None;
6298   return Context.getFunctionType(Context.VoidTy, None, EPI);
6299 }
6300 
6301 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6302 /// well-formednes of the conversion function declarator @p D with
6303 /// type @p R. If there are any errors in the declarator, this routine
6304 /// will emit diagnostics and return true. Otherwise, it will return
6305 /// false. Either way, the type @p R will be updated to reflect a
6306 /// well-formed type for the conversion operator.
6307 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
6308                                      StorageClass& SC) {
6309   // C++ [class.conv.fct]p1:
6310   //   Neither parameter types nor return type can be specified. The
6311   //   type of a conversion function (8.3.5) is "function taking no
6312   //   parameter returning conversion-type-id."
6313   if (SC == SC_Static) {
6314     if (!D.isInvalidType())
6315       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
6316         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6317         << D.getName().getSourceRange();
6318     D.setInvalidType();
6319     SC = SC_None;
6320   }
6321 
6322   QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6323 
6324   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
6325     // Conversion functions don't have return types, but the parser will
6326     // happily parse something like:
6327     //
6328     //   class X {
6329     //     float operator bool();
6330     //   };
6331     //
6332     // The return type will be changed later anyway.
6333     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6334       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6335       << SourceRange(D.getIdentifierLoc());
6336     D.setInvalidType();
6337   }
6338 
6339   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6340 
6341   // Make sure we don't have any parameters.
6342   if (Proto->getNumArgs() > 0) {
6343     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6344 
6345     // Delete the parameters.
6346     D.getFunctionTypeInfo().freeArgs();
6347     D.setInvalidType();
6348   } else if (Proto->isVariadic()) {
6349     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
6350     D.setInvalidType();
6351   }
6352 
6353   // Diagnose "&operator bool()" and other such nonsense.  This
6354   // is actually a gcc extension which we don't support.
6355   if (Proto->getResultType() != ConvType) {
6356     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6357       << Proto->getResultType();
6358     D.setInvalidType();
6359     ConvType = Proto->getResultType();
6360   }
6361 
6362   // C++ [class.conv.fct]p4:
6363   //   The conversion-type-id shall not represent a function type nor
6364   //   an array type.
6365   if (ConvType->isArrayType()) {
6366     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6367     ConvType = Context.getPointerType(ConvType);
6368     D.setInvalidType();
6369   } else if (ConvType->isFunctionType()) {
6370     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6371     ConvType = Context.getPointerType(ConvType);
6372     D.setInvalidType();
6373   }
6374 
6375   // Rebuild the function type "R" without any parameters (in case any
6376   // of the errors above fired) and with the conversion type as the
6377   // return type.
6378   if (D.isInvalidType())
6379     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
6380 
6381   // C++0x explicit conversion operators.
6382   if (D.getDeclSpec().isExplicitSpecified())
6383     Diag(D.getDeclSpec().getExplicitSpecLoc(),
6384          getLangOpts().CPlusPlus11 ?
6385            diag::warn_cxx98_compat_explicit_conversion_functions :
6386            diag::ext_explicit_conversion_functions)
6387       << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
6388 }
6389 
6390 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6391 /// the declaration of the given C++ conversion function. This routine
6392 /// is responsible for recording the conversion function in the C++
6393 /// class, if possible.
6394 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
6395   assert(Conversion && "Expected to receive a conversion function declaration");
6396 
6397   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
6398 
6399   // Make sure we aren't redeclaring the conversion function.
6400   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
6401 
6402   // C++ [class.conv.fct]p1:
6403   //   [...] A conversion function is never used to convert a
6404   //   (possibly cv-qualified) object to the (possibly cv-qualified)
6405   //   same object type (or a reference to it), to a (possibly
6406   //   cv-qualified) base class of that type (or a reference to it),
6407   //   or to (possibly cv-qualified) void.
6408   // FIXME: Suppress this warning if the conversion function ends up being a
6409   // virtual function that overrides a virtual function in a base class.
6410   QualType ClassType
6411     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6412   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
6413     ConvType = ConvTypeRef->getPointeeType();
6414   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6415       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
6416     /* Suppress diagnostics for instantiations. */;
6417   else if (ConvType->isRecordType()) {
6418     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6419     if (ConvType == ClassType)
6420       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
6421         << ClassType;
6422     else if (IsDerivedFrom(ClassType, ConvType))
6423       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
6424         <<  ClassType << ConvType;
6425   } else if (ConvType->isVoidType()) {
6426     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
6427       << ClassType << ConvType;
6428   }
6429 
6430   if (FunctionTemplateDecl *ConversionTemplate
6431                                 = Conversion->getDescribedFunctionTemplate())
6432     return ConversionTemplate;
6433 
6434   return Conversion;
6435 }
6436 
6437 //===----------------------------------------------------------------------===//
6438 // Namespace Handling
6439 //===----------------------------------------------------------------------===//
6440 
6441 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6442 /// reopened.
6443 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6444                                             SourceLocation Loc,
6445                                             IdentifierInfo *II, bool *IsInline,
6446                                             NamespaceDecl *PrevNS) {
6447   assert(*IsInline != PrevNS->isInline());
6448 
6449   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6450   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6451   // inline namespaces, with the intention of bringing names into namespace std.
6452   //
6453   // We support this just well enough to get that case working; this is not
6454   // sufficient to support reopening namespaces as inline in general.
6455   if (*IsInline && II && II->getName().startswith("__atomic") &&
6456       S.getSourceManager().isInSystemHeader(Loc)) {
6457     // Mark all prior declarations of the namespace as inline.
6458     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6459          NS = NS->getPreviousDecl())
6460       NS->setInline(*IsInline);
6461     // Patch up the lookup table for the containing namespace. This isn't really
6462     // correct, but it's good enough for this particular case.
6463     for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6464                                     E = PrevNS->decls_end(); I != E; ++I)
6465       if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6466         PrevNS->getParent()->makeDeclVisibleInContext(ND);
6467     return;
6468   }
6469 
6470   if (PrevNS->isInline())
6471     // The user probably just forgot the 'inline', so suggest that it
6472     // be added back.
6473     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6474       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6475   else
6476     S.Diag(Loc, diag::err_inline_namespace_mismatch)
6477       << IsInline;
6478 
6479   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6480   *IsInline = PrevNS->isInline();
6481 }
6482 
6483 /// ActOnStartNamespaceDef - This is called at the start of a namespace
6484 /// definition.
6485 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
6486                                    SourceLocation InlineLoc,
6487                                    SourceLocation NamespaceLoc,
6488                                    SourceLocation IdentLoc,
6489                                    IdentifierInfo *II,
6490                                    SourceLocation LBrace,
6491                                    AttributeList *AttrList) {
6492   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6493   // For anonymous namespace, take the location of the left brace.
6494   SourceLocation Loc = II ? IdentLoc : LBrace;
6495   bool IsInline = InlineLoc.isValid();
6496   bool IsInvalid = false;
6497   bool IsStd = false;
6498   bool AddToKnown = false;
6499   Scope *DeclRegionScope = NamespcScope->getParent();
6500 
6501   NamespaceDecl *PrevNS = 0;
6502   if (II) {
6503     // C++ [namespace.def]p2:
6504     //   The identifier in an original-namespace-definition shall not
6505     //   have been previously defined in the declarative region in
6506     //   which the original-namespace-definition appears. The
6507     //   identifier in an original-namespace-definition is the name of
6508     //   the namespace. Subsequently in that declarative region, it is
6509     //   treated as an original-namespace-name.
6510     //
6511     // Since namespace names are unique in their scope, and we don't
6512     // look through using directives, just look for any ordinary names.
6513 
6514     const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
6515     Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6516     Decl::IDNS_Namespace;
6517     NamedDecl *PrevDecl = 0;
6518     DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6519     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6520          ++I) {
6521       if ((*I)->getIdentifierNamespace() & IDNS) {
6522         PrevDecl = *I;
6523         break;
6524       }
6525     }
6526 
6527     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6528 
6529     if (PrevNS) {
6530       // This is an extended namespace definition.
6531       if (IsInline != PrevNS->isInline())
6532         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6533                                         &IsInline, PrevNS);
6534     } else if (PrevDecl) {
6535       // This is an invalid name redefinition.
6536       Diag(Loc, diag::err_redefinition_different_kind)
6537         << II;
6538       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6539       IsInvalid = true;
6540       // Continue on to push Namespc as current DeclContext and return it.
6541     } else if (II->isStr("std") &&
6542                CurContext->getRedeclContext()->isTranslationUnit()) {
6543       // This is the first "real" definition of the namespace "std", so update
6544       // our cache of the "std" namespace to point at this definition.
6545       PrevNS = getStdNamespace();
6546       IsStd = true;
6547       AddToKnown = !IsInline;
6548     } else {
6549       // We've seen this namespace for the first time.
6550       AddToKnown = !IsInline;
6551     }
6552   } else {
6553     // Anonymous namespaces.
6554 
6555     // Determine whether the parent already has an anonymous namespace.
6556     DeclContext *Parent = CurContext->getRedeclContext();
6557     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6558       PrevNS = TU->getAnonymousNamespace();
6559     } else {
6560       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
6561       PrevNS = ND->getAnonymousNamespace();
6562     }
6563 
6564     if (PrevNS && IsInline != PrevNS->isInline())
6565       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6566                                       &IsInline, PrevNS);
6567   }
6568 
6569   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6570                                                  StartLoc, Loc, II, PrevNS);
6571   if (IsInvalid)
6572     Namespc->setInvalidDecl();
6573 
6574   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
6575 
6576   // FIXME: Should we be merging attributes?
6577   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
6578     PushNamespaceVisibilityAttr(Attr, Loc);
6579 
6580   if (IsStd)
6581     StdNamespace = Namespc;
6582   if (AddToKnown)
6583     KnownNamespaces[Namespc] = false;
6584 
6585   if (II) {
6586     PushOnScopeChains(Namespc, DeclRegionScope);
6587   } else {
6588     // Link the anonymous namespace into its parent.
6589     DeclContext *Parent = CurContext->getRedeclContext();
6590     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6591       TU->setAnonymousNamespace(Namespc);
6592     } else {
6593       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
6594     }
6595 
6596     CurContext->addDecl(Namespc);
6597 
6598     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
6599     //   behaves as if it were replaced by
6600     //     namespace unique { /* empty body */ }
6601     //     using namespace unique;
6602     //     namespace unique { namespace-body }
6603     //   where all occurrences of 'unique' in a translation unit are
6604     //   replaced by the same identifier and this identifier differs
6605     //   from all other identifiers in the entire program.
6606 
6607     // We just create the namespace with an empty name and then add an
6608     // implicit using declaration, just like the standard suggests.
6609     //
6610     // CodeGen enforces the "universally unique" aspect by giving all
6611     // declarations semantically contained within an anonymous
6612     // namespace internal linkage.
6613 
6614     if (!PrevNS) {
6615       UsingDirectiveDecl* UD
6616         = UsingDirectiveDecl::Create(Context, Parent,
6617                                      /* 'using' */ LBrace,
6618                                      /* 'namespace' */ SourceLocation(),
6619                                      /* qualifier */ NestedNameSpecifierLoc(),
6620                                      /* identifier */ SourceLocation(),
6621                                      Namespc,
6622                                      /* Ancestor */ Parent);
6623       UD->setImplicit();
6624       Parent->addDecl(UD);
6625     }
6626   }
6627 
6628   ActOnDocumentableDecl(Namespc);
6629 
6630   // Although we could have an invalid decl (i.e. the namespace name is a
6631   // redefinition), push it as current DeclContext and try to continue parsing.
6632   // FIXME: We should be able to push Namespc here, so that the each DeclContext
6633   // for the namespace has the declarations that showed up in that particular
6634   // namespace definition.
6635   PushDeclContext(NamespcScope, Namespc);
6636   return Namespc;
6637 }
6638 
6639 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6640 /// is a namespace alias, returns the namespace it points to.
6641 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6642   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6643     return AD->getNamespace();
6644   return dyn_cast_or_null<NamespaceDecl>(D);
6645 }
6646 
6647 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
6648 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
6649 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
6650   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6651   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
6652   Namespc->setRBraceLoc(RBrace);
6653   PopDeclContext();
6654   if (Namespc->hasAttr<VisibilityAttr>())
6655     PopPragmaVisibility(true, RBrace);
6656 }
6657 
6658 CXXRecordDecl *Sema::getStdBadAlloc() const {
6659   return cast_or_null<CXXRecordDecl>(
6660                                   StdBadAlloc.get(Context.getExternalSource()));
6661 }
6662 
6663 NamespaceDecl *Sema::getStdNamespace() const {
6664   return cast_or_null<NamespaceDecl>(
6665                                  StdNamespace.get(Context.getExternalSource()));
6666 }
6667 
6668 /// \brief Retrieve the special "std" namespace, which may require us to
6669 /// implicitly define the namespace.
6670 NamespaceDecl *Sema::getOrCreateStdNamespace() {
6671   if (!StdNamespace) {
6672     // The "std" namespace has not yet been defined, so build one implicitly.
6673     StdNamespace = NamespaceDecl::Create(Context,
6674                                          Context.getTranslationUnitDecl(),
6675                                          /*Inline=*/false,
6676                                          SourceLocation(), SourceLocation(),
6677                                          &PP.getIdentifierTable().get("std"),
6678                                          /*PrevDecl=*/0);
6679     getStdNamespace()->setImplicit(true);
6680   }
6681 
6682   return getStdNamespace();
6683 }
6684 
6685 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
6686   assert(getLangOpts().CPlusPlus &&
6687          "Looking for std::initializer_list outside of C++.");
6688 
6689   // We're looking for implicit instantiations of
6690   // template <typename E> class std::initializer_list.
6691 
6692   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6693     return false;
6694 
6695   ClassTemplateDecl *Template = 0;
6696   const TemplateArgument *Arguments = 0;
6697 
6698   if (const RecordType *RT = Ty->getAs<RecordType>()) {
6699 
6700     ClassTemplateSpecializationDecl *Specialization =
6701         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6702     if (!Specialization)
6703       return false;
6704 
6705     Template = Specialization->getSpecializedTemplate();
6706     Arguments = Specialization->getTemplateArgs().data();
6707   } else if (const TemplateSpecializationType *TST =
6708                  Ty->getAs<TemplateSpecializationType>()) {
6709     Template = dyn_cast_or_null<ClassTemplateDecl>(
6710         TST->getTemplateName().getAsTemplateDecl());
6711     Arguments = TST->getArgs();
6712   }
6713   if (!Template)
6714     return false;
6715 
6716   if (!StdInitializerList) {
6717     // Haven't recognized std::initializer_list yet, maybe this is it.
6718     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6719     if (TemplateClass->getIdentifier() !=
6720             &PP.getIdentifierTable().get("initializer_list") ||
6721         !getStdNamespace()->InEnclosingNamespaceSetOf(
6722             TemplateClass->getDeclContext()))
6723       return false;
6724     // This is a template called std::initializer_list, but is it the right
6725     // template?
6726     TemplateParameterList *Params = Template->getTemplateParameters();
6727     if (Params->getMinRequiredArguments() != 1)
6728       return false;
6729     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6730       return false;
6731 
6732     // It's the right template.
6733     StdInitializerList = Template;
6734   }
6735 
6736   if (Template != StdInitializerList)
6737     return false;
6738 
6739   // This is an instance of std::initializer_list. Find the argument type.
6740   if (Element)
6741     *Element = Arguments[0].getAsType();
6742   return true;
6743 }
6744 
6745 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6746   NamespaceDecl *Std = S.getStdNamespace();
6747   if (!Std) {
6748     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6749     return 0;
6750   }
6751 
6752   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6753                       Loc, Sema::LookupOrdinaryName);
6754   if (!S.LookupQualifiedName(Result, Std)) {
6755     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6756     return 0;
6757   }
6758   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6759   if (!Template) {
6760     Result.suppressDiagnostics();
6761     // We found something weird. Complain about the first thing we found.
6762     NamedDecl *Found = *Result.begin();
6763     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6764     return 0;
6765   }
6766 
6767   // We found some template called std::initializer_list. Now verify that it's
6768   // correct.
6769   TemplateParameterList *Params = Template->getTemplateParameters();
6770   if (Params->getMinRequiredArguments() != 1 ||
6771       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6772     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6773     return 0;
6774   }
6775 
6776   return Template;
6777 }
6778 
6779 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6780   if (!StdInitializerList) {
6781     StdInitializerList = LookupStdInitializerList(*this, Loc);
6782     if (!StdInitializerList)
6783       return QualType();
6784   }
6785 
6786   TemplateArgumentListInfo Args(Loc, Loc);
6787   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6788                                        Context.getTrivialTypeSourceInfo(Element,
6789                                                                         Loc)));
6790   return Context.getCanonicalType(
6791       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6792 }
6793 
6794 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6795   // C++ [dcl.init.list]p2:
6796   //   A constructor is an initializer-list constructor if its first parameter
6797   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
6798   //   std::initializer_list<E> for some type E, and either there are no other
6799   //   parameters or else all other parameters have default arguments.
6800   if (Ctor->getNumParams() < 1 ||
6801       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6802     return false;
6803 
6804   QualType ArgType = Ctor->getParamDecl(0)->getType();
6805   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6806     ArgType = RT->getPointeeType().getUnqualifiedType();
6807 
6808   return isStdInitializerList(ArgType, 0);
6809 }
6810 
6811 /// \brief Determine whether a using statement is in a context where it will be
6812 /// apply in all contexts.
6813 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6814   switch (CurContext->getDeclKind()) {
6815     case Decl::TranslationUnit:
6816       return true;
6817     case Decl::LinkageSpec:
6818       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6819     default:
6820       return false;
6821   }
6822 }
6823 
6824 namespace {
6825 
6826 // Callback to only accept typo corrections that are namespaces.
6827 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6828 public:
6829   bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE {
6830     if (NamedDecl *ND = candidate.getCorrectionDecl())
6831       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6832     return false;
6833   }
6834 };
6835 
6836 }
6837 
6838 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6839                                        CXXScopeSpec &SS,
6840                                        SourceLocation IdentLoc,
6841                                        IdentifierInfo *Ident) {
6842   NamespaceValidatorCCC Validator;
6843   R.clear();
6844   if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
6845                                                R.getLookupKind(), Sc, &SS,
6846                                                Validator)) {
6847     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
6848       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6849       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
6850                               Ident->getName().equals(CorrectedStr);
6851       S.diagnoseTypo(Corrected,
6852                      S.PDiag(diag::err_using_directive_member_suggest)
6853                        << Ident << DC << DroppedSpecifier << SS.getRange(),
6854                      S.PDiag(diag::note_namespace_defined_here));
6855     } else {
6856       S.diagnoseTypo(Corrected,
6857                      S.PDiag(diag::err_using_directive_suggest) << Ident,
6858                      S.PDiag(diag::note_namespace_defined_here));
6859     }
6860     R.addDecl(Corrected.getCorrectionDecl());
6861     return true;
6862   }
6863   return false;
6864 }
6865 
6866 Decl *Sema::ActOnUsingDirective(Scope *S,
6867                                           SourceLocation UsingLoc,
6868                                           SourceLocation NamespcLoc,
6869                                           CXXScopeSpec &SS,
6870                                           SourceLocation IdentLoc,
6871                                           IdentifierInfo *NamespcName,
6872                                           AttributeList *AttrList) {
6873   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6874   assert(NamespcName && "Invalid NamespcName.");
6875   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
6876 
6877   // This can only happen along a recovery path.
6878   while (S->getFlags() & Scope::TemplateParamScope)
6879     S = S->getParent();
6880   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
6881 
6882   UsingDirectiveDecl *UDir = 0;
6883   NestedNameSpecifier *Qualifier = 0;
6884   if (SS.isSet())
6885     Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6886 
6887   // Lookup namespace name.
6888   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6889   LookupParsedName(R, S, &SS);
6890   if (R.isAmbiguous())
6891     return 0;
6892 
6893   if (R.empty()) {
6894     R.clear();
6895     // Allow "using namespace std;" or "using namespace ::std;" even if
6896     // "std" hasn't been defined yet, for GCC compatibility.
6897     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6898         NamespcName->isStr("std")) {
6899       Diag(IdentLoc, diag::ext_using_undefined_std);
6900       R.addDecl(getOrCreateStdNamespace());
6901       R.resolveKind();
6902     }
6903     // Otherwise, attempt typo correction.
6904     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
6905   }
6906 
6907   if (!R.empty()) {
6908     NamedDecl *Named = R.getFoundDecl();
6909     assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6910         && "expected namespace decl");
6911     // C++ [namespace.udir]p1:
6912     //   A using-directive specifies that the names in the nominated
6913     //   namespace can be used in the scope in which the
6914     //   using-directive appears after the using-directive. During
6915     //   unqualified name lookup (3.4.1), the names appear as if they
6916     //   were declared in the nearest enclosing namespace which
6917     //   contains both the using-directive and the nominated
6918     //   namespace. [Note: in this context, "contains" means "contains
6919     //   directly or indirectly". ]
6920 
6921     // Find enclosing context containing both using-directive and
6922     // nominated namespace.
6923     NamespaceDecl *NS = getNamespaceDecl(Named);
6924     DeclContext *CommonAncestor = cast<DeclContext>(NS);
6925     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6926       CommonAncestor = CommonAncestor->getParent();
6927 
6928     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
6929                                       SS.getWithLocInContext(Context),
6930                                       IdentLoc, Named, CommonAncestor);
6931 
6932     if (IsUsingDirectiveInToplevelContext(CurContext) &&
6933         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
6934       Diag(IdentLoc, diag::warn_using_directive_in_header);
6935     }
6936 
6937     PushUsingDirective(S, UDir);
6938   } else {
6939     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
6940   }
6941 
6942   if (UDir)
6943     ProcessDeclAttributeList(S, UDir, AttrList);
6944 
6945   return UDir;
6946 }
6947 
6948 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
6949   // If the scope has an associated entity and the using directive is at
6950   // namespace or translation unit scope, add the UsingDirectiveDecl into
6951   // its lookup structure so qualified name lookup can find it.
6952   DeclContext *Ctx = S->getEntity();
6953   if (Ctx && !Ctx->isFunctionOrMethod())
6954     Ctx->addDecl(UDir);
6955   else
6956     // Otherwise, it is at block sope. The using-directives will affect lookup
6957     // only to the end of the scope.
6958     S->PushUsingDirective(UDir);
6959 }
6960 
6961 
6962 Decl *Sema::ActOnUsingDeclaration(Scope *S,
6963                                   AccessSpecifier AS,
6964                                   bool HasUsingKeyword,
6965                                   SourceLocation UsingLoc,
6966                                   CXXScopeSpec &SS,
6967                                   UnqualifiedId &Name,
6968                                   AttributeList *AttrList,
6969                                   bool HasTypenameKeyword,
6970                                   SourceLocation TypenameLoc) {
6971   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
6972 
6973   switch (Name.getKind()) {
6974   case UnqualifiedId::IK_ImplicitSelfParam:
6975   case UnqualifiedId::IK_Identifier:
6976   case UnqualifiedId::IK_OperatorFunctionId:
6977   case UnqualifiedId::IK_LiteralOperatorId:
6978   case UnqualifiedId::IK_ConversionFunctionId:
6979     break;
6980 
6981   case UnqualifiedId::IK_ConstructorName:
6982   case UnqualifiedId::IK_ConstructorTemplateId:
6983     // C++11 inheriting constructors.
6984     Diag(Name.getLocStart(),
6985          getLangOpts().CPlusPlus11 ?
6986            diag::warn_cxx98_compat_using_decl_constructor :
6987            diag::err_using_decl_constructor)
6988       << SS.getRange();
6989 
6990     if (getLangOpts().CPlusPlus11) break;
6991 
6992     return 0;
6993 
6994   case UnqualifiedId::IK_DestructorName:
6995     Diag(Name.getLocStart(), diag::err_using_decl_destructor)
6996       << SS.getRange();
6997     return 0;
6998 
6999   case UnqualifiedId::IK_TemplateId:
7000     Diag(Name.getLocStart(), diag::err_using_decl_template_id)
7001       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
7002     return 0;
7003   }
7004 
7005   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7006   DeclarationName TargetName = TargetNameInfo.getName();
7007   if (!TargetName)
7008     return 0;
7009 
7010   // Warn about access declarations.
7011   if (!HasUsingKeyword) {
7012     Diag(Name.getLocStart(),
7013          getLangOpts().CPlusPlus11 ? diag::err_access_decl
7014                                    : diag::warn_access_decl_deprecated)
7015       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
7016   }
7017 
7018   if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7019       DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7020     return 0;
7021 
7022   NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
7023                                         TargetNameInfo, AttrList,
7024                                         /* IsInstantiation */ false,
7025                                         HasTypenameKeyword, TypenameLoc);
7026   if (UD)
7027     PushOnScopeChains(UD, S, /*AddToContext*/ false);
7028 
7029   return UD;
7030 }
7031 
7032 /// \brief Determine whether a using declaration considers the given
7033 /// declarations as "equivalent", e.g., if they are redeclarations of
7034 /// the same entity or are both typedefs of the same type.
7035 static bool
7036 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7037   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
7038     return true;
7039 
7040   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
7041     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
7042       return Context.hasSameType(TD1->getUnderlyingType(),
7043                                  TD2->getUnderlyingType());
7044 
7045   return false;
7046 }
7047 
7048 
7049 /// Determines whether to create a using shadow decl for a particular
7050 /// decl, given the set of decls existing prior to this using lookup.
7051 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
7052                                 const LookupResult &Previous,
7053                                 UsingShadowDecl *&PrevShadow) {
7054   // Diagnose finding a decl which is not from a base class of the
7055   // current class.  We do this now because there are cases where this
7056   // function will silently decide not to build a shadow decl, which
7057   // will pre-empt further diagnostics.
7058   //
7059   // We don't need to do this in C++0x because we do the check once on
7060   // the qualifier.
7061   //
7062   // FIXME: diagnose the following if we care enough:
7063   //   struct A { int foo; };
7064   //   struct B : A { using A::foo; };
7065   //   template <class T> struct C : A {};
7066   //   template <class T> struct D : C<T> { using B::foo; } // <---
7067   // This is invalid (during instantiation) in C++03 because B::foo
7068   // resolves to the using decl in B, which is not a base class of D<T>.
7069   // We can't diagnose it immediately because C<T> is an unknown
7070   // specialization.  The UsingShadowDecl in D<T> then points directly
7071   // to A::foo, which will look well-formed when we instantiate.
7072   // The right solution is to not collapse the shadow-decl chain.
7073   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
7074     DeclContext *OrigDC = Orig->getDeclContext();
7075 
7076     // Handle enums and anonymous structs.
7077     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7078     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7079     while (OrigRec->isAnonymousStructOrUnion())
7080       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7081 
7082     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7083       if (OrigDC == CurContext) {
7084         Diag(Using->getLocation(),
7085              diag::err_using_decl_nested_name_specifier_is_current_class)
7086           << Using->getQualifierLoc().getSourceRange();
7087         Diag(Orig->getLocation(), diag::note_using_decl_target);
7088         return true;
7089       }
7090 
7091       Diag(Using->getQualifierLoc().getBeginLoc(),
7092            diag::err_using_decl_nested_name_specifier_is_not_base_class)
7093         << Using->getQualifier()
7094         << cast<CXXRecordDecl>(CurContext)
7095         << Using->getQualifierLoc().getSourceRange();
7096       Diag(Orig->getLocation(), diag::note_using_decl_target);
7097       return true;
7098     }
7099   }
7100 
7101   if (Previous.empty()) return false;
7102 
7103   NamedDecl *Target = Orig;
7104   if (isa<UsingShadowDecl>(Target))
7105     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7106 
7107   // If the target happens to be one of the previous declarations, we
7108   // don't have a conflict.
7109   //
7110   // FIXME: but we might be increasing its access, in which case we
7111   // should redeclare it.
7112   NamedDecl *NonTag = 0, *Tag = 0;
7113   bool FoundEquivalentDecl = false;
7114   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7115          I != E; ++I) {
7116     NamedDecl *D = (*I)->getUnderlyingDecl();
7117     if (IsEquivalentForUsingDecl(Context, D, Target)) {
7118       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7119         PrevShadow = Shadow;
7120       FoundEquivalentDecl = true;
7121     }
7122 
7123     (isa<TagDecl>(D) ? Tag : NonTag) = D;
7124   }
7125 
7126   if (FoundEquivalentDecl)
7127     return false;
7128 
7129   if (Target->isFunctionOrFunctionTemplate()) {
7130     FunctionDecl *FD;
7131     if (isa<FunctionTemplateDecl>(Target))
7132       FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
7133     else
7134       FD = cast<FunctionDecl>(Target);
7135 
7136     NamedDecl *OldDecl = 0;
7137     switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
7138     case Ovl_Overload:
7139       return false;
7140 
7141     case Ovl_NonFunction:
7142       Diag(Using->getLocation(), diag::err_using_decl_conflict);
7143       break;
7144 
7145     // We found a decl with the exact signature.
7146     case Ovl_Match:
7147       // If we're in a record, we want to hide the target, so we
7148       // return true (without a diagnostic) to tell the caller not to
7149       // build a shadow decl.
7150       if (CurContext->isRecord())
7151         return true;
7152 
7153       // If we're not in a record, this is an error.
7154       Diag(Using->getLocation(), diag::err_using_decl_conflict);
7155       break;
7156     }
7157 
7158     Diag(Target->getLocation(), diag::note_using_decl_target);
7159     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7160     return true;
7161   }
7162 
7163   // Target is not a function.
7164 
7165   if (isa<TagDecl>(Target)) {
7166     // No conflict between a tag and a non-tag.
7167     if (!Tag) return false;
7168 
7169     Diag(Using->getLocation(), diag::err_using_decl_conflict);
7170     Diag(Target->getLocation(), diag::note_using_decl_target);
7171     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7172     return true;
7173   }
7174 
7175   // No conflict between a tag and a non-tag.
7176   if (!NonTag) return false;
7177 
7178   Diag(Using->getLocation(), diag::err_using_decl_conflict);
7179   Diag(Target->getLocation(), diag::note_using_decl_target);
7180   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7181   return true;
7182 }
7183 
7184 /// Builds a shadow declaration corresponding to a 'using' declaration.
7185 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
7186                                             UsingDecl *UD,
7187                                             NamedDecl *Orig,
7188                                             UsingShadowDecl *PrevDecl) {
7189 
7190   // If we resolved to another shadow declaration, just coalesce them.
7191   NamedDecl *Target = Orig;
7192   if (isa<UsingShadowDecl>(Target)) {
7193     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7194     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
7195   }
7196 
7197   UsingShadowDecl *Shadow
7198     = UsingShadowDecl::Create(Context, CurContext,
7199                               UD->getLocation(), UD, Target);
7200   UD->addShadowDecl(Shadow);
7201 
7202   Shadow->setAccess(UD->getAccess());
7203   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7204     Shadow->setInvalidDecl();
7205 
7206   Shadow->setPreviousDecl(PrevDecl);
7207 
7208   if (S)
7209     PushOnScopeChains(Shadow, S);
7210   else
7211     CurContext->addDecl(Shadow);
7212 
7213 
7214   return Shadow;
7215 }
7216 
7217 /// Hides a using shadow declaration.  This is required by the current
7218 /// using-decl implementation when a resolvable using declaration in a
7219 /// class is followed by a declaration which would hide or override
7220 /// one or more of the using decl's targets; for example:
7221 ///
7222 ///   struct Base { void foo(int); };
7223 ///   struct Derived : Base {
7224 ///     using Base::foo;
7225 ///     void foo(int);
7226 ///   };
7227 ///
7228 /// The governing language is C++03 [namespace.udecl]p12:
7229 ///
7230 ///   When a using-declaration brings names from a base class into a
7231 ///   derived class scope, member functions in the derived class
7232 ///   override and/or hide member functions with the same name and
7233 ///   parameter types in a base class (rather than conflicting).
7234 ///
7235 /// There are two ways to implement this:
7236 ///   (1) optimistically create shadow decls when they're not hidden
7237 ///       by existing declarations, or
7238 ///   (2) don't create any shadow decls (or at least don't make them
7239 ///       visible) until we've fully parsed/instantiated the class.
7240 /// The problem with (1) is that we might have to retroactively remove
7241 /// a shadow decl, which requires several O(n) operations because the
7242 /// decl structures are (very reasonably) not designed for removal.
7243 /// (2) avoids this but is very fiddly and phase-dependent.
7244 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
7245   if (Shadow->getDeclName().getNameKind() ==
7246         DeclarationName::CXXConversionFunctionName)
7247     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7248 
7249   // Remove it from the DeclContext...
7250   Shadow->getDeclContext()->removeDecl(Shadow);
7251 
7252   // ...and the scope, if applicable...
7253   if (S) {
7254     S->RemoveDecl(Shadow);
7255     IdResolver.RemoveDecl(Shadow);
7256   }
7257 
7258   // ...and the using decl.
7259   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7260 
7261   // TODO: complain somehow if Shadow was used.  It shouldn't
7262   // be possible for this to happen, because...?
7263 }
7264 
7265 namespace {
7266 class UsingValidatorCCC : public CorrectionCandidateCallback {
7267 public:
7268   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
7269                     bool RequireMember)
7270       : HasTypenameKeyword(HasTypenameKeyword),
7271         IsInstantiation(IsInstantiation), RequireMember(RequireMember) {}
7272 
7273   bool ValidateCandidate(const TypoCorrection &Candidate) LLVM_OVERRIDE {
7274     NamedDecl *ND = Candidate.getCorrectionDecl();
7275 
7276     // Keywords are not valid here.
7277     if (!ND || isa<NamespaceDecl>(ND))
7278       return false;
7279 
7280     if (RequireMember && !isa<FieldDecl>(ND) && !isa<CXXMethodDecl>(ND) &&
7281         !isa<TypeDecl>(ND))
7282       return false;
7283 
7284     // Completely unqualified names are invalid for a 'using' declaration.
7285     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7286       return false;
7287 
7288     if (isa<TypeDecl>(ND))
7289       return HasTypenameKeyword || !IsInstantiation;
7290 
7291     return !HasTypenameKeyword;
7292   }
7293 
7294 private:
7295   bool HasTypenameKeyword;
7296   bool IsInstantiation;
7297   bool RequireMember;
7298 };
7299 } // end anonymous namespace
7300 
7301 /// Builds a using declaration.
7302 ///
7303 /// \param IsInstantiation - Whether this call arises from an
7304 ///   instantiation of an unresolved using declaration.  We treat
7305 ///   the lookup differently for these declarations.
7306 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7307                                        SourceLocation UsingLoc,
7308                                        CXXScopeSpec &SS,
7309                                        const DeclarationNameInfo &NameInfo,
7310                                        AttributeList *AttrList,
7311                                        bool IsInstantiation,
7312                                        bool HasTypenameKeyword,
7313                                        SourceLocation TypenameLoc) {
7314   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7315   SourceLocation IdentLoc = NameInfo.getLoc();
7316   assert(IdentLoc.isValid() && "Invalid TargetName location.");
7317 
7318   // FIXME: We ignore attributes for now.
7319 
7320   if (SS.isEmpty()) {
7321     Diag(IdentLoc, diag::err_using_requires_qualname);
7322     return 0;
7323   }
7324 
7325   // Do the redeclaration lookup in the current scope.
7326   LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
7327                         ForRedeclaration);
7328   Previous.setHideTags(false);
7329   if (S) {
7330     LookupName(Previous, S);
7331 
7332     // It is really dumb that we have to do this.
7333     LookupResult::Filter F = Previous.makeFilter();
7334     while (F.hasNext()) {
7335       NamedDecl *D = F.next();
7336       if (!isDeclInScope(D, CurContext, S))
7337         F.erase();
7338     }
7339     F.done();
7340   } else {
7341     assert(IsInstantiation && "no scope in non-instantiation");
7342     assert(CurContext->isRecord() && "scope not record in instantiation");
7343     LookupQualifiedName(Previous, CurContext);
7344   }
7345 
7346   // Check for invalid redeclarations.
7347   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7348                                   SS, IdentLoc, Previous))
7349     return 0;
7350 
7351   // Check for bad qualifiers.
7352   if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7353     return 0;
7354 
7355   DeclContext *LookupContext = computeDeclContext(SS);
7356   NamedDecl *D;
7357   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
7358   if (!LookupContext) {
7359     if (HasTypenameKeyword) {
7360       // FIXME: not all declaration name kinds are legal here
7361       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7362                                               UsingLoc, TypenameLoc,
7363                                               QualifierLoc,
7364                                               IdentLoc, NameInfo.getName());
7365     } else {
7366       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7367                                            QualifierLoc, NameInfo);
7368     }
7369   } else {
7370     D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
7371                           NameInfo, HasTypenameKeyword);
7372   }
7373   D->setAccess(AS);
7374   CurContext->addDecl(D);
7375 
7376   if (!LookupContext) return D;
7377   UsingDecl *UD = cast<UsingDecl>(D);
7378 
7379   if (RequireCompleteDeclContext(SS, LookupContext)) {
7380     UD->setInvalidDecl();
7381     return UD;
7382   }
7383 
7384   // The normal rules do not apply to inheriting constructor declarations.
7385   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
7386     if (CheckInheritingConstructorUsingDecl(UD))
7387       UD->setInvalidDecl();
7388     return UD;
7389   }
7390 
7391   // Otherwise, look up the target name.
7392 
7393   LookupResult R(*this, NameInfo, LookupOrdinaryName);
7394 
7395   // Unlike most lookups, we don't always want to hide tag
7396   // declarations: tag names are visible through the using declaration
7397   // even if hidden by ordinary names, *except* in a dependent context
7398   // where it's important for the sanity of two-phase lookup.
7399   if (!IsInstantiation)
7400     R.setHideTags(false);
7401 
7402   // For the purposes of this lookup, we have a base object type
7403   // equal to that of the current context.
7404   if (CurContext->isRecord()) {
7405     R.setBaseObjectType(
7406                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7407   }
7408 
7409   LookupQualifiedName(R, LookupContext);
7410 
7411   // Try to correct typos if possible.
7412   if (R.empty()) {
7413     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation,
7414                           CurContext->isRecord());
7415     if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
7416                                                R.getLookupKind(), S, &SS, CCC)){
7417       // We reject any correction for which ND would be NULL.
7418       NamedDecl *ND = Corrected.getCorrectionDecl();
7419       R.setLookupName(Corrected.getCorrection());
7420       R.addDecl(ND);
7421       // We reject candidates where DroppedSpecifier == true, hence the
7422       // literal '0' below.
7423       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7424                                 << NameInfo.getName() << LookupContext << 0
7425                                 << SS.getRange());
7426     } else {
7427       Diag(IdentLoc, diag::err_no_member)
7428         << NameInfo.getName() << LookupContext << SS.getRange();
7429       UD->setInvalidDecl();
7430       return UD;
7431     }
7432   }
7433 
7434   if (R.isAmbiguous()) {
7435     UD->setInvalidDecl();
7436     return UD;
7437   }
7438 
7439   if (HasTypenameKeyword) {
7440     // If we asked for a typename and got a non-type decl, error out.
7441     if (!R.getAsSingle<TypeDecl>()) {
7442       Diag(IdentLoc, diag::err_using_typename_non_type);
7443       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7444         Diag((*I)->getUnderlyingDecl()->getLocation(),
7445              diag::note_using_decl_target);
7446       UD->setInvalidDecl();
7447       return UD;
7448     }
7449   } else {
7450     // If we asked for a non-typename and we got a type, error out,
7451     // but only if this is an instantiation of an unresolved using
7452     // decl.  Otherwise just silently find the type name.
7453     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
7454       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7455       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
7456       UD->setInvalidDecl();
7457       return UD;
7458     }
7459   }
7460 
7461   // C++0x N2914 [namespace.udecl]p6:
7462   // A using-declaration shall not name a namespace.
7463   if (R.getAsSingle<NamespaceDecl>()) {
7464     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7465       << SS.getRange();
7466     UD->setInvalidDecl();
7467     return UD;
7468   }
7469 
7470   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7471     UsingShadowDecl *PrevDecl = 0;
7472     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
7473       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
7474   }
7475 
7476   return UD;
7477 }
7478 
7479 /// Additional checks for a using declaration referring to a constructor name.
7480 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
7481   assert(!UD->hasTypename() && "expecting a constructor name");
7482 
7483   const Type *SourceType = UD->getQualifier()->getAsType();
7484   assert(SourceType &&
7485          "Using decl naming constructor doesn't have type in scope spec.");
7486   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7487 
7488   // Check whether the named type is a direct base class.
7489   CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7490   CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7491   for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7492        BaseIt != BaseE; ++BaseIt) {
7493     CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7494     if (CanonicalSourceType == BaseType)
7495       break;
7496     if (BaseIt->getType()->isDependentType())
7497       break;
7498   }
7499 
7500   if (BaseIt == BaseE) {
7501     // Did not find SourceType in the bases.
7502     Diag(UD->getUsingLoc(),
7503          diag::err_using_decl_constructor_not_in_direct_base)
7504       << UD->getNameInfo().getSourceRange()
7505       << QualType(SourceType, 0) << TargetClass;
7506     return true;
7507   }
7508 
7509   if (!CurContext->isDependentContext())
7510     BaseIt->setInheritConstructors();
7511 
7512   return false;
7513 }
7514 
7515 /// Checks that the given using declaration is not an invalid
7516 /// redeclaration.  Note that this is checking only for the using decl
7517 /// itself, not for any ill-formedness among the UsingShadowDecls.
7518 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7519                                        bool HasTypenameKeyword,
7520                                        const CXXScopeSpec &SS,
7521                                        SourceLocation NameLoc,
7522                                        const LookupResult &Prev) {
7523   // C++03 [namespace.udecl]p8:
7524   // C++0x [namespace.udecl]p10:
7525   //   A using-declaration is a declaration and can therefore be used
7526   //   repeatedly where (and only where) multiple declarations are
7527   //   allowed.
7528   //
7529   // That's in non-member contexts.
7530   if (!CurContext->getRedeclContext()->isRecord())
7531     return false;
7532 
7533   NestedNameSpecifier *Qual
7534     = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7535 
7536   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7537     NamedDecl *D = *I;
7538 
7539     bool DTypename;
7540     NestedNameSpecifier *DQual;
7541     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7542       DTypename = UD->hasTypename();
7543       DQual = UD->getQualifier();
7544     } else if (UnresolvedUsingValueDecl *UD
7545                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7546       DTypename = false;
7547       DQual = UD->getQualifier();
7548     } else if (UnresolvedUsingTypenameDecl *UD
7549                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7550       DTypename = true;
7551       DQual = UD->getQualifier();
7552     } else continue;
7553 
7554     // using decls differ if one says 'typename' and the other doesn't.
7555     // FIXME: non-dependent using decls?
7556     if (HasTypenameKeyword != DTypename) continue;
7557 
7558     // using decls differ if they name different scopes (but note that
7559     // template instantiation can cause this check to trigger when it
7560     // didn't before instantiation).
7561     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7562         Context.getCanonicalNestedNameSpecifier(DQual))
7563       continue;
7564 
7565     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
7566     Diag(D->getLocation(), diag::note_using_decl) << 1;
7567     return true;
7568   }
7569 
7570   return false;
7571 }
7572 
7573 
7574 /// Checks that the given nested-name qualifier used in a using decl
7575 /// in the current context is appropriately related to the current
7576 /// scope.  If an error is found, diagnoses it and returns true.
7577 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7578                                    const CXXScopeSpec &SS,
7579                                    SourceLocation NameLoc) {
7580   DeclContext *NamedContext = computeDeclContext(SS);
7581 
7582   if (!CurContext->isRecord()) {
7583     // C++03 [namespace.udecl]p3:
7584     // C++0x [namespace.udecl]p8:
7585     //   A using-declaration for a class member shall be a member-declaration.
7586 
7587     // If we weren't able to compute a valid scope, it must be a
7588     // dependent class scope.
7589     if (!NamedContext || NamedContext->isRecord()) {
7590       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7591         << SS.getRange();
7592       return true;
7593     }
7594 
7595     // Otherwise, everything is known to be fine.
7596     return false;
7597   }
7598 
7599   // The current scope is a record.
7600 
7601   // If the named context is dependent, we can't decide much.
7602   if (!NamedContext) {
7603     // FIXME: in C++0x, we can diagnose if we can prove that the
7604     // nested-name-specifier does not refer to a base class, which is
7605     // still possible in some cases.
7606 
7607     // Otherwise we have to conservatively report that things might be
7608     // okay.
7609     return false;
7610   }
7611 
7612   if (!NamedContext->isRecord()) {
7613     // Ideally this would point at the last name in the specifier,
7614     // but we don't have that level of source info.
7615     Diag(SS.getRange().getBegin(),
7616          diag::err_using_decl_nested_name_specifier_is_not_class)
7617       << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7618     return true;
7619   }
7620 
7621   if (!NamedContext->isDependentContext() &&
7622       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7623     return true;
7624 
7625   if (getLangOpts().CPlusPlus11) {
7626     // C++0x [namespace.udecl]p3:
7627     //   In a using-declaration used as a member-declaration, the
7628     //   nested-name-specifier shall name a base class of the class
7629     //   being defined.
7630 
7631     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7632                                  cast<CXXRecordDecl>(NamedContext))) {
7633       if (CurContext == NamedContext) {
7634         Diag(NameLoc,
7635              diag::err_using_decl_nested_name_specifier_is_current_class)
7636           << SS.getRange();
7637         return true;
7638       }
7639 
7640       Diag(SS.getRange().getBegin(),
7641            diag::err_using_decl_nested_name_specifier_is_not_base_class)
7642         << (NestedNameSpecifier*) SS.getScopeRep()
7643         << cast<CXXRecordDecl>(CurContext)
7644         << SS.getRange();
7645       return true;
7646     }
7647 
7648     return false;
7649   }
7650 
7651   // C++03 [namespace.udecl]p4:
7652   //   A using-declaration used as a member-declaration shall refer
7653   //   to a member of a base class of the class being defined [etc.].
7654 
7655   // Salient point: SS doesn't have to name a base class as long as
7656   // lookup only finds members from base classes.  Therefore we can
7657   // diagnose here only if we can prove that that can't happen,
7658   // i.e. if the class hierarchies provably don't intersect.
7659 
7660   // TODO: it would be nice if "definitely valid" results were cached
7661   // in the UsingDecl and UsingShadowDecl so that these checks didn't
7662   // need to be repeated.
7663 
7664   struct UserData {
7665     llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
7666 
7667     static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7668       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7669       Data->Bases.insert(Base);
7670       return true;
7671     }
7672 
7673     bool hasDependentBases(const CXXRecordDecl *Class) {
7674       return !Class->forallBases(collect, this);
7675     }
7676 
7677     /// Returns true if the base is dependent or is one of the
7678     /// accumulated base classes.
7679     static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7680       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7681       return !Data->Bases.count(Base);
7682     }
7683 
7684     bool mightShareBases(const CXXRecordDecl *Class) {
7685       return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7686     }
7687   };
7688 
7689   UserData Data;
7690 
7691   // Returns false if we find a dependent base.
7692   if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7693     return false;
7694 
7695   // Returns false if the class has a dependent base or if it or one
7696   // of its bases is present in the base set of the current context.
7697   if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7698     return false;
7699 
7700   Diag(SS.getRange().getBegin(),
7701        diag::err_using_decl_nested_name_specifier_is_not_base_class)
7702     << (NestedNameSpecifier*) SS.getScopeRep()
7703     << cast<CXXRecordDecl>(CurContext)
7704     << SS.getRange();
7705 
7706   return true;
7707 }
7708 
7709 Decl *Sema::ActOnAliasDeclaration(Scope *S,
7710                                   AccessSpecifier AS,
7711                                   MultiTemplateParamsArg TemplateParamLists,
7712                                   SourceLocation UsingLoc,
7713                                   UnqualifiedId &Name,
7714                                   AttributeList *AttrList,
7715                                   TypeResult Type) {
7716   // Skip up to the relevant declaration scope.
7717   while (S->getFlags() & Scope::TemplateParamScope)
7718     S = S->getParent();
7719   assert((S->getFlags() & Scope::DeclScope) &&
7720          "got alias-declaration outside of declaration scope");
7721 
7722   if (Type.isInvalid())
7723     return 0;
7724 
7725   bool Invalid = false;
7726   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7727   TypeSourceInfo *TInfo = 0;
7728   GetTypeFromParser(Type.get(), &TInfo);
7729 
7730   if (DiagnoseClassNameShadow(CurContext, NameInfo))
7731     return 0;
7732 
7733   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
7734                                       UPPC_DeclarationType)) {
7735     Invalid = true;
7736     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7737                                              TInfo->getTypeLoc().getBeginLoc());
7738   }
7739 
7740   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7741   LookupName(Previous, S);
7742 
7743   // Warn about shadowing the name of a template parameter.
7744   if (Previous.isSingleResult() &&
7745       Previous.getFoundDecl()->isTemplateParameter()) {
7746     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
7747     Previous.clear();
7748   }
7749 
7750   assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7751          "name in alias declaration must be an identifier");
7752   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7753                                                Name.StartLocation,
7754                                                Name.Identifier, TInfo);
7755 
7756   NewTD->setAccess(AS);
7757 
7758   if (Invalid)
7759     NewTD->setInvalidDecl();
7760 
7761   ProcessDeclAttributeList(S, NewTD, AttrList);
7762 
7763   CheckTypedefForVariablyModifiedType(S, NewTD);
7764   Invalid |= NewTD->isInvalidDecl();
7765 
7766   bool Redeclaration = false;
7767 
7768   NamedDecl *NewND;
7769   if (TemplateParamLists.size()) {
7770     TypeAliasTemplateDecl *OldDecl = 0;
7771     TemplateParameterList *OldTemplateParams = 0;
7772 
7773     if (TemplateParamLists.size() != 1) {
7774       Diag(UsingLoc, diag::err_alias_template_extra_headers)
7775         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7776          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
7777     }
7778     TemplateParameterList *TemplateParams = TemplateParamLists[0];
7779 
7780     // Only consider previous declarations in the same scope.
7781     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7782                          /*ExplicitInstantiationOrSpecialization*/false);
7783     if (!Previous.empty()) {
7784       Redeclaration = true;
7785 
7786       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7787       if (!OldDecl && !Invalid) {
7788         Diag(UsingLoc, diag::err_redefinition_different_kind)
7789           << Name.Identifier;
7790 
7791         NamedDecl *OldD = Previous.getRepresentativeDecl();
7792         if (OldD->getLocation().isValid())
7793           Diag(OldD->getLocation(), diag::note_previous_definition);
7794 
7795         Invalid = true;
7796       }
7797 
7798       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7799         if (TemplateParameterListsAreEqual(TemplateParams,
7800                                            OldDecl->getTemplateParameters(),
7801                                            /*Complain=*/true,
7802                                            TPL_TemplateMatch))
7803           OldTemplateParams = OldDecl->getTemplateParameters();
7804         else
7805           Invalid = true;
7806 
7807         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7808         if (!Invalid &&
7809             !Context.hasSameType(OldTD->getUnderlyingType(),
7810                                  NewTD->getUnderlyingType())) {
7811           // FIXME: The C++0x standard does not clearly say this is ill-formed,
7812           // but we can't reasonably accept it.
7813           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7814             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7815           if (OldTD->getLocation().isValid())
7816             Diag(OldTD->getLocation(), diag::note_previous_definition);
7817           Invalid = true;
7818         }
7819       }
7820     }
7821 
7822     // Merge any previous default template arguments into our parameters,
7823     // and check the parameter list.
7824     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7825                                    TPC_TypeAliasTemplate))
7826       return 0;
7827 
7828     TypeAliasTemplateDecl *NewDecl =
7829       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7830                                     Name.Identifier, TemplateParams,
7831                                     NewTD);
7832 
7833     NewDecl->setAccess(AS);
7834 
7835     if (Invalid)
7836       NewDecl->setInvalidDecl();
7837     else if (OldDecl)
7838       NewDecl->setPreviousDecl(OldDecl);
7839 
7840     NewND = NewDecl;
7841   } else {
7842     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7843     NewND = NewTD;
7844   }
7845 
7846   if (!Redeclaration)
7847     PushOnScopeChains(NewND, S);
7848 
7849   ActOnDocumentableDecl(NewND);
7850   return NewND;
7851 }
7852 
7853 Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
7854                                              SourceLocation NamespaceLoc,
7855                                              SourceLocation AliasLoc,
7856                                              IdentifierInfo *Alias,
7857                                              CXXScopeSpec &SS,
7858                                              SourceLocation IdentLoc,
7859                                              IdentifierInfo *Ident) {
7860 
7861   // Lookup the namespace name.
7862   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7863   LookupParsedName(R, S, &SS);
7864 
7865   // Check if we have a previous declaration with the same name.
7866   NamedDecl *PrevDecl
7867     = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7868                        ForRedeclaration);
7869   if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7870     PrevDecl = 0;
7871 
7872   if (PrevDecl) {
7873     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
7874       // We already have an alias with the same name that points to the same
7875       // namespace, so don't create a new one.
7876       // FIXME: At some point, we'll want to create the (redundant)
7877       // declaration to maintain better source information.
7878       if (!R.isAmbiguous() && !R.empty() &&
7879           AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
7880         return 0;
7881     }
7882 
7883     unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7884       diag::err_redefinition_different_kind;
7885     Diag(AliasLoc, DiagID) << Alias;
7886     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
7887     return 0;
7888   }
7889 
7890   if (R.isAmbiguous())
7891     return 0;
7892 
7893   if (R.empty()) {
7894     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
7895       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
7896       return 0;
7897     }
7898   }
7899 
7900   NamespaceAliasDecl *AliasDecl =
7901     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
7902                                Alias, SS.getWithLocInContext(Context),
7903                                IdentLoc, R.getFoundDecl());
7904 
7905   PushOnScopeChains(AliasDecl, S);
7906   return AliasDecl;
7907 }
7908 
7909 Sema::ImplicitExceptionSpecification
7910 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7911                                                CXXMethodDecl *MD) {
7912   CXXRecordDecl *ClassDecl = MD->getParent();
7913 
7914   // C++ [except.spec]p14:
7915   //   An implicitly declared special member function (Clause 12) shall have an
7916   //   exception-specification. [...]
7917   ImplicitExceptionSpecification ExceptSpec(*this);
7918   if (ClassDecl->isInvalidDecl())
7919     return ExceptSpec;
7920 
7921   // Direct base-class constructors.
7922   for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7923                                        BEnd = ClassDecl->bases_end();
7924        B != BEnd; ++B) {
7925     if (B->isVirtual()) // Handled below.
7926       continue;
7927 
7928     if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7929       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7930       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7931       // If this is a deleted function, add it anyway. This might be conformant
7932       // with the standard. This might not. I'm not sure. It might not matter.
7933       if (Constructor)
7934         ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7935     }
7936   }
7937 
7938   // Virtual base-class constructors.
7939   for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7940                                        BEnd = ClassDecl->vbases_end();
7941        B != BEnd; ++B) {
7942     if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7943       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7944       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7945       // If this is a deleted function, add it anyway. This might be conformant
7946       // with the standard. This might not. I'm not sure. It might not matter.
7947       if (Constructor)
7948         ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7949     }
7950   }
7951 
7952   // Field constructors.
7953   for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7954                                FEnd = ClassDecl->field_end();
7955        F != FEnd; ++F) {
7956     if (F->hasInClassInitializer()) {
7957       if (Expr *E = F->getInClassInitializer())
7958         ExceptSpec.CalledExpr(E);
7959       else if (!F->isInvalidDecl())
7960         // DR1351:
7961         //   If the brace-or-equal-initializer of a non-static data member
7962         //   invokes a defaulted default constructor of its class or of an
7963         //   enclosing class in a potentially evaluated subexpression, the
7964         //   program is ill-formed.
7965         //
7966         // This resolution is unworkable: the exception specification of the
7967         // default constructor can be needed in an unevaluated context, in
7968         // particular, in the operand of a noexcept-expression, and we can be
7969         // unable to compute an exception specification for an enclosed class.
7970         //
7971         // We do not allow an in-class initializer to require the evaluation
7972         // of the exception specification for any in-class initializer whose
7973         // definition is not lexically complete.
7974         Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
7975     } else if (const RecordType *RecordTy
7976               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7977       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7978       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7979       // If this is a deleted function, add it anyway. This might be conformant
7980       // with the standard. This might not. I'm not sure. It might not matter.
7981       // In particular, the problem is that this function never gets called. It
7982       // might just be ill-formed because this function attempts to refer to
7983       // a deleted function here.
7984       if (Constructor)
7985         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7986     }
7987   }
7988 
7989   return ExceptSpec;
7990 }
7991 
7992 Sema::ImplicitExceptionSpecification
7993 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
7994   CXXRecordDecl *ClassDecl = CD->getParent();
7995 
7996   // C++ [except.spec]p14:
7997   //   An inheriting constructor [...] shall have an exception-specification. [...]
7998   ImplicitExceptionSpecification ExceptSpec(*this);
7999   if (ClassDecl->isInvalidDecl())
8000     return ExceptSpec;
8001 
8002   // Inherited constructor.
8003   const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8004   const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8005   // FIXME: Copying or moving the parameters could add extra exceptions to the
8006   // set, as could the default arguments for the inherited constructor. This
8007   // will be addressed when we implement the resolution of core issue 1351.
8008   ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8009 
8010   // Direct base-class constructors.
8011   for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8012                                        BEnd = ClassDecl->bases_end();
8013        B != BEnd; ++B) {
8014     if (B->isVirtual()) // Handled below.
8015       continue;
8016 
8017     if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8018       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8019       if (BaseClassDecl == InheritedDecl)
8020         continue;
8021       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8022       if (Constructor)
8023         ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8024     }
8025   }
8026 
8027   // Virtual base-class constructors.
8028   for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8029                                        BEnd = ClassDecl->vbases_end();
8030        B != BEnd; ++B) {
8031     if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8032       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8033       if (BaseClassDecl == InheritedDecl)
8034         continue;
8035       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8036       if (Constructor)
8037         ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8038     }
8039   }
8040 
8041   // Field constructors.
8042   for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8043                                FEnd = ClassDecl->field_end();
8044        F != FEnd; ++F) {
8045     if (F->hasInClassInitializer()) {
8046       if (Expr *E = F->getInClassInitializer())
8047         ExceptSpec.CalledExpr(E);
8048       else if (!F->isInvalidDecl())
8049         Diag(CD->getLocation(),
8050              diag::err_in_class_initializer_references_def_ctor) << CD;
8051     } else if (const RecordType *RecordTy
8052               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8053       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8054       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8055       if (Constructor)
8056         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8057     }
8058   }
8059 
8060   return ExceptSpec;
8061 }
8062 
8063 namespace {
8064 /// RAII object to register a special member as being currently declared.
8065 struct DeclaringSpecialMember {
8066   Sema &S;
8067   Sema::SpecialMemberDecl D;
8068   bool WasAlreadyBeingDeclared;
8069 
8070   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8071     : S(S), D(RD, CSM) {
8072     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8073     if (WasAlreadyBeingDeclared)
8074       // This almost never happens, but if it does, ensure that our cache
8075       // doesn't contain a stale result.
8076       S.SpecialMemberCache.clear();
8077 
8078     // FIXME: Register a note to be produced if we encounter an error while
8079     // declaring the special member.
8080   }
8081   ~DeclaringSpecialMember() {
8082     if (!WasAlreadyBeingDeclared)
8083       S.SpecialMembersBeingDeclared.erase(D);
8084   }
8085 
8086   /// \brief Are we already trying to declare this special member?
8087   bool isAlreadyBeingDeclared() const {
8088     return WasAlreadyBeingDeclared;
8089   }
8090 };
8091 }
8092 
8093 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8094                                                      CXXRecordDecl *ClassDecl) {
8095   // C++ [class.ctor]p5:
8096   //   A default constructor for a class X is a constructor of class X
8097   //   that can be called without an argument. If there is no
8098   //   user-declared constructor for class X, a default constructor is
8099   //   implicitly declared. An implicitly-declared default constructor
8100   //   is an inline public member of its class.
8101   assert(ClassDecl->needsImplicitDefaultConstructor() &&
8102          "Should not build implicit default constructor!");
8103 
8104   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8105   if (DSM.isAlreadyBeingDeclared())
8106     return 0;
8107 
8108   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8109                                                      CXXDefaultConstructor,
8110                                                      false);
8111 
8112   // Create the actual constructor declaration.
8113   CanQualType ClassType
8114     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8115   SourceLocation ClassLoc = ClassDecl->getLocation();
8116   DeclarationName Name
8117     = Context.DeclarationNames.getCXXConstructorName(ClassType);
8118   DeclarationNameInfo NameInfo(Name, ClassLoc);
8119   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
8120       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
8121       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8122       Constexpr);
8123   DefaultCon->setAccess(AS_public);
8124   DefaultCon->setDefaulted();
8125   DefaultCon->setImplicit();
8126 
8127   // Build an exception specification pointing back at this constructor.
8128   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
8129   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8130 
8131   // We don't need to use SpecialMemberIsTrivial here; triviality for default
8132   // constructors is easy to compute.
8133   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8134 
8135   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
8136     SetDeclDeleted(DefaultCon, ClassLoc);
8137 
8138   // Note that we have declared this constructor.
8139   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
8140 
8141   if (Scope *S = getScopeForContext(ClassDecl))
8142     PushOnScopeChains(DefaultCon, S, false);
8143   ClassDecl->addDecl(DefaultCon);
8144 
8145   return DefaultCon;
8146 }
8147 
8148 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8149                                             CXXConstructorDecl *Constructor) {
8150   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
8151           !Constructor->doesThisDeclarationHaveABody() &&
8152           !Constructor->isDeleted()) &&
8153     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
8154 
8155   CXXRecordDecl *ClassDecl = Constructor->getParent();
8156   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
8157 
8158   SynthesizedFunctionScope Scope(*this, Constructor);
8159   DiagnosticErrorTrap Trap(Diags);
8160   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8161       Trap.hasErrorOccurred()) {
8162     Diag(CurrentLocation, diag::note_member_synthesized_at)
8163       << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
8164     Constructor->setInvalidDecl();
8165     return;
8166   }
8167 
8168   SourceLocation Loc = Constructor->getLocation();
8169   Constructor->setBody(new (Context) CompoundStmt(Loc));
8170 
8171   Constructor->markUsed(Context);
8172   MarkVTableUsed(CurrentLocation, ClassDecl);
8173 
8174   if (ASTMutationListener *L = getASTMutationListener()) {
8175     L->CompletedImplicitDefinition(Constructor);
8176   }
8177 
8178   DiagnoseUninitializedFields(*this, Constructor);
8179 }
8180 
8181 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
8182   // Perform any delayed checks on exception specifications.
8183   CheckDelayedMemberExceptionSpecs();
8184 }
8185 
8186 namespace {
8187 /// Information on inheriting constructors to declare.
8188 class InheritingConstructorInfo {
8189 public:
8190   InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8191       : SemaRef(SemaRef), Derived(Derived) {
8192     // Mark the constructors that we already have in the derived class.
8193     //
8194     // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8195     //   unless there is a user-declared constructor with the same signature in
8196     //   the class where the using-declaration appears.
8197     visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8198   }
8199 
8200   void inheritAll(CXXRecordDecl *RD) {
8201     visitAll(RD, &InheritingConstructorInfo::inherit);
8202   }
8203 
8204 private:
8205   /// Information about an inheriting constructor.
8206   struct InheritingConstructor {
8207     InheritingConstructor()
8208       : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
8209 
8210     /// If \c true, a constructor with this signature is already declared
8211     /// in the derived class.
8212     bool DeclaredInDerived;
8213 
8214     /// The constructor which is inherited.
8215     const CXXConstructorDecl *BaseCtor;
8216 
8217     /// The derived constructor we declared.
8218     CXXConstructorDecl *DerivedCtor;
8219   };
8220 
8221   /// Inheriting constructors with a given canonical type. There can be at
8222   /// most one such non-template constructor, and any number of templated
8223   /// constructors.
8224   struct InheritingConstructorsForType {
8225     InheritingConstructor NonTemplate;
8226     SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8227         Templates;
8228 
8229     InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8230       if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8231         TemplateParameterList *ParamList = FTD->getTemplateParameters();
8232         for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8233           if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8234                                                false, S.TPL_TemplateMatch))
8235             return Templates[I].second;
8236         Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8237         return Templates.back().second;
8238       }
8239 
8240       return NonTemplate;
8241     }
8242   };
8243 
8244   /// Get or create the inheriting constructor record for a constructor.
8245   InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8246                                   QualType CtorType) {
8247     return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8248         .getEntry(SemaRef, Ctor);
8249   }
8250 
8251   typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8252 
8253   /// Process all constructors for a class.
8254   void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
8255     for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
8256                                       CtorE = RD->ctor_end();
8257          CtorIt != CtorE; ++CtorIt)
8258       (this->*Callback)(*CtorIt);
8259     for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8260              I(RD->decls_begin()), E(RD->decls_end());
8261          I != E; ++I) {
8262       const FunctionDecl *FD = (*I)->getTemplatedDecl();
8263       if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8264         (this->*Callback)(CD);
8265     }
8266   }
8267 
8268   /// Note that a constructor (or constructor template) was declared in Derived.
8269   void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8270     getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8271   }
8272 
8273   /// Inherit a single constructor.
8274   void inherit(const CXXConstructorDecl *Ctor) {
8275     const FunctionProtoType *CtorType =
8276         Ctor->getType()->castAs<FunctionProtoType>();
8277     ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
8278     FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8279 
8280     SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8281 
8282     // Core issue (no number yet): the ellipsis is always discarded.
8283     if (EPI.Variadic) {
8284       SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8285       SemaRef.Diag(Ctor->getLocation(),
8286                    diag::note_using_decl_constructor_ellipsis);
8287       EPI.Variadic = false;
8288     }
8289 
8290     // Declare a constructor for each number of parameters.
8291     //
8292     // C++11 [class.inhctor]p1:
8293     //   The candidate set of inherited constructors from the class X named in
8294     //   the using-declaration consists of [... modulo defects ...] for each
8295     //   constructor or constructor template of X, the set of constructors or
8296     //   constructor templates that results from omitting any ellipsis parameter
8297     //   specification and successively omitting parameters with a default
8298     //   argument from the end of the parameter-type-list
8299     unsigned MinParams = minParamsToInherit(Ctor);
8300     unsigned Params = Ctor->getNumParams();
8301     if (Params >= MinParams) {
8302       do
8303         declareCtor(UsingLoc, Ctor,
8304                     SemaRef.Context.getFunctionType(
8305                         Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
8306       while (Params > MinParams &&
8307              Ctor->getParamDecl(--Params)->hasDefaultArg());
8308     }
8309   }
8310 
8311   /// Find the using-declaration which specified that we should inherit the
8312   /// constructors of \p Base.
8313   SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8314     // No fancy lookup required; just look for the base constructor name
8315     // directly within the derived class.
8316     ASTContext &Context = SemaRef.Context;
8317     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8318         Context.getCanonicalType(Context.getRecordType(Base)));
8319     DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8320     return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8321   }
8322 
8323   unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8324     // C++11 [class.inhctor]p3:
8325     //   [F]or each constructor template in the candidate set of inherited
8326     //   constructors, a constructor template is implicitly declared
8327     if (Ctor->getDescribedFunctionTemplate())
8328       return 0;
8329 
8330     //   For each non-template constructor in the candidate set of inherited
8331     //   constructors other than a constructor having no parameters or a
8332     //   copy/move constructor having a single parameter, a constructor is
8333     //   implicitly declared [...]
8334     if (Ctor->getNumParams() == 0)
8335       return 1;
8336     if (Ctor->isCopyOrMoveConstructor())
8337       return 2;
8338 
8339     // Per discussion on core reflector, never inherit a constructor which
8340     // would become a default, copy, or move constructor of Derived either.
8341     const ParmVarDecl *PD = Ctor->getParamDecl(0);
8342     const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8343     return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8344   }
8345 
8346   /// Declare a single inheriting constructor, inheriting the specified
8347   /// constructor, with the given type.
8348   void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8349                    QualType DerivedType) {
8350     InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8351 
8352     // C++11 [class.inhctor]p3:
8353     //   ... a constructor is implicitly declared with the same constructor
8354     //   characteristics unless there is a user-declared constructor with
8355     //   the same signature in the class where the using-declaration appears
8356     if (Entry.DeclaredInDerived)
8357       return;
8358 
8359     // C++11 [class.inhctor]p7:
8360     //   If two using-declarations declare inheriting constructors with the
8361     //   same signature, the program is ill-formed
8362     if (Entry.DerivedCtor) {
8363       if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8364         // Only diagnose this once per constructor.
8365         if (Entry.DerivedCtor->isInvalidDecl())
8366           return;
8367         Entry.DerivedCtor->setInvalidDecl();
8368 
8369         SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8370         SemaRef.Diag(BaseCtor->getLocation(),
8371                      diag::note_using_decl_constructor_conflict_current_ctor);
8372         SemaRef.Diag(Entry.BaseCtor->getLocation(),
8373                      diag::note_using_decl_constructor_conflict_previous_ctor);
8374         SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8375                      diag::note_using_decl_constructor_conflict_previous_using);
8376       } else {
8377         // Core issue (no number): if the same inheriting constructor is
8378         // produced by multiple base class constructors from the same base
8379         // class, the inheriting constructor is defined as deleted.
8380         SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8381       }
8382 
8383       return;
8384     }
8385 
8386     ASTContext &Context = SemaRef.Context;
8387     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8388         Context.getCanonicalType(Context.getRecordType(Derived)));
8389     DeclarationNameInfo NameInfo(Name, UsingLoc);
8390 
8391     TemplateParameterList *TemplateParams = 0;
8392     if (const FunctionTemplateDecl *FTD =
8393             BaseCtor->getDescribedFunctionTemplate()) {
8394       TemplateParams = FTD->getTemplateParameters();
8395       // We're reusing template parameters from a different DeclContext. This
8396       // is questionable at best, but works out because the template depth in
8397       // both places is guaranteed to be 0.
8398       // FIXME: Rebuild the template parameters in the new context, and
8399       // transform the function type to refer to them.
8400     }
8401 
8402     // Build type source info pointing at the using-declaration. This is
8403     // required by template instantiation.
8404     TypeSourceInfo *TInfo =
8405         Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8406     FunctionProtoTypeLoc ProtoLoc =
8407         TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8408 
8409     CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8410         Context, Derived, UsingLoc, NameInfo, DerivedType,
8411         TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8412         /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8413 
8414     // Build an unevaluated exception specification for this constructor.
8415     const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8416     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8417     EPI.ExceptionSpecType = EST_Unevaluated;
8418     EPI.ExceptionSpecDecl = DerivedCtor;
8419     DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
8420                                                  FPT->getArgTypes(), EPI));
8421 
8422     // Build the parameter declarations.
8423     SmallVector<ParmVarDecl *, 16> ParamDecls;
8424     for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
8425       TypeSourceInfo *TInfo =
8426           Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
8427       ParmVarDecl *PD = ParmVarDecl::Create(
8428           Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
8429           FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
8430       PD->setScopeInfo(0, I);
8431       PD->setImplicit();
8432       ParamDecls.push_back(PD);
8433       ProtoLoc.setArg(I, PD);
8434     }
8435 
8436     // Set up the new constructor.
8437     DerivedCtor->setAccess(BaseCtor->getAccess());
8438     DerivedCtor->setParams(ParamDecls);
8439     DerivedCtor->setInheritedConstructor(BaseCtor);
8440     if (BaseCtor->isDeleted())
8441       SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8442 
8443     // If this is a constructor template, build the template declaration.
8444     if (TemplateParams) {
8445       FunctionTemplateDecl *DerivedTemplate =
8446           FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8447                                        TemplateParams, DerivedCtor);
8448       DerivedTemplate->setAccess(BaseCtor->getAccess());
8449       DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8450       Derived->addDecl(DerivedTemplate);
8451     } else {
8452       Derived->addDecl(DerivedCtor);
8453     }
8454 
8455     Entry.BaseCtor = BaseCtor;
8456     Entry.DerivedCtor = DerivedCtor;
8457   }
8458 
8459   Sema &SemaRef;
8460   CXXRecordDecl *Derived;
8461   typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8462   MapType Map;
8463 };
8464 }
8465 
8466 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8467   // Defer declaring the inheriting constructors until the class is
8468   // instantiated.
8469   if (ClassDecl->isDependentContext())
8470     return;
8471 
8472   // Find base classes from which we might inherit constructors.
8473   SmallVector<CXXRecordDecl*, 4> InheritedBases;
8474   for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8475                                           BaseE = ClassDecl->bases_end();
8476        BaseIt != BaseE; ++BaseIt)
8477     if (BaseIt->getInheritConstructors())
8478       InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
8479 
8480   // Go no further if we're not inheriting any constructors.
8481   if (InheritedBases.empty())
8482     return;
8483 
8484   // Declare the inherited constructors.
8485   InheritingConstructorInfo ICI(*this, ClassDecl);
8486   for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8487     ICI.inheritAll(InheritedBases[I]);
8488 }
8489 
8490 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8491                                        CXXConstructorDecl *Constructor) {
8492   CXXRecordDecl *ClassDecl = Constructor->getParent();
8493   assert(Constructor->getInheritedConstructor() &&
8494          !Constructor->doesThisDeclarationHaveABody() &&
8495          !Constructor->isDeleted());
8496 
8497   SynthesizedFunctionScope Scope(*this, Constructor);
8498   DiagnosticErrorTrap Trap(Diags);
8499   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8500       Trap.hasErrorOccurred()) {
8501     Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8502       << Context.getTagDeclType(ClassDecl);
8503     Constructor->setInvalidDecl();
8504     return;
8505   }
8506 
8507   SourceLocation Loc = Constructor->getLocation();
8508   Constructor->setBody(new (Context) CompoundStmt(Loc));
8509 
8510   Constructor->markUsed(Context);
8511   MarkVTableUsed(CurrentLocation, ClassDecl);
8512 
8513   if (ASTMutationListener *L = getASTMutationListener()) {
8514     L->CompletedImplicitDefinition(Constructor);
8515   }
8516 }
8517 
8518 
8519 Sema::ImplicitExceptionSpecification
8520 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8521   CXXRecordDecl *ClassDecl = MD->getParent();
8522 
8523   // C++ [except.spec]p14:
8524   //   An implicitly declared special member function (Clause 12) shall have
8525   //   an exception-specification.
8526   ImplicitExceptionSpecification ExceptSpec(*this);
8527   if (ClassDecl->isInvalidDecl())
8528     return ExceptSpec;
8529 
8530   // Direct base-class destructors.
8531   for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8532                                        BEnd = ClassDecl->bases_end();
8533        B != BEnd; ++B) {
8534     if (B->isVirtual()) // Handled below.
8535       continue;
8536 
8537     if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
8538       ExceptSpec.CalledDecl(B->getLocStart(),
8539                    LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
8540   }
8541 
8542   // Virtual base-class destructors.
8543   for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8544                                        BEnd = ClassDecl->vbases_end();
8545        B != BEnd; ++B) {
8546     if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
8547       ExceptSpec.CalledDecl(B->getLocStart(),
8548                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
8549   }
8550 
8551   // Field destructors.
8552   for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8553                                FEnd = ClassDecl->field_end();
8554        F != FEnd; ++F) {
8555     if (const RecordType *RecordTy
8556         = Context.getBaseElementType(F->getType())->getAs<RecordType>())
8557       ExceptSpec.CalledDecl(F->getLocation(),
8558                   LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
8559   }
8560 
8561   return ExceptSpec;
8562 }
8563 
8564 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8565   // C++ [class.dtor]p2:
8566   //   If a class has no user-declared destructor, a destructor is
8567   //   declared implicitly. An implicitly-declared destructor is an
8568   //   inline public member of its class.
8569   assert(ClassDecl->needsImplicitDestructor());
8570 
8571   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8572   if (DSM.isAlreadyBeingDeclared())
8573     return 0;
8574 
8575   // Create the actual destructor declaration.
8576   CanQualType ClassType
8577     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8578   SourceLocation ClassLoc = ClassDecl->getLocation();
8579   DeclarationName Name
8580     = Context.DeclarationNames.getCXXDestructorName(ClassType);
8581   DeclarationNameInfo NameInfo(Name, ClassLoc);
8582   CXXDestructorDecl *Destructor
8583       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8584                                   QualType(), 0, /*isInline=*/true,
8585                                   /*isImplicitlyDeclared=*/true);
8586   Destructor->setAccess(AS_public);
8587   Destructor->setDefaulted();
8588   Destructor->setImplicit();
8589 
8590   // Build an exception specification pointing back at this destructor.
8591   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
8592   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8593 
8594   AddOverriddenMethods(ClassDecl, Destructor);
8595 
8596   // We don't need to use SpecialMemberIsTrivial here; triviality for
8597   // destructors is easy to compute.
8598   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8599 
8600   if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
8601     SetDeclDeleted(Destructor, ClassLoc);
8602 
8603   // Note that we have declared this destructor.
8604   ++ASTContext::NumImplicitDestructorsDeclared;
8605 
8606   // Introduce this destructor into its scope.
8607   if (Scope *S = getScopeForContext(ClassDecl))
8608     PushOnScopeChains(Destructor, S, false);
8609   ClassDecl->addDecl(Destructor);
8610 
8611   return Destructor;
8612 }
8613 
8614 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
8615                                     CXXDestructorDecl *Destructor) {
8616   assert((Destructor->isDefaulted() &&
8617           !Destructor->doesThisDeclarationHaveABody() &&
8618           !Destructor->isDeleted()) &&
8619          "DefineImplicitDestructor - call it for implicit default dtor");
8620   CXXRecordDecl *ClassDecl = Destructor->getParent();
8621   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
8622 
8623   if (Destructor->isInvalidDecl())
8624     return;
8625 
8626   SynthesizedFunctionScope Scope(*this, Destructor);
8627 
8628   DiagnosticErrorTrap Trap(Diags);
8629   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8630                                          Destructor->getParent());
8631 
8632   if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
8633     Diag(CurrentLocation, diag::note_member_synthesized_at)
8634       << CXXDestructor << Context.getTagDeclType(ClassDecl);
8635 
8636     Destructor->setInvalidDecl();
8637     return;
8638   }
8639 
8640   SourceLocation Loc = Destructor->getLocation();
8641   Destructor->setBody(new (Context) CompoundStmt(Loc));
8642   Destructor->markUsed(Context);
8643   MarkVTableUsed(CurrentLocation, ClassDecl);
8644 
8645   if (ASTMutationListener *L = getASTMutationListener()) {
8646     L->CompletedImplicitDefinition(Destructor);
8647   }
8648 }
8649 
8650 /// \brief Perform any semantic analysis which needs to be delayed until all
8651 /// pending class member declarations have been parsed.
8652 void Sema::ActOnFinishCXXMemberDecls() {
8653   // If the context is an invalid C++ class, just suppress these checks.
8654   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8655     if (Record->isInvalidDecl()) {
8656       DelayedDefaultedMemberExceptionSpecs.clear();
8657       DelayedDestructorExceptionSpecChecks.clear();
8658       return;
8659     }
8660   }
8661 }
8662 
8663 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8664                                          CXXDestructorDecl *Destructor) {
8665   assert(getLangOpts().CPlusPlus11 &&
8666          "adjusting dtor exception specs was introduced in c++11");
8667 
8668   // C++11 [class.dtor]p3:
8669   //   A declaration of a destructor that does not have an exception-
8670   //   specification is implicitly considered to have the same exception-
8671   //   specification as an implicit declaration.
8672   const FunctionProtoType *DtorType = Destructor->getType()->
8673                                         getAs<FunctionProtoType>();
8674   if (DtorType->hasExceptionSpec())
8675     return;
8676 
8677   // Replace the destructor's type, building off the existing one. Fortunately,
8678   // the only thing of interest in the destructor type is its extended info.
8679   // The return and arguments are fixed.
8680   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8681   EPI.ExceptionSpecType = EST_Unevaluated;
8682   EPI.ExceptionSpecDecl = Destructor;
8683   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8684 
8685   // FIXME: If the destructor has a body that could throw, and the newly created
8686   // spec doesn't allow exceptions, we should emit a warning, because this
8687   // change in behavior can break conforming C++03 programs at runtime.
8688   // However, we don't have a body or an exception specification yet, so it
8689   // needs to be done somewhere else.
8690 }
8691 
8692 namespace {
8693 /// \brief An abstract base class for all helper classes used in building the
8694 //  copy/move operators. These classes serve as factory functions and help us
8695 //  avoid using the same Expr* in the AST twice.
8696 class ExprBuilder {
8697   ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8698   ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8699 
8700 protected:
8701   static Expr *assertNotNull(Expr *E) {
8702     assert(E && "Expression construction must not fail.");
8703     return E;
8704   }
8705 
8706 public:
8707   ExprBuilder() {}
8708   virtual ~ExprBuilder() {}
8709 
8710   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
8711 };
8712 
8713 class RefBuilder: public ExprBuilder {
8714   VarDecl *Var;
8715   QualType VarType;
8716 
8717 public:
8718   virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8719     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).take());
8720   }
8721 
8722   RefBuilder(VarDecl *Var, QualType VarType)
8723       : Var(Var), VarType(VarType) {}
8724 };
8725 
8726 class ThisBuilder: public ExprBuilder {
8727 public:
8728   virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8729     return assertNotNull(S.ActOnCXXThis(Loc).takeAs<Expr>());
8730   }
8731 };
8732 
8733 class CastBuilder: public ExprBuilder {
8734   const ExprBuilder &Builder;
8735   QualType Type;
8736   ExprValueKind Kind;
8737   const CXXCastPath &Path;
8738 
8739 public:
8740   virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8741     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
8742                                              CK_UncheckedDerivedToBase, Kind,
8743                                              &Path).take());
8744   }
8745 
8746   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
8747               const CXXCastPath &Path)
8748       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
8749 };
8750 
8751 class DerefBuilder: public ExprBuilder {
8752   const ExprBuilder &Builder;
8753 
8754 public:
8755   virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8756     return assertNotNull(
8757         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).take());
8758   }
8759 
8760   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8761 };
8762 
8763 class MemberBuilder: public ExprBuilder {
8764   const ExprBuilder &Builder;
8765   QualType Type;
8766   CXXScopeSpec SS;
8767   bool IsArrow;
8768   LookupResult &MemberLookup;
8769 
8770 public:
8771   virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8772     return assertNotNull(S.BuildMemberReferenceExpr(
8773         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 0,
8774         MemberLookup, 0).take());
8775   }
8776 
8777   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
8778                 LookupResult &MemberLookup)
8779       : Builder(Builder), Type(Type), IsArrow(IsArrow),
8780         MemberLookup(MemberLookup) {}
8781 };
8782 
8783 class MoveCastBuilder: public ExprBuilder {
8784   const ExprBuilder &Builder;
8785 
8786 public:
8787   virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8788     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
8789   }
8790 
8791   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8792 };
8793 
8794 class LvalueConvBuilder: public ExprBuilder {
8795   const ExprBuilder &Builder;
8796 
8797 public:
8798   virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8799     return assertNotNull(
8800         S.DefaultLvalueConversion(Builder.build(S, Loc)).take());
8801   }
8802 
8803   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8804 };
8805 
8806 class SubscriptBuilder: public ExprBuilder {
8807   const ExprBuilder &Base;
8808   const ExprBuilder &Index;
8809 
8810 public:
8811   virtual Expr *build(Sema &S, SourceLocation Loc) const
8812       LLVM_OVERRIDE {
8813     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
8814         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).take());
8815   }
8816 
8817   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
8818       : Base(Base), Index(Index) {}
8819 };
8820 
8821 } // end anonymous namespace
8822 
8823 /// When generating a defaulted copy or move assignment operator, if a field
8824 /// should be copied with __builtin_memcpy rather than via explicit assignments,
8825 /// do so. This optimization only applies for arrays of scalars, and for arrays
8826 /// of class type where the selected copy/move-assignment operator is trivial.
8827 static StmtResult
8828 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
8829                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
8830   // Compute the size of the memory buffer to be copied.
8831   QualType SizeType = S.Context.getSizeType();
8832   llvm::APInt Size(S.Context.getTypeSize(SizeType),
8833                    S.Context.getTypeSizeInChars(T).getQuantity());
8834 
8835   // Take the address of the field references for "from" and "to". We
8836   // directly construct UnaryOperators here because semantic analysis
8837   // does not permit us to take the address of an xvalue.
8838   Expr *From = FromB.build(S, Loc);
8839   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8840                          S.Context.getPointerType(From->getType()),
8841                          VK_RValue, OK_Ordinary, Loc);
8842   Expr *To = ToB.build(S, Loc);
8843   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8844                        S.Context.getPointerType(To->getType()),
8845                        VK_RValue, OK_Ordinary, Loc);
8846 
8847   const Type *E = T->getBaseElementTypeUnsafe();
8848   bool NeedsCollectableMemCpy =
8849     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8850 
8851   // Create a reference to the __builtin_objc_memmove_collectable function
8852   StringRef MemCpyName = NeedsCollectableMemCpy ?
8853     "__builtin_objc_memmove_collectable" :
8854     "__builtin_memcpy";
8855   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8856                  Sema::LookupOrdinaryName);
8857   S.LookupName(R, S.TUScope, true);
8858 
8859   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8860   if (!MemCpy)
8861     // Something went horribly wrong earlier, and we will have complained
8862     // about it.
8863     return StmtError();
8864 
8865   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8866                                             VK_RValue, Loc, 0);
8867   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8868 
8869   Expr *CallArgs[] = {
8870     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8871   };
8872   ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8873                                     Loc, CallArgs, Loc);
8874 
8875   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8876   return S.Owned(Call.takeAs<Stmt>());
8877 }
8878 
8879 /// \brief Builds a statement that copies/moves the given entity from \p From to
8880 /// \c To.
8881 ///
8882 /// This routine is used to copy/move the members of a class with an
8883 /// implicitly-declared copy/move assignment operator. When the entities being
8884 /// copied are arrays, this routine builds for loops to copy them.
8885 ///
8886 /// \param S The Sema object used for type-checking.
8887 ///
8888 /// \param Loc The location where the implicit copy/move is being generated.
8889 ///
8890 /// \param T The type of the expressions being copied/moved. Both expressions
8891 /// must have this type.
8892 ///
8893 /// \param To The expression we are copying/moving to.
8894 ///
8895 /// \param From The expression we are copying/moving from.
8896 ///
8897 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
8898 /// Otherwise, it's a non-static member subobject.
8899 ///
8900 /// \param Copying Whether we're copying or moving.
8901 ///
8902 /// \param Depth Internal parameter recording the depth of the recursion.
8903 ///
8904 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8905 /// if a memcpy should be used instead.
8906 static StmtResult
8907 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8908                                  const ExprBuilder &To, const ExprBuilder &From,
8909                                  bool CopyingBaseSubobject, bool Copying,
8910                                  unsigned Depth = 0) {
8911   // C++11 [class.copy]p28:
8912   //   Each subobject is assigned in the manner appropriate to its type:
8913   //
8914   //     - if the subobject is of class type, as if by a call to operator= with
8915   //       the subobject as the object expression and the corresponding
8916   //       subobject of x as a single function argument (as if by explicit
8917   //       qualification; that is, ignoring any possible virtual overriding
8918   //       functions in more derived classes);
8919   //
8920   // C++03 [class.copy]p13:
8921   //     - if the subobject is of class type, the copy assignment operator for
8922   //       the class is used (as if by explicit qualification; that is,
8923   //       ignoring any possible virtual overriding functions in more derived
8924   //       classes);
8925   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8926     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8927 
8928     // Look for operator=.
8929     DeclarationName Name
8930       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8931     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8932     S.LookupQualifiedName(OpLookup, ClassDecl, false);
8933 
8934     // Prior to C++11, filter out any result that isn't a copy/move-assignment
8935     // operator.
8936     if (!S.getLangOpts().CPlusPlus11) {
8937       LookupResult::Filter F = OpLookup.makeFilter();
8938       while (F.hasNext()) {
8939         NamedDecl *D = F.next();
8940         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8941           if (Method->isCopyAssignmentOperator() ||
8942               (!Copying && Method->isMoveAssignmentOperator()))
8943             continue;
8944 
8945         F.erase();
8946       }
8947       F.done();
8948     }
8949 
8950     // Suppress the protected check (C++ [class.protected]) for each of the
8951     // assignment operators we found. This strange dance is required when
8952     // we're assigning via a base classes's copy-assignment operator. To
8953     // ensure that we're getting the right base class subobject (without
8954     // ambiguities), we need to cast "this" to that subobject type; to
8955     // ensure that we don't go through the virtual call mechanism, we need
8956     // to qualify the operator= name with the base class (see below). However,
8957     // this means that if the base class has a protected copy assignment
8958     // operator, the protected member access check will fail. So, we
8959     // rewrite "protected" access to "public" access in this case, since we
8960     // know by construction that we're calling from a derived class.
8961     if (CopyingBaseSubobject) {
8962       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8963            L != LEnd; ++L) {
8964         if (L.getAccess() == AS_protected)
8965           L.setAccess(AS_public);
8966       }
8967     }
8968 
8969     // Create the nested-name-specifier that will be used to qualify the
8970     // reference to operator=; this is required to suppress the virtual
8971     // call mechanism.
8972     CXXScopeSpec SS;
8973     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
8974     SS.MakeTrivial(S.Context,
8975                    NestedNameSpecifier::Create(S.Context, 0, false,
8976                                                CanonicalT),
8977                    Loc);
8978 
8979     // Create the reference to operator=.
8980     ExprResult OpEqualRef
8981       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
8982                                    SS, /*TemplateKWLoc=*/SourceLocation(),
8983                                    /*FirstQualifierInScope=*/0,
8984                                    OpLookup,
8985                                    /*TemplateArgs=*/0,
8986                                    /*SuppressQualifierCheck=*/true);
8987     if (OpEqualRef.isInvalid())
8988       return StmtError();
8989 
8990     // Build the call to the assignment operator.
8991 
8992     Expr *FromInst = From.build(S, Loc);
8993     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
8994                                                   OpEqualRef.takeAs<Expr>(),
8995                                                   Loc, FromInst, Loc);
8996     if (Call.isInvalid())
8997       return StmtError();
8998 
8999     // If we built a call to a trivial 'operator=' while copying an array,
9000     // bail out. We'll replace the whole shebang with a memcpy.
9001     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9002     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9003       return StmtResult((Stmt*)0);
9004 
9005     // Convert to an expression-statement, and clean up any produced
9006     // temporaries.
9007     return S.ActOnExprStmt(Call);
9008   }
9009 
9010   //     - if the subobject is of scalar type, the built-in assignment
9011   //       operator is used.
9012   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
9013   if (!ArrayTy) {
9014     ExprResult Assignment = S.CreateBuiltinBinOp(
9015         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
9016     if (Assignment.isInvalid())
9017       return StmtError();
9018     return S.ActOnExprStmt(Assignment);
9019   }
9020 
9021   //     - if the subobject is an array, each element is assigned, in the
9022   //       manner appropriate to the element type;
9023 
9024   // Construct a loop over the array bounds, e.g.,
9025   //
9026   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9027   //
9028   // that will copy each of the array elements.
9029   QualType SizeType = S.Context.getSizeType();
9030 
9031   // Create the iteration variable.
9032   IdentifierInfo *IterationVarName = 0;
9033   {
9034     SmallString<8> Str;
9035     llvm::raw_svector_ostream OS(Str);
9036     OS << "__i" << Depth;
9037     IterationVarName = &S.Context.Idents.get(OS.str());
9038   }
9039   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
9040                                           IterationVarName, SizeType,
9041                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
9042                                           SC_None);
9043 
9044   // Initialize the iteration variable to zero.
9045   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
9046   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
9047 
9048   // Creates a reference to the iteration variable.
9049   RefBuilder IterationVarRef(IterationVar, SizeType);
9050   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
9051 
9052   // Create the DeclStmt that holds the iteration variable.
9053   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
9054 
9055   // Subscript the "from" and "to" expressions with the iteration variable.
9056   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9057   MoveCastBuilder FromIndexMove(FromIndexCopy);
9058   const ExprBuilder *FromIndex;
9059   if (Copying)
9060     FromIndex = &FromIndexCopy;
9061   else
9062     FromIndex = &FromIndexMove;
9063 
9064   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
9065 
9066   // Build the copy/move for an individual element of the array.
9067   StmtResult Copy =
9068     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
9069                                      ToIndex, *FromIndex, CopyingBaseSubobject,
9070                                      Copying, Depth + 1);
9071   // Bail out if copying fails or if we determined that we should use memcpy.
9072   if (Copy.isInvalid() || !Copy.get())
9073     return Copy;
9074 
9075   // Create the comparison against the array bound.
9076   llvm::APInt Upper
9077     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9078   Expr *Comparison
9079     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
9080                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9081                                      BO_NE, S.Context.BoolTy,
9082                                      VK_RValue, OK_Ordinary, Loc, false);
9083 
9084   // Create the pre-increment of the iteration variable.
9085   Expr *Increment
9086     = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9087                                     SizeType, VK_LValue, OK_Ordinary, Loc);
9088 
9089   // Construct the loop that copies all elements of this array.
9090   return S.ActOnForStmt(Loc, Loc, InitStmt,
9091                         S.MakeFullExpr(Comparison),
9092                         0, S.MakeFullDiscardedValueExpr(Increment),
9093                         Loc, Copy.take());
9094 }
9095 
9096 static StmtResult
9097 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
9098                       const ExprBuilder &To, const ExprBuilder &From,
9099                       bool CopyingBaseSubobject, bool Copying) {
9100   // Maybe we should use a memcpy?
9101   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9102       T.isTriviallyCopyableType(S.Context))
9103     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9104 
9105   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9106                                                      CopyingBaseSubobject,
9107                                                      Copying, 0));
9108 
9109   // If we ended up picking a trivial assignment operator for an array of a
9110   // non-trivially-copyable class type, just emit a memcpy.
9111   if (!Result.isInvalid() && !Result.get())
9112     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9113 
9114   return Result;
9115 }
9116 
9117 Sema::ImplicitExceptionSpecification
9118 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9119   CXXRecordDecl *ClassDecl = MD->getParent();
9120 
9121   ImplicitExceptionSpecification ExceptSpec(*this);
9122   if (ClassDecl->isInvalidDecl())
9123     return ExceptSpec;
9124 
9125   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9126   assert(T->getNumArgs() == 1 && "not a copy assignment op");
9127   unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9128 
9129   // C++ [except.spec]p14:
9130   //   An implicitly declared special member function (Clause 12) shall have an
9131   //   exception-specification. [...]
9132 
9133   // It is unspecified whether or not an implicit copy assignment operator
9134   // attempts to deduplicate calls to assignment operators of virtual bases are
9135   // made. As such, this exception specification is effectively unspecified.
9136   // Based on a similar decision made for constness in C++0x, we're erring on
9137   // the side of assuming such calls to be made regardless of whether they
9138   // actually happen.
9139   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9140                                        BaseEnd = ClassDecl->bases_end();
9141        Base != BaseEnd; ++Base) {
9142     if (Base->isVirtual())
9143       continue;
9144 
9145     CXXRecordDecl *BaseClassDecl
9146       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9147     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9148                                                             ArgQuals, false, 0))
9149       ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
9150   }
9151 
9152   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9153                                        BaseEnd = ClassDecl->vbases_end();
9154        Base != BaseEnd; ++Base) {
9155     CXXRecordDecl *BaseClassDecl
9156       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9157     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9158                                                             ArgQuals, false, 0))
9159       ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
9160   }
9161 
9162   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9163                                   FieldEnd = ClassDecl->field_end();
9164        Field != FieldEnd;
9165        ++Field) {
9166     QualType FieldType = Context.getBaseElementType(Field->getType());
9167     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9168       if (CXXMethodDecl *CopyAssign =
9169           LookupCopyingAssignment(FieldClassDecl,
9170                                   ArgQuals | FieldType.getCVRQualifiers(),
9171                                   false, 0))
9172         ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
9173     }
9174   }
9175 
9176   return ExceptSpec;
9177 }
9178 
9179 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9180   // Note: The following rules are largely analoguous to the copy
9181   // constructor rules. Note that virtual bases are not taken into account
9182   // for determining the argument type of the operator. Note also that
9183   // operators taking an object instead of a reference are allowed.
9184   assert(ClassDecl->needsImplicitCopyAssignment());
9185 
9186   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9187   if (DSM.isAlreadyBeingDeclared())
9188     return 0;
9189 
9190   QualType ArgType = Context.getTypeDeclType(ClassDecl);
9191   QualType RetType = Context.getLValueReferenceType(ArgType);
9192   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9193   if (Const)
9194     ArgType = ArgType.withConst();
9195   ArgType = Context.getLValueReferenceType(ArgType);
9196 
9197   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9198                                                      CXXCopyAssignment,
9199                                                      Const);
9200 
9201   //   An implicitly-declared copy assignment operator is an inline public
9202   //   member of its class.
9203   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9204   SourceLocation ClassLoc = ClassDecl->getLocation();
9205   DeclarationNameInfo NameInfo(Name, ClassLoc);
9206   CXXMethodDecl *CopyAssignment =
9207       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9208                             /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
9209                             /*isInline=*/ true, Constexpr, SourceLocation());
9210   CopyAssignment->setAccess(AS_public);
9211   CopyAssignment->setDefaulted();
9212   CopyAssignment->setImplicit();
9213 
9214   // Build an exception specification pointing back at this member.
9215   FunctionProtoType::ExtProtoInfo EPI =
9216       getImplicitMethodEPI(*this, CopyAssignment);
9217   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
9218 
9219   // Add the parameter to the operator.
9220   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
9221                                                ClassLoc, ClassLoc, /*Id=*/0,
9222                                                ArgType, /*TInfo=*/0,
9223                                                SC_None, 0);
9224   CopyAssignment->setParams(FromParam);
9225 
9226   AddOverriddenMethods(ClassDecl, CopyAssignment);
9227 
9228   CopyAssignment->setTrivial(
9229     ClassDecl->needsOverloadResolutionForCopyAssignment()
9230       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9231       : ClassDecl->hasTrivialCopyAssignment());
9232 
9233   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
9234     SetDeclDeleted(CopyAssignment, ClassLoc);
9235 
9236   // Note that we have added this copy-assignment operator.
9237   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9238 
9239   if (Scope *S = getScopeForContext(ClassDecl))
9240     PushOnScopeChains(CopyAssignment, S, false);
9241   ClassDecl->addDecl(CopyAssignment);
9242 
9243   return CopyAssignment;
9244 }
9245 
9246 /// Diagnose an implicit copy operation for a class which is odr-used, but
9247 /// which is deprecated because the class has a user-declared copy constructor,
9248 /// copy assignment operator, or destructor.
9249 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9250                                             SourceLocation UseLoc) {
9251   assert(CopyOp->isImplicit());
9252 
9253   CXXRecordDecl *RD = CopyOp->getParent();
9254   CXXMethodDecl *UserDeclaredOperation = 0;
9255 
9256   // In Microsoft mode, assignment operations don't affect constructors and
9257   // vice versa.
9258   if (RD->hasUserDeclaredDestructor()) {
9259     UserDeclaredOperation = RD->getDestructor();
9260   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9261              RD->hasUserDeclaredCopyConstructor() &&
9262              !S.getLangOpts().MicrosoftMode) {
9263     // Find any user-declared copy constructor.
9264     for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
9265                                       E = RD->ctor_end(); I != E; ++I) {
9266       if (I->isCopyConstructor()) {
9267         UserDeclaredOperation = *I;
9268         break;
9269       }
9270     }
9271     assert(UserDeclaredOperation);
9272   } else if (isa<CXXConstructorDecl>(CopyOp) &&
9273              RD->hasUserDeclaredCopyAssignment() &&
9274              !S.getLangOpts().MicrosoftMode) {
9275     // Find any user-declared move assignment operator.
9276     for (CXXRecordDecl::method_iterator I = RD->method_begin(),
9277                                         E = RD->method_end(); I != E; ++I) {
9278       if (I->isCopyAssignmentOperator()) {
9279         UserDeclaredOperation = *I;
9280         break;
9281       }
9282     }
9283     assert(UserDeclaredOperation);
9284   }
9285 
9286   if (UserDeclaredOperation) {
9287     S.Diag(UserDeclaredOperation->getLocation(),
9288          diag::warn_deprecated_copy_operation)
9289       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9290       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9291     S.Diag(UseLoc, diag::note_member_synthesized_at)
9292       << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9293                                           : Sema::CXXCopyAssignment)
9294       << RD;
9295   }
9296 }
9297 
9298 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9299                                         CXXMethodDecl *CopyAssignOperator) {
9300   assert((CopyAssignOperator->isDefaulted() &&
9301           CopyAssignOperator->isOverloadedOperator() &&
9302           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
9303           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9304           !CopyAssignOperator->isDeleted()) &&
9305          "DefineImplicitCopyAssignment called for wrong function");
9306 
9307   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9308 
9309   if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9310     CopyAssignOperator->setInvalidDecl();
9311     return;
9312   }
9313 
9314   // C++11 [class.copy]p18:
9315   //   The [definition of an implicitly declared copy assignment operator] is
9316   //   deprecated if the class has a user-declared copy constructor or a
9317   //   user-declared destructor.
9318   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9319     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9320 
9321   CopyAssignOperator->markUsed(Context);
9322 
9323   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
9324   DiagnosticErrorTrap Trap(Diags);
9325 
9326   // C++0x [class.copy]p30:
9327   //   The implicitly-defined or explicitly-defaulted copy assignment operator
9328   //   for a non-union class X performs memberwise copy assignment of its
9329   //   subobjects. The direct base classes of X are assigned first, in the
9330   //   order of their declaration in the base-specifier-list, and then the
9331   //   immediate non-static data members of X are assigned, in the order in
9332   //   which they were declared in the class definition.
9333 
9334   // The statements that form the synthesized function body.
9335   SmallVector<Stmt*, 8> Statements;
9336 
9337   // The parameter for the "other" object, which we are copying from.
9338   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9339   Qualifiers OtherQuals = Other->getType().getQualifiers();
9340   QualType OtherRefType = Other->getType();
9341   if (const LValueReferenceType *OtherRef
9342                                 = OtherRefType->getAs<LValueReferenceType>()) {
9343     OtherRefType = OtherRef->getPointeeType();
9344     OtherQuals = OtherRefType.getQualifiers();
9345   }
9346 
9347   // Our location for everything implicitly-generated.
9348   SourceLocation Loc = CopyAssignOperator->getLocation();
9349 
9350   // Builds a DeclRefExpr for the "other" object.
9351   RefBuilder OtherRef(Other, OtherRefType);
9352 
9353   // Builds the "this" pointer.
9354   ThisBuilder This;
9355 
9356   // Assign base classes.
9357   bool Invalid = false;
9358   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9359        E = ClassDecl->bases_end(); Base != E; ++Base) {
9360     // Form the assignment:
9361     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
9362     QualType BaseType = Base->getType().getUnqualifiedType();
9363     if (!BaseType->isRecordType()) {
9364       Invalid = true;
9365       continue;
9366     }
9367 
9368     CXXCastPath BasePath;
9369     BasePath.push_back(Base);
9370 
9371     // Construct the "from" expression, which is an implicit cast to the
9372     // appropriately-qualified base type.
9373     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9374                      VK_LValue, BasePath);
9375 
9376     // Dereference "this".
9377     DerefBuilder DerefThis(This);
9378     CastBuilder To(DerefThis,
9379                    Context.getCVRQualifiedType(
9380                        BaseType, CopyAssignOperator->getTypeQualifiers()),
9381                    VK_LValue, BasePath);
9382 
9383     // Build the copy.
9384     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
9385                                             To, From,
9386                                             /*CopyingBaseSubobject=*/true,
9387                                             /*Copying=*/true);
9388     if (Copy.isInvalid()) {
9389       Diag(CurrentLocation, diag::note_member_synthesized_at)
9390         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9391       CopyAssignOperator->setInvalidDecl();
9392       return;
9393     }
9394 
9395     // Success! Record the copy.
9396     Statements.push_back(Copy.takeAs<Expr>());
9397   }
9398 
9399   // Assign non-static members.
9400   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9401                                   FieldEnd = ClassDecl->field_end();
9402        Field != FieldEnd; ++Field) {
9403     if (Field->isUnnamedBitfield())
9404       continue;
9405 
9406     if (Field->isInvalidDecl()) {
9407       Invalid = true;
9408       continue;
9409     }
9410 
9411     // Check for members of reference type; we can't copy those.
9412     if (Field->getType()->isReferenceType()) {
9413       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9414         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9415       Diag(Field->getLocation(), diag::note_declared_at);
9416       Diag(CurrentLocation, diag::note_member_synthesized_at)
9417         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9418       Invalid = true;
9419       continue;
9420     }
9421 
9422     // Check for members of const-qualified, non-class type.
9423     QualType BaseType = Context.getBaseElementType(Field->getType());
9424     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9425       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9426         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9427       Diag(Field->getLocation(), diag::note_declared_at);
9428       Diag(CurrentLocation, diag::note_member_synthesized_at)
9429         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9430       Invalid = true;
9431       continue;
9432     }
9433 
9434     // Suppress assigning zero-width bitfields.
9435     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9436       continue;
9437 
9438     QualType FieldType = Field->getType().getNonReferenceType();
9439     if (FieldType->isIncompleteArrayType()) {
9440       assert(ClassDecl->hasFlexibleArrayMember() &&
9441              "Incomplete array type is not valid");
9442       continue;
9443     }
9444 
9445     // Build references to the field in the object we're copying from and to.
9446     CXXScopeSpec SS; // Intentionally empty
9447     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9448                               LookupMemberName);
9449     MemberLookup.addDecl(*Field);
9450     MemberLookup.resolveKind();
9451 
9452     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9453 
9454     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
9455 
9456     // Build the copy of this field.
9457     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
9458                                             To, From,
9459                                             /*CopyingBaseSubobject=*/false,
9460                                             /*Copying=*/true);
9461     if (Copy.isInvalid()) {
9462       Diag(CurrentLocation, diag::note_member_synthesized_at)
9463         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9464       CopyAssignOperator->setInvalidDecl();
9465       return;
9466     }
9467 
9468     // Success! Record the copy.
9469     Statements.push_back(Copy.takeAs<Stmt>());
9470   }
9471 
9472   if (!Invalid) {
9473     // Add a "return *this;"
9474     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
9475 
9476     StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9477     if (Return.isInvalid())
9478       Invalid = true;
9479     else {
9480       Statements.push_back(Return.takeAs<Stmt>());
9481 
9482       if (Trap.hasErrorOccurred()) {
9483         Diag(CurrentLocation, diag::note_member_synthesized_at)
9484           << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9485         Invalid = true;
9486       }
9487     }
9488   }
9489 
9490   if (Invalid) {
9491     CopyAssignOperator->setInvalidDecl();
9492     return;
9493   }
9494 
9495   StmtResult Body;
9496   {
9497     CompoundScopeRAII CompoundScope(*this);
9498     Body = ActOnCompoundStmt(Loc, Loc, Statements,
9499                              /*isStmtExpr=*/false);
9500     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9501   }
9502   CopyAssignOperator->setBody(Body.takeAs<Stmt>());
9503 
9504   if (ASTMutationListener *L = getASTMutationListener()) {
9505     L->CompletedImplicitDefinition(CopyAssignOperator);
9506   }
9507 }
9508 
9509 Sema::ImplicitExceptionSpecification
9510 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9511   CXXRecordDecl *ClassDecl = MD->getParent();
9512 
9513   ImplicitExceptionSpecification ExceptSpec(*this);
9514   if (ClassDecl->isInvalidDecl())
9515     return ExceptSpec;
9516 
9517   // C++0x [except.spec]p14:
9518   //   An implicitly declared special member function (Clause 12) shall have an
9519   //   exception-specification. [...]
9520 
9521   // It is unspecified whether or not an implicit move assignment operator
9522   // attempts to deduplicate calls to assignment operators of virtual bases are
9523   // made. As such, this exception specification is effectively unspecified.
9524   // Based on a similar decision made for constness in C++0x, we're erring on
9525   // the side of assuming such calls to be made regardless of whether they
9526   // actually happen.
9527   // Note that a move constructor is not implicitly declared when there are
9528   // virtual bases, but it can still be user-declared and explicitly defaulted.
9529   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9530                                        BaseEnd = ClassDecl->bases_end();
9531        Base != BaseEnd; ++Base) {
9532     if (Base->isVirtual())
9533       continue;
9534 
9535     CXXRecordDecl *BaseClassDecl
9536       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9537     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
9538                                                            0, false, 0))
9539       ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
9540   }
9541 
9542   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9543                                        BaseEnd = ClassDecl->vbases_end();
9544        Base != BaseEnd; ++Base) {
9545     CXXRecordDecl *BaseClassDecl
9546       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9547     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
9548                                                            0, false, 0))
9549       ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
9550   }
9551 
9552   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9553                                   FieldEnd = ClassDecl->field_end();
9554        Field != FieldEnd;
9555        ++Field) {
9556     QualType FieldType = Context.getBaseElementType(Field->getType());
9557     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9558       if (CXXMethodDecl *MoveAssign =
9559               LookupMovingAssignment(FieldClassDecl,
9560                                      FieldType.getCVRQualifiers(),
9561                                      false, 0))
9562         ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
9563     }
9564   }
9565 
9566   return ExceptSpec;
9567 }
9568 
9569 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
9570   assert(ClassDecl->needsImplicitMoveAssignment());
9571 
9572   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9573   if (DSM.isAlreadyBeingDeclared())
9574     return 0;
9575 
9576   // Note: The following rules are largely analoguous to the move
9577   // constructor rules.
9578 
9579   QualType ArgType = Context.getTypeDeclType(ClassDecl);
9580   QualType RetType = Context.getLValueReferenceType(ArgType);
9581   ArgType = Context.getRValueReferenceType(ArgType);
9582 
9583   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9584                                                      CXXMoveAssignment,
9585                                                      false);
9586 
9587   //   An implicitly-declared move assignment operator is an inline public
9588   //   member of its class.
9589   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9590   SourceLocation ClassLoc = ClassDecl->getLocation();
9591   DeclarationNameInfo NameInfo(Name, ClassLoc);
9592   CXXMethodDecl *MoveAssignment =
9593       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9594                             /*TInfo=*/0, /*StorageClass=*/SC_None,
9595                             /*isInline=*/true, Constexpr, SourceLocation());
9596   MoveAssignment->setAccess(AS_public);
9597   MoveAssignment->setDefaulted();
9598   MoveAssignment->setImplicit();
9599 
9600   // Build an exception specification pointing back at this member.
9601   FunctionProtoType::ExtProtoInfo EPI =
9602       getImplicitMethodEPI(*this, MoveAssignment);
9603   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
9604 
9605   // Add the parameter to the operator.
9606   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9607                                                ClassLoc, ClassLoc, /*Id=*/0,
9608                                                ArgType, /*TInfo=*/0,
9609                                                SC_None, 0);
9610   MoveAssignment->setParams(FromParam);
9611 
9612   AddOverriddenMethods(ClassDecl, MoveAssignment);
9613 
9614   MoveAssignment->setTrivial(
9615     ClassDecl->needsOverloadResolutionForMoveAssignment()
9616       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9617       : ClassDecl->hasTrivialMoveAssignment());
9618 
9619   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
9620     ClassDecl->setImplicitMoveAssignmentIsDeleted();
9621     SetDeclDeleted(MoveAssignment, ClassLoc);
9622   }
9623 
9624   // Note that we have added this copy-assignment operator.
9625   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9626 
9627   if (Scope *S = getScopeForContext(ClassDecl))
9628     PushOnScopeChains(MoveAssignment, S, false);
9629   ClassDecl->addDecl(MoveAssignment);
9630 
9631   return MoveAssignment;
9632 }
9633 
9634 /// Check if we're implicitly defining a move assignment operator for a class
9635 /// with virtual bases. Such a move assignment might move-assign the virtual
9636 /// base multiple times.
9637 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
9638                                                SourceLocation CurrentLocation) {
9639   assert(!Class->isDependentContext() && "should not define dependent move");
9640 
9641   // Only a virtual base could get implicitly move-assigned multiple times.
9642   // Only a non-trivial move assignment can observe this. We only want to
9643   // diagnose if we implicitly define an assignment operator that assigns
9644   // two base classes, both of which move-assign the same virtual base.
9645   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
9646       Class->getNumBases() < 2)
9647     return;
9648 
9649   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
9650   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
9651   VBaseMap VBases;
9652 
9653   for (CXXRecordDecl::base_class_iterator BI = Class->bases_begin(),
9654                                           BE = Class->bases_end();
9655        BI != BE; ++BI) {
9656     Worklist.push_back(&*BI);
9657     while (!Worklist.empty()) {
9658       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
9659       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
9660 
9661       // If the base has no non-trivial move assignment operators,
9662       // we don't care about moves from it.
9663       if (!Base->hasNonTrivialMoveAssignment())
9664         continue;
9665 
9666       // If there's nothing virtual here, skip it.
9667       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
9668         continue;
9669 
9670       // If we're not actually going to call a move assignment for this base,
9671       // or the selected move assignment is trivial, skip it.
9672       Sema::SpecialMemberOverloadResult *SMOR =
9673         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
9674                               /*ConstArg*/false, /*VolatileArg*/false,
9675                               /*RValueThis*/true, /*ConstThis*/false,
9676                               /*VolatileThis*/false);
9677       if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
9678           !SMOR->getMethod()->isMoveAssignmentOperator())
9679         continue;
9680 
9681       if (BaseSpec->isVirtual()) {
9682         // We're going to move-assign this virtual base, and its move
9683         // assignment operator is not trivial. If this can happen for
9684         // multiple distinct direct bases of Class, diagnose it. (If it
9685         // only happens in one base, we'll diagnose it when synthesizing
9686         // that base class's move assignment operator.)
9687         CXXBaseSpecifier *&Existing =
9688             VBases.insert(std::make_pair(Base->getCanonicalDecl(), BI))
9689                 .first->second;
9690         if (Existing && Existing != BI) {
9691           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
9692             << Class << Base;
9693           S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
9694             << (Base->getCanonicalDecl() ==
9695                 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9696             << Base << Existing->getType() << Existing->getSourceRange();
9697           S.Diag(BI->getLocStart(), diag::note_vbase_moved_here)
9698             << (Base->getCanonicalDecl() ==
9699                 BI->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9700             << Base << BI->getType() << BaseSpec->getSourceRange();
9701 
9702           // Only diagnose each vbase once.
9703           Existing = 0;
9704         }
9705       } else {
9706         // Only walk over bases that have defaulted move assignment operators.
9707         // We assume that any user-provided move assignment operator handles
9708         // the multiple-moves-of-vbase case itself somehow.
9709         if (!SMOR->getMethod()->isDefaulted())
9710           continue;
9711 
9712         // We're going to move the base classes of Base. Add them to the list.
9713         for (CXXRecordDecl::base_class_iterator BI = Base->bases_begin(),
9714                                                 BE = Base->bases_end();
9715              BI != BE; ++BI)
9716           Worklist.push_back(&*BI);
9717       }
9718     }
9719   }
9720 }
9721 
9722 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9723                                         CXXMethodDecl *MoveAssignOperator) {
9724   assert((MoveAssignOperator->isDefaulted() &&
9725           MoveAssignOperator->isOverloadedOperator() &&
9726           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
9727           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9728           !MoveAssignOperator->isDeleted()) &&
9729          "DefineImplicitMoveAssignment called for wrong function");
9730 
9731   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9732 
9733   if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9734     MoveAssignOperator->setInvalidDecl();
9735     return;
9736   }
9737 
9738   MoveAssignOperator->markUsed(Context);
9739 
9740   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
9741   DiagnosticErrorTrap Trap(Diags);
9742 
9743   // C++0x [class.copy]p28:
9744   //   The implicitly-defined or move assignment operator for a non-union class
9745   //   X performs memberwise move assignment of its subobjects. The direct base
9746   //   classes of X are assigned first, in the order of their declaration in the
9747   //   base-specifier-list, and then the immediate non-static data members of X
9748   //   are assigned, in the order in which they were declared in the class
9749   //   definition.
9750 
9751   // Issue a warning if our implicit move assignment operator will move
9752   // from a virtual base more than once.
9753   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
9754 
9755   // The statements that form the synthesized function body.
9756   SmallVector<Stmt*, 8> Statements;
9757 
9758   // The parameter for the "other" object, which we are move from.
9759   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9760   QualType OtherRefType = Other->getType()->
9761       getAs<RValueReferenceType>()->getPointeeType();
9762   assert(!OtherRefType.getQualifiers() &&
9763          "Bad argument type of defaulted move assignment");
9764 
9765   // Our location for everything implicitly-generated.
9766   SourceLocation Loc = MoveAssignOperator->getLocation();
9767 
9768   // Builds a reference to the "other" object.
9769   RefBuilder OtherRef(Other, OtherRefType);
9770   // Cast to rvalue.
9771   MoveCastBuilder MoveOther(OtherRef);
9772 
9773   // Builds the "this" pointer.
9774   ThisBuilder This;
9775 
9776   // Assign base classes.
9777   bool Invalid = false;
9778   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9779        E = ClassDecl->bases_end(); Base != E; ++Base) {
9780     // C++11 [class.copy]p28:
9781     //   It is unspecified whether subobjects representing virtual base classes
9782     //   are assigned more than once by the implicitly-defined copy assignment
9783     //   operator.
9784     // FIXME: Do not assign to a vbase that will be assigned by some other base
9785     // class. For a move-assignment, this can result in the vbase being moved
9786     // multiple times.
9787 
9788     // Form the assignment:
9789     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9790     QualType BaseType = Base->getType().getUnqualifiedType();
9791     if (!BaseType->isRecordType()) {
9792       Invalid = true;
9793       continue;
9794     }
9795 
9796     CXXCastPath BasePath;
9797     BasePath.push_back(Base);
9798 
9799     // Construct the "from" expression, which is an implicit cast to the
9800     // appropriately-qualified base type.
9801     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
9802 
9803     // Dereference "this".
9804     DerefBuilder DerefThis(This);
9805 
9806     // Implicitly cast "this" to the appropriately-qualified base type.
9807     CastBuilder To(DerefThis,
9808                    Context.getCVRQualifiedType(
9809                        BaseType, MoveAssignOperator->getTypeQualifiers()),
9810                    VK_LValue, BasePath);
9811 
9812     // Build the move.
9813     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
9814                                             To, From,
9815                                             /*CopyingBaseSubobject=*/true,
9816                                             /*Copying=*/false);
9817     if (Move.isInvalid()) {
9818       Diag(CurrentLocation, diag::note_member_synthesized_at)
9819         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9820       MoveAssignOperator->setInvalidDecl();
9821       return;
9822     }
9823 
9824     // Success! Record the move.
9825     Statements.push_back(Move.takeAs<Expr>());
9826   }
9827 
9828   // Assign non-static members.
9829   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9830                                   FieldEnd = ClassDecl->field_end();
9831        Field != FieldEnd; ++Field) {
9832     if (Field->isUnnamedBitfield())
9833       continue;
9834 
9835     if (Field->isInvalidDecl()) {
9836       Invalid = true;
9837       continue;
9838     }
9839 
9840     // Check for members of reference type; we can't move those.
9841     if (Field->getType()->isReferenceType()) {
9842       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9843         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9844       Diag(Field->getLocation(), diag::note_declared_at);
9845       Diag(CurrentLocation, diag::note_member_synthesized_at)
9846         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9847       Invalid = true;
9848       continue;
9849     }
9850 
9851     // Check for members of const-qualified, non-class type.
9852     QualType BaseType = Context.getBaseElementType(Field->getType());
9853     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9854       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9855         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9856       Diag(Field->getLocation(), diag::note_declared_at);
9857       Diag(CurrentLocation, diag::note_member_synthesized_at)
9858         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9859       Invalid = true;
9860       continue;
9861     }
9862 
9863     // Suppress assigning zero-width bitfields.
9864     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9865       continue;
9866 
9867     QualType FieldType = Field->getType().getNonReferenceType();
9868     if (FieldType->isIncompleteArrayType()) {
9869       assert(ClassDecl->hasFlexibleArrayMember() &&
9870              "Incomplete array type is not valid");
9871       continue;
9872     }
9873 
9874     // Build references to the field in the object we're copying from and to.
9875     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9876                               LookupMemberName);
9877     MemberLookup.addDecl(*Field);
9878     MemberLookup.resolveKind();
9879     MemberBuilder From(MoveOther, OtherRefType,
9880                        /*IsArrow=*/false, MemberLookup);
9881     MemberBuilder To(This, getCurrentThisType(),
9882                      /*IsArrow=*/true, MemberLookup);
9883 
9884     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
9885         "Member reference with rvalue base must be rvalue except for reference "
9886         "members, which aren't allowed for move assignment.");
9887 
9888     // Build the move of this field.
9889     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
9890                                             To, From,
9891                                             /*CopyingBaseSubobject=*/false,
9892                                             /*Copying=*/false);
9893     if (Move.isInvalid()) {
9894       Diag(CurrentLocation, diag::note_member_synthesized_at)
9895         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9896       MoveAssignOperator->setInvalidDecl();
9897       return;
9898     }
9899 
9900     // Success! Record the copy.
9901     Statements.push_back(Move.takeAs<Stmt>());
9902   }
9903 
9904   if (!Invalid) {
9905     // Add a "return *this;"
9906     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
9907 
9908     StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9909     if (Return.isInvalid())
9910       Invalid = true;
9911     else {
9912       Statements.push_back(Return.takeAs<Stmt>());
9913 
9914       if (Trap.hasErrorOccurred()) {
9915         Diag(CurrentLocation, diag::note_member_synthesized_at)
9916           << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9917         Invalid = true;
9918       }
9919     }
9920   }
9921 
9922   if (Invalid) {
9923     MoveAssignOperator->setInvalidDecl();
9924     return;
9925   }
9926 
9927   StmtResult Body;
9928   {
9929     CompoundScopeRAII CompoundScope(*this);
9930     Body = ActOnCompoundStmt(Loc, Loc, Statements,
9931                              /*isStmtExpr=*/false);
9932     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9933   }
9934   MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9935 
9936   if (ASTMutationListener *L = getASTMutationListener()) {
9937     L->CompletedImplicitDefinition(MoveAssignOperator);
9938   }
9939 }
9940 
9941 Sema::ImplicitExceptionSpecification
9942 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9943   CXXRecordDecl *ClassDecl = MD->getParent();
9944 
9945   ImplicitExceptionSpecification ExceptSpec(*this);
9946   if (ClassDecl->isInvalidDecl())
9947     return ExceptSpec;
9948 
9949   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9950   assert(T->getNumArgs() >= 1 && "not a copy ctor");
9951   unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9952 
9953   // C++ [except.spec]p14:
9954   //   An implicitly declared special member function (Clause 12) shall have an
9955   //   exception-specification. [...]
9956   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9957                                        BaseEnd = ClassDecl->bases_end();
9958        Base != BaseEnd;
9959        ++Base) {
9960     // Virtual bases are handled below.
9961     if (Base->isVirtual())
9962       continue;
9963 
9964     CXXRecordDecl *BaseClassDecl
9965       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9966     if (CXXConstructorDecl *CopyConstructor =
9967           LookupCopyingConstructor(BaseClassDecl, Quals))
9968       ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
9969   }
9970   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9971                                        BaseEnd = ClassDecl->vbases_end();
9972        Base != BaseEnd;
9973        ++Base) {
9974     CXXRecordDecl *BaseClassDecl
9975       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9976     if (CXXConstructorDecl *CopyConstructor =
9977           LookupCopyingConstructor(BaseClassDecl, Quals))
9978       ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
9979   }
9980   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9981                                   FieldEnd = ClassDecl->field_end();
9982        Field != FieldEnd;
9983        ++Field) {
9984     QualType FieldType = Context.getBaseElementType(Field->getType());
9985     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9986       if (CXXConstructorDecl *CopyConstructor =
9987               LookupCopyingConstructor(FieldClassDecl,
9988                                        Quals | FieldType.getCVRQualifiers()))
9989       ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
9990     }
9991   }
9992 
9993   return ExceptSpec;
9994 }
9995 
9996 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9997                                                     CXXRecordDecl *ClassDecl) {
9998   // C++ [class.copy]p4:
9999   //   If the class definition does not explicitly declare a copy
10000   //   constructor, one is declared implicitly.
10001   assert(ClassDecl->needsImplicitCopyConstructor());
10002 
10003   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10004   if (DSM.isAlreadyBeingDeclared())
10005     return 0;
10006 
10007   QualType ClassType = Context.getTypeDeclType(ClassDecl);
10008   QualType ArgType = ClassType;
10009   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
10010   if (Const)
10011     ArgType = ArgType.withConst();
10012   ArgType = Context.getLValueReferenceType(ArgType);
10013 
10014   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10015                                                      CXXCopyConstructor,
10016                                                      Const);
10017 
10018   DeclarationName Name
10019     = Context.DeclarationNames.getCXXConstructorName(
10020                                            Context.getCanonicalType(ClassType));
10021   SourceLocation ClassLoc = ClassDecl->getLocation();
10022   DeclarationNameInfo NameInfo(Name, ClassLoc);
10023 
10024   //   An implicitly-declared copy constructor is an inline public
10025   //   member of its class.
10026   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
10027       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
10028       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10029       Constexpr);
10030   CopyConstructor->setAccess(AS_public);
10031   CopyConstructor->setDefaulted();
10032 
10033   // Build an exception specification pointing back at this member.
10034   FunctionProtoType::ExtProtoInfo EPI =
10035       getImplicitMethodEPI(*this, CopyConstructor);
10036   CopyConstructor->setType(
10037       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10038 
10039   // Add the parameter to the constructor.
10040   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
10041                                                ClassLoc, ClassLoc,
10042                                                /*IdentifierInfo=*/0,
10043                                                ArgType, /*TInfo=*/0,
10044                                                SC_None, 0);
10045   CopyConstructor->setParams(FromParam);
10046 
10047   CopyConstructor->setTrivial(
10048     ClassDecl->needsOverloadResolutionForCopyConstructor()
10049       ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10050       : ClassDecl->hasTrivialCopyConstructor());
10051 
10052   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
10053     SetDeclDeleted(CopyConstructor, ClassLoc);
10054 
10055   // Note that we have declared this constructor.
10056   ++ASTContext::NumImplicitCopyConstructorsDeclared;
10057 
10058   if (Scope *S = getScopeForContext(ClassDecl))
10059     PushOnScopeChains(CopyConstructor, S, false);
10060   ClassDecl->addDecl(CopyConstructor);
10061 
10062   return CopyConstructor;
10063 }
10064 
10065 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
10066                                    CXXConstructorDecl *CopyConstructor) {
10067   assert((CopyConstructor->isDefaulted() &&
10068           CopyConstructor->isCopyConstructor() &&
10069           !CopyConstructor->doesThisDeclarationHaveABody() &&
10070           !CopyConstructor->isDeleted()) &&
10071          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
10072 
10073   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
10074   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
10075 
10076   // C++11 [class.copy]p7:
10077   //   The [definition of an implicitly declared copy constructor] is
10078   //   deprecated if the class has a user-declared copy assignment operator
10079   //   or a user-declared destructor.
10080   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10081     diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10082 
10083   SynthesizedFunctionScope Scope(*this, CopyConstructor);
10084   DiagnosticErrorTrap Trap(Diags);
10085 
10086   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
10087       Trap.hasErrorOccurred()) {
10088     Diag(CurrentLocation, diag::note_member_synthesized_at)
10089       << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
10090     CopyConstructor->setInvalidDecl();
10091   }  else {
10092     Sema::CompoundScopeRAII CompoundScope(*this);
10093     CopyConstructor->setBody(ActOnCompoundStmt(
10094         CopyConstructor->getLocation(), CopyConstructor->getLocation(), None,
10095         /*isStmtExpr=*/ false).takeAs<Stmt>());
10096   }
10097 
10098   CopyConstructor->markUsed(Context);
10099   if (ASTMutationListener *L = getASTMutationListener()) {
10100     L->CompletedImplicitDefinition(CopyConstructor);
10101   }
10102 }
10103 
10104 Sema::ImplicitExceptionSpecification
10105 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10106   CXXRecordDecl *ClassDecl = MD->getParent();
10107 
10108   // C++ [except.spec]p14:
10109   //   An implicitly declared special member function (Clause 12) shall have an
10110   //   exception-specification. [...]
10111   ImplicitExceptionSpecification ExceptSpec(*this);
10112   if (ClassDecl->isInvalidDecl())
10113     return ExceptSpec;
10114 
10115   // Direct base-class constructors.
10116   for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
10117                                        BEnd = ClassDecl->bases_end();
10118        B != BEnd; ++B) {
10119     if (B->isVirtual()) // Handled below.
10120       continue;
10121 
10122     if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
10123       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10124       CXXConstructorDecl *Constructor =
10125           LookupMovingConstructor(BaseClassDecl, 0);
10126       // If this is a deleted function, add it anyway. This might be conformant
10127       // with the standard. This might not. I'm not sure. It might not matter.
10128       if (Constructor)
10129         ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
10130     }
10131   }
10132 
10133   // Virtual base-class constructors.
10134   for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
10135                                        BEnd = ClassDecl->vbases_end();
10136        B != BEnd; ++B) {
10137     if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
10138       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10139       CXXConstructorDecl *Constructor =
10140           LookupMovingConstructor(BaseClassDecl, 0);
10141       // If this is a deleted function, add it anyway. This might be conformant
10142       // with the standard. This might not. I'm not sure. It might not matter.
10143       if (Constructor)
10144         ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
10145     }
10146   }
10147 
10148   // Field constructors.
10149   for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
10150                                FEnd = ClassDecl->field_end();
10151        F != FEnd; ++F) {
10152     QualType FieldType = Context.getBaseElementType(F->getType());
10153     if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10154       CXXConstructorDecl *Constructor =
10155           LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
10156       // If this is a deleted function, add it anyway. This might be conformant
10157       // with the standard. This might not. I'm not sure. It might not matter.
10158       // In particular, the problem is that this function never gets called. It
10159       // might just be ill-formed because this function attempts to refer to
10160       // a deleted function here.
10161       if (Constructor)
10162         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
10163     }
10164   }
10165 
10166   return ExceptSpec;
10167 }
10168 
10169 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10170                                                     CXXRecordDecl *ClassDecl) {
10171   assert(ClassDecl->needsImplicitMoveConstructor());
10172 
10173   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10174   if (DSM.isAlreadyBeingDeclared())
10175     return 0;
10176 
10177   QualType ClassType = Context.getTypeDeclType(ClassDecl);
10178   QualType ArgType = Context.getRValueReferenceType(ClassType);
10179 
10180   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10181                                                      CXXMoveConstructor,
10182                                                      false);
10183 
10184   DeclarationName Name
10185     = Context.DeclarationNames.getCXXConstructorName(
10186                                            Context.getCanonicalType(ClassType));
10187   SourceLocation ClassLoc = ClassDecl->getLocation();
10188   DeclarationNameInfo NameInfo(Name, ClassLoc);
10189 
10190   // C++11 [class.copy]p11:
10191   //   An implicitly-declared copy/move constructor is an inline public
10192   //   member of its class.
10193   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
10194       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
10195       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10196       Constexpr);
10197   MoveConstructor->setAccess(AS_public);
10198   MoveConstructor->setDefaulted();
10199 
10200   // Build an exception specification pointing back at this member.
10201   FunctionProtoType::ExtProtoInfo EPI =
10202       getImplicitMethodEPI(*this, MoveConstructor);
10203   MoveConstructor->setType(
10204       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10205 
10206   // Add the parameter to the constructor.
10207   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10208                                                ClassLoc, ClassLoc,
10209                                                /*IdentifierInfo=*/0,
10210                                                ArgType, /*TInfo=*/0,
10211                                                SC_None, 0);
10212   MoveConstructor->setParams(FromParam);
10213 
10214   MoveConstructor->setTrivial(
10215     ClassDecl->needsOverloadResolutionForMoveConstructor()
10216       ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10217       : ClassDecl->hasTrivialMoveConstructor());
10218 
10219   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
10220     ClassDecl->setImplicitMoveConstructorIsDeleted();
10221     SetDeclDeleted(MoveConstructor, ClassLoc);
10222   }
10223 
10224   // Note that we have declared this constructor.
10225   ++ASTContext::NumImplicitMoveConstructorsDeclared;
10226 
10227   if (Scope *S = getScopeForContext(ClassDecl))
10228     PushOnScopeChains(MoveConstructor, S, false);
10229   ClassDecl->addDecl(MoveConstructor);
10230 
10231   return MoveConstructor;
10232 }
10233 
10234 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10235                                    CXXConstructorDecl *MoveConstructor) {
10236   assert((MoveConstructor->isDefaulted() &&
10237           MoveConstructor->isMoveConstructor() &&
10238           !MoveConstructor->doesThisDeclarationHaveABody() &&
10239           !MoveConstructor->isDeleted()) &&
10240          "DefineImplicitMoveConstructor - call it for implicit move ctor");
10241 
10242   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10243   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10244 
10245   SynthesizedFunctionScope Scope(*this, MoveConstructor);
10246   DiagnosticErrorTrap Trap(Diags);
10247 
10248   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
10249       Trap.hasErrorOccurred()) {
10250     Diag(CurrentLocation, diag::note_member_synthesized_at)
10251       << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10252     MoveConstructor->setInvalidDecl();
10253   }  else {
10254     Sema::CompoundScopeRAII CompoundScope(*this);
10255     MoveConstructor->setBody(ActOnCompoundStmt(
10256         MoveConstructor->getLocation(), MoveConstructor->getLocation(), None,
10257         /*isStmtExpr=*/ false).takeAs<Stmt>());
10258   }
10259 
10260   MoveConstructor->markUsed(Context);
10261 
10262   if (ASTMutationListener *L = getASTMutationListener()) {
10263     L->CompletedImplicitDefinition(MoveConstructor);
10264   }
10265 }
10266 
10267 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
10268   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
10269 }
10270 
10271 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
10272                             SourceLocation CurrentLocation,
10273                             CXXConversionDecl *Conv) {
10274   CXXRecordDecl *Lambda = Conv->getParent();
10275   CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10276   // If we are defining a specialization of a conversion to function-ptr
10277   // cache the deduced template arguments for this specialization
10278   // so that we can use them to retrieve the corresponding call-operator
10279   // and static-invoker.
10280   const TemplateArgumentList *DeducedTemplateArgs = 0;
10281 
10282 
10283   // Retrieve the corresponding call-operator specialization.
10284   if (Lambda->isGenericLambda()) {
10285     assert(Conv->isFunctionTemplateSpecialization());
10286     FunctionTemplateDecl *CallOpTemplate =
10287         CallOp->getDescribedFunctionTemplate();
10288     DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
10289     void *InsertPos = 0;
10290     FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
10291                                                 DeducedTemplateArgs->data(),
10292                                                 DeducedTemplateArgs->size(),
10293                                                 InsertPos);
10294     assert(CallOpSpec &&
10295           "Conversion operator must have a corresponding call operator");
10296     CallOp = cast<CXXMethodDecl>(CallOpSpec);
10297   }
10298   // Mark the call operator referenced (and add to pending instantiations
10299   // if necessary).
10300   // For both the conversion and static-invoker template specializations
10301   // we construct their body's in this function, so no need to add them
10302   // to the PendingInstantiations.
10303   MarkFunctionReferenced(CurrentLocation, CallOp);
10304 
10305   SynthesizedFunctionScope Scope(*this, Conv);
10306   DiagnosticErrorTrap Trap(Diags);
10307 
10308   // Retreive the static invoker...
10309   CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10310   // ... and get the corresponding specialization for a generic lambda.
10311   if (Lambda->isGenericLambda()) {
10312     assert(DeducedTemplateArgs &&
10313       "Must have deduced template arguments from Conversion Operator");
10314     FunctionTemplateDecl *InvokeTemplate =
10315                           Invoker->getDescribedFunctionTemplate();
10316     void *InsertPos = 0;
10317     FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
10318                                                 DeducedTemplateArgs->data(),
10319                                                 DeducedTemplateArgs->size(),
10320                                                 InsertPos);
10321     assert(InvokeSpec &&
10322       "Must have a corresponding static invoker specialization");
10323     Invoker = cast<CXXMethodDecl>(InvokeSpec);
10324   }
10325   // Construct the body of the conversion function { return __invoke; }.
10326   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
10327                                         VK_LValue, Conv->getLocation()).take();
10328    assert(FunctionRef && "Can't refer to __invoke function?");
10329    Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
10330    Conv->setBody(new (Context) CompoundStmt(Context, Return,
10331                                             Conv->getLocation(),
10332                                             Conv->getLocation()));
10333 
10334   Conv->markUsed(Context);
10335   Conv->setReferenced();
10336 
10337   // Fill in the __invoke function with a dummy implementation. IR generation
10338   // will fill in the actual details.
10339   Invoker->markUsed(Context);
10340   Invoker->setReferenced();
10341   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10342 
10343   if (ASTMutationListener *L = getASTMutationListener()) {
10344     L->CompletedImplicitDefinition(Conv);
10345     L->CompletedImplicitDefinition(Invoker);
10346    }
10347 }
10348 
10349 
10350 
10351 void Sema::DefineImplicitLambdaToBlockPointerConversion(
10352        SourceLocation CurrentLocation,
10353        CXXConversionDecl *Conv)
10354 {
10355   assert(!Conv->getParent()->isGenericLambda());
10356 
10357   Conv->markUsed(Context);
10358 
10359   SynthesizedFunctionScope Scope(*this, Conv);
10360   DiagnosticErrorTrap Trap(Diags);
10361 
10362   // Copy-initialize the lambda object as needed to capture it.
10363   Expr *This = ActOnCXXThis(CurrentLocation).take();
10364   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
10365 
10366   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10367                                                         Conv->getLocation(),
10368                                                         Conv, DerefThis);
10369 
10370   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10371   // behavior.  Note that only the general conversion function does this
10372   // (since it's unusable otherwise); in the case where we inline the
10373   // block literal, it has block literal lifetime semantics.
10374   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
10375     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10376                                           CK_CopyAndAutoreleaseBlockObject,
10377                                           BuildBlock.get(), 0, VK_RValue);
10378 
10379   if (BuildBlock.isInvalid()) {
10380     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10381     Conv->setInvalidDecl();
10382     return;
10383   }
10384 
10385   // Create the return statement that returns the block from the conversion
10386   // function.
10387   StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
10388   if (Return.isInvalid()) {
10389     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10390     Conv->setInvalidDecl();
10391     return;
10392   }
10393 
10394   // Set the body of the conversion function.
10395   Stmt *ReturnS = Return.take();
10396   Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
10397                                            Conv->getLocation(),
10398                                            Conv->getLocation()));
10399 
10400   // We're done; notify the mutation listener, if any.
10401   if (ASTMutationListener *L = getASTMutationListener()) {
10402     L->CompletedImplicitDefinition(Conv);
10403   }
10404 }
10405 
10406 /// \brief Determine whether the given list arguments contains exactly one
10407 /// "real" (non-default) argument.
10408 static bool hasOneRealArgument(MultiExprArg Args) {
10409   switch (Args.size()) {
10410   case 0:
10411     return false;
10412 
10413   default:
10414     if (!Args[1]->isDefaultArgument())
10415       return false;
10416 
10417     // fall through
10418   case 1:
10419     return !Args[0]->isDefaultArgument();
10420   }
10421 
10422   return false;
10423 }
10424 
10425 ExprResult
10426 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10427                             CXXConstructorDecl *Constructor,
10428                             MultiExprArg ExprArgs,
10429                             bool HadMultipleCandidates,
10430                             bool IsListInitialization,
10431                             bool RequiresZeroInit,
10432                             unsigned ConstructKind,
10433                             SourceRange ParenRange) {
10434   bool Elidable = false;
10435 
10436   // C++0x [class.copy]p34:
10437   //   When certain criteria are met, an implementation is allowed to
10438   //   omit the copy/move construction of a class object, even if the
10439   //   copy/move constructor and/or destructor for the object have
10440   //   side effects. [...]
10441   //     - when a temporary class object that has not been bound to a
10442   //       reference (12.2) would be copied/moved to a class object
10443   //       with the same cv-unqualified type, the copy/move operation
10444   //       can be omitted by constructing the temporary object
10445   //       directly into the target of the omitted copy/move
10446   if (ConstructKind == CXXConstructExpr::CK_Complete &&
10447       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
10448     Expr *SubExpr = ExprArgs[0];
10449     Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
10450   }
10451 
10452   return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
10453                                Elidable, ExprArgs, HadMultipleCandidates,
10454                                IsListInitialization, RequiresZeroInit,
10455                                ConstructKind, ParenRange);
10456 }
10457 
10458 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
10459 /// including handling of its default argument expressions.
10460 ExprResult
10461 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10462                             CXXConstructorDecl *Constructor, bool Elidable,
10463                             MultiExprArg ExprArgs,
10464                             bool HadMultipleCandidates,
10465                             bool IsListInitialization,
10466                             bool RequiresZeroInit,
10467                             unsigned ConstructKind,
10468                             SourceRange ParenRange) {
10469   MarkFunctionReferenced(ConstructLoc, Constructor);
10470   return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
10471                                         Constructor, Elidable, ExprArgs,
10472                                         HadMultipleCandidates,
10473                                         IsListInitialization, RequiresZeroInit,
10474               static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10475                                         ParenRange));
10476 }
10477 
10478 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
10479   if (VD->isInvalidDecl()) return;
10480 
10481   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
10482   if (ClassDecl->isInvalidDecl()) return;
10483   if (ClassDecl->hasIrrelevantDestructor()) return;
10484   if (ClassDecl->isDependentContext()) return;
10485 
10486   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10487   MarkFunctionReferenced(VD->getLocation(), Destructor);
10488   CheckDestructorAccess(VD->getLocation(), Destructor,
10489                         PDiag(diag::err_access_dtor_var)
10490                         << VD->getDeclName()
10491                         << VD->getType());
10492   DiagnoseUseOfDecl(Destructor, VD->getLocation());
10493 
10494   if (!VD->hasGlobalStorage()) return;
10495 
10496   // Emit warning for non-trivial dtor in global scope (a real global,
10497   // class-static, function-static).
10498   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10499 
10500   // TODO: this should be re-enabled for static locals by !CXAAtExit
10501   if (!VD->isStaticLocal())
10502     Diag(VD->getLocation(), diag::warn_global_destructor);
10503 }
10504 
10505 /// \brief Given a constructor and the set of arguments provided for the
10506 /// constructor, convert the arguments and add any required default arguments
10507 /// to form a proper call to this constructor.
10508 ///
10509 /// \returns true if an error occurred, false otherwise.
10510 bool
10511 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10512                               MultiExprArg ArgsPtr,
10513                               SourceLocation Loc,
10514                               SmallVectorImpl<Expr*> &ConvertedArgs,
10515                               bool AllowExplicit,
10516                               bool IsListInitialization) {
10517   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10518   unsigned NumArgs = ArgsPtr.size();
10519   Expr **Args = ArgsPtr.data();
10520 
10521   const FunctionProtoType *Proto
10522     = Constructor->getType()->getAs<FunctionProtoType>();
10523   assert(Proto && "Constructor without a prototype?");
10524   unsigned NumArgsInProto = Proto->getNumArgs();
10525 
10526   // If too few arguments are available, we'll fill in the rest with defaults.
10527   if (NumArgs < NumArgsInProto)
10528     ConvertedArgs.reserve(NumArgsInProto);
10529   else
10530     ConvertedArgs.reserve(NumArgs);
10531 
10532   VariadicCallType CallType =
10533     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
10534   SmallVector<Expr *, 8> AllArgs;
10535   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
10536                                         Proto, 0,
10537                                         llvm::makeArrayRef(Args, NumArgs),
10538                                         AllArgs,
10539                                         CallType, AllowExplicit,
10540                                         IsListInitialization);
10541   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
10542 
10543   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
10544 
10545   CheckConstructorCall(Constructor,
10546                        llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10547                                                         AllArgs.size()),
10548                        Proto, Loc);
10549 
10550   return Invalid;
10551 }
10552 
10553 static inline bool
10554 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10555                                        const FunctionDecl *FnDecl) {
10556   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
10557   if (isa<NamespaceDecl>(DC)) {
10558     return SemaRef.Diag(FnDecl->getLocation(),
10559                         diag::err_operator_new_delete_declared_in_namespace)
10560       << FnDecl->getDeclName();
10561   }
10562 
10563   if (isa<TranslationUnitDecl>(DC) &&
10564       FnDecl->getStorageClass() == SC_Static) {
10565     return SemaRef.Diag(FnDecl->getLocation(),
10566                         diag::err_operator_new_delete_declared_static)
10567       << FnDecl->getDeclName();
10568   }
10569 
10570   return false;
10571 }
10572 
10573 static inline bool
10574 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10575                             CanQualType ExpectedResultType,
10576                             CanQualType ExpectedFirstParamType,
10577                             unsigned DependentParamTypeDiag,
10578                             unsigned InvalidParamTypeDiag) {
10579   QualType ResultType =
10580     FnDecl->getType()->getAs<FunctionType>()->getResultType();
10581 
10582   // Check that the result type is not dependent.
10583   if (ResultType->isDependentType())
10584     return SemaRef.Diag(FnDecl->getLocation(),
10585                         diag::err_operator_new_delete_dependent_result_type)
10586     << FnDecl->getDeclName() << ExpectedResultType;
10587 
10588   // Check that the result type is what we expect.
10589   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10590     return SemaRef.Diag(FnDecl->getLocation(),
10591                         diag::err_operator_new_delete_invalid_result_type)
10592     << FnDecl->getDeclName() << ExpectedResultType;
10593 
10594   // A function template must have at least 2 parameters.
10595   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10596     return SemaRef.Diag(FnDecl->getLocation(),
10597                       diag::err_operator_new_delete_template_too_few_parameters)
10598         << FnDecl->getDeclName();
10599 
10600   // The function decl must have at least 1 parameter.
10601   if (FnDecl->getNumParams() == 0)
10602     return SemaRef.Diag(FnDecl->getLocation(),
10603                         diag::err_operator_new_delete_too_few_parameters)
10604       << FnDecl->getDeclName();
10605 
10606   // Check the first parameter type is not dependent.
10607   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10608   if (FirstParamType->isDependentType())
10609     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10610       << FnDecl->getDeclName() << ExpectedFirstParamType;
10611 
10612   // Check that the first parameter type is what we expect.
10613   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
10614       ExpectedFirstParamType)
10615     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10616     << FnDecl->getDeclName() << ExpectedFirstParamType;
10617 
10618   return false;
10619 }
10620 
10621 static bool
10622 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
10623   // C++ [basic.stc.dynamic.allocation]p1:
10624   //   A program is ill-formed if an allocation function is declared in a
10625   //   namespace scope other than global scope or declared static in global
10626   //   scope.
10627   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10628     return true;
10629 
10630   CanQualType SizeTy =
10631     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10632 
10633   // C++ [basic.stc.dynamic.allocation]p1:
10634   //  The return type shall be void*. The first parameter shall have type
10635   //  std::size_t.
10636   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10637                                   SizeTy,
10638                                   diag::err_operator_new_dependent_param_type,
10639                                   diag::err_operator_new_param_type))
10640     return true;
10641 
10642   // C++ [basic.stc.dynamic.allocation]p1:
10643   //  The first parameter shall not have an associated default argument.
10644   if (FnDecl->getParamDecl(0)->hasDefaultArg())
10645     return SemaRef.Diag(FnDecl->getLocation(),
10646                         diag::err_operator_new_default_arg)
10647       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10648 
10649   return false;
10650 }
10651 
10652 static bool
10653 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
10654   // C++ [basic.stc.dynamic.deallocation]p1:
10655   //   A program is ill-formed if deallocation functions are declared in a
10656   //   namespace scope other than global scope or declared static in global
10657   //   scope.
10658   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10659     return true;
10660 
10661   // C++ [basic.stc.dynamic.deallocation]p2:
10662   //   Each deallocation function shall return void and its first parameter
10663   //   shall be void*.
10664   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10665                                   SemaRef.Context.VoidPtrTy,
10666                                  diag::err_operator_delete_dependent_param_type,
10667                                  diag::err_operator_delete_param_type))
10668     return true;
10669 
10670   return false;
10671 }
10672 
10673 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
10674 /// of this overloaded operator is well-formed. If so, returns false;
10675 /// otherwise, emits appropriate diagnostics and returns true.
10676 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
10677   assert(FnDecl && FnDecl->isOverloadedOperator() &&
10678          "Expected an overloaded operator declaration");
10679 
10680   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10681 
10682   // C++ [over.oper]p5:
10683   //   The allocation and deallocation functions, operator new,
10684   //   operator new[], operator delete and operator delete[], are
10685   //   described completely in 3.7.3. The attributes and restrictions
10686   //   found in the rest of this subclause do not apply to them unless
10687   //   explicitly stated in 3.7.3.
10688   if (Op == OO_Delete || Op == OO_Array_Delete)
10689     return CheckOperatorDeleteDeclaration(*this, FnDecl);
10690 
10691   if (Op == OO_New || Op == OO_Array_New)
10692     return CheckOperatorNewDeclaration(*this, FnDecl);
10693 
10694   // C++ [over.oper]p6:
10695   //   An operator function shall either be a non-static member
10696   //   function or be a non-member function and have at least one
10697   //   parameter whose type is a class, a reference to a class, an
10698   //   enumeration, or a reference to an enumeration.
10699   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10700     if (MethodDecl->isStatic())
10701       return Diag(FnDecl->getLocation(),
10702                   diag::err_operator_overload_static) << FnDecl->getDeclName();
10703   } else {
10704     bool ClassOrEnumParam = false;
10705     for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10706                                    ParamEnd = FnDecl->param_end();
10707          Param != ParamEnd; ++Param) {
10708       QualType ParamType = (*Param)->getType().getNonReferenceType();
10709       if (ParamType->isDependentType() || ParamType->isRecordType() ||
10710           ParamType->isEnumeralType()) {
10711         ClassOrEnumParam = true;
10712         break;
10713       }
10714     }
10715 
10716     if (!ClassOrEnumParam)
10717       return Diag(FnDecl->getLocation(),
10718                   diag::err_operator_overload_needs_class_or_enum)
10719         << FnDecl->getDeclName();
10720   }
10721 
10722   // C++ [over.oper]p8:
10723   //   An operator function cannot have default arguments (8.3.6),
10724   //   except where explicitly stated below.
10725   //
10726   // Only the function-call operator allows default arguments
10727   // (C++ [over.call]p1).
10728   if (Op != OO_Call) {
10729     for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10730          Param != FnDecl->param_end(); ++Param) {
10731       if ((*Param)->hasDefaultArg())
10732         return Diag((*Param)->getLocation(),
10733                     diag::err_operator_overload_default_arg)
10734           << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
10735     }
10736   }
10737 
10738   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10739     { false, false, false }
10740 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10741     , { Unary, Binary, MemberOnly }
10742 #include "clang/Basic/OperatorKinds.def"
10743   };
10744 
10745   bool CanBeUnaryOperator = OperatorUses[Op][0];
10746   bool CanBeBinaryOperator = OperatorUses[Op][1];
10747   bool MustBeMemberOperator = OperatorUses[Op][2];
10748 
10749   // C++ [over.oper]p8:
10750   //   [...] Operator functions cannot have more or fewer parameters
10751   //   than the number required for the corresponding operator, as
10752   //   described in the rest of this subclause.
10753   unsigned NumParams = FnDecl->getNumParams()
10754                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
10755   if (Op != OO_Call &&
10756       ((NumParams == 1 && !CanBeUnaryOperator) ||
10757        (NumParams == 2 && !CanBeBinaryOperator) ||
10758        (NumParams < 1) || (NumParams > 2))) {
10759     // We have the wrong number of parameters.
10760     unsigned ErrorKind;
10761     if (CanBeUnaryOperator && CanBeBinaryOperator) {
10762       ErrorKind = 2;  // 2 -> unary or binary.
10763     } else if (CanBeUnaryOperator) {
10764       ErrorKind = 0;  // 0 -> unary
10765     } else {
10766       assert(CanBeBinaryOperator &&
10767              "All non-call overloaded operators are unary or binary!");
10768       ErrorKind = 1;  // 1 -> binary
10769     }
10770 
10771     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
10772       << FnDecl->getDeclName() << NumParams << ErrorKind;
10773   }
10774 
10775   // Overloaded operators other than operator() cannot be variadic.
10776   if (Op != OO_Call &&
10777       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
10778     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
10779       << FnDecl->getDeclName();
10780   }
10781 
10782   // Some operators must be non-static member functions.
10783   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10784     return Diag(FnDecl->getLocation(),
10785                 diag::err_operator_overload_must_be_member)
10786       << FnDecl->getDeclName();
10787   }
10788 
10789   // C++ [over.inc]p1:
10790   //   The user-defined function called operator++ implements the
10791   //   prefix and postfix ++ operator. If this function is a member
10792   //   function with no parameters, or a non-member function with one
10793   //   parameter of class or enumeration type, it defines the prefix
10794   //   increment operator ++ for objects of that type. If the function
10795   //   is a member function with one parameter (which shall be of type
10796   //   int) or a non-member function with two parameters (the second
10797   //   of which shall be of type int), it defines the postfix
10798   //   increment operator ++ for objects of that type.
10799   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10800     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10801     bool ParamIsInt = false;
10802     if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
10803       ParamIsInt = BT->getKind() == BuiltinType::Int;
10804 
10805     if (!ParamIsInt)
10806       return Diag(LastParam->getLocation(),
10807                   diag::err_operator_overload_post_incdec_must_be_int)
10808         << LastParam->getType() << (Op == OO_MinusMinus);
10809   }
10810 
10811   return false;
10812 }
10813 
10814 /// CheckLiteralOperatorDeclaration - Check whether the declaration
10815 /// of this literal operator function is well-formed. If so, returns
10816 /// false; otherwise, emits appropriate diagnostics and returns true.
10817 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
10818   if (isa<CXXMethodDecl>(FnDecl)) {
10819     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10820       << FnDecl->getDeclName();
10821     return true;
10822   }
10823 
10824   if (FnDecl->isExternC()) {
10825     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10826     return true;
10827   }
10828 
10829   bool Valid = false;
10830 
10831   // This might be the definition of a literal operator template.
10832   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10833   // This might be a specialization of a literal operator template.
10834   if (!TpDecl)
10835     TpDecl = FnDecl->getPrimaryTemplate();
10836 
10837   // template <char...> type operator "" name() and
10838   // template <class T, T...> type operator "" name() are the only valid
10839   // template signatures, and the only valid signatures with no parameters.
10840   if (TpDecl) {
10841     if (FnDecl->param_size() == 0) {
10842       // Must have one or two template parameters
10843       TemplateParameterList *Params = TpDecl->getTemplateParameters();
10844       if (Params->size() == 1) {
10845         NonTypeTemplateParmDecl *PmDecl =
10846           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
10847 
10848         // The template parameter must be a char parameter pack.
10849         if (PmDecl && PmDecl->isTemplateParameterPack() &&
10850             Context.hasSameType(PmDecl->getType(), Context.CharTy))
10851           Valid = true;
10852       } else if (Params->size() == 2) {
10853         TemplateTypeParmDecl *PmType =
10854           dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
10855         NonTypeTemplateParmDecl *PmArgs =
10856           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
10857 
10858         // The second template parameter must be a parameter pack with the
10859         // first template parameter as its type.
10860         if (PmType && PmArgs &&
10861             !PmType->isTemplateParameterPack() &&
10862             PmArgs->isTemplateParameterPack()) {
10863           const TemplateTypeParmType *TArgs =
10864             PmArgs->getType()->getAs<TemplateTypeParmType>();
10865           if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
10866               TArgs->getIndex() == PmType->getIndex()) {
10867             Valid = true;
10868             if (ActiveTemplateInstantiations.empty())
10869               Diag(FnDecl->getLocation(),
10870                    diag::ext_string_literal_operator_template);
10871           }
10872         }
10873       }
10874     }
10875   } else if (FnDecl->param_size()) {
10876     // Check the first parameter
10877     FunctionDecl::param_iterator Param = FnDecl->param_begin();
10878 
10879     QualType T = (*Param)->getType().getUnqualifiedType();
10880 
10881     // unsigned long long int, long double, and any character type are allowed
10882     // as the only parameters.
10883     if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10884         Context.hasSameType(T, Context.LongDoubleTy) ||
10885         Context.hasSameType(T, Context.CharTy) ||
10886         Context.hasSameType(T, Context.WideCharTy) ||
10887         Context.hasSameType(T, Context.Char16Ty) ||
10888         Context.hasSameType(T, Context.Char32Ty)) {
10889       if (++Param == FnDecl->param_end())
10890         Valid = true;
10891       goto FinishedParams;
10892     }
10893 
10894     // Otherwise it must be a pointer to const; let's strip those qualifiers.
10895     const PointerType *PT = T->getAs<PointerType>();
10896     if (!PT)
10897       goto FinishedParams;
10898     T = PT->getPointeeType();
10899     if (!T.isConstQualified() || T.isVolatileQualified())
10900       goto FinishedParams;
10901     T = T.getUnqualifiedType();
10902 
10903     // Move on to the second parameter;
10904     ++Param;
10905 
10906     // If there is no second parameter, the first must be a const char *
10907     if (Param == FnDecl->param_end()) {
10908       if (Context.hasSameType(T, Context.CharTy))
10909         Valid = true;
10910       goto FinishedParams;
10911     }
10912 
10913     // const char *, const wchar_t*, const char16_t*, and const char32_t*
10914     // are allowed as the first parameter to a two-parameter function
10915     if (!(Context.hasSameType(T, Context.CharTy) ||
10916           Context.hasSameType(T, Context.WideCharTy) ||
10917           Context.hasSameType(T, Context.Char16Ty) ||
10918           Context.hasSameType(T, Context.Char32Ty)))
10919       goto FinishedParams;
10920 
10921     // The second and final parameter must be an std::size_t
10922     T = (*Param)->getType().getUnqualifiedType();
10923     if (Context.hasSameType(T, Context.getSizeType()) &&
10924         ++Param == FnDecl->param_end())
10925       Valid = true;
10926   }
10927 
10928   // FIXME: This diagnostic is absolutely terrible.
10929 FinishedParams:
10930   if (!Valid) {
10931     Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10932       << FnDecl->getDeclName();
10933     return true;
10934   }
10935 
10936   // A parameter-declaration-clause containing a default argument is not
10937   // equivalent to any of the permitted forms.
10938   for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10939                                     ParamEnd = FnDecl->param_end();
10940        Param != ParamEnd; ++Param) {
10941     if ((*Param)->hasDefaultArg()) {
10942       Diag((*Param)->getDefaultArgRange().getBegin(),
10943            diag::err_literal_operator_default_argument)
10944         << (*Param)->getDefaultArgRange();
10945       break;
10946     }
10947   }
10948 
10949   StringRef LiteralName
10950     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10951   if (LiteralName[0] != '_') {
10952     // C++11 [usrlit.suffix]p1:
10953     //   Literal suffix identifiers that do not start with an underscore
10954     //   are reserved for future standardization.
10955     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
10956       << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
10957   }
10958 
10959   return false;
10960 }
10961 
10962 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10963 /// linkage specification, including the language and (if present)
10964 /// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10965 /// the location of the language string literal, which is provided
10966 /// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10967 /// the '{' brace. Otherwise, this linkage specification does not
10968 /// have any braces.
10969 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10970                                            SourceLocation LangLoc,
10971                                            StringRef Lang,
10972                                            SourceLocation LBraceLoc) {
10973   LinkageSpecDecl::LanguageIDs Language;
10974   if (Lang == "\"C\"")
10975     Language = LinkageSpecDecl::lang_c;
10976   else if (Lang == "\"C++\"")
10977     Language = LinkageSpecDecl::lang_cxx;
10978   else {
10979     Diag(LangLoc, diag::err_bad_language);
10980     return 0;
10981   }
10982 
10983   // FIXME: Add all the various semantics of linkage specifications
10984 
10985   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
10986                                                ExternLoc, LangLoc, Language,
10987                                                LBraceLoc.isValid());
10988   CurContext->addDecl(D);
10989   PushDeclContext(S, D);
10990   return D;
10991 }
10992 
10993 /// ActOnFinishLinkageSpecification - Complete the definition of
10994 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
10995 /// valid, it's the position of the closing '}' brace in a linkage
10996 /// specification that uses braces.
10997 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
10998                                             Decl *LinkageSpec,
10999                                             SourceLocation RBraceLoc) {
11000   if (LinkageSpec) {
11001     if (RBraceLoc.isValid()) {
11002       LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11003       LSDecl->setRBraceLoc(RBraceLoc);
11004     }
11005     PopDeclContext();
11006   }
11007   return LinkageSpec;
11008 }
11009 
11010 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11011                                   AttributeList *AttrList,
11012                                   SourceLocation SemiLoc) {
11013   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11014   // Attribute declarations appertain to empty declaration so we handle
11015   // them here.
11016   if (AttrList)
11017     ProcessDeclAttributeList(S, ED, AttrList);
11018 
11019   CurContext->addDecl(ED);
11020   return ED;
11021 }
11022 
11023 /// \brief Perform semantic analysis for the variable declaration that
11024 /// occurs within a C++ catch clause, returning the newly-created
11025 /// variable.
11026 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
11027                                          TypeSourceInfo *TInfo,
11028                                          SourceLocation StartLoc,
11029                                          SourceLocation Loc,
11030                                          IdentifierInfo *Name) {
11031   bool Invalid = false;
11032   QualType ExDeclType = TInfo->getType();
11033 
11034   // Arrays and functions decay.
11035   if (ExDeclType->isArrayType())
11036     ExDeclType = Context.getArrayDecayedType(ExDeclType);
11037   else if (ExDeclType->isFunctionType())
11038     ExDeclType = Context.getPointerType(ExDeclType);
11039 
11040   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11041   // The exception-declaration shall not denote a pointer or reference to an
11042   // incomplete type, other than [cv] void*.
11043   // N2844 forbids rvalue references.
11044   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
11045     Diag(Loc, diag::err_catch_rvalue_ref);
11046     Invalid = true;
11047   }
11048 
11049   QualType BaseType = ExDeclType;
11050   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
11051   unsigned DK = diag::err_catch_incomplete;
11052   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
11053     BaseType = Ptr->getPointeeType();
11054     Mode = 1;
11055     DK = diag::err_catch_incomplete_ptr;
11056   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
11057     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
11058     BaseType = Ref->getPointeeType();
11059     Mode = 2;
11060     DK = diag::err_catch_incomplete_ref;
11061   }
11062   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
11063       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
11064     Invalid = true;
11065 
11066   if (!Invalid && !ExDeclType->isDependentType() &&
11067       RequireNonAbstractType(Loc, ExDeclType,
11068                              diag::err_abstract_type_in_decl,
11069                              AbstractVariableType))
11070     Invalid = true;
11071 
11072   // Only the non-fragile NeXT runtime currently supports C++ catches
11073   // of ObjC types, and no runtime supports catching ObjC types by value.
11074   if (!Invalid && getLangOpts().ObjC1) {
11075     QualType T = ExDeclType;
11076     if (const ReferenceType *RT = T->getAs<ReferenceType>())
11077       T = RT->getPointeeType();
11078 
11079     if (T->isObjCObjectType()) {
11080       Diag(Loc, diag::err_objc_object_catch);
11081       Invalid = true;
11082     } else if (T->isObjCObjectPointerType()) {
11083       // FIXME: should this be a test for macosx-fragile specifically?
11084       if (getLangOpts().ObjCRuntime.isFragile())
11085         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
11086     }
11087   }
11088 
11089   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
11090                                     ExDeclType, TInfo, SC_None);
11091   ExDecl->setExceptionVariable(true);
11092 
11093   // In ARC, infer 'retaining' for variables of retainable type.
11094   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
11095     Invalid = true;
11096 
11097   if (!Invalid && !ExDeclType->isDependentType()) {
11098     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
11099       // Insulate this from anything else we might currently be parsing.
11100       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11101 
11102       // C++ [except.handle]p16:
11103       //   The object declared in an exception-declaration or, if the
11104       //   exception-declaration does not specify a name, a temporary (12.2) is
11105       //   copy-initialized (8.5) from the exception object. [...]
11106       //   The object is destroyed when the handler exits, after the destruction
11107       //   of any automatic objects initialized within the handler.
11108       //
11109       // We just pretend to initialize the object with itself, then make sure
11110       // it can be destroyed later.
11111       QualType initType = ExDeclType;
11112 
11113       InitializedEntity entity =
11114         InitializedEntity::InitializeVariable(ExDecl);
11115       InitializationKind initKind =
11116         InitializationKind::CreateCopy(Loc, SourceLocation());
11117 
11118       Expr *opaqueValue =
11119         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
11120       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11121       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
11122       if (result.isInvalid())
11123         Invalid = true;
11124       else {
11125         // If the constructor used was non-trivial, set this as the
11126         // "initializer".
11127         CXXConstructExpr *construct = result.takeAs<CXXConstructExpr>();
11128         if (!construct->getConstructor()->isTrivial()) {
11129           Expr *init = MaybeCreateExprWithCleanups(construct);
11130           ExDecl->setInit(init);
11131         }
11132 
11133         // And make sure it's destructable.
11134         FinalizeVarWithDestructor(ExDecl, recordType);
11135       }
11136     }
11137   }
11138 
11139   if (Invalid)
11140     ExDecl->setInvalidDecl();
11141 
11142   return ExDecl;
11143 }
11144 
11145 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11146 /// handler.
11147 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
11148   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11149   bool Invalid = D.isInvalidType();
11150 
11151   // Check for unexpanded parameter packs.
11152   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11153                                       UPPC_ExceptionType)) {
11154     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11155                                              D.getIdentifierLoc());
11156     Invalid = true;
11157   }
11158 
11159   IdentifierInfo *II = D.getIdentifier();
11160   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
11161                                              LookupOrdinaryName,
11162                                              ForRedeclaration)) {
11163     // The scope should be freshly made just for us. There is just no way
11164     // it contains any previous declaration.
11165     assert(!S->isDeclScope(PrevDecl));
11166     if (PrevDecl->isTemplateParameter()) {
11167       // Maybe we will complain about the shadowed template parameter.
11168       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11169       PrevDecl = 0;
11170     }
11171   }
11172 
11173   if (D.getCXXScopeSpec().isSet() && !Invalid) {
11174     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11175       << D.getCXXScopeSpec().getRange();
11176     Invalid = true;
11177   }
11178 
11179   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
11180                                               D.getLocStart(),
11181                                               D.getIdentifierLoc(),
11182                                               D.getIdentifier());
11183   if (Invalid)
11184     ExDecl->setInvalidDecl();
11185 
11186   // Add the exception declaration into this scope.
11187   if (II)
11188     PushOnScopeChains(ExDecl, S);
11189   else
11190     CurContext->addDecl(ExDecl);
11191 
11192   ProcessDeclAttributes(S, ExDecl, D);
11193   return ExDecl;
11194 }
11195 
11196 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11197                                          Expr *AssertExpr,
11198                                          Expr *AssertMessageExpr,
11199                                          SourceLocation RParenLoc) {
11200   StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
11201 
11202   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
11203     return 0;
11204 
11205   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11206                                       AssertMessage, RParenLoc, false);
11207 }
11208 
11209 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11210                                          Expr *AssertExpr,
11211                                          StringLiteral *AssertMessage,
11212                                          SourceLocation RParenLoc,
11213                                          bool Failed) {
11214   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11215       !Failed) {
11216     // In a static_assert-declaration, the constant-expression shall be a
11217     // constant expression that can be contextually converted to bool.
11218     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11219     if (Converted.isInvalid())
11220       Failed = true;
11221 
11222     llvm::APSInt Cond;
11223     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
11224           diag::err_static_assert_expression_is_not_constant,
11225           /*AllowFold=*/false).isInvalid())
11226       Failed = true;
11227 
11228     if (!Failed && !Cond) {
11229       SmallString<256> MsgBuffer;
11230       llvm::raw_svector_ostream Msg(MsgBuffer);
11231       AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
11232       Diag(StaticAssertLoc, diag::err_static_assert_failed)
11233         << Msg.str() << AssertExpr->getSourceRange();
11234       Failed = true;
11235     }
11236   }
11237 
11238   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
11239                                         AssertExpr, AssertMessage, RParenLoc,
11240                                         Failed);
11241 
11242   CurContext->addDecl(Decl);
11243   return Decl;
11244 }
11245 
11246 /// \brief Perform semantic analysis of the given friend type declaration.
11247 ///
11248 /// \returns A friend declaration that.
11249 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
11250                                       SourceLocation FriendLoc,
11251                                       TypeSourceInfo *TSInfo) {
11252   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11253 
11254   QualType T = TSInfo->getType();
11255   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
11256 
11257   // C++03 [class.friend]p2:
11258   //   An elaborated-type-specifier shall be used in a friend declaration
11259   //   for a class.*
11260   //
11261   //   * The class-key of the elaborated-type-specifier is required.
11262   if (!ActiveTemplateInstantiations.empty()) {
11263     // Do not complain about the form of friend template types during
11264     // template instantiation; we will already have complained when the
11265     // template was declared.
11266   } else {
11267     if (!T->isElaboratedTypeSpecifier()) {
11268       // If we evaluated the type to a record type, suggest putting
11269       // a tag in front.
11270       if (const RecordType *RT = T->getAs<RecordType>()) {
11271         RecordDecl *RD = RT->getDecl();
11272 
11273         std::string InsertionText = std::string(" ") + RD->getKindName();
11274 
11275         Diag(TypeRange.getBegin(),
11276              getLangOpts().CPlusPlus11 ?
11277                diag::warn_cxx98_compat_unelaborated_friend_type :
11278                diag::ext_unelaborated_friend_type)
11279           << (unsigned) RD->getTagKind()
11280           << T
11281           << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11282                                         InsertionText);
11283       } else {
11284         Diag(FriendLoc,
11285              getLangOpts().CPlusPlus11 ?
11286                diag::warn_cxx98_compat_nonclass_type_friend :
11287                diag::ext_nonclass_type_friend)
11288           << T
11289           << TypeRange;
11290       }
11291     } else if (T->getAs<EnumType>()) {
11292       Diag(FriendLoc,
11293            getLangOpts().CPlusPlus11 ?
11294              diag::warn_cxx98_compat_enum_friend :
11295              diag::ext_enum_friend)
11296         << T
11297         << TypeRange;
11298     }
11299 
11300     // C++11 [class.friend]p3:
11301     //   A friend declaration that does not declare a function shall have one
11302     //   of the following forms:
11303     //     friend elaborated-type-specifier ;
11304     //     friend simple-type-specifier ;
11305     //     friend typename-specifier ;
11306     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11307       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11308   }
11309 
11310   //   If the type specifier in a friend declaration designates a (possibly
11311   //   cv-qualified) class type, that class is declared as a friend; otherwise,
11312   //   the friend declaration is ignored.
11313   return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
11314 }
11315 
11316 /// Handle a friend tag declaration where the scope specifier was
11317 /// templated.
11318 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11319                                     unsigned TagSpec, SourceLocation TagLoc,
11320                                     CXXScopeSpec &SS,
11321                                     IdentifierInfo *Name,
11322                                     SourceLocation NameLoc,
11323                                     AttributeList *Attr,
11324                                     MultiTemplateParamsArg TempParamLists) {
11325   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11326 
11327   bool isExplicitSpecialization = false;
11328   bool Invalid = false;
11329 
11330   if (TemplateParameterList *TemplateParams =
11331           MatchTemplateParametersToScopeSpecifier(
11332               TagLoc, NameLoc, SS, TempParamLists, /*friend*/ true,
11333               isExplicitSpecialization, Invalid)) {
11334     if (TemplateParams->size() > 0) {
11335       // This is a declaration of a class template.
11336       if (Invalid)
11337         return 0;
11338 
11339       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
11340                                 SS, Name, NameLoc, Attr,
11341                                 TemplateParams, AS_public,
11342                                 /*ModulePrivateLoc=*/SourceLocation(),
11343                                 TempParamLists.size() - 1,
11344                                 TempParamLists.data()).take();
11345     } else {
11346       // The "template<>" header is extraneous.
11347       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11348         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11349       isExplicitSpecialization = true;
11350     }
11351   }
11352 
11353   if (Invalid) return 0;
11354 
11355   bool isAllExplicitSpecializations = true;
11356   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
11357     if (TempParamLists[I]->size()) {
11358       isAllExplicitSpecializations = false;
11359       break;
11360     }
11361   }
11362 
11363   // FIXME: don't ignore attributes.
11364 
11365   // If it's explicit specializations all the way down, just forget
11366   // about the template header and build an appropriate non-templated
11367   // friend.  TODO: for source fidelity, remember the headers.
11368   if (isAllExplicitSpecializations) {
11369     if (SS.isEmpty()) {
11370       bool Owned = false;
11371       bool IsDependent = false;
11372       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
11373                       Attr, AS_public,
11374                       /*ModulePrivateLoc=*/SourceLocation(),
11375                       MultiTemplateParamsArg(), Owned, IsDependent,
11376                       /*ScopedEnumKWLoc=*/SourceLocation(),
11377                       /*ScopedEnumUsesClassTag=*/false,
11378                       /*UnderlyingType=*/TypeResult());
11379     }
11380 
11381     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11382     ElaboratedTypeKeyword Keyword
11383       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11384     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
11385                                    *Name, NameLoc);
11386     if (T.isNull())
11387       return 0;
11388 
11389     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11390     if (isa<DependentNameType>(T)) {
11391       DependentNameTypeLoc TL =
11392           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
11393       TL.setElaboratedKeywordLoc(TagLoc);
11394       TL.setQualifierLoc(QualifierLoc);
11395       TL.setNameLoc(NameLoc);
11396     } else {
11397       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
11398       TL.setElaboratedKeywordLoc(TagLoc);
11399       TL.setQualifierLoc(QualifierLoc);
11400       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
11401     }
11402 
11403     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
11404                                             TSI, FriendLoc, TempParamLists);
11405     Friend->setAccess(AS_public);
11406     CurContext->addDecl(Friend);
11407     return Friend;
11408   }
11409 
11410   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11411 
11412 
11413 
11414   // Handle the case of a templated-scope friend class.  e.g.
11415   //   template <class T> class A<T>::B;
11416   // FIXME: we don't support these right now.
11417   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
11418     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
11419   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11420   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11421   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11422   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
11423   TL.setElaboratedKeywordLoc(TagLoc);
11424   TL.setQualifierLoc(SS.getWithLocInContext(Context));
11425   TL.setNameLoc(NameLoc);
11426 
11427   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
11428                                           TSI, FriendLoc, TempParamLists);
11429   Friend->setAccess(AS_public);
11430   Friend->setUnsupportedFriend(true);
11431   CurContext->addDecl(Friend);
11432   return Friend;
11433 }
11434 
11435 
11436 /// Handle a friend type declaration.  This works in tandem with
11437 /// ActOnTag.
11438 ///
11439 /// Notes on friend class templates:
11440 ///
11441 /// We generally treat friend class declarations as if they were
11442 /// declaring a class.  So, for example, the elaborated type specifier
11443 /// in a friend declaration is required to obey the restrictions of a
11444 /// class-head (i.e. no typedefs in the scope chain), template
11445 /// parameters are required to match up with simple template-ids, &c.
11446 /// However, unlike when declaring a template specialization, it's
11447 /// okay to refer to a template specialization without an empty
11448 /// template parameter declaration, e.g.
11449 ///   friend class A<T>::B<unsigned>;
11450 /// We permit this as a special case; if there are any template
11451 /// parameters present at all, require proper matching, i.e.
11452 ///   template <> template \<class T> friend class A<int>::B;
11453 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
11454                                 MultiTemplateParamsArg TempParams) {
11455   SourceLocation Loc = DS.getLocStart();
11456 
11457   assert(DS.isFriendSpecified());
11458   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11459 
11460   // Try to convert the decl specifier to a type.  This works for
11461   // friend templates because ActOnTag never produces a ClassTemplateDecl
11462   // for a TUK_Friend.
11463   Declarator TheDeclarator(DS, Declarator::MemberContext);
11464   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11465   QualType T = TSI->getType();
11466   if (TheDeclarator.isInvalidType())
11467     return 0;
11468 
11469   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11470     return 0;
11471 
11472   // This is definitely an error in C++98.  It's probably meant to
11473   // be forbidden in C++0x, too, but the specification is just
11474   // poorly written.
11475   //
11476   // The problem is with declarations like the following:
11477   //   template <T> friend A<T>::foo;
11478   // where deciding whether a class C is a friend or not now hinges
11479   // on whether there exists an instantiation of A that causes
11480   // 'foo' to equal C.  There are restrictions on class-heads
11481   // (which we declare (by fiat) elaborated friend declarations to
11482   // be) that makes this tractable.
11483   //
11484   // FIXME: handle "template <> friend class A<T>;", which
11485   // is possibly well-formed?  Who even knows?
11486   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
11487     Diag(Loc, diag::err_tagless_friend_type_template)
11488       << DS.getSourceRange();
11489     return 0;
11490   }
11491 
11492   // C++98 [class.friend]p1: A friend of a class is a function
11493   //   or class that is not a member of the class . . .
11494   // This is fixed in DR77, which just barely didn't make the C++03
11495   // deadline.  It's also a very silly restriction that seriously
11496   // affects inner classes and which nobody else seems to implement;
11497   // thus we never diagnose it, not even in -pedantic.
11498   //
11499   // But note that we could warn about it: it's always useless to
11500   // friend one of your own members (it's not, however, worthless to
11501   // friend a member of an arbitrary specialization of your template).
11502 
11503   Decl *D;
11504   if (unsigned NumTempParamLists = TempParams.size())
11505     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
11506                                    NumTempParamLists,
11507                                    TempParams.data(),
11508                                    TSI,
11509                                    DS.getFriendSpecLoc());
11510   else
11511     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
11512 
11513   if (!D)
11514     return 0;
11515 
11516   D->setAccess(AS_public);
11517   CurContext->addDecl(D);
11518 
11519   return D;
11520 }
11521 
11522 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11523                                         MultiTemplateParamsArg TemplateParams) {
11524   const DeclSpec &DS = D.getDeclSpec();
11525 
11526   assert(DS.isFriendSpecified());
11527   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11528 
11529   SourceLocation Loc = D.getIdentifierLoc();
11530   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11531 
11532   // C++ [class.friend]p1
11533   //   A friend of a class is a function or class....
11534   // Note that this sees through typedefs, which is intended.
11535   // It *doesn't* see through dependent types, which is correct
11536   // according to [temp.arg.type]p3:
11537   //   If a declaration acquires a function type through a
11538   //   type dependent on a template-parameter and this causes
11539   //   a declaration that does not use the syntactic form of a
11540   //   function declarator to have a function type, the program
11541   //   is ill-formed.
11542   if (!TInfo->getType()->isFunctionType()) {
11543     Diag(Loc, diag::err_unexpected_friend);
11544 
11545     // It might be worthwhile to try to recover by creating an
11546     // appropriate declaration.
11547     return 0;
11548   }
11549 
11550   // C++ [namespace.memdef]p3
11551   //  - If a friend declaration in a non-local class first declares a
11552   //    class or function, the friend class or function is a member
11553   //    of the innermost enclosing namespace.
11554   //  - The name of the friend is not found by simple name lookup
11555   //    until a matching declaration is provided in that namespace
11556   //    scope (either before or after the class declaration granting
11557   //    friendship).
11558   //  - If a friend function is called, its name may be found by the
11559   //    name lookup that considers functions from namespaces and
11560   //    classes associated with the types of the function arguments.
11561   //  - When looking for a prior declaration of a class or a function
11562   //    declared as a friend, scopes outside the innermost enclosing
11563   //    namespace scope are not considered.
11564 
11565   CXXScopeSpec &SS = D.getCXXScopeSpec();
11566   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11567   DeclarationName Name = NameInfo.getName();
11568   assert(Name);
11569 
11570   // Check for unexpanded parameter packs.
11571   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11572       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11573       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11574     return 0;
11575 
11576   // The context we found the declaration in, or in which we should
11577   // create the declaration.
11578   DeclContext *DC;
11579   Scope *DCScope = S;
11580   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
11581                         ForRedeclaration);
11582 
11583   // There are five cases here.
11584   //   - There's no scope specifier and we're in a local class. Only look
11585   //     for functions declared in the immediately-enclosing block scope.
11586   // We recover from invalid scope qualifiers as if they just weren't there.
11587   FunctionDecl *FunctionContainingLocalClass = 0;
11588   if ((SS.isInvalid() || !SS.isSet()) &&
11589       (FunctionContainingLocalClass =
11590            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11591     // C++11 [class.friend]p11:
11592     //   If a friend declaration appears in a local class and the name
11593     //   specified is an unqualified name, a prior declaration is
11594     //   looked up without considering scopes that are outside the
11595     //   innermost enclosing non-class scope. For a friend function
11596     //   declaration, if there is no prior declaration, the program is
11597     //   ill-formed.
11598 
11599     // Find the innermost enclosing non-class scope. This is the block
11600     // scope containing the local class definition (or for a nested class,
11601     // the outer local class).
11602     DCScope = S->getFnParent();
11603 
11604     // Look up the function name in the scope.
11605     Previous.clear(LookupLocalFriendName);
11606     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11607 
11608     if (!Previous.empty()) {
11609       // All possible previous declarations must have the same context:
11610       // either they were declared at block scope or they are members of
11611       // one of the enclosing local classes.
11612       DC = Previous.getRepresentativeDecl()->getDeclContext();
11613     } else {
11614       // This is ill-formed, but provide the context that we would have
11615       // declared the function in, if we were permitted to, for error recovery.
11616       DC = FunctionContainingLocalClass;
11617     }
11618     adjustContextForLocalExternDecl(DC);
11619 
11620     // C++ [class.friend]p6:
11621     //   A function can be defined in a friend declaration of a class if and
11622     //   only if the class is a non-local class (9.8), the function name is
11623     //   unqualified, and the function has namespace scope.
11624     if (D.isFunctionDefinition()) {
11625       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11626     }
11627 
11628   //   - There's no scope specifier, in which case we just go to the
11629   //     appropriate scope and look for a function or function template
11630   //     there as appropriate.
11631   } else if (SS.isInvalid() || !SS.isSet()) {
11632     // C++11 [namespace.memdef]p3:
11633     //   If the name in a friend declaration is neither qualified nor
11634     //   a template-id and the declaration is a function or an
11635     //   elaborated-type-specifier, the lookup to determine whether
11636     //   the entity has been previously declared shall not consider
11637     //   any scopes outside the innermost enclosing namespace.
11638     bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
11639 
11640     // Find the appropriate context according to the above.
11641     DC = CurContext;
11642 
11643     // Skip class contexts.  If someone can cite chapter and verse
11644     // for this behavior, that would be nice --- it's what GCC and
11645     // EDG do, and it seems like a reasonable intent, but the spec
11646     // really only says that checks for unqualified existing
11647     // declarations should stop at the nearest enclosing namespace,
11648     // not that they should only consider the nearest enclosing
11649     // namespace.
11650     while (DC->isRecord())
11651       DC = DC->getParent();
11652 
11653     DeclContext *LookupDC = DC;
11654     while (LookupDC->isTransparentContext())
11655       LookupDC = LookupDC->getParent();
11656 
11657     while (true) {
11658       LookupQualifiedName(Previous, LookupDC);
11659 
11660       if (!Previous.empty()) {
11661         DC = LookupDC;
11662         break;
11663       }
11664 
11665       if (isTemplateId) {
11666         if (isa<TranslationUnitDecl>(LookupDC)) break;
11667       } else {
11668         if (LookupDC->isFileContext()) break;
11669       }
11670       LookupDC = LookupDC->getParent();
11671     }
11672 
11673     DCScope = getScopeForDeclContext(S, DC);
11674 
11675   //   - There's a non-dependent scope specifier, in which case we
11676   //     compute it and do a previous lookup there for a function
11677   //     or function template.
11678   } else if (!SS.getScopeRep()->isDependent()) {
11679     DC = computeDeclContext(SS);
11680     if (!DC) return 0;
11681 
11682     if (RequireCompleteDeclContext(SS, DC)) return 0;
11683 
11684     LookupQualifiedName(Previous, DC);
11685 
11686     // Ignore things found implicitly in the wrong scope.
11687     // TODO: better diagnostics for this case.  Suggesting the right
11688     // qualified scope would be nice...
11689     LookupResult::Filter F = Previous.makeFilter();
11690     while (F.hasNext()) {
11691       NamedDecl *D = F.next();
11692       if (!DC->InEnclosingNamespaceSetOf(
11693               D->getDeclContext()->getRedeclContext()))
11694         F.erase();
11695     }
11696     F.done();
11697 
11698     if (Previous.empty()) {
11699       D.setInvalidType();
11700       Diag(Loc, diag::err_qualified_friend_not_found)
11701           << Name << TInfo->getType();
11702       return 0;
11703     }
11704 
11705     // C++ [class.friend]p1: A friend of a class is a function or
11706     //   class that is not a member of the class . . .
11707     if (DC->Equals(CurContext))
11708       Diag(DS.getFriendSpecLoc(),
11709            getLangOpts().CPlusPlus11 ?
11710              diag::warn_cxx98_compat_friend_is_member :
11711              diag::err_friend_is_member);
11712 
11713     if (D.isFunctionDefinition()) {
11714       // C++ [class.friend]p6:
11715       //   A function can be defined in a friend declaration of a class if and
11716       //   only if the class is a non-local class (9.8), the function name is
11717       //   unqualified, and the function has namespace scope.
11718       SemaDiagnosticBuilder DB
11719         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11720 
11721       DB << SS.getScopeRep();
11722       if (DC->isFileContext())
11723         DB << FixItHint::CreateRemoval(SS.getRange());
11724       SS.clear();
11725     }
11726 
11727   //   - There's a scope specifier that does not match any template
11728   //     parameter lists, in which case we use some arbitrary context,
11729   //     create a method or method template, and wait for instantiation.
11730   //   - There's a scope specifier that does match some template
11731   //     parameter lists, which we don't handle right now.
11732   } else {
11733     if (D.isFunctionDefinition()) {
11734       // C++ [class.friend]p6:
11735       //   A function can be defined in a friend declaration of a class if and
11736       //   only if the class is a non-local class (9.8), the function name is
11737       //   unqualified, and the function has namespace scope.
11738       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11739         << SS.getScopeRep();
11740     }
11741 
11742     DC = CurContext;
11743     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
11744   }
11745 
11746   if (!DC->isRecord()) {
11747     // This implies that it has to be an operator or function.
11748     if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11749         D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11750         D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
11751       Diag(Loc, diag::err_introducing_special_friend) <<
11752         (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11753          D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
11754       return 0;
11755     }
11756   }
11757 
11758   // FIXME: This is an egregious hack to cope with cases where the scope stack
11759   // does not contain the declaration context, i.e., in an out-of-line
11760   // definition of a class.
11761   Scope FakeDCScope(S, Scope::DeclScope, Diags);
11762   if (!DCScope) {
11763     FakeDCScope.setEntity(DC);
11764     DCScope = &FakeDCScope;
11765   }
11766 
11767   bool AddToScope = true;
11768   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
11769                                           TemplateParams, AddToScope);
11770   if (!ND) return 0;
11771 
11772   assert(ND->getLexicalDeclContext() == CurContext);
11773 
11774   // If we performed typo correction, we might have added a scope specifier
11775   // and changed the decl context.
11776   DC = ND->getDeclContext();
11777 
11778   // Add the function declaration to the appropriate lookup tables,
11779   // adjusting the redeclarations list as necessary.  We don't
11780   // want to do this yet if the friending class is dependent.
11781   //
11782   // Also update the scope-based lookup if the target context's
11783   // lookup context is in lexical scope.
11784   if (!CurContext->isDependentContext()) {
11785     DC = DC->getRedeclContext();
11786     DC->makeDeclVisibleInContext(ND);
11787     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11788       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
11789   }
11790 
11791   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
11792                                        D.getIdentifierLoc(), ND,
11793                                        DS.getFriendSpecLoc());
11794   FrD->setAccess(AS_public);
11795   CurContext->addDecl(FrD);
11796 
11797   if (ND->isInvalidDecl()) {
11798     FrD->setInvalidDecl();
11799   } else {
11800     if (DC->isRecord()) CheckFriendAccess(ND);
11801 
11802     FunctionDecl *FD;
11803     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11804       FD = FTD->getTemplatedDecl();
11805     else
11806       FD = cast<FunctionDecl>(ND);
11807 
11808     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
11809     // default argument expression, that declaration shall be a definition
11810     // and shall be the only declaration of the function or function
11811     // template in the translation unit.
11812     if (functionDeclHasDefaultArgument(FD)) {
11813       if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
11814         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
11815         Diag(OldFD->getLocation(), diag::note_previous_declaration);
11816       } else if (!D.isFunctionDefinition())
11817         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
11818     }
11819 
11820     // Mark templated-scope function declarations as unsupported.
11821     if (FD->getNumTemplateParameterLists())
11822       FrD->setUnsupportedFriend(true);
11823   }
11824 
11825   return ND;
11826 }
11827 
11828 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11829   AdjustDeclIfTemplate(Dcl);
11830 
11831   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
11832   if (!Fn) {
11833     Diag(DelLoc, diag::err_deleted_non_function);
11834     return;
11835   }
11836 
11837   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
11838     // Don't consider the implicit declaration we generate for explicit
11839     // specializations. FIXME: Do not generate these implicit declarations.
11840     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11841         || Prev->getPreviousDecl()) && !Prev->isDefined()) {
11842       Diag(DelLoc, diag::err_deleted_decl_not_first);
11843       Diag(Prev->getLocation(), diag::note_previous_declaration);
11844     }
11845     // If the declaration wasn't the first, we delete the function anyway for
11846     // recovery.
11847     Fn = Fn->getCanonicalDecl();
11848   }
11849 
11850   if (Fn->isDeleted())
11851     return;
11852 
11853   // See if we're deleting a function which is already known to override a
11854   // non-deleted virtual function.
11855   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11856     bool IssuedDiagnostic = false;
11857     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11858                                         E = MD->end_overridden_methods();
11859          I != E; ++I) {
11860       if (!(*MD->begin_overridden_methods())->isDeleted()) {
11861         if (!IssuedDiagnostic) {
11862           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11863           IssuedDiagnostic = true;
11864         }
11865         Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11866       }
11867     }
11868   }
11869 
11870   Fn->setDeletedAsWritten();
11871 }
11872 
11873 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
11874   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
11875 
11876   if (MD) {
11877     if (MD->getParent()->isDependentType()) {
11878       MD->setDefaulted();
11879       MD->setExplicitlyDefaulted();
11880       return;
11881     }
11882 
11883     CXXSpecialMember Member = getSpecialMember(MD);
11884     if (Member == CXXInvalid) {
11885       if (!MD->isInvalidDecl())
11886         Diag(DefaultLoc, diag::err_default_special_members);
11887       return;
11888     }
11889 
11890     MD->setDefaulted();
11891     MD->setExplicitlyDefaulted();
11892 
11893     // If this definition appears within the record, do the checking when
11894     // the record is complete.
11895     const FunctionDecl *Primary = MD;
11896     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
11897       // Find the uninstantiated declaration that actually had the '= default'
11898       // on it.
11899       Pattern->isDefined(Primary);
11900 
11901     // If the method was defaulted on its first declaration, we will have
11902     // already performed the checking in CheckCompletedCXXClass. Such a
11903     // declaration doesn't trigger an implicit definition.
11904     if (Primary == Primary->getCanonicalDecl())
11905       return;
11906 
11907     CheckExplicitlyDefaultedSpecialMember(MD);
11908 
11909     // The exception specification is needed because we are defining the
11910     // function.
11911     ResolveExceptionSpec(DefaultLoc,
11912                          MD->getType()->castAs<FunctionProtoType>());
11913 
11914     if (MD->isInvalidDecl())
11915       return;
11916 
11917     switch (Member) {
11918     case CXXDefaultConstructor:
11919       DefineImplicitDefaultConstructor(DefaultLoc,
11920                                        cast<CXXConstructorDecl>(MD));
11921       break;
11922     case CXXCopyConstructor:
11923       DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
11924       break;
11925     case CXXCopyAssignment:
11926       DefineImplicitCopyAssignment(DefaultLoc, MD);
11927       break;
11928     case CXXDestructor:
11929       DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
11930       break;
11931     case CXXMoveConstructor:
11932       DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
11933       break;
11934     case CXXMoveAssignment:
11935       DefineImplicitMoveAssignment(DefaultLoc, MD);
11936       break;
11937     case CXXInvalid:
11938       llvm_unreachable("Invalid special member.");
11939     }
11940   } else {
11941     Diag(DefaultLoc, diag::err_default_special_members);
11942   }
11943 }
11944 
11945 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
11946   for (Stmt::child_range CI = S->children(); CI; ++CI) {
11947     Stmt *SubStmt = *CI;
11948     if (!SubStmt)
11949       continue;
11950     if (isa<ReturnStmt>(SubStmt))
11951       Self.Diag(SubStmt->getLocStart(),
11952            diag::err_return_in_constructor_handler);
11953     if (!isa<Expr>(SubStmt))
11954       SearchForReturnInStmt(Self, SubStmt);
11955   }
11956 }
11957 
11958 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11959   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11960     CXXCatchStmt *Handler = TryBlock->getHandler(I);
11961     SearchForReturnInStmt(*this, Handler);
11962   }
11963 }
11964 
11965 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
11966                                              const CXXMethodDecl *Old) {
11967   const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11968   const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11969 
11970   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11971 
11972   // If the calling conventions match, everything is fine
11973   if (NewCC == OldCC)
11974     return false;
11975 
11976   Diag(New->getLocation(),
11977        diag::err_conflicting_overriding_cc_attributes)
11978     << New->getDeclName() << New->getType() << Old->getType();
11979   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11980   return true;
11981 }
11982 
11983 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
11984                                              const CXXMethodDecl *Old) {
11985   QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11986   QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
11987 
11988   if (Context.hasSameType(NewTy, OldTy) ||
11989       NewTy->isDependentType() || OldTy->isDependentType())
11990     return false;
11991 
11992   // Check if the return types are covariant
11993   QualType NewClassTy, OldClassTy;
11994 
11995   /// Both types must be pointers or references to classes.
11996   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11997     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
11998       NewClassTy = NewPT->getPointeeType();
11999       OldClassTy = OldPT->getPointeeType();
12000     }
12001   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12002     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12003       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12004         NewClassTy = NewRT->getPointeeType();
12005         OldClassTy = OldRT->getPointeeType();
12006       }
12007     }
12008   }
12009 
12010   // The return types aren't either both pointers or references to a class type.
12011   if (NewClassTy.isNull()) {
12012     Diag(New->getLocation(),
12013          diag::err_different_return_type_for_overriding_virtual_function)
12014       << New->getDeclName() << NewTy << OldTy;
12015     Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12016 
12017     return true;
12018   }
12019 
12020   // C++ [class.virtual]p6:
12021   //   If the return type of D::f differs from the return type of B::f, the
12022   //   class type in the return type of D::f shall be complete at the point of
12023   //   declaration of D::f or shall be the class type D.
12024   if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12025     if (!RT->isBeingDefined() &&
12026         RequireCompleteType(New->getLocation(), NewClassTy,
12027                             diag::err_covariant_return_incomplete,
12028                             New->getDeclName()))
12029     return true;
12030   }
12031 
12032   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
12033     // Check if the new class derives from the old class.
12034     if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12035       Diag(New->getLocation(),
12036            diag::err_covariant_return_not_derived)
12037       << New->getDeclName() << NewTy << OldTy;
12038       Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12039       return true;
12040     }
12041 
12042     // Check if we the conversion from derived to base is valid.
12043     if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
12044                     diag::err_covariant_return_inaccessible_base,
12045                     diag::err_covariant_return_ambiguous_derived_to_base_conv,
12046                     // FIXME: Should this point to the return type?
12047                     New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
12048       // FIXME: this note won't trigger for delayed access control
12049       // diagnostics, and it's impossible to get an undelayed error
12050       // here from access control during the original parse because
12051       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
12052       Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12053       return true;
12054     }
12055   }
12056 
12057   // The qualifiers of the return types must be the same.
12058   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
12059     Diag(New->getLocation(),
12060          diag::err_covariant_return_type_different_qualifications)
12061     << New->getDeclName() << NewTy << OldTy;
12062     Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12063     return true;
12064   };
12065 
12066 
12067   // The new class type must have the same or less qualifiers as the old type.
12068   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12069     Diag(New->getLocation(),
12070          diag::err_covariant_return_type_class_type_more_qualified)
12071     << New->getDeclName() << NewTy << OldTy;
12072     Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12073     return true;
12074   };
12075 
12076   return false;
12077 }
12078 
12079 /// \brief Mark the given method pure.
12080 ///
12081 /// \param Method the method to be marked pure.
12082 ///
12083 /// \param InitRange the source range that covers the "0" initializer.
12084 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
12085   SourceLocation EndLoc = InitRange.getEnd();
12086   if (EndLoc.isValid())
12087     Method->setRangeEnd(EndLoc);
12088 
12089   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12090     Method->setPure();
12091     return false;
12092   }
12093 
12094   if (!Method->isInvalidDecl())
12095     Diag(Method->getLocation(), diag::err_non_virtual_pure)
12096       << Method->getDeclName() << InitRange;
12097   return true;
12098 }
12099 
12100 /// \brief Determine whether the given declaration is a static data member.
12101 static bool isStaticDataMember(const Decl *D) {
12102   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12103     return Var->isStaticDataMember();
12104 
12105   return false;
12106 }
12107 
12108 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12109 /// an initializer for the out-of-line declaration 'Dcl'.  The scope
12110 /// is a fresh scope pushed for just this purpose.
12111 ///
12112 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12113 /// static data member of class X, names should be looked up in the scope of
12114 /// class X.
12115 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
12116   // If there is no declaration, there was an error parsing it.
12117   if (D == 0 || D->isInvalidDecl()) return;
12118 
12119   // We should only get called for declarations with scope specifiers, like:
12120   //   int foo::bar;
12121   assert(D->isOutOfLine());
12122   EnterDeclaratorContext(S, D->getDeclContext());
12123 
12124   // If we are parsing the initializer for a static data member, push a
12125   // new expression evaluation context that is associated with this static
12126   // data member.
12127   if (isStaticDataMember(D))
12128     PushExpressionEvaluationContext(PotentiallyEvaluated, D);
12129 }
12130 
12131 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
12132 /// initializer for the out-of-line declaration 'D'.
12133 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
12134   // If there is no declaration, there was an error parsing it.
12135   if (D == 0 || D->isInvalidDecl()) return;
12136 
12137   if (isStaticDataMember(D))
12138     PopExpressionEvaluationContext();
12139 
12140   assert(D->isOutOfLine());
12141   ExitDeclaratorContext(S);
12142 }
12143 
12144 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12145 /// C++ if/switch/while/for statement.
12146 /// e.g: "if (int x = f()) {...}"
12147 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
12148   // C++ 6.4p2:
12149   // The declarator shall not specify a function or an array.
12150   // The type-specifier-seq shall not contain typedef and shall not declare a
12151   // new class or enumeration.
12152   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12153          "Parser allowed 'typedef' as storage class of condition decl.");
12154 
12155   Decl *Dcl = ActOnDeclarator(S, D);
12156   if (!Dcl)
12157     return true;
12158 
12159   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12160     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
12161       << D.getSourceRange();
12162     return true;
12163   }
12164 
12165   return Dcl;
12166 }
12167 
12168 void Sema::LoadExternalVTableUses() {
12169   if (!ExternalSource)
12170     return;
12171 
12172   SmallVector<ExternalVTableUse, 4> VTables;
12173   ExternalSource->ReadUsedVTables(VTables);
12174   SmallVector<VTableUse, 4> NewUses;
12175   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12176     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12177       = VTablesUsed.find(VTables[I].Record);
12178     // Even if a definition wasn't required before, it may be required now.
12179     if (Pos != VTablesUsed.end()) {
12180       if (!Pos->second && VTables[I].DefinitionRequired)
12181         Pos->second = true;
12182       continue;
12183     }
12184 
12185     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12186     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12187   }
12188 
12189   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12190 }
12191 
12192 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12193                           bool DefinitionRequired) {
12194   // Ignore any vtable uses in unevaluated operands or for classes that do
12195   // not have a vtable.
12196   if (!Class->isDynamicClass() || Class->isDependentContext() ||
12197       CurContext->isDependentContext() || isUnevaluatedContext())
12198     return;
12199 
12200   // Try to insert this class into the map.
12201   LoadExternalVTableUses();
12202   Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12203   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12204     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12205   if (!Pos.second) {
12206     // If we already had an entry, check to see if we are promoting this vtable
12207     // to required a definition. If so, we need to reappend to the VTableUses
12208     // list, since we may have already processed the first entry.
12209     if (DefinitionRequired && !Pos.first->second) {
12210       Pos.first->second = true;
12211     } else {
12212       // Otherwise, we can early exit.
12213       return;
12214     }
12215   }
12216 
12217   // Local classes need to have their virtual members marked
12218   // immediately. For all other classes, we mark their virtual members
12219   // at the end of the translation unit.
12220   if (Class->isLocalClass())
12221     MarkVirtualMembersReferenced(Loc, Class);
12222   else
12223     VTableUses.push_back(std::make_pair(Class, Loc));
12224 }
12225 
12226 bool Sema::DefineUsedVTables() {
12227   LoadExternalVTableUses();
12228   if (VTableUses.empty())
12229     return false;
12230 
12231   // Note: The VTableUses vector could grow as a result of marking
12232   // the members of a class as "used", so we check the size each
12233   // time through the loop and prefer indices (which are stable) to
12234   // iterators (which are not).
12235   bool DefinedAnything = false;
12236   for (unsigned I = 0; I != VTableUses.size(); ++I) {
12237     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
12238     if (!Class)
12239       continue;
12240 
12241     SourceLocation Loc = VTableUses[I].second;
12242 
12243     bool DefineVTable = true;
12244 
12245     // If this class has a key function, but that key function is
12246     // defined in another translation unit, we don't need to emit the
12247     // vtable even though we're using it.
12248     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
12249     if (KeyFunction && !KeyFunction->hasBody()) {
12250       // The key function is in another translation unit.
12251       DefineVTable = false;
12252       TemplateSpecializationKind TSK =
12253           KeyFunction->getTemplateSpecializationKind();
12254       assert(TSK != TSK_ExplicitInstantiationDefinition &&
12255              TSK != TSK_ImplicitInstantiation &&
12256              "Instantiations don't have key functions");
12257       (void)TSK;
12258     } else if (!KeyFunction) {
12259       // If we have a class with no key function that is the subject
12260       // of an explicit instantiation declaration, suppress the
12261       // vtable; it will live with the explicit instantiation
12262       // definition.
12263       bool IsExplicitInstantiationDeclaration
12264         = Class->getTemplateSpecializationKind()
12265                                       == TSK_ExplicitInstantiationDeclaration;
12266       for (TagDecl::redecl_iterator R = Class->redecls_begin(),
12267                                  REnd = Class->redecls_end();
12268            R != REnd; ++R) {
12269         TemplateSpecializationKind TSK
12270           = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
12271         if (TSK == TSK_ExplicitInstantiationDeclaration)
12272           IsExplicitInstantiationDeclaration = true;
12273         else if (TSK == TSK_ExplicitInstantiationDefinition) {
12274           IsExplicitInstantiationDeclaration = false;
12275           break;
12276         }
12277       }
12278 
12279       if (IsExplicitInstantiationDeclaration)
12280         DefineVTable = false;
12281     }
12282 
12283     // The exception specifications for all virtual members may be needed even
12284     // if we are not providing an authoritative form of the vtable in this TU.
12285     // We may choose to emit it available_externally anyway.
12286     if (!DefineVTable) {
12287       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12288       continue;
12289     }
12290 
12291     // Mark all of the virtual members of this class as referenced, so
12292     // that we can build a vtable. Then, tell the AST consumer that a
12293     // vtable for this class is required.
12294     DefinedAnything = true;
12295     MarkVirtualMembersReferenced(Loc, Class);
12296     CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12297     Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12298 
12299     // Optionally warn if we're emitting a weak vtable.
12300     if (Class->isExternallyVisible() &&
12301         Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
12302       const FunctionDecl *KeyFunctionDef = 0;
12303       if (!KeyFunction ||
12304           (KeyFunction->hasBody(KeyFunctionDef) &&
12305            KeyFunctionDef->isInlined()))
12306         Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12307              TSK_ExplicitInstantiationDefinition
12308              ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12309           << Class;
12310     }
12311   }
12312   VTableUses.clear();
12313 
12314   return DefinedAnything;
12315 }
12316 
12317 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12318                                                  const CXXRecordDecl *RD) {
12319   for (CXXRecordDecl::method_iterator I = RD->method_begin(),
12320                                       E = RD->method_end(); I != E; ++I)
12321     if ((*I)->isVirtual() && !(*I)->isPure())
12322       ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
12323 }
12324 
12325 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12326                                         const CXXRecordDecl *RD) {
12327   // Mark all functions which will appear in RD's vtable as used.
12328   CXXFinalOverriderMap FinalOverriders;
12329   RD->getFinalOverriders(FinalOverriders);
12330   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12331                                             E = FinalOverriders.end();
12332        I != E; ++I) {
12333     for (OverridingMethods::const_iterator OI = I->second.begin(),
12334                                            OE = I->second.end();
12335          OI != OE; ++OI) {
12336       assert(OI->second.size() > 0 && "no final overrider");
12337       CXXMethodDecl *Overrider = OI->second.front().Method;
12338 
12339       // C++ [basic.def.odr]p2:
12340       //   [...] A virtual member function is used if it is not pure. [...]
12341       if (!Overrider->isPure())
12342         MarkFunctionReferenced(Loc, Overrider);
12343     }
12344   }
12345 
12346   // Only classes that have virtual bases need a VTT.
12347   if (RD->getNumVBases() == 0)
12348     return;
12349 
12350   for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
12351            e = RD->bases_end(); i != e; ++i) {
12352     const CXXRecordDecl *Base =
12353         cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
12354     if (Base->getNumVBases() == 0)
12355       continue;
12356     MarkVirtualMembersReferenced(Loc, Base);
12357   }
12358 }
12359 
12360 /// SetIvarInitializers - This routine builds initialization ASTs for the
12361 /// Objective-C implementation whose ivars need be initialized.
12362 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
12363   if (!getLangOpts().CPlusPlus)
12364     return;
12365   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
12366     SmallVector<ObjCIvarDecl*, 8> ivars;
12367     CollectIvarsToConstructOrDestruct(OID, ivars);
12368     if (ivars.empty())
12369       return;
12370     SmallVector<CXXCtorInitializer*, 32> AllToInit;
12371     for (unsigned i = 0; i < ivars.size(); i++) {
12372       FieldDecl *Field = ivars[i];
12373       if (Field->isInvalidDecl())
12374         continue;
12375 
12376       CXXCtorInitializer *Member;
12377       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12378       InitializationKind InitKind =
12379         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
12380 
12381       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12382       ExprResult MemberInit =
12383         InitSeq.Perform(*this, InitEntity, InitKind, None);
12384       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
12385       // Note, MemberInit could actually come back empty if no initialization
12386       // is required (e.g., because it would call a trivial default constructor)
12387       if (!MemberInit.get() || MemberInit.isInvalid())
12388         continue;
12389 
12390       Member =
12391         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12392                                          SourceLocation(),
12393                                          MemberInit.takeAs<Expr>(),
12394                                          SourceLocation());
12395       AllToInit.push_back(Member);
12396 
12397       // Be sure that the destructor is accessible and is marked as referenced.
12398       if (const RecordType *RecordTy
12399                   = Context.getBaseElementType(Field->getType())
12400                                                         ->getAs<RecordType>()) {
12401                     CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
12402         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
12403           MarkFunctionReferenced(Field->getLocation(), Destructor);
12404           CheckDestructorAccess(Field->getLocation(), Destructor,
12405                             PDiag(diag::err_access_dtor_ivar)
12406                               << Context.getBaseElementType(Field->getType()));
12407         }
12408       }
12409     }
12410     ObjCImplementation->setIvarInitializers(Context,
12411                                             AllToInit.data(), AllToInit.size());
12412   }
12413 }
12414 
12415 static
12416 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12417                            llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12418                            llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12419                            llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12420                            Sema &S) {
12421   if (Ctor->isInvalidDecl())
12422     return;
12423 
12424   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12425 
12426   // Target may not be determinable yet, for instance if this is a dependent
12427   // call in an uninstantiated template.
12428   if (Target) {
12429     const FunctionDecl *FNTarget = 0;
12430     (void)Target->hasBody(FNTarget);
12431     Target = const_cast<CXXConstructorDecl*>(
12432       cast_or_null<CXXConstructorDecl>(FNTarget));
12433   }
12434 
12435   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12436                      // Avoid dereferencing a null pointer here.
12437                      *TCanonical = Target ? Target->getCanonicalDecl() : 0;
12438 
12439   if (!Current.insert(Canonical))
12440     return;
12441 
12442   // We know that beyond here, we aren't chaining into a cycle.
12443   if (!Target || !Target->isDelegatingConstructor() ||
12444       Target->isInvalidDecl() || Valid.count(TCanonical)) {
12445     Valid.insert(Current.begin(), Current.end());
12446     Current.clear();
12447   // We've hit a cycle.
12448   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12449              Current.count(TCanonical)) {
12450     // If we haven't diagnosed this cycle yet, do so now.
12451     if (!Invalid.count(TCanonical)) {
12452       S.Diag((*Ctor->init_begin())->getSourceLocation(),
12453              diag::warn_delegating_ctor_cycle)
12454         << Ctor;
12455 
12456       // Don't add a note for a function delegating directly to itself.
12457       if (TCanonical != Canonical)
12458         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12459 
12460       CXXConstructorDecl *C = Target;
12461       while (C->getCanonicalDecl() != Canonical) {
12462         const FunctionDecl *FNTarget = 0;
12463         (void)C->getTargetConstructor()->hasBody(FNTarget);
12464         assert(FNTarget && "Ctor cycle through bodiless function");
12465 
12466         C = const_cast<CXXConstructorDecl*>(
12467           cast<CXXConstructorDecl>(FNTarget));
12468         S.Diag(C->getLocation(), diag::note_which_delegates_to);
12469       }
12470     }
12471 
12472     Invalid.insert(Current.begin(), Current.end());
12473     Current.clear();
12474   } else {
12475     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12476   }
12477 }
12478 
12479 
12480 void Sema::CheckDelegatingCtorCycles() {
12481   llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12482 
12483   for (DelegatingCtorDeclsType::iterator
12484          I = DelegatingCtorDecls.begin(ExternalSource),
12485          E = DelegatingCtorDecls.end();
12486        I != E; ++I)
12487     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
12488 
12489   for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12490                                                          CE = Invalid.end();
12491        CI != CE; ++CI)
12492     (*CI)->setInvalidDecl();
12493 }
12494 
12495 namespace {
12496   /// \brief AST visitor that finds references to the 'this' expression.
12497   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12498     Sema &S;
12499 
12500   public:
12501     explicit FindCXXThisExpr(Sema &S) : S(S) { }
12502 
12503     bool VisitCXXThisExpr(CXXThisExpr *E) {
12504       S.Diag(E->getLocation(), diag::err_this_static_member_func)
12505         << E->isImplicit();
12506       return false;
12507     }
12508   };
12509 }
12510 
12511 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12512   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12513   if (!TSInfo)
12514     return false;
12515 
12516   TypeLoc TL = TSInfo->getTypeLoc();
12517   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
12518   if (!ProtoTL)
12519     return false;
12520 
12521   // C++11 [expr.prim.general]p3:
12522   //   [The expression this] shall not appear before the optional
12523   //   cv-qualifier-seq and it shall not appear within the declaration of a
12524   //   static member function (although its type and value category are defined
12525   //   within a static member function as they are within a non-static member
12526   //   function). [ Note: this is because declaration matching does not occur
12527   //  until the complete declarator is known. - end note ]
12528   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
12529   FindCXXThisExpr Finder(*this);
12530 
12531   // If the return type came after the cv-qualifier-seq, check it now.
12532   if (Proto->hasTrailingReturn() &&
12533       !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
12534     return true;
12535 
12536   // Check the exception specification.
12537   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12538     return true;
12539 
12540   return checkThisInStaticMemberFunctionAttributes(Method);
12541 }
12542 
12543 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12544   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12545   if (!TSInfo)
12546     return false;
12547 
12548   TypeLoc TL = TSInfo->getTypeLoc();
12549   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
12550   if (!ProtoTL)
12551     return false;
12552 
12553   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
12554   FindCXXThisExpr Finder(*this);
12555 
12556   switch (Proto->getExceptionSpecType()) {
12557   case EST_Uninstantiated:
12558   case EST_Unevaluated:
12559   case EST_BasicNoexcept:
12560   case EST_DynamicNone:
12561   case EST_MSAny:
12562   case EST_None:
12563     break;
12564 
12565   case EST_ComputedNoexcept:
12566     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12567       return true;
12568 
12569   case EST_Dynamic:
12570     for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
12571          EEnd = Proto->exception_end();
12572          E != EEnd; ++E) {
12573       if (!Finder.TraverseType(*E))
12574         return true;
12575     }
12576     break;
12577   }
12578 
12579   return false;
12580 }
12581 
12582 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12583   FindCXXThisExpr Finder(*this);
12584 
12585   // Check attributes.
12586   for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
12587        A != AEnd; ++A) {
12588     // FIXME: This should be emitted by tblgen.
12589     Expr *Arg = 0;
12590     ArrayRef<Expr *> Args;
12591     if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
12592       Arg = G->getArg();
12593     else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
12594       Arg = G->getArg();
12595     else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
12596       Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12597     else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
12598       Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12599     else if (ExclusiveLockFunctionAttr *ELF
12600                = dyn_cast<ExclusiveLockFunctionAttr>(*A))
12601       Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
12602     else if (SharedLockFunctionAttr *SLF
12603                = dyn_cast<SharedLockFunctionAttr>(*A))
12604       Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
12605     else if (ExclusiveTrylockFunctionAttr *ETLF
12606                = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
12607       Arg = ETLF->getSuccessValue();
12608       Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12609     } else if (SharedTrylockFunctionAttr *STLF
12610                  = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
12611       Arg = STLF->getSuccessValue();
12612       Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12613     } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
12614       Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
12615     else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
12616       Arg = LR->getArg();
12617     else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
12618       Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12619     else if (ExclusiveLocksRequiredAttr *ELR
12620                = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
12621       Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
12622     else if (SharedLocksRequiredAttr *SLR
12623                = dyn_cast<SharedLocksRequiredAttr>(*A))
12624       Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
12625 
12626     if (Arg && !Finder.TraverseStmt(Arg))
12627       return true;
12628 
12629     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12630       if (!Finder.TraverseStmt(Args[I]))
12631         return true;
12632     }
12633   }
12634 
12635   return false;
12636 }
12637 
12638 void
12639 Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12640                                   ArrayRef<ParsedType> DynamicExceptions,
12641                                   ArrayRef<SourceRange> DynamicExceptionRanges,
12642                                   Expr *NoexceptExpr,
12643                                   SmallVectorImpl<QualType> &Exceptions,
12644                                   FunctionProtoType::ExtProtoInfo &EPI) {
12645   Exceptions.clear();
12646   EPI.ExceptionSpecType = EST;
12647   if (EST == EST_Dynamic) {
12648     Exceptions.reserve(DynamicExceptions.size());
12649     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12650       // FIXME: Preserve type source info.
12651       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12652 
12653       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12654       collectUnexpandedParameterPacks(ET, Unexpanded);
12655       if (!Unexpanded.empty()) {
12656         DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12657                                          UPPC_ExceptionType,
12658                                          Unexpanded);
12659         continue;
12660       }
12661 
12662       // Check that the type is valid for an exception spec, and
12663       // drop it if not.
12664       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12665         Exceptions.push_back(ET);
12666     }
12667     EPI.NumExceptions = Exceptions.size();
12668     EPI.Exceptions = Exceptions.data();
12669     return;
12670   }
12671 
12672   if (EST == EST_ComputedNoexcept) {
12673     // If an error occurred, there's no expression here.
12674     if (NoexceptExpr) {
12675       assert((NoexceptExpr->isTypeDependent() ||
12676               NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12677               Context.BoolTy) &&
12678              "Parser should have made sure that the expression is boolean");
12679       if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12680         EPI.ExceptionSpecType = EST_BasicNoexcept;
12681         return;
12682       }
12683 
12684       if (!NoexceptExpr->isValueDependent())
12685         NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
12686                          diag::err_noexcept_needs_constant_expression,
12687                          /*AllowFold*/ false).take();
12688       EPI.NoexceptExpr = NoexceptExpr;
12689     }
12690     return;
12691   }
12692 }
12693 
12694 /// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12695 Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12696   // Implicitly declared functions (e.g. copy constructors) are
12697   // __host__ __device__
12698   if (D->isImplicit())
12699     return CFT_HostDevice;
12700 
12701   if (D->hasAttr<CUDAGlobalAttr>())
12702     return CFT_Global;
12703 
12704   if (D->hasAttr<CUDADeviceAttr>()) {
12705     if (D->hasAttr<CUDAHostAttr>())
12706       return CFT_HostDevice;
12707     return CFT_Device;
12708   }
12709 
12710   return CFT_Host;
12711 }
12712 
12713 bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12714                            CUDAFunctionTarget CalleeTarget) {
12715   // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12716   // Callable from the device only."
12717   if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12718     return true;
12719 
12720   // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12721   // Callable from the host only."
12722   // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12723   // Callable from the host only."
12724   if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12725       (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12726     return true;
12727 
12728   if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12729     return true;
12730 
12731   return false;
12732 }
12733 
12734 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12735 ///
12736 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12737                                        SourceLocation DeclStart,
12738                                        Declarator &D, Expr *BitWidth,
12739                                        InClassInitStyle InitStyle,
12740                                        AccessSpecifier AS,
12741                                        AttributeList *MSPropertyAttr) {
12742   IdentifierInfo *II = D.getIdentifier();
12743   if (!II) {
12744     Diag(DeclStart, diag::err_anonymous_property);
12745     return NULL;
12746   }
12747   SourceLocation Loc = D.getIdentifierLoc();
12748 
12749   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12750   QualType T = TInfo->getType();
12751   if (getLangOpts().CPlusPlus) {
12752     CheckExtraCXXDefaultArguments(D);
12753 
12754     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12755                                         UPPC_DataMemberType)) {
12756       D.setInvalidType();
12757       T = Context.IntTy;
12758       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12759     }
12760   }
12761 
12762   DiagnoseFunctionSpecifiers(D.getDeclSpec());
12763 
12764   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12765     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12766          diag::err_invalid_thread)
12767       << DeclSpec::getSpecifierName(TSCS);
12768 
12769   // Check to see if this name was declared as a member previously
12770   NamedDecl *PrevDecl = 0;
12771   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12772   LookupName(Previous, S);
12773   switch (Previous.getResultKind()) {
12774   case LookupResult::Found:
12775   case LookupResult::FoundUnresolvedValue:
12776     PrevDecl = Previous.getAsSingle<NamedDecl>();
12777     break;
12778 
12779   case LookupResult::FoundOverloaded:
12780     PrevDecl = Previous.getRepresentativeDecl();
12781     break;
12782 
12783   case LookupResult::NotFound:
12784   case LookupResult::NotFoundInCurrentInstantiation:
12785   case LookupResult::Ambiguous:
12786     break;
12787   }
12788 
12789   if (PrevDecl && PrevDecl->isTemplateParameter()) {
12790     // Maybe we will complain about the shadowed template parameter.
12791     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12792     // Just pretend that we didn't see the previous declaration.
12793     PrevDecl = 0;
12794   }
12795 
12796   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12797     PrevDecl = 0;
12798 
12799   SourceLocation TSSL = D.getLocStart();
12800   MSPropertyDecl *NewPD;
12801   const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12802   NewPD = new (Context) MSPropertyDecl(Record, Loc,
12803                                        II, T, TInfo, TSSL,
12804                                        Data.GetterId, Data.SetterId);
12805   ProcessDeclAttributes(TUScope, NewPD, D);
12806   NewPD->setAccess(AS);
12807 
12808   if (NewPD->isInvalidDecl())
12809     Record->setInvalidDecl();
12810 
12811   if (D.getDeclSpec().isModulePrivateSpecified())
12812     NewPD->setModulePrivate();
12813 
12814   if (NewPD->isInvalidDecl() && PrevDecl) {
12815     // Don't introduce NewFD into scope; there's already something
12816     // with the same name in the same scope.
12817   } else if (II) {
12818     PushOnScopeChains(NewPD, S);
12819   } else
12820     Record->addDecl(NewPD);
12821 
12822   return NewPD;
12823 }
12824