1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for C++ declarations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/DeclVisitor.h"
21 #include "clang/AST/EvaluatedExprVisitor.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/RecordLayout.h"
24 #include "clang/AST/RecursiveASTVisitor.h"
25 #include "clang/AST/StmtVisitor.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "clang/AST/TypeOrdering.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/Preprocessor.h"
31 #include "clang/Sema/CXXFieldCollector.h"
32 #include "clang/Sema/DeclSpec.h"
33 #include "clang/Sema/Initialization.h"
34 #include "clang/Sema/Lookup.h"
35 #include "clang/Sema/ParsedTemplate.h"
36 #include "clang/Sema/Scope.h"
37 #include "clang/Sema/ScopeInfo.h"
38 #include "llvm/ADT/STLExtras.h"
39 #include "llvm/ADT/SmallString.h"
40 #include <map>
41 #include <set>
42 
43 using namespace clang;
44 
45 //===----------------------------------------------------------------------===//
46 // CheckDefaultArgumentVisitor
47 //===----------------------------------------------------------------------===//
48 
49 namespace {
50   /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
51   /// the default argument of a parameter to determine whether it
52   /// contains any ill-formed subexpressions. For example, this will
53   /// diagnose the use of local variables or parameters within the
54   /// default argument expression.
55   class CheckDefaultArgumentVisitor
56     : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
57     Expr *DefaultArg;
58     Sema *S;
59 
60   public:
61     CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
62       : DefaultArg(defarg), S(s) {}
63 
64     bool VisitExpr(Expr *Node);
65     bool VisitDeclRefExpr(DeclRefExpr *DRE);
66     bool VisitCXXThisExpr(CXXThisExpr *ThisE);
67     bool VisitLambdaExpr(LambdaExpr *Lambda);
68     bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
69   };
70 
71   /// VisitExpr - Visit all of the children of this expression.
72   bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
73     bool IsInvalid = false;
74     for (Stmt::child_range I = Node->children(); I; ++I)
75       IsInvalid |= Visit(*I);
76     return IsInvalid;
77   }
78 
79   /// VisitDeclRefExpr - Visit a reference to a declaration, to
80   /// determine whether this declaration can be used in the default
81   /// argument expression.
82   bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
83     NamedDecl *Decl = DRE->getDecl();
84     if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
85       // C++ [dcl.fct.default]p9
86       //   Default arguments are evaluated each time the function is
87       //   called. The order of evaluation of function arguments is
88       //   unspecified. Consequently, parameters of a function shall not
89       //   be used in default argument expressions, even if they are not
90       //   evaluated. Parameters of a function declared before a default
91       //   argument expression are in scope and can hide namespace and
92       //   class member names.
93       return S->Diag(DRE->getLocStart(),
94                      diag::err_param_default_argument_references_param)
95          << Param->getDeclName() << DefaultArg->getSourceRange();
96     } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
97       // C++ [dcl.fct.default]p7
98       //   Local variables shall not be used in default argument
99       //   expressions.
100       if (VDecl->isLocalVarDecl())
101         return S->Diag(DRE->getLocStart(),
102                        diag::err_param_default_argument_references_local)
103           << VDecl->getDeclName() << DefaultArg->getSourceRange();
104     }
105 
106     return false;
107   }
108 
109   /// VisitCXXThisExpr - Visit a C++ "this" expression.
110   bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
111     // C++ [dcl.fct.default]p8:
112     //   The keyword this shall not be used in a default argument of a
113     //   member function.
114     return S->Diag(ThisE->getLocStart(),
115                    diag::err_param_default_argument_references_this)
116                << ThisE->getSourceRange();
117   }
118 
119   bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
120     bool Invalid = false;
121     for (PseudoObjectExpr::semantics_iterator
122            i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
123       Expr *E = *i;
124 
125       // Look through bindings.
126       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
127         E = OVE->getSourceExpr();
128         assert(E && "pseudo-object binding without source expression?");
129       }
130 
131       Invalid |= Visit(E);
132     }
133     return Invalid;
134   }
135 
136   bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
137     // C++11 [expr.lambda.prim]p13:
138     //   A lambda-expression appearing in a default argument shall not
139     //   implicitly or explicitly capture any entity.
140     if (Lambda->capture_begin() == Lambda->capture_end())
141       return false;
142 
143     return S->Diag(Lambda->getLocStart(),
144                    diag::err_lambda_capture_default_arg);
145   }
146 }
147 
148 void
149 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
150                                                  const CXXMethodDecl *Method) {
151   // If we have an MSAny spec already, don't bother.
152   if (!Method || ComputedEST == EST_MSAny)
153     return;
154 
155   const FunctionProtoType *Proto
156     = Method->getType()->getAs<FunctionProtoType>();
157   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
158   if (!Proto)
159     return;
160 
161   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
162 
163   // If this function can throw any exceptions, make a note of that.
164   if (EST == EST_MSAny || EST == EST_None) {
165     ClearExceptions();
166     ComputedEST = EST;
167     return;
168   }
169 
170   // FIXME: If the call to this decl is using any of its default arguments, we
171   // need to search them for potentially-throwing calls.
172 
173   // If this function has a basic noexcept, it doesn't affect the outcome.
174   if (EST == EST_BasicNoexcept)
175     return;
176 
177   // If we have a throw-all spec at this point, ignore the function.
178   if (ComputedEST == EST_None)
179     return;
180 
181   // If we're still at noexcept(true) and there's a nothrow() callee,
182   // change to that specification.
183   if (EST == EST_DynamicNone) {
184     if (ComputedEST == EST_BasicNoexcept)
185       ComputedEST = EST_DynamicNone;
186     return;
187   }
188 
189   // Check out noexcept specs.
190   if (EST == EST_ComputedNoexcept) {
191     FunctionProtoType::NoexceptResult NR =
192         Proto->getNoexceptSpec(Self->Context);
193     assert(NR != FunctionProtoType::NR_NoNoexcept &&
194            "Must have noexcept result for EST_ComputedNoexcept.");
195     assert(NR != FunctionProtoType::NR_Dependent &&
196            "Should not generate implicit declarations for dependent cases, "
197            "and don't know how to handle them anyway.");
198 
199     // noexcept(false) -> no spec on the new function
200     if (NR == FunctionProtoType::NR_Throw) {
201       ClearExceptions();
202       ComputedEST = EST_None;
203     }
204     // noexcept(true) won't change anything either.
205     return;
206   }
207 
208   assert(EST == EST_Dynamic && "EST case not considered earlier.");
209   assert(ComputedEST != EST_None &&
210          "Shouldn't collect exceptions when throw-all is guaranteed.");
211   ComputedEST = EST_Dynamic;
212   // Record the exceptions in this function's exception specification.
213   for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
214                                           EEnd = Proto->exception_end();
215        E != EEnd; ++E)
216     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
217       Exceptions.push_back(*E);
218 }
219 
220 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
221   if (!E || ComputedEST == EST_MSAny)
222     return;
223 
224   // FIXME:
225   //
226   // C++0x [except.spec]p14:
227   //   [An] implicit exception-specification specifies the type-id T if and
228   // only if T is allowed by the exception-specification of a function directly
229   // invoked by f's implicit definition; f shall allow all exceptions if any
230   // function it directly invokes allows all exceptions, and f shall allow no
231   // exceptions if every function it directly invokes allows no exceptions.
232   //
233   // Note in particular that if an implicit exception-specification is generated
234   // for a function containing a throw-expression, that specification can still
235   // be noexcept(true).
236   //
237   // Note also that 'directly invoked' is not defined in the standard, and there
238   // is no indication that we should only consider potentially-evaluated calls.
239   //
240   // Ultimately we should implement the intent of the standard: the exception
241   // specification should be the set of exceptions which can be thrown by the
242   // implicit definition. For now, we assume that any non-nothrow expression can
243   // throw any exception.
244 
245   if (Self->canThrow(E))
246     ComputedEST = EST_None;
247 }
248 
249 bool
250 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
251                               SourceLocation EqualLoc) {
252   if (RequireCompleteType(Param->getLocation(), Param->getType(),
253                           diag::err_typecheck_decl_incomplete_type)) {
254     Param->setInvalidDecl();
255     return true;
256   }
257 
258   // C++ [dcl.fct.default]p5
259   //   A default argument expression is implicitly converted (clause
260   //   4) to the parameter type. The default argument expression has
261   //   the same semantic constraints as the initializer expression in
262   //   a declaration of a variable of the parameter type, using the
263   //   copy-initialization semantics (8.5).
264   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
265                                                                     Param);
266   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
267                                                            EqualLoc);
268   InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
269   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
270   if (Result.isInvalid())
271     return true;
272   Arg = Result.takeAs<Expr>();
273 
274   CheckCompletedExpr(Arg, EqualLoc);
275   Arg = MaybeCreateExprWithCleanups(Arg);
276 
277   // Okay: add the default argument to the parameter
278   Param->setDefaultArg(Arg);
279 
280   // We have already instantiated this parameter; provide each of the
281   // instantiations with the uninstantiated default argument.
282   UnparsedDefaultArgInstantiationsMap::iterator InstPos
283     = UnparsedDefaultArgInstantiations.find(Param);
284   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
285     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
286       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
287 
288     // We're done tracking this parameter's instantiations.
289     UnparsedDefaultArgInstantiations.erase(InstPos);
290   }
291 
292   return false;
293 }
294 
295 /// ActOnParamDefaultArgument - Check whether the default argument
296 /// provided for a function parameter is well-formed. If so, attach it
297 /// to the parameter declaration.
298 void
299 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
300                                 Expr *DefaultArg) {
301   if (!param || !DefaultArg)
302     return;
303 
304   ParmVarDecl *Param = cast<ParmVarDecl>(param);
305   UnparsedDefaultArgLocs.erase(Param);
306 
307   // Default arguments are only permitted in C++
308   if (!getLangOpts().CPlusPlus) {
309     Diag(EqualLoc, diag::err_param_default_argument)
310       << DefaultArg->getSourceRange();
311     Param->setInvalidDecl();
312     return;
313   }
314 
315   // Check for unexpanded parameter packs.
316   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
317     Param->setInvalidDecl();
318     return;
319   }
320 
321   // Check that the default argument is well-formed
322   CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
323   if (DefaultArgChecker.Visit(DefaultArg)) {
324     Param->setInvalidDecl();
325     return;
326   }
327 
328   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
329 }
330 
331 /// ActOnParamUnparsedDefaultArgument - We've seen a default
332 /// argument for a function parameter, but we can't parse it yet
333 /// because we're inside a class definition. Note that this default
334 /// argument will be parsed later.
335 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
336                                              SourceLocation EqualLoc,
337                                              SourceLocation ArgLoc) {
338   if (!param)
339     return;
340 
341   ParmVarDecl *Param = cast<ParmVarDecl>(param);
342   if (Param)
343     Param->setUnparsedDefaultArg();
344 
345   UnparsedDefaultArgLocs[Param] = ArgLoc;
346 }
347 
348 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
349 /// the default argument for the parameter param failed.
350 void Sema::ActOnParamDefaultArgumentError(Decl *param) {
351   if (!param)
352     return;
353 
354   ParmVarDecl *Param = cast<ParmVarDecl>(param);
355 
356   Param->setInvalidDecl();
357 
358   UnparsedDefaultArgLocs.erase(Param);
359 }
360 
361 /// CheckExtraCXXDefaultArguments - Check for any extra default
362 /// arguments in the declarator, which is not a function declaration
363 /// or definition and therefore is not permitted to have default
364 /// arguments. This routine should be invoked for every declarator
365 /// that is not a function declaration or definition.
366 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
367   // C++ [dcl.fct.default]p3
368   //   A default argument expression shall be specified only in the
369   //   parameter-declaration-clause of a function declaration or in a
370   //   template-parameter (14.1). It shall not be specified for a
371   //   parameter pack. If it is specified in a
372   //   parameter-declaration-clause, it shall not occur within a
373   //   declarator or abstract-declarator of a parameter-declaration.
374   bool MightBeFunction = D.isFunctionDeclarationContext();
375   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
376     DeclaratorChunk &chunk = D.getTypeObject(i);
377     if (chunk.Kind == DeclaratorChunk::Function) {
378       if (MightBeFunction) {
379         // This is a function declaration. It can have default arguments, but
380         // keep looking in case its return type is a function type with default
381         // arguments.
382         MightBeFunction = false;
383         continue;
384       }
385       for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
386         ParmVarDecl *Param =
387           cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
388         if (Param->hasUnparsedDefaultArg()) {
389           CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
390           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
391             << SourceRange((*Toks)[1].getLocation(),
392                            Toks->back().getLocation());
393           delete Toks;
394           chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
395         } else if (Param->getDefaultArg()) {
396           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
397             << Param->getDefaultArg()->getSourceRange();
398           Param->setDefaultArg(0);
399         }
400       }
401     } else if (chunk.Kind != DeclaratorChunk::Paren) {
402       MightBeFunction = false;
403     }
404   }
405 }
406 
407 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
408 /// function, once we already know that they have the same
409 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
410 /// error, false otherwise.
411 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
412                                 Scope *S) {
413   bool Invalid = false;
414 
415   // C++ [dcl.fct.default]p4:
416   //   For non-template functions, default arguments can be added in
417   //   later declarations of a function in the same
418   //   scope. Declarations in different scopes have completely
419   //   distinct sets of default arguments. That is, declarations in
420   //   inner scopes do not acquire default arguments from
421   //   declarations in outer scopes, and vice versa. In a given
422   //   function declaration, all parameters subsequent to a
423   //   parameter with a default argument shall have default
424   //   arguments supplied in this or previous declarations. A
425   //   default argument shall not be redefined by a later
426   //   declaration (not even to the same value).
427   //
428   // C++ [dcl.fct.default]p6:
429   //   Except for member functions of class templates, the default arguments
430   //   in a member function definition that appears outside of the class
431   //   definition are added to the set of default arguments provided by the
432   //   member function declaration in the class definition.
433   for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
434     ParmVarDecl *OldParam = Old->getParamDecl(p);
435     ParmVarDecl *NewParam = New->getParamDecl(p);
436 
437     bool OldParamHasDfl = OldParam->hasDefaultArg();
438     bool NewParamHasDfl = NewParam->hasDefaultArg();
439 
440     NamedDecl *ND = Old;
441     if (S && !isDeclInScope(ND, New->getDeclContext(), S))
442       // Ignore default parameters of old decl if they are not in
443       // the same scope.
444       OldParamHasDfl = false;
445 
446     if (OldParamHasDfl && NewParamHasDfl) {
447 
448       unsigned DiagDefaultParamID =
449         diag::err_param_default_argument_redefinition;
450 
451       // MSVC accepts that default parameters be redefined for member functions
452       // of template class. The new default parameter's value is ignored.
453       Invalid = true;
454       if (getLangOpts().MicrosoftExt) {
455         CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
456         if (MD && MD->getParent()->getDescribedClassTemplate()) {
457           // Merge the old default argument into the new parameter.
458           NewParam->setHasInheritedDefaultArg();
459           if (OldParam->hasUninstantiatedDefaultArg())
460             NewParam->setUninstantiatedDefaultArg(
461                                       OldParam->getUninstantiatedDefaultArg());
462           else
463             NewParam->setDefaultArg(OldParam->getInit());
464           DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
465           Invalid = false;
466         }
467       }
468 
469       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
470       // hint here. Alternatively, we could walk the type-source information
471       // for NewParam to find the last source location in the type... but it
472       // isn't worth the effort right now. This is the kind of test case that
473       // is hard to get right:
474       //   int f(int);
475       //   void g(int (*fp)(int) = f);
476       //   void g(int (*fp)(int) = &f);
477       Diag(NewParam->getLocation(), DiagDefaultParamID)
478         << NewParam->getDefaultArgRange();
479 
480       // Look for the function declaration where the default argument was
481       // actually written, which may be a declaration prior to Old.
482       for (FunctionDecl *Older = Old->getPreviousDecl();
483            Older; Older = Older->getPreviousDecl()) {
484         if (!Older->getParamDecl(p)->hasDefaultArg())
485           break;
486 
487         OldParam = Older->getParamDecl(p);
488       }
489 
490       Diag(OldParam->getLocation(), diag::note_previous_definition)
491         << OldParam->getDefaultArgRange();
492     } else if (OldParamHasDfl) {
493       // Merge the old default argument into the new parameter.
494       // It's important to use getInit() here;  getDefaultArg()
495       // strips off any top-level ExprWithCleanups.
496       NewParam->setHasInheritedDefaultArg();
497       if (OldParam->hasUninstantiatedDefaultArg())
498         NewParam->setUninstantiatedDefaultArg(
499                                       OldParam->getUninstantiatedDefaultArg());
500       else
501         NewParam->setDefaultArg(OldParam->getInit());
502     } else if (NewParamHasDfl) {
503       if (New->getDescribedFunctionTemplate()) {
504         // Paragraph 4, quoted above, only applies to non-template functions.
505         Diag(NewParam->getLocation(),
506              diag::err_param_default_argument_template_redecl)
507           << NewParam->getDefaultArgRange();
508         Diag(Old->getLocation(), diag::note_template_prev_declaration)
509           << false;
510       } else if (New->getTemplateSpecializationKind()
511                    != TSK_ImplicitInstantiation &&
512                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
513         // C++ [temp.expr.spec]p21:
514         //   Default function arguments shall not be specified in a declaration
515         //   or a definition for one of the following explicit specializations:
516         //     - the explicit specialization of a function template;
517         //     - the explicit specialization of a member function template;
518         //     - the explicit specialization of a member function of a class
519         //       template where the class template specialization to which the
520         //       member function specialization belongs is implicitly
521         //       instantiated.
522         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
523           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
524           << New->getDeclName()
525           << NewParam->getDefaultArgRange();
526       } else if (New->getDeclContext()->isDependentContext()) {
527         // C++ [dcl.fct.default]p6 (DR217):
528         //   Default arguments for a member function of a class template shall
529         //   be specified on the initial declaration of the member function
530         //   within the class template.
531         //
532         // Reading the tea leaves a bit in DR217 and its reference to DR205
533         // leads me to the conclusion that one cannot add default function
534         // arguments for an out-of-line definition of a member function of a
535         // dependent type.
536         int WhichKind = 2;
537         if (CXXRecordDecl *Record
538               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
539           if (Record->getDescribedClassTemplate())
540             WhichKind = 0;
541           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
542             WhichKind = 1;
543           else
544             WhichKind = 2;
545         }
546 
547         Diag(NewParam->getLocation(),
548              diag::err_param_default_argument_member_template_redecl)
549           << WhichKind
550           << NewParam->getDefaultArgRange();
551       }
552     }
553   }
554 
555   // DR1344: If a default argument is added outside a class definition and that
556   // default argument makes the function a special member function, the program
557   // is ill-formed. This can only happen for constructors.
558   if (isa<CXXConstructorDecl>(New) &&
559       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
560     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
561                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
562     if (NewSM != OldSM) {
563       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
564       assert(NewParam->hasDefaultArg());
565       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
566         << NewParam->getDefaultArgRange() << NewSM;
567       Diag(Old->getLocation(), diag::note_previous_declaration);
568     }
569   }
570 
571   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
572   // template has a constexpr specifier then all its declarations shall
573   // contain the constexpr specifier.
574   if (New->isConstexpr() != Old->isConstexpr()) {
575     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
576       << New << New->isConstexpr();
577     Diag(Old->getLocation(), diag::note_previous_declaration);
578     Invalid = true;
579   }
580 
581   if (CheckEquivalentExceptionSpec(Old, New))
582     Invalid = true;
583 
584   return Invalid;
585 }
586 
587 /// \brief Merge the exception specifications of two variable declarations.
588 ///
589 /// This is called when there's a redeclaration of a VarDecl. The function
590 /// checks if the redeclaration might have an exception specification and
591 /// validates compatibility and merges the specs if necessary.
592 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
593   // Shortcut if exceptions are disabled.
594   if (!getLangOpts().CXXExceptions)
595     return;
596 
597   assert(Context.hasSameType(New->getType(), Old->getType()) &&
598          "Should only be called if types are otherwise the same.");
599 
600   QualType NewType = New->getType();
601   QualType OldType = Old->getType();
602 
603   // We're only interested in pointers and references to functions, as well
604   // as pointers to member functions.
605   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
606     NewType = R->getPointeeType();
607     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
608   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
609     NewType = P->getPointeeType();
610     OldType = OldType->getAs<PointerType>()->getPointeeType();
611   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
612     NewType = M->getPointeeType();
613     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
614   }
615 
616   if (!NewType->isFunctionProtoType())
617     return;
618 
619   // There's lots of special cases for functions. For function pointers, system
620   // libraries are hopefully not as broken so that we don't need these
621   // workarounds.
622   if (CheckEquivalentExceptionSpec(
623         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
624         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
625     New->setInvalidDecl();
626   }
627 }
628 
629 /// CheckCXXDefaultArguments - Verify that the default arguments for a
630 /// function declaration are well-formed according to C++
631 /// [dcl.fct.default].
632 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
633   unsigned NumParams = FD->getNumParams();
634   unsigned p;
635 
636   // Find first parameter with a default argument
637   for (p = 0; p < NumParams; ++p) {
638     ParmVarDecl *Param = FD->getParamDecl(p);
639     if (Param->hasDefaultArg())
640       break;
641   }
642 
643   // C++ [dcl.fct.default]p4:
644   //   In a given function declaration, all parameters
645   //   subsequent to a parameter with a default argument shall
646   //   have default arguments supplied in this or previous
647   //   declarations. A default argument shall not be redefined
648   //   by a later declaration (not even to the same value).
649   unsigned LastMissingDefaultArg = 0;
650   for (; p < NumParams; ++p) {
651     ParmVarDecl *Param = FD->getParamDecl(p);
652     if (!Param->hasDefaultArg()) {
653       if (Param->isInvalidDecl())
654         /* We already complained about this parameter. */;
655       else if (Param->getIdentifier())
656         Diag(Param->getLocation(),
657              diag::err_param_default_argument_missing_name)
658           << Param->getIdentifier();
659       else
660         Diag(Param->getLocation(),
661              diag::err_param_default_argument_missing);
662 
663       LastMissingDefaultArg = p;
664     }
665   }
666 
667   if (LastMissingDefaultArg > 0) {
668     // Some default arguments were missing. Clear out all of the
669     // default arguments up to (and including) the last missing
670     // default argument, so that we leave the function parameters
671     // in a semantically valid state.
672     for (p = 0; p <= LastMissingDefaultArg; ++p) {
673       ParmVarDecl *Param = FD->getParamDecl(p);
674       if (Param->hasDefaultArg()) {
675         Param->setDefaultArg(0);
676       }
677     }
678   }
679 }
680 
681 // CheckConstexprParameterTypes - Check whether a function's parameter types
682 // are all literal types. If so, return true. If not, produce a suitable
683 // diagnostic and return false.
684 static bool CheckConstexprParameterTypes(Sema &SemaRef,
685                                          const FunctionDecl *FD) {
686   unsigned ArgIndex = 0;
687   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
688   for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
689        e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
690     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
691     SourceLocation ParamLoc = PD->getLocation();
692     if (!(*i)->isDependentType() &&
693         SemaRef.RequireLiteralType(ParamLoc, *i,
694                                    diag::err_constexpr_non_literal_param,
695                                    ArgIndex+1, PD->getSourceRange(),
696                                    isa<CXXConstructorDecl>(FD)))
697       return false;
698   }
699   return true;
700 }
701 
702 /// \brief Get diagnostic %select index for tag kind for
703 /// record diagnostic message.
704 /// WARNING: Indexes apply to particular diagnostics only!
705 ///
706 /// \returns diagnostic %select index.
707 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
708   switch (Tag) {
709   case TTK_Struct: return 0;
710   case TTK_Interface: return 1;
711   case TTK_Class:  return 2;
712   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
713   }
714 }
715 
716 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
717 // the requirements of a constexpr function definition or a constexpr
718 // constructor definition. If so, return true. If not, produce appropriate
719 // diagnostics and return false.
720 //
721 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
722 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
723   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
724   if (MD && MD->isInstance()) {
725     // C++11 [dcl.constexpr]p4:
726     //  The definition of a constexpr constructor shall satisfy the following
727     //  constraints:
728     //  - the class shall not have any virtual base classes;
729     const CXXRecordDecl *RD = MD->getParent();
730     if (RD->getNumVBases()) {
731       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
732         << isa<CXXConstructorDecl>(NewFD)
733         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
734       for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
735              E = RD->vbases_end(); I != E; ++I)
736         Diag(I->getLocStart(),
737              diag::note_constexpr_virtual_base_here) << I->getSourceRange();
738       return false;
739     }
740   }
741 
742   if (!isa<CXXConstructorDecl>(NewFD)) {
743     // C++11 [dcl.constexpr]p3:
744     //  The definition of a constexpr function shall satisfy the following
745     //  constraints:
746     // - it shall not be virtual;
747     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
748     if (Method && Method->isVirtual()) {
749       Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
750 
751       // If it's not obvious why this function is virtual, find an overridden
752       // function which uses the 'virtual' keyword.
753       const CXXMethodDecl *WrittenVirtual = Method;
754       while (!WrittenVirtual->isVirtualAsWritten())
755         WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
756       if (WrittenVirtual != Method)
757         Diag(WrittenVirtual->getLocation(),
758              diag::note_overridden_virtual_function);
759       return false;
760     }
761 
762     // - its return type shall be a literal type;
763     QualType RT = NewFD->getResultType();
764     if (!RT->isDependentType() &&
765         RequireLiteralType(NewFD->getLocation(), RT,
766                            diag::err_constexpr_non_literal_return))
767       return false;
768   }
769 
770   // - each of its parameter types shall be a literal type;
771   if (!CheckConstexprParameterTypes(*this, NewFD))
772     return false;
773 
774   return true;
775 }
776 
777 /// Check the given declaration statement is legal within a constexpr function
778 /// body. C++0x [dcl.constexpr]p3,p4.
779 ///
780 /// \return true if the body is OK, false if we have diagnosed a problem.
781 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
782                                    DeclStmt *DS) {
783   // C++0x [dcl.constexpr]p3 and p4:
784   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
785   //  contain only
786   for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
787          DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
788     switch ((*DclIt)->getKind()) {
789     case Decl::StaticAssert:
790     case Decl::Using:
791     case Decl::UsingShadow:
792     case Decl::UsingDirective:
793     case Decl::UnresolvedUsingTypename:
794       //   - static_assert-declarations
795       //   - using-declarations,
796       //   - using-directives,
797       continue;
798 
799     case Decl::Typedef:
800     case Decl::TypeAlias: {
801       //   - typedef declarations and alias-declarations that do not define
802       //     classes or enumerations,
803       TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
804       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
805         // Don't allow variably-modified types in constexpr functions.
806         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
807         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
808           << TL.getSourceRange() << TL.getType()
809           << isa<CXXConstructorDecl>(Dcl);
810         return false;
811       }
812       continue;
813     }
814 
815     case Decl::Enum:
816     case Decl::CXXRecord:
817       // As an extension, we allow the declaration (but not the definition) of
818       // classes and enumerations in all declarations, not just in typedef and
819       // alias declarations.
820       if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
821         SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
822           << isa<CXXConstructorDecl>(Dcl);
823         return false;
824       }
825       continue;
826 
827     case Decl::Var:
828       SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
829         << isa<CXXConstructorDecl>(Dcl);
830       return false;
831 
832     default:
833       SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
834         << isa<CXXConstructorDecl>(Dcl);
835       return false;
836     }
837   }
838 
839   return true;
840 }
841 
842 /// Check that the given field is initialized within a constexpr constructor.
843 ///
844 /// \param Dcl The constexpr constructor being checked.
845 /// \param Field The field being checked. This may be a member of an anonymous
846 ///        struct or union nested within the class being checked.
847 /// \param Inits All declarations, including anonymous struct/union members and
848 ///        indirect members, for which any initialization was provided.
849 /// \param Diagnosed Set to true if an error is produced.
850 static void CheckConstexprCtorInitializer(Sema &SemaRef,
851                                           const FunctionDecl *Dcl,
852                                           FieldDecl *Field,
853                                           llvm::SmallSet<Decl*, 16> &Inits,
854                                           bool &Diagnosed) {
855   if (Field->isUnnamedBitfield())
856     return;
857 
858   if (Field->isAnonymousStructOrUnion() &&
859       Field->getType()->getAsCXXRecordDecl()->isEmpty())
860     return;
861 
862   if (!Inits.count(Field)) {
863     if (!Diagnosed) {
864       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
865       Diagnosed = true;
866     }
867     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
868   } else if (Field->isAnonymousStructOrUnion()) {
869     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
870     for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
871          I != E; ++I)
872       // If an anonymous union contains an anonymous struct of which any member
873       // is initialized, all members must be initialized.
874       if (!RD->isUnion() || Inits.count(*I))
875         CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
876   }
877 }
878 
879 /// Check the body for the given constexpr function declaration only contains
880 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
881 ///
882 /// \return true if the body is OK, false if we have diagnosed a problem.
883 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
884   if (isa<CXXTryStmt>(Body)) {
885     // C++11 [dcl.constexpr]p3:
886     //  The definition of a constexpr function shall satisfy the following
887     //  constraints: [...]
888     // - its function-body shall be = delete, = default, or a
889     //   compound-statement
890     //
891     // C++11 [dcl.constexpr]p4:
892     //  In the definition of a constexpr constructor, [...]
893     // - its function-body shall not be a function-try-block;
894     Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
895       << isa<CXXConstructorDecl>(Dcl);
896     return false;
897   }
898 
899   // - its function-body shall be [...] a compound-statement that contains only
900   CompoundStmt *CompBody = cast<CompoundStmt>(Body);
901 
902   SmallVector<SourceLocation, 4> ReturnStmts;
903   for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
904          BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
905     switch ((*BodyIt)->getStmtClass()) {
906     case Stmt::NullStmtClass:
907       //   - null statements,
908       continue;
909 
910     case Stmt::DeclStmtClass:
911       //   - static_assert-declarations
912       //   - using-declarations,
913       //   - using-directives,
914       //   - typedef declarations and alias-declarations that do not define
915       //     classes or enumerations,
916       if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
917         return false;
918       continue;
919 
920     case Stmt::ReturnStmtClass:
921       //   - and exactly one return statement;
922       if (isa<CXXConstructorDecl>(Dcl))
923         break;
924 
925       ReturnStmts.push_back((*BodyIt)->getLocStart());
926       continue;
927 
928     default:
929       break;
930     }
931 
932     Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
933       << isa<CXXConstructorDecl>(Dcl);
934     return false;
935   }
936 
937   if (const CXXConstructorDecl *Constructor
938         = dyn_cast<CXXConstructorDecl>(Dcl)) {
939     const CXXRecordDecl *RD = Constructor->getParent();
940     // DR1359:
941     // - every non-variant non-static data member and base class sub-object
942     //   shall be initialized;
943     // - if the class is a non-empty union, or for each non-empty anonymous
944     //   union member of a non-union class, exactly one non-static data member
945     //   shall be initialized;
946     if (RD->isUnion()) {
947       if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
948         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
949         return false;
950       }
951     } else if (!Constructor->isDependentContext() &&
952                !Constructor->isDelegatingConstructor()) {
953       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
954 
955       // Skip detailed checking if we have enough initializers, and we would
956       // allow at most one initializer per member.
957       bool AnyAnonStructUnionMembers = false;
958       unsigned Fields = 0;
959       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
960            E = RD->field_end(); I != E; ++I, ++Fields) {
961         if (I->isAnonymousStructOrUnion()) {
962           AnyAnonStructUnionMembers = true;
963           break;
964         }
965       }
966       if (AnyAnonStructUnionMembers ||
967           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
968         // Check initialization of non-static data members. Base classes are
969         // always initialized so do not need to be checked. Dependent bases
970         // might not have initializers in the member initializer list.
971         llvm::SmallSet<Decl*, 16> Inits;
972         for (CXXConstructorDecl::init_const_iterator
973                I = Constructor->init_begin(), E = Constructor->init_end();
974              I != E; ++I) {
975           if (FieldDecl *FD = (*I)->getMember())
976             Inits.insert(FD);
977           else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
978             Inits.insert(ID->chain_begin(), ID->chain_end());
979         }
980 
981         bool Diagnosed = false;
982         for (CXXRecordDecl::field_iterator I = RD->field_begin(),
983              E = RD->field_end(); I != E; ++I)
984           CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
985         if (Diagnosed)
986           return false;
987       }
988     }
989   } else {
990     if (ReturnStmts.empty()) {
991       Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
992       return false;
993     }
994     if (ReturnStmts.size() > 1) {
995       Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
996       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
997         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
998       return false;
999     }
1000   }
1001 
1002   // C++11 [dcl.constexpr]p5:
1003   //   if no function argument values exist such that the function invocation
1004   //   substitution would produce a constant expression, the program is
1005   //   ill-formed; no diagnostic required.
1006   // C++11 [dcl.constexpr]p3:
1007   //   - every constructor call and implicit conversion used in initializing the
1008   //     return value shall be one of those allowed in a constant expression.
1009   // C++11 [dcl.constexpr]p4:
1010   //   - every constructor involved in initializing non-static data members and
1011   //     base class sub-objects shall be a constexpr constructor.
1012   SmallVector<PartialDiagnosticAt, 8> Diags;
1013   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
1014     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
1015       << isa<CXXConstructorDecl>(Dcl);
1016     for (size_t I = 0, N = Diags.size(); I != N; ++I)
1017       Diag(Diags[I].first, Diags[I].second);
1018     // Don't return false here: we allow this for compatibility in
1019     // system headers.
1020   }
1021 
1022   return true;
1023 }
1024 
1025 /// isCurrentClassName - Determine whether the identifier II is the
1026 /// name of the class type currently being defined. In the case of
1027 /// nested classes, this will only return true if II is the name of
1028 /// the innermost class.
1029 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1030                               const CXXScopeSpec *SS) {
1031   assert(getLangOpts().CPlusPlus && "No class names in C!");
1032 
1033   CXXRecordDecl *CurDecl;
1034   if (SS && SS->isSet() && !SS->isInvalid()) {
1035     DeclContext *DC = computeDeclContext(*SS, true);
1036     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1037   } else
1038     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1039 
1040   if (CurDecl && CurDecl->getIdentifier())
1041     return &II == CurDecl->getIdentifier();
1042   else
1043     return false;
1044 }
1045 
1046 /// \brief Determine whether the given class is a base class of the given
1047 /// class, including looking at dependent bases.
1048 static bool findCircularInheritance(const CXXRecordDecl *Class,
1049                                     const CXXRecordDecl *Current) {
1050   SmallVector<const CXXRecordDecl*, 8> Queue;
1051 
1052   Class = Class->getCanonicalDecl();
1053   while (true) {
1054     for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1055                                                   E = Current->bases_end();
1056          I != E; ++I) {
1057       CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1058       if (!Base)
1059         continue;
1060 
1061       Base = Base->getDefinition();
1062       if (!Base)
1063         continue;
1064 
1065       if (Base->getCanonicalDecl() == Class)
1066         return true;
1067 
1068       Queue.push_back(Base);
1069     }
1070 
1071     if (Queue.empty())
1072       return false;
1073 
1074     Current = Queue.back();
1075     Queue.pop_back();
1076   }
1077 
1078   return false;
1079 }
1080 
1081 /// \brief Check the validity of a C++ base class specifier.
1082 ///
1083 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1084 /// and returns NULL otherwise.
1085 CXXBaseSpecifier *
1086 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1087                          SourceRange SpecifierRange,
1088                          bool Virtual, AccessSpecifier Access,
1089                          TypeSourceInfo *TInfo,
1090                          SourceLocation EllipsisLoc) {
1091   QualType BaseType = TInfo->getType();
1092 
1093   // C++ [class.union]p1:
1094   //   A union shall not have base classes.
1095   if (Class->isUnion()) {
1096     Diag(Class->getLocation(), diag::err_base_clause_on_union)
1097       << SpecifierRange;
1098     return 0;
1099   }
1100 
1101   if (EllipsisLoc.isValid() &&
1102       !TInfo->getType()->containsUnexpandedParameterPack()) {
1103     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1104       << TInfo->getTypeLoc().getSourceRange();
1105     EllipsisLoc = SourceLocation();
1106   }
1107 
1108   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1109 
1110   if (BaseType->isDependentType()) {
1111     // Make sure that we don't have circular inheritance among our dependent
1112     // bases. For non-dependent bases, the check for completeness below handles
1113     // this.
1114     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1115       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1116           ((BaseDecl = BaseDecl->getDefinition()) &&
1117            findCircularInheritance(Class, BaseDecl))) {
1118         Diag(BaseLoc, diag::err_circular_inheritance)
1119           << BaseType << Context.getTypeDeclType(Class);
1120 
1121         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1122           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1123             << BaseType;
1124 
1125         return 0;
1126       }
1127     }
1128 
1129     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1130                                           Class->getTagKind() == TTK_Class,
1131                                           Access, TInfo, EllipsisLoc);
1132   }
1133 
1134   // Base specifiers must be record types.
1135   if (!BaseType->isRecordType()) {
1136     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1137     return 0;
1138   }
1139 
1140   // C++ [class.union]p1:
1141   //   A union shall not be used as a base class.
1142   if (BaseType->isUnionType()) {
1143     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1144     return 0;
1145   }
1146 
1147   // C++ [class.derived]p2:
1148   //   The class-name in a base-specifier shall not be an incompletely
1149   //   defined class.
1150   if (RequireCompleteType(BaseLoc, BaseType,
1151                           diag::err_incomplete_base_class, SpecifierRange)) {
1152     Class->setInvalidDecl();
1153     return 0;
1154   }
1155 
1156   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1157   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1158   assert(BaseDecl && "Record type has no declaration");
1159   BaseDecl = BaseDecl->getDefinition();
1160   assert(BaseDecl && "Base type is not incomplete, but has no definition");
1161   CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1162   assert(CXXBaseDecl && "Base type is not a C++ type");
1163 
1164   // C++ [class]p3:
1165   //   If a class is marked final and it appears as a base-type-specifier in
1166   //   base-clause, the program is ill-formed.
1167   if (CXXBaseDecl->hasAttr<FinalAttr>()) {
1168     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1169       << CXXBaseDecl->getDeclName();
1170     Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1171       << CXXBaseDecl->getDeclName();
1172     return 0;
1173   }
1174 
1175   if (BaseDecl->isInvalidDecl())
1176     Class->setInvalidDecl();
1177 
1178   // Create the base specifier.
1179   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1180                                         Class->getTagKind() == TTK_Class,
1181                                         Access, TInfo, EllipsisLoc);
1182 }
1183 
1184 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1185 /// one entry in the base class list of a class specifier, for
1186 /// example:
1187 ///    class foo : public bar, virtual private baz {
1188 /// 'public bar' and 'virtual private baz' are each base-specifiers.
1189 BaseResult
1190 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1191                          ParsedAttributes &Attributes,
1192                          bool Virtual, AccessSpecifier Access,
1193                          ParsedType basetype, SourceLocation BaseLoc,
1194                          SourceLocation EllipsisLoc) {
1195   if (!classdecl)
1196     return true;
1197 
1198   AdjustDeclIfTemplate(classdecl);
1199   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1200   if (!Class)
1201     return true;
1202 
1203   // We do not support any C++11 attributes on base-specifiers yet.
1204   // Diagnose any attributes we see.
1205   if (!Attributes.empty()) {
1206     for (AttributeList *Attr = Attributes.getList(); Attr;
1207          Attr = Attr->getNext()) {
1208       if (Attr->isInvalid() ||
1209           Attr->getKind() == AttributeList::IgnoredAttribute)
1210         continue;
1211       Diag(Attr->getLoc(),
1212            Attr->getKind() == AttributeList::UnknownAttribute
1213              ? diag::warn_unknown_attribute_ignored
1214              : diag::err_base_specifier_attribute)
1215         << Attr->getName();
1216     }
1217   }
1218 
1219   TypeSourceInfo *TInfo = 0;
1220   GetTypeFromParser(basetype, &TInfo);
1221 
1222   if (EllipsisLoc.isInvalid() &&
1223       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1224                                       UPPC_BaseType))
1225     return true;
1226 
1227   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1228                                                       Virtual, Access, TInfo,
1229                                                       EllipsisLoc))
1230     return BaseSpec;
1231   else
1232     Class->setInvalidDecl();
1233 
1234   return true;
1235 }
1236 
1237 /// \brief Performs the actual work of attaching the given base class
1238 /// specifiers to a C++ class.
1239 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1240                                 unsigned NumBases) {
1241  if (NumBases == 0)
1242     return false;
1243 
1244   // Used to keep track of which base types we have already seen, so
1245   // that we can properly diagnose redundant direct base types. Note
1246   // that the key is always the unqualified canonical type of the base
1247   // class.
1248   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1249 
1250   // Copy non-redundant base specifiers into permanent storage.
1251   unsigned NumGoodBases = 0;
1252   bool Invalid = false;
1253   for (unsigned idx = 0; idx < NumBases; ++idx) {
1254     QualType NewBaseType
1255       = Context.getCanonicalType(Bases[idx]->getType());
1256     NewBaseType = NewBaseType.getLocalUnqualifiedType();
1257 
1258     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1259     if (KnownBase) {
1260       // C++ [class.mi]p3:
1261       //   A class shall not be specified as a direct base class of a
1262       //   derived class more than once.
1263       Diag(Bases[idx]->getLocStart(),
1264            diag::err_duplicate_base_class)
1265         << KnownBase->getType()
1266         << Bases[idx]->getSourceRange();
1267 
1268       // Delete the duplicate base class specifier; we're going to
1269       // overwrite its pointer later.
1270       Context.Deallocate(Bases[idx]);
1271 
1272       Invalid = true;
1273     } else {
1274       // Okay, add this new base class.
1275       KnownBase = Bases[idx];
1276       Bases[NumGoodBases++] = Bases[idx];
1277       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1278         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1279         if (Class->isInterface() &&
1280               (!RD->isInterface() ||
1281                KnownBase->getAccessSpecifier() != AS_public)) {
1282           // The Microsoft extension __interface does not permit bases that
1283           // are not themselves public interfaces.
1284           Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1285             << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1286             << RD->getSourceRange();
1287           Invalid = true;
1288         }
1289         if (RD->hasAttr<WeakAttr>())
1290           Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1291       }
1292     }
1293   }
1294 
1295   // Attach the remaining base class specifiers to the derived class.
1296   Class->setBases(Bases, NumGoodBases);
1297 
1298   // Delete the remaining (good) base class specifiers, since their
1299   // data has been copied into the CXXRecordDecl.
1300   for (unsigned idx = 0; idx < NumGoodBases; ++idx)
1301     Context.Deallocate(Bases[idx]);
1302 
1303   return Invalid;
1304 }
1305 
1306 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
1307 /// class, after checking whether there are any duplicate base
1308 /// classes.
1309 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
1310                                unsigned NumBases) {
1311   if (!ClassDecl || !Bases || !NumBases)
1312     return;
1313 
1314   AdjustDeclIfTemplate(ClassDecl);
1315   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
1316                        (CXXBaseSpecifier**)(Bases), NumBases);
1317 }
1318 
1319 /// \brief Determine whether the type \p Derived is a C++ class that is
1320 /// derived from the type \p Base.
1321 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1322   if (!getLangOpts().CPlusPlus)
1323     return false;
1324 
1325   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1326   if (!DerivedRD)
1327     return false;
1328 
1329   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1330   if (!BaseRD)
1331     return false;
1332 
1333   // If either the base or the derived type is invalid, don't try to
1334   // check whether one is derived from the other.
1335   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1336     return false;
1337 
1338   // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
1339   return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
1340 }
1341 
1342 /// \brief Determine whether the type \p Derived is a C++ class that is
1343 /// derived from the type \p Base.
1344 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1345   if (!getLangOpts().CPlusPlus)
1346     return false;
1347 
1348   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1349   if (!DerivedRD)
1350     return false;
1351 
1352   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1353   if (!BaseRD)
1354     return false;
1355 
1356   return DerivedRD->isDerivedFrom(BaseRD, Paths);
1357 }
1358 
1359 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1360                               CXXCastPath &BasePathArray) {
1361   assert(BasePathArray.empty() && "Base path array must be empty!");
1362   assert(Paths.isRecordingPaths() && "Must record paths!");
1363 
1364   const CXXBasePath &Path = Paths.front();
1365 
1366   // We first go backward and check if we have a virtual base.
1367   // FIXME: It would be better if CXXBasePath had the base specifier for
1368   // the nearest virtual base.
1369   unsigned Start = 0;
1370   for (unsigned I = Path.size(); I != 0; --I) {
1371     if (Path[I - 1].Base->isVirtual()) {
1372       Start = I - 1;
1373       break;
1374     }
1375   }
1376 
1377   // Now add all bases.
1378   for (unsigned I = Start, E = Path.size(); I != E; ++I)
1379     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1380 }
1381 
1382 /// \brief Determine whether the given base path includes a virtual
1383 /// base class.
1384 bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1385   for (CXXCastPath::const_iterator B = BasePath.begin(),
1386                                 BEnd = BasePath.end();
1387        B != BEnd; ++B)
1388     if ((*B)->isVirtual())
1389       return true;
1390 
1391   return false;
1392 }
1393 
1394 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1395 /// conversion (where Derived and Base are class types) is
1396 /// well-formed, meaning that the conversion is unambiguous (and
1397 /// that all of the base classes are accessible). Returns true
1398 /// and emits a diagnostic if the code is ill-formed, returns false
1399 /// otherwise. Loc is the location where this routine should point to
1400 /// if there is an error, and Range is the source range to highlight
1401 /// if there is an error.
1402 bool
1403 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1404                                    unsigned InaccessibleBaseID,
1405                                    unsigned AmbigiousBaseConvID,
1406                                    SourceLocation Loc, SourceRange Range,
1407                                    DeclarationName Name,
1408                                    CXXCastPath *BasePath) {
1409   // First, determine whether the path from Derived to Base is
1410   // ambiguous. This is slightly more expensive than checking whether
1411   // the Derived to Base conversion exists, because here we need to
1412   // explore multiple paths to determine if there is an ambiguity.
1413   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1414                      /*DetectVirtual=*/false);
1415   bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1416   assert(DerivationOkay &&
1417          "Can only be used with a derived-to-base conversion");
1418   (void)DerivationOkay;
1419 
1420   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1421     if (InaccessibleBaseID) {
1422       // Check that the base class can be accessed.
1423       switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1424                                    InaccessibleBaseID)) {
1425         case AR_inaccessible:
1426           return true;
1427         case AR_accessible:
1428         case AR_dependent:
1429         case AR_delayed:
1430           break;
1431       }
1432     }
1433 
1434     // Build a base path if necessary.
1435     if (BasePath)
1436       BuildBasePathArray(Paths, *BasePath);
1437     return false;
1438   }
1439 
1440   // We know that the derived-to-base conversion is ambiguous, and
1441   // we're going to produce a diagnostic. Perform the derived-to-base
1442   // search just one more time to compute all of the possible paths so
1443   // that we can print them out. This is more expensive than any of
1444   // the previous derived-to-base checks we've done, but at this point
1445   // performance isn't as much of an issue.
1446   Paths.clear();
1447   Paths.setRecordingPaths(true);
1448   bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1449   assert(StillOkay && "Can only be used with a derived-to-base conversion");
1450   (void)StillOkay;
1451 
1452   // Build up a textual representation of the ambiguous paths, e.g.,
1453   // D -> B -> A, that will be used to illustrate the ambiguous
1454   // conversions in the diagnostic. We only print one of the paths
1455   // to each base class subobject.
1456   std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1457 
1458   Diag(Loc, AmbigiousBaseConvID)
1459   << Derived << Base << PathDisplayStr << Range << Name;
1460   return true;
1461 }
1462 
1463 bool
1464 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1465                                    SourceLocation Loc, SourceRange Range,
1466                                    CXXCastPath *BasePath,
1467                                    bool IgnoreAccess) {
1468   return CheckDerivedToBaseConversion(Derived, Base,
1469                                       IgnoreAccess ? 0
1470                                        : diag::err_upcast_to_inaccessible_base,
1471                                       diag::err_ambiguous_derived_to_base_conv,
1472                                       Loc, Range, DeclarationName(),
1473                                       BasePath);
1474 }
1475 
1476 
1477 /// @brief Builds a string representing ambiguous paths from a
1478 /// specific derived class to different subobjects of the same base
1479 /// class.
1480 ///
1481 /// This function builds a string that can be used in error messages
1482 /// to show the different paths that one can take through the
1483 /// inheritance hierarchy to go from the derived class to different
1484 /// subobjects of a base class. The result looks something like this:
1485 /// @code
1486 /// struct D -> struct B -> struct A
1487 /// struct D -> struct C -> struct A
1488 /// @endcode
1489 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1490   std::string PathDisplayStr;
1491   std::set<unsigned> DisplayedPaths;
1492   for (CXXBasePaths::paths_iterator Path = Paths.begin();
1493        Path != Paths.end(); ++Path) {
1494     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1495       // We haven't displayed a path to this particular base
1496       // class subobject yet.
1497       PathDisplayStr += "\n    ";
1498       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1499       for (CXXBasePath::const_iterator Element = Path->begin();
1500            Element != Path->end(); ++Element)
1501         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1502     }
1503   }
1504 
1505   return PathDisplayStr;
1506 }
1507 
1508 //===----------------------------------------------------------------------===//
1509 // C++ class member Handling
1510 //===----------------------------------------------------------------------===//
1511 
1512 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1513 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1514                                 SourceLocation ASLoc,
1515                                 SourceLocation ColonLoc,
1516                                 AttributeList *Attrs) {
1517   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1518   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1519                                                   ASLoc, ColonLoc);
1520   CurContext->addHiddenDecl(ASDecl);
1521   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1522 }
1523 
1524 /// CheckOverrideControl - Check C++11 override control semantics.
1525 void Sema::CheckOverrideControl(Decl *D) {
1526   if (D->isInvalidDecl())
1527     return;
1528 
1529   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1530 
1531   // Do we know which functions this declaration might be overriding?
1532   bool OverridesAreKnown = !MD ||
1533       (!MD->getParent()->hasAnyDependentBases() &&
1534        !MD->getType()->isDependentType());
1535 
1536   if (!MD || !MD->isVirtual()) {
1537     if (OverridesAreKnown) {
1538       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1539         Diag(OA->getLocation(),
1540              diag::override_keyword_only_allowed_on_virtual_member_functions)
1541           << "override" << FixItHint::CreateRemoval(OA->getLocation());
1542         D->dropAttr<OverrideAttr>();
1543       }
1544       if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1545         Diag(FA->getLocation(),
1546              diag::override_keyword_only_allowed_on_virtual_member_functions)
1547           << "final" << FixItHint::CreateRemoval(FA->getLocation());
1548         D->dropAttr<FinalAttr>();
1549       }
1550     }
1551     return;
1552   }
1553 
1554   if (!OverridesAreKnown)
1555     return;
1556 
1557   // C++11 [class.virtual]p5:
1558   //   If a virtual function is marked with the virt-specifier override and
1559   //   does not override a member function of a base class, the program is
1560   //   ill-formed.
1561   bool HasOverriddenMethods =
1562     MD->begin_overridden_methods() != MD->end_overridden_methods();
1563   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1564     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1565       << MD->getDeclName();
1566 }
1567 
1568 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1569 /// function overrides a virtual member function marked 'final', according to
1570 /// C++11 [class.virtual]p4.
1571 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1572                                                   const CXXMethodDecl *Old) {
1573   if (!Old->hasAttr<FinalAttr>())
1574     return false;
1575 
1576   Diag(New->getLocation(), diag::err_final_function_overridden)
1577     << New->getDeclName();
1578   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1579   return true;
1580 }
1581 
1582 static bool InitializationHasSideEffects(const FieldDecl &FD) {
1583   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1584   // FIXME: Destruction of ObjC lifetime types has side-effects.
1585   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1586     return !RD->isCompleteDefinition() ||
1587            !RD->hasTrivialDefaultConstructor() ||
1588            !RD->hasTrivialDestructor();
1589   return false;
1590 }
1591 
1592 static AttributeList *getMSPropertyAttr(AttributeList *list) {
1593   for (AttributeList* it = list; it != 0; it = it->getNext())
1594     if (it->isDeclspecPropertyAttribute())
1595       return it;
1596   return 0;
1597 }
1598 
1599 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1600 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1601 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
1602 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1603 /// present (but parsing it has been deferred).
1604 NamedDecl *
1605 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1606                                MultiTemplateParamsArg TemplateParameterLists,
1607                                Expr *BW, const VirtSpecifiers &VS,
1608                                InClassInitStyle InitStyle) {
1609   const DeclSpec &DS = D.getDeclSpec();
1610   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1611   DeclarationName Name = NameInfo.getName();
1612   SourceLocation Loc = NameInfo.getLoc();
1613 
1614   // For anonymous bitfields, the location should point to the type.
1615   if (Loc.isInvalid())
1616     Loc = D.getLocStart();
1617 
1618   Expr *BitWidth = static_cast<Expr*>(BW);
1619 
1620   assert(isa<CXXRecordDecl>(CurContext));
1621   assert(!DS.isFriendSpecified());
1622 
1623   bool isFunc = D.isDeclarationOfFunction();
1624 
1625   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1626     // The Microsoft extension __interface only permits public member functions
1627     // and prohibits constructors, destructors, operators, non-public member
1628     // functions, static methods and data members.
1629     unsigned InvalidDecl;
1630     bool ShowDeclName = true;
1631     if (!isFunc)
1632       InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1633     else if (AS != AS_public)
1634       InvalidDecl = 2;
1635     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1636       InvalidDecl = 3;
1637     else switch (Name.getNameKind()) {
1638       case DeclarationName::CXXConstructorName:
1639         InvalidDecl = 4;
1640         ShowDeclName = false;
1641         break;
1642 
1643       case DeclarationName::CXXDestructorName:
1644         InvalidDecl = 5;
1645         ShowDeclName = false;
1646         break;
1647 
1648       case DeclarationName::CXXOperatorName:
1649       case DeclarationName::CXXConversionFunctionName:
1650         InvalidDecl = 6;
1651         break;
1652 
1653       default:
1654         InvalidDecl = 0;
1655         break;
1656     }
1657 
1658     if (InvalidDecl) {
1659       if (ShowDeclName)
1660         Diag(Loc, diag::err_invalid_member_in_interface)
1661           << (InvalidDecl-1) << Name;
1662       else
1663         Diag(Loc, diag::err_invalid_member_in_interface)
1664           << (InvalidDecl-1) << "";
1665       return 0;
1666     }
1667   }
1668 
1669   // C++ 9.2p6: A member shall not be declared to have automatic storage
1670   // duration (auto, register) or with the extern storage-class-specifier.
1671   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1672   // data members and cannot be applied to names declared const or static,
1673   // and cannot be applied to reference members.
1674   switch (DS.getStorageClassSpec()) {
1675   case DeclSpec::SCS_unspecified:
1676   case DeclSpec::SCS_typedef:
1677   case DeclSpec::SCS_static:
1678     break;
1679   case DeclSpec::SCS_mutable:
1680     if (isFunc) {
1681       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
1682 
1683       // FIXME: It would be nicer if the keyword was ignored only for this
1684       // declarator. Otherwise we could get follow-up errors.
1685       D.getMutableDeclSpec().ClearStorageClassSpecs();
1686     }
1687     break;
1688   default:
1689     Diag(DS.getStorageClassSpecLoc(),
1690          diag::err_storageclass_invalid_for_member);
1691     D.getMutableDeclSpec().ClearStorageClassSpecs();
1692     break;
1693   }
1694 
1695   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1696                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
1697                       !isFunc);
1698 
1699   if (DS.isConstexprSpecified() && isInstField) {
1700     SemaDiagnosticBuilder B =
1701         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1702     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1703     if (InitStyle == ICIS_NoInit) {
1704       B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1705       D.getMutableDeclSpec().ClearConstexprSpec();
1706       const char *PrevSpec;
1707       unsigned DiagID;
1708       bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1709                                          PrevSpec, DiagID, getLangOpts());
1710       (void)Failed;
1711       assert(!Failed && "Making a constexpr member const shouldn't fail");
1712     } else {
1713       B << 1;
1714       const char *PrevSpec;
1715       unsigned DiagID;
1716       if (D.getMutableDeclSpec().SetStorageClassSpec(
1717           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
1718         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
1719                "This is the only DeclSpec that should fail to be applied");
1720         B << 1;
1721       } else {
1722         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1723         isInstField = false;
1724       }
1725     }
1726   }
1727 
1728   NamedDecl *Member;
1729   if (isInstField) {
1730     CXXScopeSpec &SS = D.getCXXScopeSpec();
1731 
1732     // Data members must have identifiers for names.
1733     if (!Name.isIdentifier()) {
1734       Diag(Loc, diag::err_bad_variable_name)
1735         << Name;
1736       return 0;
1737     }
1738 
1739     IdentifierInfo *II = Name.getAsIdentifierInfo();
1740 
1741     // Member field could not be with "template" keyword.
1742     // So TemplateParameterLists should be empty in this case.
1743     if (TemplateParameterLists.size()) {
1744       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
1745       if (TemplateParams->size()) {
1746         // There is no such thing as a member field template.
1747         Diag(D.getIdentifierLoc(), diag::err_template_member)
1748             << II
1749             << SourceRange(TemplateParams->getTemplateLoc(),
1750                 TemplateParams->getRAngleLoc());
1751       } else {
1752         // There is an extraneous 'template<>' for this member.
1753         Diag(TemplateParams->getTemplateLoc(),
1754             diag::err_template_member_noparams)
1755             << II
1756             << SourceRange(TemplateParams->getTemplateLoc(),
1757                 TemplateParams->getRAngleLoc());
1758       }
1759       return 0;
1760     }
1761 
1762     if (SS.isSet() && !SS.isInvalid()) {
1763       // The user provided a superfluous scope specifier inside a class
1764       // definition:
1765       //
1766       // class X {
1767       //   int X::member;
1768       // };
1769       if (DeclContext *DC = computeDeclContext(SS, false))
1770         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
1771       else
1772         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1773           << Name << SS.getRange();
1774 
1775       SS.clear();
1776     }
1777 
1778     AttributeList *MSPropertyAttr =
1779       getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
1780     if (MSPropertyAttr) {
1781       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1782                                 BitWidth, InitStyle, AS, MSPropertyAttr);
1783       isInstField = false;
1784     } else {
1785       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1786                                 BitWidth, InitStyle, AS);
1787     }
1788     assert(Member && "HandleField never returns null");
1789   } else {
1790     assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
1791 
1792     Member = HandleDeclarator(S, D, TemplateParameterLists);
1793     if (!Member) {
1794       return 0;
1795     }
1796 
1797     // Non-instance-fields can't have a bitfield.
1798     if (BitWidth) {
1799       if (Member->isInvalidDecl()) {
1800         // don't emit another diagnostic.
1801       } else if (isa<VarDecl>(Member)) {
1802         // C++ 9.6p3: A bit-field shall not be a static member.
1803         // "static member 'A' cannot be a bit-field"
1804         Diag(Loc, diag::err_static_not_bitfield)
1805           << Name << BitWidth->getSourceRange();
1806       } else if (isa<TypedefDecl>(Member)) {
1807         // "typedef member 'x' cannot be a bit-field"
1808         Diag(Loc, diag::err_typedef_not_bitfield)
1809           << Name << BitWidth->getSourceRange();
1810       } else {
1811         // A function typedef ("typedef int f(); f a;").
1812         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1813         Diag(Loc, diag::err_not_integral_type_bitfield)
1814           << Name << cast<ValueDecl>(Member)->getType()
1815           << BitWidth->getSourceRange();
1816       }
1817 
1818       BitWidth = 0;
1819       Member->setInvalidDecl();
1820     }
1821 
1822     Member->setAccess(AS);
1823 
1824     // If we have declared a member function template, set the access of the
1825     // templated declaration as well.
1826     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1827       FunTmpl->getTemplatedDecl()->setAccess(AS);
1828   }
1829 
1830   if (VS.isOverrideSpecified())
1831     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1832   if (VS.isFinalSpecified())
1833     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
1834 
1835   if (VS.getLastLocation().isValid()) {
1836     // Update the end location of a method that has a virt-specifiers.
1837     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1838       MD->setRangeEnd(VS.getLastLocation());
1839   }
1840 
1841   CheckOverrideControl(Member);
1842 
1843   assert((Name || isInstField) && "No identifier for non-field ?");
1844 
1845   if (isInstField) {
1846     FieldDecl *FD = cast<FieldDecl>(Member);
1847     FieldCollector->Add(FD);
1848 
1849     if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
1850                                  FD->getLocation())
1851           != DiagnosticsEngine::Ignored) {
1852       // Remember all explicit private FieldDecls that have a name, no side
1853       // effects and are not part of a dependent type declaration.
1854       if (!FD->isImplicit() && FD->getDeclName() &&
1855           FD->getAccess() == AS_private &&
1856           !FD->hasAttr<UnusedAttr>() &&
1857           !FD->getParent()->isDependentContext() &&
1858           !InitializationHasSideEffects(*FD))
1859         UnusedPrivateFields.insert(FD);
1860     }
1861   }
1862 
1863   return Member;
1864 }
1865 
1866 namespace {
1867   class UninitializedFieldVisitor
1868       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
1869     Sema &S;
1870     ValueDecl *VD;
1871   public:
1872     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
1873     UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
1874                                                         S(S) {
1875       if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
1876         this->VD = IFD->getAnonField();
1877       else
1878         this->VD = VD;
1879     }
1880 
1881     void HandleExpr(Expr *E) {
1882       if (!E) return;
1883 
1884       // Expressions like x(x) sometimes lack the surrounding expressions
1885       // but need to be checked anyways.
1886       HandleValue(E);
1887       Visit(E);
1888     }
1889 
1890     void HandleValue(Expr *E) {
1891       E = E->IgnoreParens();
1892 
1893       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1894         if (isa<EnumConstantDecl>(ME->getMemberDecl()))
1895           return;
1896 
1897         // FieldME is the inner-most MemberExpr that is not an anonymous struct
1898         // or union.
1899         MemberExpr *FieldME = ME;
1900 
1901         Expr *Base = E;
1902         while (isa<MemberExpr>(Base)) {
1903           ME = cast<MemberExpr>(Base);
1904 
1905           if (isa<VarDecl>(ME->getMemberDecl()))
1906             return;
1907 
1908           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1909             if (!FD->isAnonymousStructOrUnion())
1910               FieldME = ME;
1911 
1912           Base = ME->getBase();
1913         }
1914 
1915         if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
1916           unsigned diag = VD->getType()->isReferenceType()
1917               ? diag::warn_reference_field_is_uninit
1918               : diag::warn_field_is_uninit;
1919           S.Diag(FieldME->getExprLoc(), diag) << VD;
1920         }
1921         return;
1922       }
1923 
1924       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1925         HandleValue(CO->getTrueExpr());
1926         HandleValue(CO->getFalseExpr());
1927         return;
1928       }
1929 
1930       if (BinaryConditionalOperator *BCO =
1931               dyn_cast<BinaryConditionalOperator>(E)) {
1932         HandleValue(BCO->getCommon());
1933         HandleValue(BCO->getFalseExpr());
1934         return;
1935       }
1936 
1937       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
1938         switch (BO->getOpcode()) {
1939         default:
1940           return;
1941         case(BO_PtrMemD):
1942         case(BO_PtrMemI):
1943           HandleValue(BO->getLHS());
1944           return;
1945         case(BO_Comma):
1946           HandleValue(BO->getRHS());
1947           return;
1948         }
1949       }
1950     }
1951 
1952     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
1953       if (E->getCastKind() == CK_LValueToRValue)
1954         HandleValue(E->getSubExpr());
1955 
1956       Inherited::VisitImplicitCastExpr(E);
1957     }
1958 
1959     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
1960       Expr *Callee = E->getCallee();
1961       if (isa<MemberExpr>(Callee))
1962         HandleValue(Callee);
1963 
1964       Inherited::VisitCXXMemberCallExpr(E);
1965     }
1966   };
1967   static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
1968                                                        ValueDecl *VD) {
1969     UninitializedFieldVisitor(S, VD).HandleExpr(E);
1970   }
1971 } // namespace
1972 
1973 /// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
1974 /// in-class initializer for a non-static C++ class member, and after
1975 /// instantiating an in-class initializer in a class template. Such actions
1976 /// are deferred until the class is complete.
1977 void
1978 Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
1979                                        Expr *InitExpr) {
1980   FieldDecl *FD = cast<FieldDecl>(D);
1981   assert(FD->getInClassInitStyle() != ICIS_NoInit &&
1982          "must set init style when field is created");
1983 
1984   if (!InitExpr) {
1985     FD->setInvalidDecl();
1986     FD->removeInClassInitializer();
1987     return;
1988   }
1989 
1990   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1991     FD->setInvalidDecl();
1992     FD->removeInClassInitializer();
1993     return;
1994   }
1995 
1996   if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
1997       != DiagnosticsEngine::Ignored) {
1998     CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
1999   }
2000 
2001   ExprResult Init = InitExpr;
2002   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
2003     if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
2004       Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
2005         << /*at end of ctor*/1 << InitExpr->getSourceRange();
2006     }
2007     Expr **Inits = &InitExpr;
2008     unsigned NumInits = 1;
2009     InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
2010     InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
2011         ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
2012         : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
2013     InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
2014     Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
2015     if (Init.isInvalid()) {
2016       FD->setInvalidDecl();
2017       return;
2018     }
2019   }
2020 
2021   // C++11 [class.base.init]p7:
2022   //   The initialization of each base and member constitutes a
2023   //   full-expression.
2024   Init = ActOnFinishFullExpr(Init.take(), InitLoc);
2025   if (Init.isInvalid()) {
2026     FD->setInvalidDecl();
2027     return;
2028   }
2029 
2030   InitExpr = Init.release();
2031 
2032   FD->setInClassInitializer(InitExpr);
2033 }
2034 
2035 /// \brief Find the direct and/or virtual base specifiers that
2036 /// correspond to the given base type, for use in base initialization
2037 /// within a constructor.
2038 static bool FindBaseInitializer(Sema &SemaRef,
2039                                 CXXRecordDecl *ClassDecl,
2040                                 QualType BaseType,
2041                                 const CXXBaseSpecifier *&DirectBaseSpec,
2042                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
2043   // First, check for a direct base class.
2044   DirectBaseSpec = 0;
2045   for (CXXRecordDecl::base_class_const_iterator Base
2046          = ClassDecl->bases_begin();
2047        Base != ClassDecl->bases_end(); ++Base) {
2048     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2049       // We found a direct base of this type. That's what we're
2050       // initializing.
2051       DirectBaseSpec = &*Base;
2052       break;
2053     }
2054   }
2055 
2056   // Check for a virtual base class.
2057   // FIXME: We might be able to short-circuit this if we know in advance that
2058   // there are no virtual bases.
2059   VirtualBaseSpec = 0;
2060   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2061     // We haven't found a base yet; search the class hierarchy for a
2062     // virtual base class.
2063     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2064                        /*DetectVirtual=*/false);
2065     if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2066                               BaseType, Paths)) {
2067       for (CXXBasePaths::paths_iterator Path = Paths.begin();
2068            Path != Paths.end(); ++Path) {
2069         if (Path->back().Base->isVirtual()) {
2070           VirtualBaseSpec = Path->back().Base;
2071           break;
2072         }
2073       }
2074     }
2075   }
2076 
2077   return DirectBaseSpec || VirtualBaseSpec;
2078 }
2079 
2080 /// \brief Handle a C++ member initializer using braced-init-list syntax.
2081 MemInitResult
2082 Sema::ActOnMemInitializer(Decl *ConstructorD,
2083                           Scope *S,
2084                           CXXScopeSpec &SS,
2085                           IdentifierInfo *MemberOrBase,
2086                           ParsedType TemplateTypeTy,
2087                           const DeclSpec &DS,
2088                           SourceLocation IdLoc,
2089                           Expr *InitList,
2090                           SourceLocation EllipsisLoc) {
2091   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2092                              DS, IdLoc, InitList,
2093                              EllipsisLoc);
2094 }
2095 
2096 /// \brief Handle a C++ member initializer using parentheses syntax.
2097 MemInitResult
2098 Sema::ActOnMemInitializer(Decl *ConstructorD,
2099                           Scope *S,
2100                           CXXScopeSpec &SS,
2101                           IdentifierInfo *MemberOrBase,
2102                           ParsedType TemplateTypeTy,
2103                           const DeclSpec &DS,
2104                           SourceLocation IdLoc,
2105                           SourceLocation LParenLoc,
2106                           Expr **Args, unsigned NumArgs,
2107                           SourceLocation RParenLoc,
2108                           SourceLocation EllipsisLoc) {
2109   Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2110                                            llvm::makeArrayRef(Args, NumArgs),
2111                                            RParenLoc);
2112   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2113                              DS, IdLoc, List, EllipsisLoc);
2114 }
2115 
2116 namespace {
2117 
2118 // Callback to only accept typo corrections that can be a valid C++ member
2119 // intializer: either a non-static field member or a base class.
2120 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2121  public:
2122   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2123       : ClassDecl(ClassDecl) {}
2124 
2125   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2126     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2127       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2128         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2129       else
2130         return isa<TypeDecl>(ND);
2131     }
2132     return false;
2133   }
2134 
2135  private:
2136   CXXRecordDecl *ClassDecl;
2137 };
2138 
2139 }
2140 
2141 /// \brief Handle a C++ member initializer.
2142 MemInitResult
2143 Sema::BuildMemInitializer(Decl *ConstructorD,
2144                           Scope *S,
2145                           CXXScopeSpec &SS,
2146                           IdentifierInfo *MemberOrBase,
2147                           ParsedType TemplateTypeTy,
2148                           const DeclSpec &DS,
2149                           SourceLocation IdLoc,
2150                           Expr *Init,
2151                           SourceLocation EllipsisLoc) {
2152   if (!ConstructorD)
2153     return true;
2154 
2155   AdjustDeclIfTemplate(ConstructorD);
2156 
2157   CXXConstructorDecl *Constructor
2158     = dyn_cast<CXXConstructorDecl>(ConstructorD);
2159   if (!Constructor) {
2160     // The user wrote a constructor initializer on a function that is
2161     // not a C++ constructor. Ignore the error for now, because we may
2162     // have more member initializers coming; we'll diagnose it just
2163     // once in ActOnMemInitializers.
2164     return true;
2165   }
2166 
2167   CXXRecordDecl *ClassDecl = Constructor->getParent();
2168 
2169   // C++ [class.base.init]p2:
2170   //   Names in a mem-initializer-id are looked up in the scope of the
2171   //   constructor's class and, if not found in that scope, are looked
2172   //   up in the scope containing the constructor's definition.
2173   //   [Note: if the constructor's class contains a member with the
2174   //   same name as a direct or virtual base class of the class, a
2175   //   mem-initializer-id naming the member or base class and composed
2176   //   of a single identifier refers to the class member. A
2177   //   mem-initializer-id for the hidden base class may be specified
2178   //   using a qualified name. ]
2179   if (!SS.getScopeRep() && !TemplateTypeTy) {
2180     // Look for a member, first.
2181     DeclContext::lookup_result Result
2182       = ClassDecl->lookup(MemberOrBase);
2183     if (!Result.empty()) {
2184       ValueDecl *Member;
2185       if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2186           (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
2187         if (EllipsisLoc.isValid())
2188           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
2189             << MemberOrBase
2190             << SourceRange(IdLoc, Init->getSourceRange().getEnd());
2191 
2192         return BuildMemberInitializer(Member, Init, IdLoc);
2193       }
2194     }
2195   }
2196   // It didn't name a member, so see if it names a class.
2197   QualType BaseType;
2198   TypeSourceInfo *TInfo = 0;
2199 
2200   if (TemplateTypeTy) {
2201     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
2202   } else if (DS.getTypeSpecType() == TST_decltype) {
2203     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
2204   } else {
2205     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2206     LookupParsedName(R, S, &SS);
2207 
2208     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2209     if (!TyD) {
2210       if (R.isAmbiguous()) return true;
2211 
2212       // We don't want access-control diagnostics here.
2213       R.suppressDiagnostics();
2214 
2215       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2216         bool NotUnknownSpecialization = false;
2217         DeclContext *DC = computeDeclContext(SS, false);
2218         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2219           NotUnknownSpecialization = !Record->hasAnyDependentBases();
2220 
2221         if (!NotUnknownSpecialization) {
2222           // When the scope specifier can refer to a member of an unknown
2223           // specialization, we take it as a type name.
2224           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2225                                        SS.getWithLocInContext(Context),
2226                                        *MemberOrBase, IdLoc);
2227           if (BaseType.isNull())
2228             return true;
2229 
2230           R.clear();
2231           R.setLookupName(MemberOrBase);
2232         }
2233       }
2234 
2235       // If no results were found, try to correct typos.
2236       TypoCorrection Corr;
2237       MemInitializerValidatorCCC Validator(ClassDecl);
2238       if (R.empty() && BaseType.isNull() &&
2239           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2240                               Validator, ClassDecl))) {
2241         std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2242         std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
2243         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
2244           // We have found a non-static data member with a similar
2245           // name to what was typed; complain and initialize that
2246           // member.
2247           Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2248             << MemberOrBase << true << CorrectedQuotedStr
2249             << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2250           Diag(Member->getLocation(), diag::note_previous_decl)
2251             << CorrectedQuotedStr;
2252 
2253           return BuildMemberInitializer(Member, Init, IdLoc);
2254         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
2255           const CXXBaseSpecifier *DirectBaseSpec;
2256           const CXXBaseSpecifier *VirtualBaseSpec;
2257           if (FindBaseInitializer(*this, ClassDecl,
2258                                   Context.getTypeDeclType(Type),
2259                                   DirectBaseSpec, VirtualBaseSpec)) {
2260             // We have found a direct or virtual base class with a
2261             // similar name to what was typed; complain and initialize
2262             // that base class.
2263             Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2264               << MemberOrBase << false << CorrectedQuotedStr
2265               << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2266 
2267             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2268                                                              : VirtualBaseSpec;
2269             Diag(BaseSpec->getLocStart(),
2270                  diag::note_base_class_specified_here)
2271               << BaseSpec->getType()
2272               << BaseSpec->getSourceRange();
2273 
2274             TyD = Type;
2275           }
2276         }
2277       }
2278 
2279       if (!TyD && BaseType.isNull()) {
2280         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
2281           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
2282         return true;
2283       }
2284     }
2285 
2286     if (BaseType.isNull()) {
2287       BaseType = Context.getTypeDeclType(TyD);
2288       if (SS.isSet()) {
2289         NestedNameSpecifier *Qualifier =
2290           static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2291 
2292         // FIXME: preserve source range information
2293         BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
2294       }
2295     }
2296   }
2297 
2298   if (!TInfo)
2299     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
2300 
2301   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
2302 }
2303 
2304 /// Checks a member initializer expression for cases where reference (or
2305 /// pointer) members are bound to by-value parameters (or their addresses).
2306 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2307                                                Expr *Init,
2308                                                SourceLocation IdLoc) {
2309   QualType MemberTy = Member->getType();
2310 
2311   // We only handle pointers and references currently.
2312   // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2313   if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2314     return;
2315 
2316   const bool IsPointer = MemberTy->isPointerType();
2317   if (IsPointer) {
2318     if (const UnaryOperator *Op
2319           = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2320       // The only case we're worried about with pointers requires taking the
2321       // address.
2322       if (Op->getOpcode() != UO_AddrOf)
2323         return;
2324 
2325       Init = Op->getSubExpr();
2326     } else {
2327       // We only handle address-of expression initializers for pointers.
2328       return;
2329     }
2330   }
2331 
2332   if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2333     // Taking the address of a temporary will be diagnosed as a hard error.
2334     if (IsPointer)
2335       return;
2336 
2337     S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2338       << Member << Init->getSourceRange();
2339   } else if (const DeclRefExpr *DRE
2340                = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2341     // We only warn when referring to a non-reference parameter declaration.
2342     const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2343     if (!Parameter || Parameter->getType()->isReferenceType())
2344       return;
2345 
2346     S.Diag(Init->getExprLoc(),
2347            IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2348                      : diag::warn_bind_ref_member_to_parameter)
2349       << Member << Parameter << Init->getSourceRange();
2350   } else {
2351     // Other initializers are fine.
2352     return;
2353   }
2354 
2355   S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2356     << (unsigned)IsPointer;
2357 }
2358 
2359 MemInitResult
2360 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
2361                              SourceLocation IdLoc) {
2362   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2363   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2364   assert((DirectMember || IndirectMember) &&
2365          "Member must be a FieldDecl or IndirectFieldDecl");
2366 
2367   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2368     return true;
2369 
2370   if (Member->isInvalidDecl())
2371     return true;
2372 
2373   // Diagnose value-uses of fields to initialize themselves, e.g.
2374   //   foo(foo)
2375   // where foo is not also a parameter to the constructor.
2376   // TODO: implement -Wuninitialized and fold this into that framework.
2377   Expr **Args;
2378   unsigned NumArgs;
2379   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2380     Args = ParenList->getExprs();
2381     NumArgs = ParenList->getNumExprs();
2382   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2383     Args = InitList->getInits();
2384     NumArgs = InitList->getNumInits();
2385   } else {
2386     // Template instantiation doesn't reconstruct ParenListExprs for us.
2387     Args = &Init;
2388     NumArgs = 1;
2389   }
2390 
2391   if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2392         != DiagnosticsEngine::Ignored)
2393     for (unsigned i = 0; i < NumArgs; ++i)
2394       // FIXME: Warn about the case when other fields are used before being
2395       // initialized. For example, let this field be the i'th field. When
2396       // initializing the i'th field, throw a warning if any of the >= i'th
2397       // fields are used, as they are not yet initialized.
2398       // Right now we are only handling the case where the i'th field uses
2399       // itself in its initializer.
2400       // Also need to take into account that some fields may be initialized by
2401       // in-class initializers, see C++11 [class.base.init]p9.
2402       CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
2403 
2404   SourceRange InitRange = Init->getSourceRange();
2405 
2406   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
2407     // Can't check initialization for a member of dependent type or when
2408     // any of the arguments are type-dependent expressions.
2409     DiscardCleanupsInEvaluationContext();
2410   } else {
2411     bool InitList = false;
2412     if (isa<InitListExpr>(Init)) {
2413       InitList = true;
2414       Args = &Init;
2415       NumArgs = 1;
2416 
2417       if (isStdInitializerList(Member->getType(), 0)) {
2418         Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2419             << /*at end of ctor*/1 << InitRange;
2420       }
2421     }
2422 
2423     // Initialize the member.
2424     InitializedEntity MemberEntity =
2425       DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2426                    : InitializedEntity::InitializeMember(IndirectMember, 0);
2427     InitializationKind Kind =
2428       InitList ? InitializationKind::CreateDirectList(IdLoc)
2429                : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2430                                                   InitRange.getEnd());
2431 
2432     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2433     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
2434                                             MultiExprArg(Args, NumArgs),
2435                                             0);
2436     if (MemberInit.isInvalid())
2437       return true;
2438 
2439     // C++11 [class.base.init]p7:
2440     //   The initialization of each base and member constitutes a
2441     //   full-expression.
2442     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
2443     if (MemberInit.isInvalid())
2444       return true;
2445 
2446     Init = MemberInit.get();
2447     CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2448   }
2449 
2450   if (DirectMember) {
2451     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2452                                             InitRange.getBegin(), Init,
2453                                             InitRange.getEnd());
2454   } else {
2455     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2456                                             InitRange.getBegin(), Init,
2457                                             InitRange.getEnd());
2458   }
2459 }
2460 
2461 MemInitResult
2462 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
2463                                  CXXRecordDecl *ClassDecl) {
2464   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
2465   if (!LangOpts.CPlusPlus11)
2466     return Diag(NameLoc, diag::err_delegating_ctor)
2467       << TInfo->getTypeLoc().getLocalSourceRange();
2468   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
2469 
2470   bool InitList = true;
2471   Expr **Args = &Init;
2472   unsigned NumArgs = 1;
2473   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2474     InitList = false;
2475     Args = ParenList->getExprs();
2476     NumArgs = ParenList->getNumExprs();
2477   }
2478 
2479   SourceRange InitRange = Init->getSourceRange();
2480   // Initialize the object.
2481   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2482                                      QualType(ClassDecl->getTypeForDecl(), 0));
2483   InitializationKind Kind =
2484     InitList ? InitializationKind::CreateDirectList(NameLoc)
2485              : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2486                                                 InitRange.getEnd());
2487   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2488   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2489                                               MultiExprArg(Args, NumArgs),
2490                                               0);
2491   if (DelegationInit.isInvalid())
2492     return true;
2493 
2494   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2495          "Delegating constructor with no target?");
2496 
2497   // C++11 [class.base.init]p7:
2498   //   The initialization of each base and member constitutes a
2499   //   full-expression.
2500   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2501                                        InitRange.getBegin());
2502   if (DelegationInit.isInvalid())
2503     return true;
2504 
2505   // If we are in a dependent context, template instantiation will
2506   // perform this type-checking again. Just save the arguments that we
2507   // received in a ParenListExpr.
2508   // FIXME: This isn't quite ideal, since our ASTs don't capture all
2509   // of the information that we have about the base
2510   // initializer. However, deconstructing the ASTs is a dicey process,
2511   // and this approach is far more likely to get the corner cases right.
2512   if (CurContext->isDependentContext())
2513     DelegationInit = Owned(Init);
2514 
2515   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
2516                                           DelegationInit.takeAs<Expr>(),
2517                                           InitRange.getEnd());
2518 }
2519 
2520 MemInitResult
2521 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
2522                            Expr *Init, CXXRecordDecl *ClassDecl,
2523                            SourceLocation EllipsisLoc) {
2524   SourceLocation BaseLoc
2525     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
2526 
2527   if (!BaseType->isDependentType() && !BaseType->isRecordType())
2528     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2529              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2530 
2531   // C++ [class.base.init]p2:
2532   //   [...] Unless the mem-initializer-id names a nonstatic data
2533   //   member of the constructor's class or a direct or virtual base
2534   //   of that class, the mem-initializer is ill-formed. A
2535   //   mem-initializer-list can initialize a base class using any
2536   //   name that denotes that base class type.
2537   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
2538 
2539   SourceRange InitRange = Init->getSourceRange();
2540   if (EllipsisLoc.isValid()) {
2541     // This is a pack expansion.
2542     if (!BaseType->containsUnexpandedParameterPack())  {
2543       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2544         << SourceRange(BaseLoc, InitRange.getEnd());
2545 
2546       EllipsisLoc = SourceLocation();
2547     }
2548   } else {
2549     // Check for any unexpanded parameter packs.
2550     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2551       return true;
2552 
2553     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2554       return true;
2555   }
2556 
2557   // Check for direct and virtual base classes.
2558   const CXXBaseSpecifier *DirectBaseSpec = 0;
2559   const CXXBaseSpecifier *VirtualBaseSpec = 0;
2560   if (!Dependent) {
2561     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2562                                        BaseType))
2563       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
2564 
2565     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2566                         VirtualBaseSpec);
2567 
2568     // C++ [base.class.init]p2:
2569     // Unless the mem-initializer-id names a nonstatic data member of the
2570     // constructor's class or a direct or virtual base of that class, the
2571     // mem-initializer is ill-formed.
2572     if (!DirectBaseSpec && !VirtualBaseSpec) {
2573       // If the class has any dependent bases, then it's possible that
2574       // one of those types will resolve to the same type as
2575       // BaseType. Therefore, just treat this as a dependent base
2576       // class initialization.  FIXME: Should we try to check the
2577       // initialization anyway? It seems odd.
2578       if (ClassDecl->hasAnyDependentBases())
2579         Dependent = true;
2580       else
2581         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2582           << BaseType << Context.getTypeDeclType(ClassDecl)
2583           << BaseTInfo->getTypeLoc().getLocalSourceRange();
2584     }
2585   }
2586 
2587   if (Dependent) {
2588     DiscardCleanupsInEvaluationContext();
2589 
2590     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2591                                             /*IsVirtual=*/false,
2592                                             InitRange.getBegin(), Init,
2593                                             InitRange.getEnd(), EllipsisLoc);
2594   }
2595 
2596   // C++ [base.class.init]p2:
2597   //   If a mem-initializer-id is ambiguous because it designates both
2598   //   a direct non-virtual base class and an inherited virtual base
2599   //   class, the mem-initializer is ill-formed.
2600   if (DirectBaseSpec && VirtualBaseSpec)
2601     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
2602       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2603 
2604   CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
2605   if (!BaseSpec)
2606     BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2607 
2608   // Initialize the base.
2609   bool InitList = true;
2610   Expr **Args = &Init;
2611   unsigned NumArgs = 1;
2612   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2613     InitList = false;
2614     Args = ParenList->getExprs();
2615     NumArgs = ParenList->getNumExprs();
2616   }
2617 
2618   InitializedEntity BaseEntity =
2619     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2620   InitializationKind Kind =
2621     InitList ? InitializationKind::CreateDirectList(BaseLoc)
2622              : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2623                                                 InitRange.getEnd());
2624   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2625   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
2626                                         MultiExprArg(Args, NumArgs), 0);
2627   if (BaseInit.isInvalid())
2628     return true;
2629 
2630   // C++11 [class.base.init]p7:
2631   //   The initialization of each base and member constitutes a
2632   //   full-expression.
2633   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
2634   if (BaseInit.isInvalid())
2635     return true;
2636 
2637   // If we are in a dependent context, template instantiation will
2638   // perform this type-checking again. Just save the arguments that we
2639   // received in a ParenListExpr.
2640   // FIXME: This isn't quite ideal, since our ASTs don't capture all
2641   // of the information that we have about the base
2642   // initializer. However, deconstructing the ASTs is a dicey process,
2643   // and this approach is far more likely to get the corner cases right.
2644   if (CurContext->isDependentContext())
2645     BaseInit = Owned(Init);
2646 
2647   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2648                                           BaseSpec->isVirtual(),
2649                                           InitRange.getBegin(),
2650                                           BaseInit.takeAs<Expr>(),
2651                                           InitRange.getEnd(), EllipsisLoc);
2652 }
2653 
2654 // Create a static_cast\<T&&>(expr).
2655 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2656   if (T.isNull()) T = E->getType();
2657   QualType TargetType = SemaRef.BuildReferenceType(
2658       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
2659   SourceLocation ExprLoc = E->getLocStart();
2660   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2661       TargetType, ExprLoc);
2662 
2663   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2664                                    SourceRange(ExprLoc, ExprLoc),
2665                                    E->getSourceRange()).take();
2666 }
2667 
2668 /// ImplicitInitializerKind - How an implicit base or member initializer should
2669 /// initialize its base or member.
2670 enum ImplicitInitializerKind {
2671   IIK_Default,
2672   IIK_Copy,
2673   IIK_Move,
2674   IIK_Inherit
2675 };
2676 
2677 static bool
2678 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2679                              ImplicitInitializerKind ImplicitInitKind,
2680                              CXXBaseSpecifier *BaseSpec,
2681                              bool IsInheritedVirtualBase,
2682                              CXXCtorInitializer *&CXXBaseInit) {
2683   InitializedEntity InitEntity
2684     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2685                                         IsInheritedVirtualBase);
2686 
2687   ExprResult BaseInit;
2688 
2689   switch (ImplicitInitKind) {
2690   case IIK_Inherit: {
2691     const CXXRecordDecl *Inherited =
2692         Constructor->getInheritedConstructor()->getParent();
2693     const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2694     if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2695       // C++11 [class.inhctor]p8:
2696       //   Each expression in the expression-list is of the form
2697       //   static_cast<T&&>(p), where p is the name of the corresponding
2698       //   constructor parameter and T is the declared type of p.
2699       SmallVector<Expr*, 16> Args;
2700       for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2701         ParmVarDecl *PD = Constructor->getParamDecl(I);
2702         ExprResult ArgExpr =
2703             SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2704                                      VK_LValue, SourceLocation());
2705         if (ArgExpr.isInvalid())
2706           return true;
2707         Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2708       }
2709 
2710       InitializationKind InitKind = InitializationKind::CreateDirect(
2711           Constructor->getLocation(), SourceLocation(), SourceLocation());
2712       InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2713                                      Args.data(), Args.size());
2714       BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
2715       break;
2716     }
2717   }
2718   // Fall through.
2719   case IIK_Default: {
2720     InitializationKind InitKind
2721       = InitializationKind::CreateDefault(Constructor->getLocation());
2722     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2723     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
2724     break;
2725   }
2726 
2727   case IIK_Move:
2728   case IIK_Copy: {
2729     bool Moving = ImplicitInitKind == IIK_Move;
2730     ParmVarDecl *Param = Constructor->getParamDecl(0);
2731     QualType ParamType = Param->getType().getNonReferenceType();
2732 
2733     Expr *CopyCtorArg =
2734       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2735                           SourceLocation(), Param, false,
2736                           Constructor->getLocation(), ParamType,
2737                           VK_LValue, 0);
2738 
2739     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2740 
2741     // Cast to the base class to avoid ambiguities.
2742     QualType ArgTy =
2743       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2744                                        ParamType.getQualifiers());
2745 
2746     if (Moving) {
2747       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2748     }
2749 
2750     CXXCastPath BasePath;
2751     BasePath.push_back(BaseSpec);
2752     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2753                                             CK_UncheckedDerivedToBase,
2754                                             Moving ? VK_XValue : VK_LValue,
2755                                             &BasePath).take();
2756 
2757     InitializationKind InitKind
2758       = InitializationKind::CreateDirect(Constructor->getLocation(),
2759                                          SourceLocation(), SourceLocation());
2760     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2761                                    &CopyCtorArg, 1);
2762     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
2763                                MultiExprArg(&CopyCtorArg, 1));
2764     break;
2765   }
2766   }
2767 
2768   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
2769   if (BaseInit.isInvalid())
2770     return true;
2771 
2772   CXXBaseInit =
2773     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2774                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2775                                                         SourceLocation()),
2776                                              BaseSpec->isVirtual(),
2777                                              SourceLocation(),
2778                                              BaseInit.takeAs<Expr>(),
2779                                              SourceLocation(),
2780                                              SourceLocation());
2781 
2782   return false;
2783 }
2784 
2785 static bool RefersToRValueRef(Expr *MemRef) {
2786   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2787   return Referenced->getType()->isRValueReferenceType();
2788 }
2789 
2790 static bool
2791 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2792                                ImplicitInitializerKind ImplicitInitKind,
2793                                FieldDecl *Field, IndirectFieldDecl *Indirect,
2794                                CXXCtorInitializer *&CXXMemberInit) {
2795   if (Field->isInvalidDecl())
2796     return true;
2797 
2798   SourceLocation Loc = Constructor->getLocation();
2799 
2800   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2801     bool Moving = ImplicitInitKind == IIK_Move;
2802     ParmVarDecl *Param = Constructor->getParamDecl(0);
2803     QualType ParamType = Param->getType().getNonReferenceType();
2804 
2805     // Suppress copying zero-width bitfields.
2806     if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2807       return false;
2808 
2809     Expr *MemberExprBase =
2810       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2811                           SourceLocation(), Param, false,
2812                           Loc, ParamType, VK_LValue, 0);
2813 
2814     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2815 
2816     if (Moving) {
2817       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2818     }
2819 
2820     // Build a reference to this field within the parameter.
2821     CXXScopeSpec SS;
2822     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2823                               Sema::LookupMemberName);
2824     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2825                                   : cast<ValueDecl>(Field), AS_public);
2826     MemberLookup.resolveKind();
2827     ExprResult CtorArg
2828       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
2829                                          ParamType, Loc,
2830                                          /*IsArrow=*/false,
2831                                          SS,
2832                                          /*TemplateKWLoc=*/SourceLocation(),
2833                                          /*FirstQualifierInScope=*/0,
2834                                          MemberLookup,
2835                                          /*TemplateArgs=*/0);
2836     if (CtorArg.isInvalid())
2837       return true;
2838 
2839     // C++11 [class.copy]p15:
2840     //   - if a member m has rvalue reference type T&&, it is direct-initialized
2841     //     with static_cast<T&&>(x.m);
2842     if (RefersToRValueRef(CtorArg.get())) {
2843       CtorArg = CastForMoving(SemaRef, CtorArg.take());
2844     }
2845 
2846     // When the field we are copying is an array, create index variables for
2847     // each dimension of the array. We use these index variables to subscript
2848     // the source array, and other clients (e.g., CodeGen) will perform the
2849     // necessary iteration with these index variables.
2850     SmallVector<VarDecl *, 4> IndexVariables;
2851     QualType BaseType = Field->getType();
2852     QualType SizeType = SemaRef.Context.getSizeType();
2853     bool InitializingArray = false;
2854     while (const ConstantArrayType *Array
2855                           = SemaRef.Context.getAsConstantArrayType(BaseType)) {
2856       InitializingArray = true;
2857       // Create the iteration variable for this array index.
2858       IdentifierInfo *IterationVarName = 0;
2859       {
2860         SmallString<8> Str;
2861         llvm::raw_svector_ostream OS(Str);
2862         OS << "__i" << IndexVariables.size();
2863         IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2864       }
2865       VarDecl *IterationVar
2866         = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
2867                           IterationVarName, SizeType,
2868                         SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
2869                           SC_None);
2870       IndexVariables.push_back(IterationVar);
2871 
2872       // Create a reference to the iteration variable.
2873       ExprResult IterationVarRef
2874         = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
2875       assert(!IterationVarRef.isInvalid() &&
2876              "Reference to invented variable cannot fail!");
2877       IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2878       assert(!IterationVarRef.isInvalid() &&
2879              "Conversion of invented variable cannot fail!");
2880 
2881       // Subscript the array with this iteration variable.
2882       CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
2883                                                         IterationVarRef.take(),
2884                                                         Loc);
2885       if (CtorArg.isInvalid())
2886         return true;
2887 
2888       BaseType = Array->getElementType();
2889     }
2890 
2891     // The array subscript expression is an lvalue, which is wrong for moving.
2892     if (Moving && InitializingArray)
2893       CtorArg = CastForMoving(SemaRef, CtorArg.take());
2894 
2895     // Construct the entity that we will be initializing. For an array, this
2896     // will be first element in the array, which may require several levels
2897     // of array-subscript entities.
2898     SmallVector<InitializedEntity, 4> Entities;
2899     Entities.reserve(1 + IndexVariables.size());
2900     if (Indirect)
2901       Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2902     else
2903       Entities.push_back(InitializedEntity::InitializeMember(Field));
2904     for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2905       Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2906                                                               0,
2907                                                               Entities.back()));
2908 
2909     // Direct-initialize to use the copy constructor.
2910     InitializationKind InitKind =
2911       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2912 
2913     Expr *CtorArgE = CtorArg.takeAs<Expr>();
2914     InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
2915                                    &CtorArgE, 1);
2916 
2917     ExprResult MemberInit
2918       = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
2919                         MultiExprArg(&CtorArgE, 1));
2920     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2921     if (MemberInit.isInvalid())
2922       return true;
2923 
2924     if (Indirect) {
2925       assert(IndexVariables.size() == 0 &&
2926              "Indirect field improperly initialized");
2927       CXXMemberInit
2928         = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2929                                                    Loc, Loc,
2930                                                    MemberInit.takeAs<Expr>(),
2931                                                    Loc);
2932     } else
2933       CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2934                                                  Loc, MemberInit.takeAs<Expr>(),
2935                                                  Loc,
2936                                                  IndexVariables.data(),
2937                                                  IndexVariables.size());
2938     return false;
2939   }
2940 
2941   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
2942          "Unhandled implicit init kind!");
2943 
2944   QualType FieldBaseElementType =
2945     SemaRef.Context.getBaseElementType(Field->getType());
2946 
2947   if (FieldBaseElementType->isRecordType()) {
2948     InitializedEntity InitEntity
2949       = Indirect? InitializedEntity::InitializeMember(Indirect)
2950                 : InitializedEntity::InitializeMember(Field);
2951     InitializationKind InitKind =
2952       InitializationKind::CreateDefault(Loc);
2953 
2954     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2955     ExprResult MemberInit =
2956       InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
2957 
2958     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2959     if (MemberInit.isInvalid())
2960       return true;
2961 
2962     if (Indirect)
2963       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2964                                                                Indirect, Loc,
2965                                                                Loc,
2966                                                                MemberInit.get(),
2967                                                                Loc);
2968     else
2969       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2970                                                                Field, Loc, Loc,
2971                                                                MemberInit.get(),
2972                                                                Loc);
2973     return false;
2974   }
2975 
2976   if (!Field->getParent()->isUnion()) {
2977     if (FieldBaseElementType->isReferenceType()) {
2978       SemaRef.Diag(Constructor->getLocation(),
2979                    diag::err_uninitialized_member_in_ctor)
2980       << (int)Constructor->isImplicit()
2981       << SemaRef.Context.getTagDeclType(Constructor->getParent())
2982       << 0 << Field->getDeclName();
2983       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2984       return true;
2985     }
2986 
2987     if (FieldBaseElementType.isConstQualified()) {
2988       SemaRef.Diag(Constructor->getLocation(),
2989                    diag::err_uninitialized_member_in_ctor)
2990       << (int)Constructor->isImplicit()
2991       << SemaRef.Context.getTagDeclType(Constructor->getParent())
2992       << 1 << Field->getDeclName();
2993       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2994       return true;
2995     }
2996   }
2997 
2998   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
2999       FieldBaseElementType->isObjCRetainableType() &&
3000       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3001       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
3002     // ARC:
3003     //   Default-initialize Objective-C pointers to NULL.
3004     CXXMemberInit
3005       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3006                                                  Loc, Loc,
3007                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3008                                                  Loc);
3009     return false;
3010   }
3011 
3012   // Nothing to initialize.
3013   CXXMemberInit = 0;
3014   return false;
3015 }
3016 
3017 namespace {
3018 struct BaseAndFieldInfo {
3019   Sema &S;
3020   CXXConstructorDecl *Ctor;
3021   bool AnyErrorsInInits;
3022   ImplicitInitializerKind IIK;
3023   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
3024   SmallVector<CXXCtorInitializer*, 8> AllToInit;
3025 
3026   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3027     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
3028     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3029     if (Generated && Ctor->isCopyConstructor())
3030       IIK = IIK_Copy;
3031     else if (Generated && Ctor->isMoveConstructor())
3032       IIK = IIK_Move;
3033     else if (Ctor->getInheritedConstructor())
3034       IIK = IIK_Inherit;
3035     else
3036       IIK = IIK_Default;
3037   }
3038 
3039   bool isImplicitCopyOrMove() const {
3040     switch (IIK) {
3041     case IIK_Copy:
3042     case IIK_Move:
3043       return true;
3044 
3045     case IIK_Default:
3046     case IIK_Inherit:
3047       return false;
3048     }
3049 
3050     llvm_unreachable("Invalid ImplicitInitializerKind!");
3051   }
3052 
3053   bool addFieldInitializer(CXXCtorInitializer *Init) {
3054     AllToInit.push_back(Init);
3055 
3056     // Check whether this initializer makes the field "used".
3057     if (Init->getInit()->HasSideEffects(S.Context))
3058       S.UnusedPrivateFields.remove(Init->getAnyMember());
3059 
3060     return false;
3061   }
3062 };
3063 }
3064 
3065 /// \brief Determine whether the given indirect field declaration is somewhere
3066 /// within an anonymous union.
3067 static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3068   for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3069                                       CEnd = F->chain_end();
3070        C != CEnd; ++C)
3071     if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3072       if (Record->isUnion())
3073         return true;
3074 
3075   return false;
3076 }
3077 
3078 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
3079 /// array type.
3080 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3081   if (T->isIncompleteArrayType())
3082     return true;
3083 
3084   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3085     if (!ArrayT->getSize())
3086       return true;
3087 
3088     T = ArrayT->getElementType();
3089   }
3090 
3091   return false;
3092 }
3093 
3094 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
3095                                     FieldDecl *Field,
3096                                     IndirectFieldDecl *Indirect = 0) {
3097 
3098   // Overwhelmingly common case: we have a direct initializer for this field.
3099   if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3100     return Info.addFieldInitializer(Init);
3101 
3102   // C++11 [class.base.init]p8: if the entity is a non-static data member that
3103   // has a brace-or-equal-initializer, the entity is initialized as specified
3104   // in [dcl.init].
3105   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
3106     Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3107                                            Info.Ctor->getLocation(), Field);
3108     CXXCtorInitializer *Init;
3109     if (Indirect)
3110       Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3111                                                       SourceLocation(),
3112                                                       SourceLocation(), DIE,
3113                                                       SourceLocation());
3114     else
3115       Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3116                                                       SourceLocation(),
3117                                                       SourceLocation(), DIE,
3118                                                       SourceLocation());
3119     return Info.addFieldInitializer(Init);
3120   }
3121 
3122   // Don't build an implicit initializer for union members if none was
3123   // explicitly specified.
3124   if (Field->getParent()->isUnion() ||
3125       (Indirect && isWithinAnonymousUnion(Indirect)))
3126     return false;
3127 
3128   // Don't initialize incomplete or zero-length arrays.
3129   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3130     return false;
3131 
3132   // Don't try to build an implicit initializer if there were semantic
3133   // errors in any of the initializers (and therefore we might be
3134   // missing some that the user actually wrote).
3135   if (Info.AnyErrorsInInits || Field->isInvalidDecl())
3136     return false;
3137 
3138   CXXCtorInitializer *Init = 0;
3139   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3140                                      Indirect, Init))
3141     return true;
3142 
3143   if (!Init)
3144     return false;
3145 
3146   return Info.addFieldInitializer(Init);
3147 }
3148 
3149 bool
3150 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3151                                CXXCtorInitializer *Initializer) {
3152   assert(Initializer->isDelegatingInitializer());
3153   Constructor->setNumCtorInitializers(1);
3154   CXXCtorInitializer **initializer =
3155     new (Context) CXXCtorInitializer*[1];
3156   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3157   Constructor->setCtorInitializers(initializer);
3158 
3159   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
3160     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
3161     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3162   }
3163 
3164   DelegatingCtorDecls.push_back(Constructor);
3165 
3166   return false;
3167 }
3168 
3169 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3170                                ArrayRef<CXXCtorInitializer *> Initializers) {
3171   if (Constructor->isDependentContext()) {
3172     // Just store the initializers as written, they will be checked during
3173     // instantiation.
3174     if (!Initializers.empty()) {
3175       Constructor->setNumCtorInitializers(Initializers.size());
3176       CXXCtorInitializer **baseOrMemberInitializers =
3177         new (Context) CXXCtorInitializer*[Initializers.size()];
3178       memcpy(baseOrMemberInitializers, Initializers.data(),
3179              Initializers.size() * sizeof(CXXCtorInitializer*));
3180       Constructor->setCtorInitializers(baseOrMemberInitializers);
3181     }
3182 
3183     // Let template instantiation know whether we had errors.
3184     if (AnyErrors)
3185       Constructor->setInvalidDecl();
3186 
3187     return false;
3188   }
3189 
3190   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
3191 
3192   // We need to build the initializer AST according to order of construction
3193   // and not what user specified in the Initializers list.
3194   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
3195   if (!ClassDecl)
3196     return true;
3197 
3198   bool HadError = false;
3199 
3200   for (unsigned i = 0; i < Initializers.size(); i++) {
3201     CXXCtorInitializer *Member = Initializers[i];
3202 
3203     if (Member->isBaseInitializer())
3204       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
3205     else
3206       Info.AllBaseFields[Member->getAnyMember()] = Member;
3207   }
3208 
3209   // Keep track of the direct virtual bases.
3210   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3211   for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3212        E = ClassDecl->bases_end(); I != E; ++I) {
3213     if (I->isVirtual())
3214       DirectVBases.insert(I);
3215   }
3216 
3217   // Push virtual bases before others.
3218   for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3219        E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3220 
3221     if (CXXCtorInitializer *Value
3222         = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3223       Info.AllToInit.push_back(Value);
3224     } else if (!AnyErrors) {
3225       bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
3226       CXXCtorInitializer *CXXBaseInit;
3227       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3228                                        VBase, IsInheritedVirtualBase,
3229                                        CXXBaseInit)) {
3230         HadError = true;
3231         continue;
3232       }
3233 
3234       Info.AllToInit.push_back(CXXBaseInit);
3235     }
3236   }
3237 
3238   // Non-virtual bases.
3239   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3240        E = ClassDecl->bases_end(); Base != E; ++Base) {
3241     // Virtuals are in the virtual base list and already constructed.
3242     if (Base->isVirtual())
3243       continue;
3244 
3245     if (CXXCtorInitializer *Value
3246           = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3247       Info.AllToInit.push_back(Value);
3248     } else if (!AnyErrors) {
3249       CXXCtorInitializer *CXXBaseInit;
3250       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3251                                        Base, /*IsInheritedVirtualBase=*/false,
3252                                        CXXBaseInit)) {
3253         HadError = true;
3254         continue;
3255       }
3256 
3257       Info.AllToInit.push_back(CXXBaseInit);
3258     }
3259   }
3260 
3261   // Fields.
3262   for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3263                                MemEnd = ClassDecl->decls_end();
3264        Mem != MemEnd; ++Mem) {
3265     if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
3266       // C++ [class.bit]p2:
3267       //   A declaration for a bit-field that omits the identifier declares an
3268       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
3269       //   initialized.
3270       if (F->isUnnamedBitfield())
3271         continue;
3272 
3273       // If we're not generating the implicit copy/move constructor, then we'll
3274       // handle anonymous struct/union fields based on their individual
3275       // indirect fields.
3276       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
3277         continue;
3278 
3279       if (CollectFieldInitializer(*this, Info, F))
3280         HadError = true;
3281       continue;
3282     }
3283 
3284     // Beyond this point, we only consider default initialization.
3285     if (Info.isImplicitCopyOrMove())
3286       continue;
3287 
3288     if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3289       if (F->getType()->isIncompleteArrayType()) {
3290         assert(ClassDecl->hasFlexibleArrayMember() &&
3291                "Incomplete array type is not valid");
3292         continue;
3293       }
3294 
3295       // Initialize each field of an anonymous struct individually.
3296       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3297         HadError = true;
3298 
3299       continue;
3300     }
3301   }
3302 
3303   unsigned NumInitializers = Info.AllToInit.size();
3304   if (NumInitializers > 0) {
3305     Constructor->setNumCtorInitializers(NumInitializers);
3306     CXXCtorInitializer **baseOrMemberInitializers =
3307       new (Context) CXXCtorInitializer*[NumInitializers];
3308     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
3309            NumInitializers * sizeof(CXXCtorInitializer*));
3310     Constructor->setCtorInitializers(baseOrMemberInitializers);
3311 
3312     // Constructors implicitly reference the base and member
3313     // destructors.
3314     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3315                                            Constructor->getParent());
3316   }
3317 
3318   return HadError;
3319 }
3320 
3321 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
3322   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
3323     const RecordDecl *RD = RT->getDecl();
3324     if (RD->isAnonymousStructOrUnion()) {
3325       for (RecordDecl::field_iterator Field = RD->field_begin(),
3326           E = RD->field_end(); Field != E; ++Field)
3327         PopulateKeysForFields(*Field, IdealInits);
3328       return;
3329     }
3330   }
3331   IdealInits.push_back(Field);
3332 }
3333 
3334 static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3335   return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
3336 }
3337 
3338 static void *GetKeyForMember(ASTContext &Context,
3339                              CXXCtorInitializer *Member) {
3340   if (!Member->isAnyMemberInitializer())
3341     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
3342 
3343   return Member->getAnyMember();
3344 }
3345 
3346 static void DiagnoseBaseOrMemInitializerOrder(
3347     Sema &SemaRef, const CXXConstructorDecl *Constructor,
3348     ArrayRef<CXXCtorInitializer *> Inits) {
3349   if (Constructor->getDeclContext()->isDependentContext())
3350     return;
3351 
3352   // Don't check initializers order unless the warning is enabled at the
3353   // location of at least one initializer.
3354   bool ShouldCheckOrder = false;
3355   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3356     CXXCtorInitializer *Init = Inits[InitIndex];
3357     if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3358                                          Init->getSourceLocation())
3359           != DiagnosticsEngine::Ignored) {
3360       ShouldCheckOrder = true;
3361       break;
3362     }
3363   }
3364   if (!ShouldCheckOrder)
3365     return;
3366 
3367   // Build the list of bases and members in the order that they'll
3368   // actually be initialized.  The explicit initializers should be in
3369   // this same order but may be missing things.
3370   SmallVector<const void*, 32> IdealInitKeys;
3371 
3372   const CXXRecordDecl *ClassDecl = Constructor->getParent();
3373 
3374   // 1. Virtual bases.
3375   for (CXXRecordDecl::base_class_const_iterator VBase =
3376        ClassDecl->vbases_begin(),
3377        E = ClassDecl->vbases_end(); VBase != E; ++VBase)
3378     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
3379 
3380   // 2. Non-virtual bases.
3381   for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
3382        E = ClassDecl->bases_end(); Base != E; ++Base) {
3383     if (Base->isVirtual())
3384       continue;
3385     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
3386   }
3387 
3388   // 3. Direct fields.
3389   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3390        E = ClassDecl->field_end(); Field != E; ++Field) {
3391     if (Field->isUnnamedBitfield())
3392       continue;
3393 
3394     PopulateKeysForFields(*Field, IdealInitKeys);
3395   }
3396 
3397   unsigned NumIdealInits = IdealInitKeys.size();
3398   unsigned IdealIndex = 0;
3399 
3400   CXXCtorInitializer *PrevInit = 0;
3401   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3402     CXXCtorInitializer *Init = Inits[InitIndex];
3403     void *InitKey = GetKeyForMember(SemaRef.Context, Init);
3404 
3405     // Scan forward to try to find this initializer in the idealized
3406     // initializers list.
3407     for (; IdealIndex != NumIdealInits; ++IdealIndex)
3408       if (InitKey == IdealInitKeys[IdealIndex])
3409         break;
3410 
3411     // If we didn't find this initializer, it must be because we
3412     // scanned past it on a previous iteration.  That can only
3413     // happen if we're out of order;  emit a warning.
3414     if (IdealIndex == NumIdealInits && PrevInit) {
3415       Sema::SemaDiagnosticBuilder D =
3416         SemaRef.Diag(PrevInit->getSourceLocation(),
3417                      diag::warn_initializer_out_of_order);
3418 
3419       if (PrevInit->isAnyMemberInitializer())
3420         D << 0 << PrevInit->getAnyMember()->getDeclName();
3421       else
3422         D << 1 << PrevInit->getTypeSourceInfo()->getType();
3423 
3424       if (Init->isAnyMemberInitializer())
3425         D << 0 << Init->getAnyMember()->getDeclName();
3426       else
3427         D << 1 << Init->getTypeSourceInfo()->getType();
3428 
3429       // Move back to the initializer's location in the ideal list.
3430       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3431         if (InitKey == IdealInitKeys[IdealIndex])
3432           break;
3433 
3434       assert(IdealIndex != NumIdealInits &&
3435              "initializer not found in initializer list");
3436     }
3437 
3438     PrevInit = Init;
3439   }
3440 }
3441 
3442 namespace {
3443 bool CheckRedundantInit(Sema &S,
3444                         CXXCtorInitializer *Init,
3445                         CXXCtorInitializer *&PrevInit) {
3446   if (!PrevInit) {
3447     PrevInit = Init;
3448     return false;
3449   }
3450 
3451   if (FieldDecl *Field = Init->getAnyMember())
3452     S.Diag(Init->getSourceLocation(),
3453            diag::err_multiple_mem_initialization)
3454       << Field->getDeclName()
3455       << Init->getSourceRange();
3456   else {
3457     const Type *BaseClass = Init->getBaseClass();
3458     assert(BaseClass && "neither field nor base");
3459     S.Diag(Init->getSourceLocation(),
3460            diag::err_multiple_base_initialization)
3461       << QualType(BaseClass, 0)
3462       << Init->getSourceRange();
3463   }
3464   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3465     << 0 << PrevInit->getSourceRange();
3466 
3467   return true;
3468 }
3469 
3470 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
3471 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3472 
3473 bool CheckRedundantUnionInit(Sema &S,
3474                              CXXCtorInitializer *Init,
3475                              RedundantUnionMap &Unions) {
3476   FieldDecl *Field = Init->getAnyMember();
3477   RecordDecl *Parent = Field->getParent();
3478   NamedDecl *Child = Field;
3479 
3480   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
3481     if (Parent->isUnion()) {
3482       UnionEntry &En = Unions[Parent];
3483       if (En.first && En.first != Child) {
3484         S.Diag(Init->getSourceLocation(),
3485                diag::err_multiple_mem_union_initialization)
3486           << Field->getDeclName()
3487           << Init->getSourceRange();
3488         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3489           << 0 << En.second->getSourceRange();
3490         return true;
3491       }
3492       if (!En.first) {
3493         En.first = Child;
3494         En.second = Init;
3495       }
3496       if (!Parent->isAnonymousStructOrUnion())
3497         return false;
3498     }
3499 
3500     Child = Parent;
3501     Parent = cast<RecordDecl>(Parent->getDeclContext());
3502   }
3503 
3504   return false;
3505 }
3506 }
3507 
3508 /// ActOnMemInitializers - Handle the member initializers for a constructor.
3509 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
3510                                 SourceLocation ColonLoc,
3511                                 ArrayRef<CXXCtorInitializer*> MemInits,
3512                                 bool AnyErrors) {
3513   if (!ConstructorDecl)
3514     return;
3515 
3516   AdjustDeclIfTemplate(ConstructorDecl);
3517 
3518   CXXConstructorDecl *Constructor
3519     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
3520 
3521   if (!Constructor) {
3522     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3523     return;
3524   }
3525 
3526   // Mapping for the duplicate initializers check.
3527   // For member initializers, this is keyed with a FieldDecl*.
3528   // For base initializers, this is keyed with a Type*.
3529   llvm::DenseMap<void*, CXXCtorInitializer *> Members;
3530 
3531   // Mapping for the inconsistent anonymous-union initializers check.
3532   RedundantUnionMap MemberUnions;
3533 
3534   bool HadError = false;
3535   for (unsigned i = 0; i < MemInits.size(); i++) {
3536     CXXCtorInitializer *Init = MemInits[i];
3537 
3538     // Set the source order index.
3539     Init->setSourceOrder(i);
3540 
3541     if (Init->isAnyMemberInitializer()) {
3542       FieldDecl *Field = Init->getAnyMember();
3543       if (CheckRedundantInit(*this, Init, Members[Field]) ||
3544           CheckRedundantUnionInit(*this, Init, MemberUnions))
3545         HadError = true;
3546     } else if (Init->isBaseInitializer()) {
3547       void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3548       if (CheckRedundantInit(*this, Init, Members[Key]))
3549         HadError = true;
3550     } else {
3551       assert(Init->isDelegatingInitializer());
3552       // This must be the only initializer
3553       if (MemInits.size() != 1) {
3554         Diag(Init->getSourceLocation(),
3555              diag::err_delegating_initializer_alone)
3556           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
3557         // We will treat this as being the only initializer.
3558       }
3559       SetDelegatingInitializer(Constructor, MemInits[i]);
3560       // Return immediately as the initializer is set.
3561       return;
3562     }
3563   }
3564 
3565   if (HadError)
3566     return;
3567 
3568   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
3569 
3570   SetCtorInitializers(Constructor, AnyErrors, MemInits);
3571 }
3572 
3573 void
3574 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3575                                              CXXRecordDecl *ClassDecl) {
3576   // Ignore dependent contexts. Also ignore unions, since their members never
3577   // have destructors implicitly called.
3578   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
3579     return;
3580 
3581   // FIXME: all the access-control diagnostics are positioned on the
3582   // field/base declaration.  That's probably good; that said, the
3583   // user might reasonably want to know why the destructor is being
3584   // emitted, and we currently don't say.
3585 
3586   // Non-static data members.
3587   for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3588        E = ClassDecl->field_end(); I != E; ++I) {
3589     FieldDecl *Field = *I;
3590     if (Field->isInvalidDecl())
3591       continue;
3592 
3593     // Don't destroy incomplete or zero-length arrays.
3594     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3595       continue;
3596 
3597     QualType FieldType = Context.getBaseElementType(Field->getType());
3598 
3599     const RecordType* RT = FieldType->getAs<RecordType>();
3600     if (!RT)
3601       continue;
3602 
3603     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3604     if (FieldClassDecl->isInvalidDecl())
3605       continue;
3606     if (FieldClassDecl->hasIrrelevantDestructor())
3607       continue;
3608     // The destructor for an implicit anonymous union member is never invoked.
3609     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3610       continue;
3611 
3612     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
3613     assert(Dtor && "No dtor found for FieldClassDecl!");
3614     CheckDestructorAccess(Field->getLocation(), Dtor,
3615                           PDiag(diag::err_access_dtor_field)
3616                             << Field->getDeclName()
3617                             << FieldType);
3618 
3619     MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3620     DiagnoseUseOfDecl(Dtor, Location);
3621   }
3622 
3623   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3624 
3625   // Bases.
3626   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3627        E = ClassDecl->bases_end(); Base != E; ++Base) {
3628     // Bases are always records in a well-formed non-dependent class.
3629     const RecordType *RT = Base->getType()->getAs<RecordType>();
3630 
3631     // Remember direct virtual bases.
3632     if (Base->isVirtual())
3633       DirectVirtualBases.insert(RT);
3634 
3635     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3636     // If our base class is invalid, we probably can't get its dtor anyway.
3637     if (BaseClassDecl->isInvalidDecl())
3638       continue;
3639     if (BaseClassDecl->hasIrrelevantDestructor())
3640       continue;
3641 
3642     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3643     assert(Dtor && "No dtor found for BaseClassDecl!");
3644 
3645     // FIXME: caret should be on the start of the class name
3646     CheckDestructorAccess(Base->getLocStart(), Dtor,
3647                           PDiag(diag::err_access_dtor_base)
3648                             << Base->getType()
3649                             << Base->getSourceRange(),
3650                           Context.getTypeDeclType(ClassDecl));
3651 
3652     MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3653     DiagnoseUseOfDecl(Dtor, Location);
3654   }
3655 
3656   // Virtual bases.
3657   for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3658        E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3659 
3660     // Bases are always records in a well-formed non-dependent class.
3661     const RecordType *RT = VBase->getType()->castAs<RecordType>();
3662 
3663     // Ignore direct virtual bases.
3664     if (DirectVirtualBases.count(RT))
3665       continue;
3666 
3667     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3668     // If our base class is invalid, we probably can't get its dtor anyway.
3669     if (BaseClassDecl->isInvalidDecl())
3670       continue;
3671     if (BaseClassDecl->hasIrrelevantDestructor())
3672       continue;
3673 
3674     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3675     assert(Dtor && "No dtor found for BaseClassDecl!");
3676     CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
3677                           PDiag(diag::err_access_dtor_vbase)
3678                             << VBase->getType(),
3679                           Context.getTypeDeclType(ClassDecl));
3680 
3681     MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3682     DiagnoseUseOfDecl(Dtor, Location);
3683   }
3684 }
3685 
3686 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
3687   if (!CDtorDecl)
3688     return;
3689 
3690   if (CXXConstructorDecl *Constructor
3691       = dyn_cast<CXXConstructorDecl>(CDtorDecl))
3692     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
3693 }
3694 
3695 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3696                                   unsigned DiagID, AbstractDiagSelID SelID) {
3697   class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3698     unsigned DiagID;
3699     AbstractDiagSelID SelID;
3700 
3701   public:
3702     NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3703       : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3704 
3705     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
3706       if (Suppressed) return;
3707       if (SelID == -1)
3708         S.Diag(Loc, DiagID) << T;
3709       else
3710         S.Diag(Loc, DiagID) << SelID << T;
3711     }
3712   } Diagnoser(DiagID, SelID);
3713 
3714   return RequireNonAbstractType(Loc, T, Diagnoser);
3715 }
3716 
3717 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3718                                   TypeDiagnoser &Diagnoser) {
3719   if (!getLangOpts().CPlusPlus)
3720     return false;
3721 
3722   if (const ArrayType *AT = Context.getAsArrayType(T))
3723     return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
3724 
3725   if (const PointerType *PT = T->getAs<PointerType>()) {
3726     // Find the innermost pointer type.
3727     while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
3728       PT = T;
3729 
3730     if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
3731       return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
3732   }
3733 
3734   const RecordType *RT = T->getAs<RecordType>();
3735   if (!RT)
3736     return false;
3737 
3738   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3739 
3740   // We can't answer whether something is abstract until it has a
3741   // definition.  If it's currently being defined, we'll walk back
3742   // over all the declarations when we have a full definition.
3743   const CXXRecordDecl *Def = RD->getDefinition();
3744   if (!Def || Def->isBeingDefined())
3745     return false;
3746 
3747   if (!RD->isAbstract())
3748     return false;
3749 
3750   Diagnoser.diagnose(*this, Loc, T);
3751   DiagnoseAbstractType(RD);
3752 
3753   return true;
3754 }
3755 
3756 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3757   // Check if we've already emitted the list of pure virtual functions
3758   // for this class.
3759   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
3760     return;
3761 
3762   CXXFinalOverriderMap FinalOverriders;
3763   RD->getFinalOverriders(FinalOverriders);
3764 
3765   // Keep a set of seen pure methods so we won't diagnose the same method
3766   // more than once.
3767   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3768 
3769   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3770                                    MEnd = FinalOverriders.end();
3771        M != MEnd;
3772        ++M) {
3773     for (OverridingMethods::iterator SO = M->second.begin(),
3774                                   SOEnd = M->second.end();
3775          SO != SOEnd; ++SO) {
3776       // C++ [class.abstract]p4:
3777       //   A class is abstract if it contains or inherits at least one
3778       //   pure virtual function for which the final overrider is pure
3779       //   virtual.
3780 
3781       //
3782       if (SO->second.size() != 1)
3783         continue;
3784 
3785       if (!SO->second.front().Method->isPure())
3786         continue;
3787 
3788       if (!SeenPureMethods.insert(SO->second.front().Method))
3789         continue;
3790 
3791       Diag(SO->second.front().Method->getLocation(),
3792            diag::note_pure_virtual_function)
3793         << SO->second.front().Method->getDeclName() << RD->getDeclName();
3794     }
3795   }
3796 
3797   if (!PureVirtualClassDiagSet)
3798     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3799   PureVirtualClassDiagSet->insert(RD);
3800 }
3801 
3802 namespace {
3803 struct AbstractUsageInfo {
3804   Sema &S;
3805   CXXRecordDecl *Record;
3806   CanQualType AbstractType;
3807   bool Invalid;
3808 
3809   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3810     : S(S), Record(Record),
3811       AbstractType(S.Context.getCanonicalType(
3812                    S.Context.getTypeDeclType(Record))),
3813       Invalid(false) {}
3814 
3815   void DiagnoseAbstractType() {
3816     if (Invalid) return;
3817     S.DiagnoseAbstractType(Record);
3818     Invalid = true;
3819   }
3820 
3821   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3822 };
3823 
3824 struct CheckAbstractUsage {
3825   AbstractUsageInfo &Info;
3826   const NamedDecl *Ctx;
3827 
3828   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3829     : Info(Info), Ctx(Ctx) {}
3830 
3831   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3832     switch (TL.getTypeLocClass()) {
3833 #define ABSTRACT_TYPELOC(CLASS, PARENT)
3834 #define TYPELOC(CLASS, PARENT) \
3835     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
3836 #include "clang/AST/TypeLocNodes.def"
3837     }
3838   }
3839 
3840   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3841     Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3842     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3843       if (!TL.getArg(I))
3844         continue;
3845 
3846       TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3847       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
3848     }
3849   }
3850 
3851   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3852     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3853   }
3854 
3855   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3856     // Visit the type parameters from a permissive context.
3857     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3858       TemplateArgumentLoc TAL = TL.getArgLoc(I);
3859       if (TAL.getArgument().getKind() == TemplateArgument::Type)
3860         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3861           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3862       // TODO: other template argument types?
3863     }
3864   }
3865 
3866   // Visit pointee types from a permissive context.
3867 #define CheckPolymorphic(Type) \
3868   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3869     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3870   }
3871   CheckPolymorphic(PointerTypeLoc)
3872   CheckPolymorphic(ReferenceTypeLoc)
3873   CheckPolymorphic(MemberPointerTypeLoc)
3874   CheckPolymorphic(BlockPointerTypeLoc)
3875   CheckPolymorphic(AtomicTypeLoc)
3876 
3877   /// Handle all the types we haven't given a more specific
3878   /// implementation for above.
3879   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3880     // Every other kind of type that we haven't called out already
3881     // that has an inner type is either (1) sugar or (2) contains that
3882     // inner type in some way as a subobject.
3883     if (TypeLoc Next = TL.getNextTypeLoc())
3884       return Visit(Next, Sel);
3885 
3886     // If there's no inner type and we're in a permissive context,
3887     // don't diagnose.
3888     if (Sel == Sema::AbstractNone) return;
3889 
3890     // Check whether the type matches the abstract type.
3891     QualType T = TL.getType();
3892     if (T->isArrayType()) {
3893       Sel = Sema::AbstractArrayType;
3894       T = Info.S.Context.getBaseElementType(T);
3895     }
3896     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3897     if (CT != Info.AbstractType) return;
3898 
3899     // It matched; do some magic.
3900     if (Sel == Sema::AbstractArrayType) {
3901       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3902         << T << TL.getSourceRange();
3903     } else {
3904       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3905         << Sel << T << TL.getSourceRange();
3906     }
3907     Info.DiagnoseAbstractType();
3908   }
3909 };
3910 
3911 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3912                                   Sema::AbstractDiagSelID Sel) {
3913   CheckAbstractUsage(*this, D).Visit(TL, Sel);
3914 }
3915 
3916 }
3917 
3918 /// Check for invalid uses of an abstract type in a method declaration.
3919 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3920                                     CXXMethodDecl *MD) {
3921   // No need to do the check on definitions, which require that
3922   // the return/param types be complete.
3923   if (MD->doesThisDeclarationHaveABody())
3924     return;
3925 
3926   // For safety's sake, just ignore it if we don't have type source
3927   // information.  This should never happen for non-implicit methods,
3928   // but...
3929   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3930     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3931 }
3932 
3933 /// Check for invalid uses of an abstract type within a class definition.
3934 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3935                                     CXXRecordDecl *RD) {
3936   for (CXXRecordDecl::decl_iterator
3937          I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3938     Decl *D = *I;
3939     if (D->isImplicit()) continue;
3940 
3941     // Methods and method templates.
3942     if (isa<CXXMethodDecl>(D)) {
3943       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3944     } else if (isa<FunctionTemplateDecl>(D)) {
3945       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3946       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3947 
3948     // Fields and static variables.
3949     } else if (isa<FieldDecl>(D)) {
3950       FieldDecl *FD = cast<FieldDecl>(D);
3951       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3952         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3953     } else if (isa<VarDecl>(D)) {
3954       VarDecl *VD = cast<VarDecl>(D);
3955       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3956         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3957 
3958     // Nested classes and class templates.
3959     } else if (isa<CXXRecordDecl>(D)) {
3960       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3961     } else if (isa<ClassTemplateDecl>(D)) {
3962       CheckAbstractClassUsage(Info,
3963                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3964     }
3965   }
3966 }
3967 
3968 /// \brief Perform semantic checks on a class definition that has been
3969 /// completing, introducing implicitly-declared members, checking for
3970 /// abstract types, etc.
3971 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
3972   if (!Record)
3973     return;
3974 
3975   if (Record->isAbstract() && !Record->isInvalidDecl()) {
3976     AbstractUsageInfo Info(*this, Record);
3977     CheckAbstractClassUsage(Info, Record);
3978   }
3979 
3980   // If this is not an aggregate type and has no user-declared constructor,
3981   // complain about any non-static data members of reference or const scalar
3982   // type, since they will never get initializers.
3983   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3984       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3985       !Record->isLambda()) {
3986     bool Complained = false;
3987     for (RecordDecl::field_iterator F = Record->field_begin(),
3988                                  FEnd = Record->field_end();
3989          F != FEnd; ++F) {
3990       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
3991         continue;
3992 
3993       if (F->getType()->isReferenceType() ||
3994           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
3995         if (!Complained) {
3996           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3997             << Record->getTagKind() << Record;
3998           Complained = true;
3999         }
4000 
4001         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4002           << F->getType()->isReferenceType()
4003           << F->getDeclName();
4004       }
4005     }
4006   }
4007 
4008   if (Record->isDynamicClass() && !Record->isDependentType())
4009     DynamicClasses.push_back(Record);
4010 
4011   if (Record->getIdentifier()) {
4012     // C++ [class.mem]p13:
4013     //   If T is the name of a class, then each of the following shall have a
4014     //   name different from T:
4015     //     - every member of every anonymous union that is a member of class T.
4016     //
4017     // C++ [class.mem]p14:
4018     //   In addition, if class T has a user-declared constructor (12.1), every
4019     //   non-static data member of class T shall have a name different from T.
4020     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4021     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4022          ++I) {
4023       NamedDecl *D = *I;
4024       if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4025           isa<IndirectFieldDecl>(D)) {
4026         Diag(D->getLocation(), diag::err_member_name_of_class)
4027           << D->getDeclName();
4028         break;
4029       }
4030     }
4031   }
4032 
4033   // Warn if the class has virtual methods but non-virtual public destructor.
4034   if (Record->isPolymorphic() && !Record->isDependentType()) {
4035     CXXDestructorDecl *dtor = Record->getDestructor();
4036     if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
4037       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4038            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4039   }
4040 
4041   if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
4042     Diag(Record->getLocation(), diag::warn_abstract_final_class);
4043     DiagnoseAbstractType(Record);
4044   }
4045 
4046   if (!Record->isDependentType()) {
4047     for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4048                                      MEnd = Record->method_end();
4049          M != MEnd; ++M) {
4050       // See if a method overloads virtual methods in a base
4051       // class without overriding any.
4052       if (!M->isStatic())
4053         DiagnoseHiddenVirtualMethods(Record, *M);
4054 
4055       // Check whether the explicitly-defaulted special members are valid.
4056       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4057         CheckExplicitlyDefaultedSpecialMember(*M);
4058 
4059       // For an explicitly defaulted or deleted special member, we defer
4060       // determining triviality until the class is complete. That time is now!
4061       if (!M->isImplicit() && !M->isUserProvided()) {
4062         CXXSpecialMember CSM = getSpecialMember(*M);
4063         if (CSM != CXXInvalid) {
4064           M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4065 
4066           // Inform the class that we've finished declaring this member.
4067           Record->finishedDefaultedOrDeletedMember(*M);
4068         }
4069       }
4070     }
4071   }
4072 
4073   // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4074   // function that is not a constructor declares that member function to be
4075   // const. [...] The class of which that function is a member shall be
4076   // a literal type.
4077   //
4078   // If the class has virtual bases, any constexpr members will already have
4079   // been diagnosed by the checks performed on the member declaration, so
4080   // suppress this (less useful) diagnostic.
4081   //
4082   // We delay this until we know whether an explicitly-defaulted (or deleted)
4083   // destructor for the class is trivial.
4084   if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
4085       !Record->isLiteral() && !Record->getNumVBases()) {
4086     for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4087                                      MEnd = Record->method_end();
4088          M != MEnd; ++M) {
4089       if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4090         switch (Record->getTemplateSpecializationKind()) {
4091         case TSK_ImplicitInstantiation:
4092         case TSK_ExplicitInstantiationDeclaration:
4093         case TSK_ExplicitInstantiationDefinition:
4094           // If a template instantiates to a non-literal type, but its members
4095           // instantiate to constexpr functions, the template is technically
4096           // ill-formed, but we allow it for sanity.
4097           continue;
4098 
4099         case TSK_Undeclared:
4100         case TSK_ExplicitSpecialization:
4101           RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4102                              diag::err_constexpr_method_non_literal);
4103           break;
4104         }
4105 
4106         // Only produce one error per class.
4107         break;
4108       }
4109     }
4110   }
4111 
4112   // Declare inheriting constructors. We do this eagerly here because:
4113   // - The standard requires an eager diagnostic for conflicting inheriting
4114   //   constructors from different classes.
4115   // - The lazy declaration of the other implicit constructors is so as to not
4116   //   waste space and performance on classes that are not meant to be
4117   //   instantiated (e.g. meta-functions). This doesn't apply to classes that
4118   //   have inheriting constructors.
4119   DeclareInheritingConstructors(Record);
4120 }
4121 
4122 /// Is the special member function which would be selected to perform the
4123 /// specified operation on the specified class type a constexpr constructor?
4124 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4125                                      Sema::CXXSpecialMember CSM,
4126                                      bool ConstArg) {
4127   Sema::SpecialMemberOverloadResult *SMOR =
4128       S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4129                             false, false, false, false);
4130   if (!SMOR || !SMOR->getMethod())
4131     // A constructor we wouldn't select can't be "involved in initializing"
4132     // anything.
4133     return true;
4134   return SMOR->getMethod()->isConstexpr();
4135 }
4136 
4137 /// Determine whether the specified special member function would be constexpr
4138 /// if it were implicitly defined.
4139 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4140                                               Sema::CXXSpecialMember CSM,
4141                                               bool ConstArg) {
4142   if (!S.getLangOpts().CPlusPlus11)
4143     return false;
4144 
4145   // C++11 [dcl.constexpr]p4:
4146   // In the definition of a constexpr constructor [...]
4147   switch (CSM) {
4148   case Sema::CXXDefaultConstructor:
4149     // Since default constructor lookup is essentially trivial (and cannot
4150     // involve, for instance, template instantiation), we compute whether a
4151     // defaulted default constructor is constexpr directly within CXXRecordDecl.
4152     //
4153     // This is important for performance; we need to know whether the default
4154     // constructor is constexpr to determine whether the type is a literal type.
4155     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4156 
4157   case Sema::CXXCopyConstructor:
4158   case Sema::CXXMoveConstructor:
4159     // For copy or move constructors, we need to perform overload resolution.
4160     break;
4161 
4162   case Sema::CXXCopyAssignment:
4163   case Sema::CXXMoveAssignment:
4164   case Sema::CXXDestructor:
4165   case Sema::CXXInvalid:
4166     return false;
4167   }
4168 
4169   //   -- if the class is a non-empty union, or for each non-empty anonymous
4170   //      union member of a non-union class, exactly one non-static data member
4171   //      shall be initialized; [DR1359]
4172   //
4173   // If we squint, this is guaranteed, since exactly one non-static data member
4174   // will be initialized (if the constructor isn't deleted), we just don't know
4175   // which one.
4176   if (ClassDecl->isUnion())
4177     return true;
4178 
4179   //   -- the class shall not have any virtual base classes;
4180   if (ClassDecl->getNumVBases())
4181     return false;
4182 
4183   //   -- every constructor involved in initializing [...] base class
4184   //      sub-objects shall be a constexpr constructor;
4185   for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4186                                        BEnd = ClassDecl->bases_end();
4187        B != BEnd; ++B) {
4188     const RecordType *BaseType = B->getType()->getAs<RecordType>();
4189     if (!BaseType) continue;
4190 
4191     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4192     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4193       return false;
4194   }
4195 
4196   //   -- every constructor involved in initializing non-static data members
4197   //      [...] shall be a constexpr constructor;
4198   //   -- every non-static data member and base class sub-object shall be
4199   //      initialized
4200   for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4201                                FEnd = ClassDecl->field_end();
4202        F != FEnd; ++F) {
4203     if (F->isInvalidDecl())
4204       continue;
4205     if (const RecordType *RecordTy =
4206             S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4207       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4208       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4209         return false;
4210     }
4211   }
4212 
4213   // All OK, it's constexpr!
4214   return true;
4215 }
4216 
4217 static Sema::ImplicitExceptionSpecification
4218 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4219   switch (S.getSpecialMember(MD)) {
4220   case Sema::CXXDefaultConstructor:
4221     return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4222   case Sema::CXXCopyConstructor:
4223     return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4224   case Sema::CXXCopyAssignment:
4225     return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4226   case Sema::CXXMoveConstructor:
4227     return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4228   case Sema::CXXMoveAssignment:
4229     return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4230   case Sema::CXXDestructor:
4231     return S.ComputeDefaultedDtorExceptionSpec(MD);
4232   case Sema::CXXInvalid:
4233     break;
4234   }
4235   assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4236          "only special members have implicit exception specs");
4237   return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
4238 }
4239 
4240 static void
4241 updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4242                     const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4243   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4244   ExceptSpec.getEPI(EPI);
4245   FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4246                                         FPT->getArgTypes(), EPI));
4247 }
4248 
4249 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4250   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4251   if (FPT->getExceptionSpecType() != EST_Unevaluated)
4252     return;
4253 
4254   // Evaluate the exception specification.
4255   ImplicitExceptionSpecification ExceptSpec =
4256       computeImplicitExceptionSpec(*this, Loc, MD);
4257 
4258   // Update the type of the special member to use it.
4259   updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4260 
4261   // A user-provided destructor can be defined outside the class. When that
4262   // happens, be sure to update the exception specification on both
4263   // declarations.
4264   const FunctionProtoType *CanonicalFPT =
4265     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4266   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4267     updateExceptionSpec(*this, MD->getCanonicalDecl(),
4268                         CanonicalFPT, ExceptSpec);
4269 }
4270 
4271 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4272   CXXRecordDecl *RD = MD->getParent();
4273   CXXSpecialMember CSM = getSpecialMember(MD);
4274 
4275   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4276          "not an explicitly-defaulted special member");
4277 
4278   // Whether this was the first-declared instance of the constructor.
4279   // This affects whether we implicitly add an exception spec and constexpr.
4280   bool First = MD == MD->getCanonicalDecl();
4281 
4282   bool HadError = false;
4283 
4284   // C++11 [dcl.fct.def.default]p1:
4285   //   A function that is explicitly defaulted shall
4286   //     -- be a special member function (checked elsewhere),
4287   //     -- have the same type (except for ref-qualifiers, and except that a
4288   //        copy operation can take a non-const reference) as an implicit
4289   //        declaration, and
4290   //     -- not have default arguments.
4291   unsigned ExpectedParams = 1;
4292   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4293     ExpectedParams = 0;
4294   if (MD->getNumParams() != ExpectedParams) {
4295     // This also checks for default arguments: a copy or move constructor with a
4296     // default argument is classified as a default constructor, and assignment
4297     // operations and destructors can't have default arguments.
4298     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4299       << CSM << MD->getSourceRange();
4300     HadError = true;
4301   } else if (MD->isVariadic()) {
4302     Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4303       << CSM << MD->getSourceRange();
4304     HadError = true;
4305   }
4306 
4307   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
4308 
4309   bool CanHaveConstParam = false;
4310   if (CSM == CXXCopyConstructor)
4311     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
4312   else if (CSM == CXXCopyAssignment)
4313     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
4314 
4315   QualType ReturnType = Context.VoidTy;
4316   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4317     // Check for return type matching.
4318     ReturnType = Type->getResultType();
4319     QualType ExpectedReturnType =
4320         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4321     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4322       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4323         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4324       HadError = true;
4325     }
4326 
4327     // A defaulted special member cannot have cv-qualifiers.
4328     if (Type->getTypeQuals()) {
4329       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4330         << (CSM == CXXMoveAssignment);
4331       HadError = true;
4332     }
4333   }
4334 
4335   // Check for parameter type matching.
4336   QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
4337   bool HasConstParam = false;
4338   if (ExpectedParams && ArgType->isReferenceType()) {
4339     // Argument must be reference to possibly-const T.
4340     QualType ReferentType = ArgType->getPointeeType();
4341     HasConstParam = ReferentType.isConstQualified();
4342 
4343     if (ReferentType.isVolatileQualified()) {
4344       Diag(MD->getLocation(),
4345            diag::err_defaulted_special_member_volatile_param) << CSM;
4346       HadError = true;
4347     }
4348 
4349     if (HasConstParam && !CanHaveConstParam) {
4350       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4351         Diag(MD->getLocation(),
4352              diag::err_defaulted_special_member_copy_const_param)
4353           << (CSM == CXXCopyAssignment);
4354         // FIXME: Explain why this special member can't be const.
4355       } else {
4356         Diag(MD->getLocation(),
4357              diag::err_defaulted_special_member_move_const_param)
4358           << (CSM == CXXMoveAssignment);
4359       }
4360       HadError = true;
4361     }
4362   } else if (ExpectedParams) {
4363     // A copy assignment operator can take its argument by value, but a
4364     // defaulted one cannot.
4365     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
4366     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
4367     HadError = true;
4368   }
4369 
4370   // C++11 [dcl.fct.def.default]p2:
4371   //   An explicitly-defaulted function may be declared constexpr only if it
4372   //   would have been implicitly declared as constexpr,
4373   // Do not apply this rule to members of class templates, since core issue 1358
4374   // makes such functions always instantiate to constexpr functions. For
4375   // non-constructors, this is checked elsewhere.
4376   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4377                                                      HasConstParam);
4378   if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4379       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4380     Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
4381     // FIXME: Explain why the constructor can't be constexpr.
4382     HadError = true;
4383   }
4384 
4385   //   and may have an explicit exception-specification only if it is compatible
4386   //   with the exception-specification on the implicit declaration.
4387   if (Type->hasExceptionSpec()) {
4388     // Delay the check if this is the first declaration of the special member,
4389     // since we may not have parsed some necessary in-class initializers yet.
4390     if (First) {
4391       // If the exception specification needs to be instantiated, do so now,
4392       // before we clobber it with an EST_Unevaluated specification below.
4393       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4394         InstantiateExceptionSpec(MD->getLocStart(), MD);
4395         Type = MD->getType()->getAs<FunctionProtoType>();
4396       }
4397       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
4398     } else
4399       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4400   }
4401 
4402   //   If a function is explicitly defaulted on its first declaration,
4403   if (First) {
4404     //  -- it is implicitly considered to be constexpr if the implicit
4405     //     definition would be,
4406     MD->setConstexpr(Constexpr);
4407 
4408     //  -- it is implicitly considered to have the same exception-specification
4409     //     as if it had been implicitly declared,
4410     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4411     EPI.ExceptionSpecType = EST_Unevaluated;
4412     EPI.ExceptionSpecDecl = MD;
4413     MD->setType(Context.getFunctionType(ReturnType,
4414                                         ArrayRef<QualType>(&ArgType,
4415                                                            ExpectedParams),
4416                                         EPI));
4417   }
4418 
4419   if (ShouldDeleteSpecialMember(MD, CSM)) {
4420     if (First) {
4421       SetDeclDeleted(MD, MD->getLocation());
4422     } else {
4423       // C++11 [dcl.fct.def.default]p4:
4424       //   [For a] user-provided explicitly-defaulted function [...] if such a
4425       //   function is implicitly defined as deleted, the program is ill-formed.
4426       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4427       HadError = true;
4428     }
4429   }
4430 
4431   if (HadError)
4432     MD->setInvalidDecl();
4433 }
4434 
4435 /// Check whether the exception specification provided for an
4436 /// explicitly-defaulted special member matches the exception specification
4437 /// that would have been generated for an implicit special member, per
4438 /// C++11 [dcl.fct.def.default]p2.
4439 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4440     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4441   // Compute the implicit exception specification.
4442   FunctionProtoType::ExtProtoInfo EPI;
4443   computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4444   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
4445     Context.getFunctionType(Context.VoidTy, ArrayRef<QualType>(), EPI));
4446 
4447   // Ensure that it matches.
4448   CheckEquivalentExceptionSpec(
4449     PDiag(diag::err_incorrect_defaulted_exception_spec)
4450       << getSpecialMember(MD), PDiag(),
4451     ImplicitType, SourceLocation(),
4452     SpecifiedType, MD->getLocation());
4453 }
4454 
4455 void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4456   for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4457        I != N; ++I)
4458     CheckExplicitlyDefaultedMemberExceptionSpec(
4459       DelayedDefaultedMemberExceptionSpecs[I].first,
4460       DelayedDefaultedMemberExceptionSpecs[I].second);
4461 
4462   DelayedDefaultedMemberExceptionSpecs.clear();
4463 }
4464 
4465 namespace {
4466 struct SpecialMemberDeletionInfo {
4467   Sema &S;
4468   CXXMethodDecl *MD;
4469   Sema::CXXSpecialMember CSM;
4470   bool Diagnose;
4471 
4472   // Properties of the special member, computed for convenience.
4473   bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4474   SourceLocation Loc;
4475 
4476   bool AllFieldsAreConst;
4477 
4478   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
4479                             Sema::CXXSpecialMember CSM, bool Diagnose)
4480     : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
4481       IsConstructor(false), IsAssignment(false), IsMove(false),
4482       ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4483       AllFieldsAreConst(true) {
4484     switch (CSM) {
4485       case Sema::CXXDefaultConstructor:
4486       case Sema::CXXCopyConstructor:
4487         IsConstructor = true;
4488         break;
4489       case Sema::CXXMoveConstructor:
4490         IsConstructor = true;
4491         IsMove = true;
4492         break;
4493       case Sema::CXXCopyAssignment:
4494         IsAssignment = true;
4495         break;
4496       case Sema::CXXMoveAssignment:
4497         IsAssignment = true;
4498         IsMove = true;
4499         break;
4500       case Sema::CXXDestructor:
4501         break;
4502       case Sema::CXXInvalid:
4503         llvm_unreachable("invalid special member kind");
4504     }
4505 
4506     if (MD->getNumParams()) {
4507       ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4508       VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4509     }
4510   }
4511 
4512   bool inUnion() const { return MD->getParent()->isUnion(); }
4513 
4514   /// Look up the corresponding special member in the given class.
4515   Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4516                                               unsigned Quals) {
4517     unsigned TQ = MD->getTypeQualifiers();
4518     // cv-qualifiers on class members don't affect default ctor / dtor calls.
4519     if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4520       Quals = 0;
4521     return S.LookupSpecialMember(Class, CSM,
4522                                  ConstArg || (Quals & Qualifiers::Const),
4523                                  VolatileArg || (Quals & Qualifiers::Volatile),
4524                                  MD->getRefQualifier() == RQ_RValue,
4525                                  TQ & Qualifiers::Const,
4526                                  TQ & Qualifiers::Volatile);
4527   }
4528 
4529   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
4530 
4531   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
4532   bool shouldDeleteForField(FieldDecl *FD);
4533   bool shouldDeleteForAllConstMembers();
4534 
4535   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4536                                      unsigned Quals);
4537   bool shouldDeleteForSubobjectCall(Subobject Subobj,
4538                                     Sema::SpecialMemberOverloadResult *SMOR,
4539                                     bool IsDtorCallInCtor);
4540 
4541   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
4542 };
4543 }
4544 
4545 /// Is the given special member inaccessible when used on the given
4546 /// sub-object.
4547 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4548                                              CXXMethodDecl *target) {
4549   /// If we're operating on a base class, the object type is the
4550   /// type of this special member.
4551   QualType objectTy;
4552   AccessSpecifier access = target->getAccess();
4553   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4554     objectTy = S.Context.getTypeDeclType(MD->getParent());
4555     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4556 
4557   // If we're operating on a field, the object type is the type of the field.
4558   } else {
4559     objectTy = S.Context.getTypeDeclType(target->getParent());
4560   }
4561 
4562   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4563 }
4564 
4565 /// Check whether we should delete a special member due to the implicit
4566 /// definition containing a call to a special member of a subobject.
4567 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4568     Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4569     bool IsDtorCallInCtor) {
4570   CXXMethodDecl *Decl = SMOR->getMethod();
4571   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4572 
4573   int DiagKind = -1;
4574 
4575   if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4576     DiagKind = !Decl ? 0 : 1;
4577   else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4578     DiagKind = 2;
4579   else if (!isAccessible(Subobj, Decl))
4580     DiagKind = 3;
4581   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4582            !Decl->isTrivial()) {
4583     // A member of a union must have a trivial corresponding special member.
4584     // As a weird special case, a destructor call from a union's constructor
4585     // must be accessible and non-deleted, but need not be trivial. Such a
4586     // destructor is never actually called, but is semantically checked as
4587     // if it were.
4588     DiagKind = 4;
4589   }
4590 
4591   if (DiagKind == -1)
4592     return false;
4593 
4594   if (Diagnose) {
4595     if (Field) {
4596       S.Diag(Field->getLocation(),
4597              diag::note_deleted_special_member_class_subobject)
4598         << CSM << MD->getParent() << /*IsField*/true
4599         << Field << DiagKind << IsDtorCallInCtor;
4600     } else {
4601       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4602       S.Diag(Base->getLocStart(),
4603              diag::note_deleted_special_member_class_subobject)
4604         << CSM << MD->getParent() << /*IsField*/false
4605         << Base->getType() << DiagKind << IsDtorCallInCtor;
4606     }
4607 
4608     if (DiagKind == 1)
4609       S.NoteDeletedFunction(Decl);
4610     // FIXME: Explain inaccessibility if DiagKind == 3.
4611   }
4612 
4613   return true;
4614 }
4615 
4616 /// Check whether we should delete a special member function due to having a
4617 /// direct or virtual base class or non-static data member of class type M.
4618 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
4619     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
4620   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4621 
4622   // C++11 [class.ctor]p5:
4623   // -- any direct or virtual base class, or non-static data member with no
4624   //    brace-or-equal-initializer, has class type M (or array thereof) and
4625   //    either M has no default constructor or overload resolution as applied
4626   //    to M's default constructor results in an ambiguity or in a function
4627   //    that is deleted or inaccessible
4628   // C++11 [class.copy]p11, C++11 [class.copy]p23:
4629   // -- a direct or virtual base class B that cannot be copied/moved because
4630   //    overload resolution, as applied to B's corresponding special member,
4631   //    results in an ambiguity or a function that is deleted or inaccessible
4632   //    from the defaulted special member
4633   // C++11 [class.dtor]p5:
4634   // -- any direct or virtual base class [...] has a type with a destructor
4635   //    that is deleted or inaccessible
4636   if (!(CSM == Sema::CXXDefaultConstructor &&
4637         Field && Field->hasInClassInitializer()) &&
4638       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
4639     return true;
4640 
4641   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4642   // -- any direct or virtual base class or non-static data member has a
4643   //    type with a destructor that is deleted or inaccessible
4644   if (IsConstructor) {
4645     Sema::SpecialMemberOverloadResult *SMOR =
4646         S.LookupSpecialMember(Class, Sema::CXXDestructor,
4647                               false, false, false, false, false);
4648     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4649       return true;
4650   }
4651 
4652   return false;
4653 }
4654 
4655 /// Check whether we should delete a special member function due to the class
4656 /// having a particular direct or virtual base class.
4657 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
4658   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
4659   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
4660 }
4661 
4662 /// Check whether we should delete a special member function due to the class
4663 /// having a particular non-static data member.
4664 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4665   QualType FieldType = S.Context.getBaseElementType(FD->getType());
4666   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4667 
4668   if (CSM == Sema::CXXDefaultConstructor) {
4669     // For a default constructor, all references must be initialized in-class
4670     // and, if a union, it must have a non-const member.
4671     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4672       if (Diagnose)
4673         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4674           << MD->getParent() << FD << FieldType << /*Reference*/0;
4675       return true;
4676     }
4677     // C++11 [class.ctor]p5: any non-variant non-static data member of
4678     // const-qualified type (or array thereof) with no
4679     // brace-or-equal-initializer does not have a user-provided default
4680     // constructor.
4681     if (!inUnion() && FieldType.isConstQualified() &&
4682         !FD->hasInClassInitializer() &&
4683         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4684       if (Diagnose)
4685         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4686           << MD->getParent() << FD << FD->getType() << /*Const*/1;
4687       return true;
4688     }
4689 
4690     if (inUnion() && !FieldType.isConstQualified())
4691       AllFieldsAreConst = false;
4692   } else if (CSM == Sema::CXXCopyConstructor) {
4693     // For a copy constructor, data members must not be of rvalue reference
4694     // type.
4695     if (FieldType->isRValueReferenceType()) {
4696       if (Diagnose)
4697         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4698           << MD->getParent() << FD << FieldType;
4699       return true;
4700     }
4701   } else if (IsAssignment) {
4702     // For an assignment operator, data members must not be of reference type.
4703     if (FieldType->isReferenceType()) {
4704       if (Diagnose)
4705         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4706           << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
4707       return true;
4708     }
4709     if (!FieldRecord && FieldType.isConstQualified()) {
4710       // C++11 [class.copy]p23:
4711       // -- a non-static data member of const non-class type (or array thereof)
4712       if (Diagnose)
4713         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4714           << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
4715       return true;
4716     }
4717   }
4718 
4719   if (FieldRecord) {
4720     // Some additional restrictions exist on the variant members.
4721     if (!inUnion() && FieldRecord->isUnion() &&
4722         FieldRecord->isAnonymousStructOrUnion()) {
4723       bool AllVariantFieldsAreConst = true;
4724 
4725       // FIXME: Handle anonymous unions declared within anonymous unions.
4726       for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4727                                          UE = FieldRecord->field_end();
4728            UI != UE; ++UI) {
4729         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
4730 
4731         if (!UnionFieldType.isConstQualified())
4732           AllVariantFieldsAreConst = false;
4733 
4734         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4735         if (UnionFieldRecord &&
4736             shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4737                                           UnionFieldType.getCVRQualifiers()))
4738           return true;
4739       }
4740 
4741       // At least one member in each anonymous union must be non-const
4742       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
4743           FieldRecord->field_begin() != FieldRecord->field_end()) {
4744         if (Diagnose)
4745           S.Diag(FieldRecord->getLocation(),
4746                  diag::note_deleted_default_ctor_all_const)
4747             << MD->getParent() << /*anonymous union*/1;
4748         return true;
4749       }
4750 
4751       // Don't check the implicit member of the anonymous union type.
4752       // This is technically non-conformant, but sanity demands it.
4753       return false;
4754     }
4755 
4756     if (shouldDeleteForClassSubobject(FieldRecord, FD,
4757                                       FieldType.getCVRQualifiers()))
4758       return true;
4759   }
4760 
4761   return false;
4762 }
4763 
4764 /// C++11 [class.ctor] p5:
4765 ///   A defaulted default constructor for a class X is defined as deleted if
4766 /// X is a union and all of its variant members are of const-qualified type.
4767 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
4768   // This is a silly definition, because it gives an empty union a deleted
4769   // default constructor. Don't do that.
4770   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4771       (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4772     if (Diagnose)
4773       S.Diag(MD->getParent()->getLocation(),
4774              diag::note_deleted_default_ctor_all_const)
4775         << MD->getParent() << /*not anonymous union*/0;
4776     return true;
4777   }
4778   return false;
4779 }
4780 
4781 /// Determine whether a defaulted special member function should be defined as
4782 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4783 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
4784 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4785                                      bool Diagnose) {
4786   if (MD->isInvalidDecl())
4787     return false;
4788   CXXRecordDecl *RD = MD->getParent();
4789   assert(!RD->isDependentType() && "do deletion after instantiation");
4790   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
4791     return false;
4792 
4793   // C++11 [expr.lambda.prim]p19:
4794   //   The closure type associated with a lambda-expression has a
4795   //   deleted (8.4.3) default constructor and a deleted copy
4796   //   assignment operator.
4797   if (RD->isLambda() &&
4798       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4799     if (Diagnose)
4800       Diag(RD->getLocation(), diag::note_lambda_decl);
4801     return true;
4802   }
4803 
4804   // For an anonymous struct or union, the copy and assignment special members
4805   // will never be used, so skip the check. For an anonymous union declared at
4806   // namespace scope, the constructor and destructor are used.
4807   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4808       RD->isAnonymousStructOrUnion())
4809     return false;
4810 
4811   // C++11 [class.copy]p7, p18:
4812   //   If the class definition declares a move constructor or move assignment
4813   //   operator, an implicitly declared copy constructor or copy assignment
4814   //   operator is defined as deleted.
4815   if (MD->isImplicit() &&
4816       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4817     CXXMethodDecl *UserDeclaredMove = 0;
4818 
4819     // In Microsoft mode, a user-declared move only causes the deletion of the
4820     // corresponding copy operation, not both copy operations.
4821     if (RD->hasUserDeclaredMoveConstructor() &&
4822         (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4823       if (!Diagnose) return true;
4824 
4825       // Find any user-declared move constructor.
4826       for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4827                                         E = RD->ctor_end(); I != E; ++I) {
4828         if (I->isMoveConstructor()) {
4829           UserDeclaredMove = *I;
4830           break;
4831         }
4832       }
4833       assert(UserDeclaredMove);
4834     } else if (RD->hasUserDeclaredMoveAssignment() &&
4835                (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4836       if (!Diagnose) return true;
4837 
4838       // Find any user-declared move assignment operator.
4839       for (CXXRecordDecl::method_iterator I = RD->method_begin(),
4840                                           E = RD->method_end(); I != E; ++I) {
4841         if (I->isMoveAssignmentOperator()) {
4842           UserDeclaredMove = *I;
4843           break;
4844         }
4845       }
4846       assert(UserDeclaredMove);
4847     }
4848 
4849     if (UserDeclaredMove) {
4850       Diag(UserDeclaredMove->getLocation(),
4851            diag::note_deleted_copy_user_declared_move)
4852         << (CSM == CXXCopyAssignment) << RD
4853         << UserDeclaredMove->isMoveAssignmentOperator();
4854       return true;
4855     }
4856   }
4857 
4858   // Do access control from the special member function
4859   ContextRAII MethodContext(*this, MD);
4860 
4861   // C++11 [class.dtor]p5:
4862   // -- for a virtual destructor, lookup of the non-array deallocation function
4863   //    results in an ambiguity or in a function that is deleted or inaccessible
4864   if (CSM == CXXDestructor && MD->isVirtual()) {
4865     FunctionDecl *OperatorDelete = 0;
4866     DeclarationName Name =
4867       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4868     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
4869                                  OperatorDelete, false)) {
4870       if (Diagnose)
4871         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
4872       return true;
4873     }
4874   }
4875 
4876   SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
4877 
4878   for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4879                                           BE = RD->bases_end(); BI != BE; ++BI)
4880     if (!BI->isVirtual() &&
4881         SMI.shouldDeleteForBase(BI))
4882       return true;
4883 
4884   for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4885                                           BE = RD->vbases_end(); BI != BE; ++BI)
4886     if (SMI.shouldDeleteForBase(BI))
4887       return true;
4888 
4889   for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4890                                      FE = RD->field_end(); FI != FE; ++FI)
4891     if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
4892         SMI.shouldDeleteForField(*FI))
4893       return true;
4894 
4895   if (SMI.shouldDeleteForAllConstMembers())
4896     return true;
4897 
4898   return false;
4899 }
4900 
4901 /// Perform lookup for a special member of the specified kind, and determine
4902 /// whether it is trivial. If the triviality can be determined without the
4903 /// lookup, skip it. This is intended for use when determining whether a
4904 /// special member of a containing object is trivial, and thus does not ever
4905 /// perform overload resolution for default constructors.
4906 ///
4907 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
4908 /// member that was most likely to be intended to be trivial, if any.
4909 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
4910                                      Sema::CXXSpecialMember CSM, unsigned Quals,
4911                                      CXXMethodDecl **Selected) {
4912   if (Selected)
4913     *Selected = 0;
4914 
4915   switch (CSM) {
4916   case Sema::CXXInvalid:
4917     llvm_unreachable("not a special member");
4918 
4919   case Sema::CXXDefaultConstructor:
4920     // C++11 [class.ctor]p5:
4921     //   A default constructor is trivial if:
4922     //    - all the [direct subobjects] have trivial default constructors
4923     //
4924     // Note, no overload resolution is performed in this case.
4925     if (RD->hasTrivialDefaultConstructor())
4926       return true;
4927 
4928     if (Selected) {
4929       // If there's a default constructor which could have been trivial, dig it
4930       // out. Otherwise, if there's any user-provided default constructor, point
4931       // to that as an example of why there's not a trivial one.
4932       CXXConstructorDecl *DefCtor = 0;
4933       if (RD->needsImplicitDefaultConstructor())
4934         S.DeclareImplicitDefaultConstructor(RD);
4935       for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
4936                                         CE = RD->ctor_end(); CI != CE; ++CI) {
4937         if (!CI->isDefaultConstructor())
4938           continue;
4939         DefCtor = *CI;
4940         if (!DefCtor->isUserProvided())
4941           break;
4942       }
4943 
4944       *Selected = DefCtor;
4945     }
4946 
4947     return false;
4948 
4949   case Sema::CXXDestructor:
4950     // C++11 [class.dtor]p5:
4951     //   A destructor is trivial if:
4952     //    - all the direct [subobjects] have trivial destructors
4953     if (RD->hasTrivialDestructor())
4954       return true;
4955 
4956     if (Selected) {
4957       if (RD->needsImplicitDestructor())
4958         S.DeclareImplicitDestructor(RD);
4959       *Selected = RD->getDestructor();
4960     }
4961 
4962     return false;
4963 
4964   case Sema::CXXCopyConstructor:
4965     // C++11 [class.copy]p12:
4966     //   A copy constructor is trivial if:
4967     //    - the constructor selected to copy each direct [subobject] is trivial
4968     if (RD->hasTrivialCopyConstructor()) {
4969       if (Quals == Qualifiers::Const)
4970         // We must either select the trivial copy constructor or reach an
4971         // ambiguity; no need to actually perform overload resolution.
4972         return true;
4973     } else if (!Selected) {
4974       return false;
4975     }
4976     // In C++98, we are not supposed to perform overload resolution here, but we
4977     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
4978     // cases like B as having a non-trivial copy constructor:
4979     //   struct A { template<typename T> A(T&); };
4980     //   struct B { mutable A a; };
4981     goto NeedOverloadResolution;
4982 
4983   case Sema::CXXCopyAssignment:
4984     // C++11 [class.copy]p25:
4985     //   A copy assignment operator is trivial if:
4986     //    - the assignment operator selected to copy each direct [subobject] is
4987     //      trivial
4988     if (RD->hasTrivialCopyAssignment()) {
4989       if (Quals == Qualifiers::Const)
4990         return true;
4991     } else if (!Selected) {
4992       return false;
4993     }
4994     // In C++98, we are not supposed to perform overload resolution here, but we
4995     // treat that as a language defect.
4996     goto NeedOverloadResolution;
4997 
4998   case Sema::CXXMoveConstructor:
4999   case Sema::CXXMoveAssignment:
5000   NeedOverloadResolution:
5001     Sema::SpecialMemberOverloadResult *SMOR =
5002       S.LookupSpecialMember(RD, CSM,
5003                             Quals & Qualifiers::Const,
5004                             Quals & Qualifiers::Volatile,
5005                             /*RValueThis*/false, /*ConstThis*/false,
5006                             /*VolatileThis*/false);
5007 
5008     // The standard doesn't describe how to behave if the lookup is ambiguous.
5009     // We treat it as not making the member non-trivial, just like the standard
5010     // mandates for the default constructor. This should rarely matter, because
5011     // the member will also be deleted.
5012     if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5013       return true;
5014 
5015     if (!SMOR->getMethod()) {
5016       assert(SMOR->getKind() ==
5017              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5018       return false;
5019     }
5020 
5021     // We deliberately don't check if we found a deleted special member. We're
5022     // not supposed to!
5023     if (Selected)
5024       *Selected = SMOR->getMethod();
5025     return SMOR->getMethod()->isTrivial();
5026   }
5027 
5028   llvm_unreachable("unknown special method kind");
5029 }
5030 
5031 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
5032   for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5033        CI != CE; ++CI)
5034     if (!CI->isImplicit())
5035       return *CI;
5036 
5037   // Look for constructor templates.
5038   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5039   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5040     if (CXXConstructorDecl *CD =
5041           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5042       return CD;
5043   }
5044 
5045   return 0;
5046 }
5047 
5048 /// The kind of subobject we are checking for triviality. The values of this
5049 /// enumeration are used in diagnostics.
5050 enum TrivialSubobjectKind {
5051   /// The subobject is a base class.
5052   TSK_BaseClass,
5053   /// The subobject is a non-static data member.
5054   TSK_Field,
5055   /// The object is actually the complete object.
5056   TSK_CompleteObject
5057 };
5058 
5059 /// Check whether the special member selected for a given type would be trivial.
5060 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5061                                       QualType SubType,
5062                                       Sema::CXXSpecialMember CSM,
5063                                       TrivialSubobjectKind Kind,
5064                                       bool Diagnose) {
5065   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5066   if (!SubRD)
5067     return true;
5068 
5069   CXXMethodDecl *Selected;
5070   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5071                                Diagnose ? &Selected : 0))
5072     return true;
5073 
5074   if (Diagnose) {
5075     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5076       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5077         << Kind << SubType.getUnqualifiedType();
5078       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5079         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5080     } else if (!Selected)
5081       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5082         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5083     else if (Selected->isUserProvided()) {
5084       if (Kind == TSK_CompleteObject)
5085         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5086           << Kind << SubType.getUnqualifiedType() << CSM;
5087       else {
5088         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5089           << Kind << SubType.getUnqualifiedType() << CSM;
5090         S.Diag(Selected->getLocation(), diag::note_declared_at);
5091       }
5092     } else {
5093       if (Kind != TSK_CompleteObject)
5094         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5095           << Kind << SubType.getUnqualifiedType() << CSM;
5096 
5097       // Explain why the defaulted or deleted special member isn't trivial.
5098       S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5099     }
5100   }
5101 
5102   return false;
5103 }
5104 
5105 /// Check whether the members of a class type allow a special member to be
5106 /// trivial.
5107 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5108                                      Sema::CXXSpecialMember CSM,
5109                                      bool ConstArg, bool Diagnose) {
5110   for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5111                                      FE = RD->field_end(); FI != FE; ++FI) {
5112     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5113       continue;
5114 
5115     QualType FieldType = S.Context.getBaseElementType(FI->getType());
5116 
5117     // Pretend anonymous struct or union members are members of this class.
5118     if (FI->isAnonymousStructOrUnion()) {
5119       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5120                                     CSM, ConstArg, Diagnose))
5121         return false;
5122       continue;
5123     }
5124 
5125     // C++11 [class.ctor]p5:
5126     //   A default constructor is trivial if [...]
5127     //    -- no non-static data member of its class has a
5128     //       brace-or-equal-initializer
5129     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5130       if (Diagnose)
5131         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5132       return false;
5133     }
5134 
5135     // Objective C ARC 4.3.5:
5136     //   [...] nontrivally ownership-qualified types are [...] not trivially
5137     //   default constructible, copy constructible, move constructible, copy
5138     //   assignable, move assignable, or destructible [...]
5139     if (S.getLangOpts().ObjCAutoRefCount &&
5140         FieldType.hasNonTrivialObjCLifetime()) {
5141       if (Diagnose)
5142         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5143           << RD << FieldType.getObjCLifetime();
5144       return false;
5145     }
5146 
5147     if (ConstArg && !FI->isMutable())
5148       FieldType.addConst();
5149     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5150                                    TSK_Field, Diagnose))
5151       return false;
5152   }
5153 
5154   return true;
5155 }
5156 
5157 /// Diagnose why the specified class does not have a trivial special member of
5158 /// the given kind.
5159 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5160   QualType Ty = Context.getRecordType(RD);
5161   if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5162     Ty.addConst();
5163 
5164   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5165                             TSK_CompleteObject, /*Diagnose*/true);
5166 }
5167 
5168 /// Determine whether a defaulted or deleted special member function is trivial,
5169 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5170 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5171 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5172                                   bool Diagnose) {
5173   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5174 
5175   CXXRecordDecl *RD = MD->getParent();
5176 
5177   bool ConstArg = false;
5178 
5179   // C++11 [class.copy]p12, p25:
5180   //   A [special member] is trivial if its declared parameter type is the same
5181   //   as if it had been implicitly declared [...]
5182   switch (CSM) {
5183   case CXXDefaultConstructor:
5184   case CXXDestructor:
5185     // Trivial default constructors and destructors cannot have parameters.
5186     break;
5187 
5188   case CXXCopyConstructor:
5189   case CXXCopyAssignment: {
5190     // Trivial copy operations always have const, non-volatile parameter types.
5191     ConstArg = true;
5192     const ParmVarDecl *Param0 = MD->getParamDecl(0);
5193     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5194     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5195       if (Diagnose)
5196         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5197           << Param0->getSourceRange() << Param0->getType()
5198           << Context.getLValueReferenceType(
5199                Context.getRecordType(RD).withConst());
5200       return false;
5201     }
5202     break;
5203   }
5204 
5205   case CXXMoveConstructor:
5206   case CXXMoveAssignment: {
5207     // Trivial move operations always have non-cv-qualified parameters.
5208     const ParmVarDecl *Param0 = MD->getParamDecl(0);
5209     const RValueReferenceType *RT =
5210       Param0->getType()->getAs<RValueReferenceType>();
5211     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5212       if (Diagnose)
5213         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5214           << Param0->getSourceRange() << Param0->getType()
5215           << Context.getRValueReferenceType(Context.getRecordType(RD));
5216       return false;
5217     }
5218     break;
5219   }
5220 
5221   case CXXInvalid:
5222     llvm_unreachable("not a special member");
5223   }
5224 
5225   // FIXME: We require that the parameter-declaration-clause is equivalent to
5226   // that of an implicit declaration, not just that the declared parameter type
5227   // matches, in order to prevent absuridities like a function simultaneously
5228   // being a trivial copy constructor and a non-trivial default constructor.
5229   // This issue has not yet been assigned a core issue number.
5230   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5231     if (Diagnose)
5232       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5233            diag::note_nontrivial_default_arg)
5234         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5235     return false;
5236   }
5237   if (MD->isVariadic()) {
5238     if (Diagnose)
5239       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5240     return false;
5241   }
5242 
5243   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5244   //   A copy/move [constructor or assignment operator] is trivial if
5245   //    -- the [member] selected to copy/move each direct base class subobject
5246   //       is trivial
5247   //
5248   // C++11 [class.copy]p12, C++11 [class.copy]p25:
5249   //   A [default constructor or destructor] is trivial if
5250   //    -- all the direct base classes have trivial [default constructors or
5251   //       destructors]
5252   for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5253                                           BE = RD->bases_end(); BI != BE; ++BI)
5254     if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5255                                    ConstArg ? BI->getType().withConst()
5256                                             : BI->getType(),
5257                                    CSM, TSK_BaseClass, Diagnose))
5258       return false;
5259 
5260   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5261   //   A copy/move [constructor or assignment operator] for a class X is
5262   //   trivial if
5263   //    -- for each non-static data member of X that is of class type (or array
5264   //       thereof), the constructor selected to copy/move that member is
5265   //       trivial
5266   //
5267   // C++11 [class.copy]p12, C++11 [class.copy]p25:
5268   //   A [default constructor or destructor] is trivial if
5269   //    -- for all of the non-static data members of its class that are of class
5270   //       type (or array thereof), each such class has a trivial [default
5271   //       constructor or destructor]
5272   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5273     return false;
5274 
5275   // C++11 [class.dtor]p5:
5276   //   A destructor is trivial if [...]
5277   //    -- the destructor is not virtual
5278   if (CSM == CXXDestructor && MD->isVirtual()) {
5279     if (Diagnose)
5280       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5281     return false;
5282   }
5283 
5284   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5285   //   A [special member] for class X is trivial if [...]
5286   //    -- class X has no virtual functions and no virtual base classes
5287   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5288     if (!Diagnose)
5289       return false;
5290 
5291     if (RD->getNumVBases()) {
5292       // Check for virtual bases. We already know that the corresponding
5293       // member in all bases is trivial, so vbases must all be direct.
5294       CXXBaseSpecifier &BS = *RD->vbases_begin();
5295       assert(BS.isVirtual());
5296       Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5297       return false;
5298     }
5299 
5300     // Must have a virtual method.
5301     for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5302                                         ME = RD->method_end(); MI != ME; ++MI) {
5303       if (MI->isVirtual()) {
5304         SourceLocation MLoc = MI->getLocStart();
5305         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5306         return false;
5307       }
5308     }
5309 
5310     llvm_unreachable("dynamic class with no vbases and no virtual functions");
5311   }
5312 
5313   // Looks like it's trivial!
5314   return true;
5315 }
5316 
5317 /// \brief Data used with FindHiddenVirtualMethod
5318 namespace {
5319   struct FindHiddenVirtualMethodData {
5320     Sema *S;
5321     CXXMethodDecl *Method;
5322     llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
5323     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5324   };
5325 }
5326 
5327 /// \brief Check whether any most overriden method from MD in Methods
5328 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5329                    const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5330   if (MD->size_overridden_methods() == 0)
5331     return Methods.count(MD->getCanonicalDecl());
5332   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5333                                       E = MD->end_overridden_methods();
5334        I != E; ++I)
5335     if (CheckMostOverridenMethods(*I, Methods))
5336       return true;
5337   return false;
5338 }
5339 
5340 /// \brief Member lookup function that determines whether a given C++
5341 /// method overloads virtual methods in a base class without overriding any,
5342 /// to be used with CXXRecordDecl::lookupInBases().
5343 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5344                                     CXXBasePath &Path,
5345                                     void *UserData) {
5346   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5347 
5348   FindHiddenVirtualMethodData &Data
5349     = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5350 
5351   DeclarationName Name = Data.Method->getDeclName();
5352   assert(Name.getNameKind() == DeclarationName::Identifier);
5353 
5354   bool foundSameNameMethod = false;
5355   SmallVector<CXXMethodDecl *, 8> overloadedMethods;
5356   for (Path.Decls = BaseRecord->lookup(Name);
5357        !Path.Decls.empty();
5358        Path.Decls = Path.Decls.slice(1)) {
5359     NamedDecl *D = Path.Decls.front();
5360     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5361       MD = MD->getCanonicalDecl();
5362       foundSameNameMethod = true;
5363       // Interested only in hidden virtual methods.
5364       if (!MD->isVirtual())
5365         continue;
5366       // If the method we are checking overrides a method from its base
5367       // don't warn about the other overloaded methods.
5368       if (!Data.S->IsOverload(Data.Method, MD, false))
5369         return true;
5370       // Collect the overload only if its hidden.
5371       if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
5372         overloadedMethods.push_back(MD);
5373     }
5374   }
5375 
5376   if (foundSameNameMethod)
5377     Data.OverloadedMethods.append(overloadedMethods.begin(),
5378                                    overloadedMethods.end());
5379   return foundSameNameMethod;
5380 }
5381 
5382 /// \brief Add the most overriden methods from MD to Methods
5383 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5384                          llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5385   if (MD->size_overridden_methods() == 0)
5386     Methods.insert(MD->getCanonicalDecl());
5387   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5388                                       E = MD->end_overridden_methods();
5389        I != E; ++I)
5390     AddMostOverridenMethods(*I, Methods);
5391 }
5392 
5393 /// \brief See if a method overloads virtual methods in a base class without
5394 /// overriding any.
5395 void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5396   if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
5397                                MD->getLocation()) == DiagnosticsEngine::Ignored)
5398     return;
5399   if (!MD->getDeclName().isIdentifier())
5400     return;
5401 
5402   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5403                      /*bool RecordPaths=*/false,
5404                      /*bool DetectVirtual=*/false);
5405   FindHiddenVirtualMethodData Data;
5406   Data.Method = MD;
5407   Data.S = this;
5408 
5409   // Keep the base methods that were overriden or introduced in the subclass
5410   // by 'using' in a set. A base method not in this set is hidden.
5411   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5412   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5413     NamedDecl *ND = *I;
5414     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
5415       ND = shad->getTargetDecl();
5416     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5417       AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
5418   }
5419 
5420   if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5421       !Data.OverloadedMethods.empty()) {
5422     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5423       << MD << (Data.OverloadedMethods.size() > 1);
5424 
5425     for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5426       CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
5427       PartialDiagnostic PD = PDiag(
5428            diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5429       HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5430       Diag(overloadedMD->getLocation(), PD);
5431     }
5432   }
5433 }
5434 
5435 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5436                                              Decl *TagDecl,
5437                                              SourceLocation LBrac,
5438                                              SourceLocation RBrac,
5439                                              AttributeList *AttrList) {
5440   if (!TagDecl)
5441     return;
5442 
5443   AdjustDeclIfTemplate(TagDecl);
5444 
5445   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5446     if (l->getKind() != AttributeList::AT_Visibility)
5447       continue;
5448     l->setInvalid();
5449     Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5450       l->getName();
5451   }
5452 
5453   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
5454               // strict aliasing violation!
5455               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
5456               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
5457 
5458   CheckCompletedCXXClass(
5459                         dyn_cast_or_null<CXXRecordDecl>(TagDecl));
5460 }
5461 
5462 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5463 /// special functions, such as the default constructor, copy
5464 /// constructor, or destructor, to the given C++ class (C++
5465 /// [special]p1).  This routine can only be executed just before the
5466 /// definition of the class is complete.
5467 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
5468   if (!ClassDecl->hasUserDeclaredConstructor())
5469     ++ASTContext::NumImplicitDefaultConstructors;
5470 
5471   if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
5472     ++ASTContext::NumImplicitCopyConstructors;
5473 
5474     // If the properties or semantics of the copy constructor couldn't be
5475     // determined while the class was being declared, force a declaration
5476     // of it now.
5477     if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5478       DeclareImplicitCopyConstructor(ClassDecl);
5479   }
5480 
5481   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
5482     ++ASTContext::NumImplicitMoveConstructors;
5483 
5484     if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5485       DeclareImplicitMoveConstructor(ClassDecl);
5486   }
5487 
5488   if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5489     ++ASTContext::NumImplicitCopyAssignmentOperators;
5490 
5491     // If we have a dynamic class, then the copy assignment operator may be
5492     // virtual, so we have to declare it immediately. This ensures that, e.g.,
5493     // it shows up in the right place in the vtable and that we diagnose
5494     // problems with the implicit exception specification.
5495     if (ClassDecl->isDynamicClass() ||
5496         ClassDecl->needsOverloadResolutionForCopyAssignment())
5497       DeclareImplicitCopyAssignment(ClassDecl);
5498   }
5499 
5500   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
5501     ++ASTContext::NumImplicitMoveAssignmentOperators;
5502 
5503     // Likewise for the move assignment operator.
5504     if (ClassDecl->isDynamicClass() ||
5505         ClassDecl->needsOverloadResolutionForMoveAssignment())
5506       DeclareImplicitMoveAssignment(ClassDecl);
5507   }
5508 
5509   if (!ClassDecl->hasUserDeclaredDestructor()) {
5510     ++ASTContext::NumImplicitDestructors;
5511 
5512     // If we have a dynamic class, then the destructor may be virtual, so we
5513     // have to declare the destructor immediately. This ensures that, e.g., it
5514     // shows up in the right place in the vtable and that we diagnose problems
5515     // with the implicit exception specification.
5516     if (ClassDecl->isDynamicClass() ||
5517         ClassDecl->needsOverloadResolutionForDestructor())
5518       DeclareImplicitDestructor(ClassDecl);
5519   }
5520 }
5521 
5522 void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5523   if (!D)
5524     return;
5525 
5526   int NumParamList = D->getNumTemplateParameterLists();
5527   for (int i = 0; i < NumParamList; i++) {
5528     TemplateParameterList* Params = D->getTemplateParameterList(i);
5529     for (TemplateParameterList::iterator Param = Params->begin(),
5530                                       ParamEnd = Params->end();
5531           Param != ParamEnd; ++Param) {
5532       NamedDecl *Named = cast<NamedDecl>(*Param);
5533       if (Named->getDeclName()) {
5534         S->AddDecl(Named);
5535         IdResolver.AddDecl(Named);
5536       }
5537     }
5538   }
5539 }
5540 
5541 void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
5542   if (!D)
5543     return;
5544 
5545   TemplateParameterList *Params = 0;
5546   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5547     Params = Template->getTemplateParameters();
5548   else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5549            = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5550     Params = PartialSpec->getTemplateParameters();
5551   else
5552     return;
5553 
5554   for (TemplateParameterList::iterator Param = Params->begin(),
5555                                     ParamEnd = Params->end();
5556        Param != ParamEnd; ++Param) {
5557     NamedDecl *Named = cast<NamedDecl>(*Param);
5558     if (Named->getDeclName()) {
5559       S->AddDecl(Named);
5560       IdResolver.AddDecl(Named);
5561     }
5562   }
5563 }
5564 
5565 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
5566   if (!RecordD) return;
5567   AdjustDeclIfTemplate(RecordD);
5568   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
5569   PushDeclContext(S, Record);
5570 }
5571 
5572 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
5573   if (!RecordD) return;
5574   PopDeclContext();
5575 }
5576 
5577 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
5578 /// parsing a top-level (non-nested) C++ class, and we are now
5579 /// parsing those parts of the given Method declaration that could
5580 /// not be parsed earlier (C++ [class.mem]p2), such as default
5581 /// arguments. This action should enter the scope of the given
5582 /// Method declaration as if we had just parsed the qualified method
5583 /// name. However, it should not bring the parameters into scope;
5584 /// that will be performed by ActOnDelayedCXXMethodParameter.
5585 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
5586 }
5587 
5588 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
5589 /// C++ method declaration. We're (re-)introducing the given
5590 /// function parameter into scope for use in parsing later parts of
5591 /// the method declaration. For example, we could see an
5592 /// ActOnParamDefaultArgument event for this parameter.
5593 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
5594   if (!ParamD)
5595     return;
5596 
5597   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
5598 
5599   // If this parameter has an unparsed default argument, clear it out
5600   // to make way for the parsed default argument.
5601   if (Param->hasUnparsedDefaultArg())
5602     Param->setDefaultArg(0);
5603 
5604   S->AddDecl(Param);
5605   if (Param->getDeclName())
5606     IdResolver.AddDecl(Param);
5607 }
5608 
5609 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5610 /// processing the delayed method declaration for Method. The method
5611 /// declaration is now considered finished. There may be a separate
5612 /// ActOnStartOfFunctionDef action later (not necessarily
5613 /// immediately!) for this method, if it was also defined inside the
5614 /// class body.
5615 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
5616   if (!MethodD)
5617     return;
5618 
5619   AdjustDeclIfTemplate(MethodD);
5620 
5621   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
5622 
5623   // Now that we have our default arguments, check the constructor
5624   // again. It could produce additional diagnostics or affect whether
5625   // the class has implicitly-declared destructors, among other
5626   // things.
5627   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5628     CheckConstructor(Constructor);
5629 
5630   // Check the default arguments, which we may have added.
5631   if (!Method->isInvalidDecl())
5632     CheckCXXDefaultArguments(Method);
5633 }
5634 
5635 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
5636 /// the well-formedness of the constructor declarator @p D with type @p
5637 /// R. If there are any errors in the declarator, this routine will
5638 /// emit diagnostics and set the invalid bit to true.  In any case, the type
5639 /// will be updated to reflect a well-formed type for the constructor and
5640 /// returned.
5641 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
5642                                           StorageClass &SC) {
5643   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
5644 
5645   // C++ [class.ctor]p3:
5646   //   A constructor shall not be virtual (10.3) or static (9.4). A
5647   //   constructor can be invoked for a const, volatile or const
5648   //   volatile object. A constructor shall not be declared const,
5649   //   volatile, or const volatile (9.3.2).
5650   if (isVirtual) {
5651     if (!D.isInvalidType())
5652       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5653         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5654         << SourceRange(D.getIdentifierLoc());
5655     D.setInvalidType();
5656   }
5657   if (SC == SC_Static) {
5658     if (!D.isInvalidType())
5659       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5660         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5661         << SourceRange(D.getIdentifierLoc());
5662     D.setInvalidType();
5663     SC = SC_None;
5664   }
5665 
5666   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5667   if (FTI.TypeQuals != 0) {
5668     if (FTI.TypeQuals & Qualifiers::Const)
5669       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5670         << "const" << SourceRange(D.getIdentifierLoc());
5671     if (FTI.TypeQuals & Qualifiers::Volatile)
5672       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5673         << "volatile" << SourceRange(D.getIdentifierLoc());
5674     if (FTI.TypeQuals & Qualifiers::Restrict)
5675       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5676         << "restrict" << SourceRange(D.getIdentifierLoc());
5677     D.setInvalidType();
5678   }
5679 
5680   // C++0x [class.ctor]p4:
5681   //   A constructor shall not be declared with a ref-qualifier.
5682   if (FTI.hasRefQualifier()) {
5683     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5684       << FTI.RefQualifierIsLValueRef
5685       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5686     D.setInvalidType();
5687   }
5688 
5689   // Rebuild the function type "R" without any type qualifiers (in
5690   // case any of the errors above fired) and with "void" as the
5691   // return type, since constructors don't have return types.
5692   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5693   if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5694     return R;
5695 
5696   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5697   EPI.TypeQuals = 0;
5698   EPI.RefQualifier = RQ_None;
5699 
5700   return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
5701 }
5702 
5703 /// CheckConstructor - Checks a fully-formed constructor for
5704 /// well-formedness, issuing any diagnostics required. Returns true if
5705 /// the constructor declarator is invalid.
5706 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
5707   CXXRecordDecl *ClassDecl
5708     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5709   if (!ClassDecl)
5710     return Constructor->setInvalidDecl();
5711 
5712   // C++ [class.copy]p3:
5713   //   A declaration of a constructor for a class X is ill-formed if
5714   //   its first parameter is of type (optionally cv-qualified) X and
5715   //   either there are no other parameters or else all other
5716   //   parameters have default arguments.
5717   if (!Constructor->isInvalidDecl() &&
5718       ((Constructor->getNumParams() == 1) ||
5719        (Constructor->getNumParams() > 1 &&
5720         Constructor->getParamDecl(1)->hasDefaultArg())) &&
5721       Constructor->getTemplateSpecializationKind()
5722                                               != TSK_ImplicitInstantiation) {
5723     QualType ParamType = Constructor->getParamDecl(0)->getType();
5724     QualType ClassTy = Context.getTagDeclType(ClassDecl);
5725     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
5726       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
5727       const char *ConstRef
5728         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5729                                                         : " const &";
5730       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
5731         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
5732 
5733       // FIXME: Rather that making the constructor invalid, we should endeavor
5734       // to fix the type.
5735       Constructor->setInvalidDecl();
5736     }
5737   }
5738 }
5739 
5740 /// CheckDestructor - Checks a fully-formed destructor definition for
5741 /// well-formedness, issuing any diagnostics required.  Returns true
5742 /// on error.
5743 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
5744   CXXRecordDecl *RD = Destructor->getParent();
5745 
5746   if (Destructor->isVirtual()) {
5747     SourceLocation Loc;
5748 
5749     if (!Destructor->isImplicit())
5750       Loc = Destructor->getLocation();
5751     else
5752       Loc = RD->getLocation();
5753 
5754     // If we have a virtual destructor, look up the deallocation function
5755     FunctionDecl *OperatorDelete = 0;
5756     DeclarationName Name =
5757     Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5758     if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
5759       return true;
5760 
5761     MarkFunctionReferenced(Loc, OperatorDelete);
5762 
5763     Destructor->setOperatorDelete(OperatorDelete);
5764   }
5765 
5766   return false;
5767 }
5768 
5769 static inline bool
5770 FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5771   return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5772           FTI.ArgInfo[0].Param &&
5773           cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
5774 }
5775 
5776 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5777 /// the well-formednes of the destructor declarator @p D with type @p
5778 /// R. If there are any errors in the declarator, this routine will
5779 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
5780 /// will be updated to reflect a well-formed type for the destructor and
5781 /// returned.
5782 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
5783                                          StorageClass& SC) {
5784   // C++ [class.dtor]p1:
5785   //   [...] A typedef-name that names a class is a class-name
5786   //   (7.1.3); however, a typedef-name that names a class shall not
5787   //   be used as the identifier in the declarator for a destructor
5788   //   declaration.
5789   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
5790   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
5791     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5792       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
5793   else if (const TemplateSpecializationType *TST =
5794              DeclaratorType->getAs<TemplateSpecializationType>())
5795     if (TST->isTypeAlias())
5796       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5797         << DeclaratorType << 1;
5798 
5799   // C++ [class.dtor]p2:
5800   //   A destructor is used to destroy objects of its class type. A
5801   //   destructor takes no parameters, and no return type can be
5802   //   specified for it (not even void). The address of a destructor
5803   //   shall not be taken. A destructor shall not be static. A
5804   //   destructor can be invoked for a const, volatile or const
5805   //   volatile object. A destructor shall not be declared const,
5806   //   volatile or const volatile (9.3.2).
5807   if (SC == SC_Static) {
5808     if (!D.isInvalidType())
5809       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5810         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5811         << SourceRange(D.getIdentifierLoc())
5812         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5813 
5814     SC = SC_None;
5815   }
5816   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
5817     // Destructors don't have return types, but the parser will
5818     // happily parse something like:
5819     //
5820     //   class X {
5821     //     float ~X();
5822     //   };
5823     //
5824     // The return type will be eliminated later.
5825     Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5826       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5827       << SourceRange(D.getIdentifierLoc());
5828   }
5829 
5830   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5831   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
5832     if (FTI.TypeQuals & Qualifiers::Const)
5833       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5834         << "const" << SourceRange(D.getIdentifierLoc());
5835     if (FTI.TypeQuals & Qualifiers::Volatile)
5836       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5837         << "volatile" << SourceRange(D.getIdentifierLoc());
5838     if (FTI.TypeQuals & Qualifiers::Restrict)
5839       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5840         << "restrict" << SourceRange(D.getIdentifierLoc());
5841     D.setInvalidType();
5842   }
5843 
5844   // C++0x [class.dtor]p2:
5845   //   A destructor shall not be declared with a ref-qualifier.
5846   if (FTI.hasRefQualifier()) {
5847     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5848       << FTI.RefQualifierIsLValueRef
5849       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5850     D.setInvalidType();
5851   }
5852 
5853   // Make sure we don't have any parameters.
5854   if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
5855     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5856 
5857     // Delete the parameters.
5858     FTI.freeArgs();
5859     D.setInvalidType();
5860   }
5861 
5862   // Make sure the destructor isn't variadic.
5863   if (FTI.isVariadic) {
5864     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
5865     D.setInvalidType();
5866   }
5867 
5868   // Rebuild the function type "R" without any type qualifiers or
5869   // parameters (in case any of the errors above fired) and with
5870   // "void" as the return type, since destructors don't have return
5871   // types.
5872   if (!D.isInvalidType())
5873     return R;
5874 
5875   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5876   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5877   EPI.Variadic = false;
5878   EPI.TypeQuals = 0;
5879   EPI.RefQualifier = RQ_None;
5880   return Context.getFunctionType(Context.VoidTy, ArrayRef<QualType>(), EPI);
5881 }
5882 
5883 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5884 /// well-formednes of the conversion function declarator @p D with
5885 /// type @p R. If there are any errors in the declarator, this routine
5886 /// will emit diagnostics and return true. Otherwise, it will return
5887 /// false. Either way, the type @p R will be updated to reflect a
5888 /// well-formed type for the conversion operator.
5889 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
5890                                      StorageClass& SC) {
5891   // C++ [class.conv.fct]p1:
5892   //   Neither parameter types nor return type can be specified. The
5893   //   type of a conversion function (8.3.5) is "function taking no
5894   //   parameter returning conversion-type-id."
5895   if (SC == SC_Static) {
5896     if (!D.isInvalidType())
5897       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5898         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5899         << SourceRange(D.getIdentifierLoc());
5900     D.setInvalidType();
5901     SC = SC_None;
5902   }
5903 
5904   QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5905 
5906   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
5907     // Conversion functions don't have return types, but the parser will
5908     // happily parse something like:
5909     //
5910     //   class X {
5911     //     float operator bool();
5912     //   };
5913     //
5914     // The return type will be changed later anyway.
5915     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5916       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5917       << SourceRange(D.getIdentifierLoc());
5918     D.setInvalidType();
5919   }
5920 
5921   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5922 
5923   // Make sure we don't have any parameters.
5924   if (Proto->getNumArgs() > 0) {
5925     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5926 
5927     // Delete the parameters.
5928     D.getFunctionTypeInfo().freeArgs();
5929     D.setInvalidType();
5930   } else if (Proto->isVariadic()) {
5931     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
5932     D.setInvalidType();
5933   }
5934 
5935   // Diagnose "&operator bool()" and other such nonsense.  This
5936   // is actually a gcc extension which we don't support.
5937   if (Proto->getResultType() != ConvType) {
5938     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5939       << Proto->getResultType();
5940     D.setInvalidType();
5941     ConvType = Proto->getResultType();
5942   }
5943 
5944   // C++ [class.conv.fct]p4:
5945   //   The conversion-type-id shall not represent a function type nor
5946   //   an array type.
5947   if (ConvType->isArrayType()) {
5948     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5949     ConvType = Context.getPointerType(ConvType);
5950     D.setInvalidType();
5951   } else if (ConvType->isFunctionType()) {
5952     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5953     ConvType = Context.getPointerType(ConvType);
5954     D.setInvalidType();
5955   }
5956 
5957   // Rebuild the function type "R" without any parameters (in case any
5958   // of the errors above fired) and with the conversion type as the
5959   // return type.
5960   if (D.isInvalidType())
5961     R = Context.getFunctionType(ConvType, ArrayRef<QualType>(),
5962                                 Proto->getExtProtoInfo());
5963 
5964   // C++0x explicit conversion operators.
5965   if (D.getDeclSpec().isExplicitSpecified())
5966     Diag(D.getDeclSpec().getExplicitSpecLoc(),
5967          getLangOpts().CPlusPlus11 ?
5968            diag::warn_cxx98_compat_explicit_conversion_functions :
5969            diag::ext_explicit_conversion_functions)
5970       << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
5971 }
5972 
5973 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5974 /// the declaration of the given C++ conversion function. This routine
5975 /// is responsible for recording the conversion function in the C++
5976 /// class, if possible.
5977 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
5978   assert(Conversion && "Expected to receive a conversion function declaration");
5979 
5980   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
5981 
5982   // Make sure we aren't redeclaring the conversion function.
5983   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
5984 
5985   // C++ [class.conv.fct]p1:
5986   //   [...] A conversion function is never used to convert a
5987   //   (possibly cv-qualified) object to the (possibly cv-qualified)
5988   //   same object type (or a reference to it), to a (possibly
5989   //   cv-qualified) base class of that type (or a reference to it),
5990   //   or to (possibly cv-qualified) void.
5991   // FIXME: Suppress this warning if the conversion function ends up being a
5992   // virtual function that overrides a virtual function in a base class.
5993   QualType ClassType
5994     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
5995   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
5996     ConvType = ConvTypeRef->getPointeeType();
5997   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5998       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
5999     /* Suppress diagnostics for instantiations. */;
6000   else if (ConvType->isRecordType()) {
6001     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6002     if (ConvType == ClassType)
6003       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
6004         << ClassType;
6005     else if (IsDerivedFrom(ClassType, ConvType))
6006       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
6007         <<  ClassType << ConvType;
6008   } else if (ConvType->isVoidType()) {
6009     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
6010       << ClassType << ConvType;
6011   }
6012 
6013   if (FunctionTemplateDecl *ConversionTemplate
6014                                 = Conversion->getDescribedFunctionTemplate())
6015     return ConversionTemplate;
6016 
6017   return Conversion;
6018 }
6019 
6020 //===----------------------------------------------------------------------===//
6021 // Namespace Handling
6022 //===----------------------------------------------------------------------===//
6023 
6024 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6025 /// reopened.
6026 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6027                                             SourceLocation Loc,
6028                                             IdentifierInfo *II, bool *IsInline,
6029                                             NamespaceDecl *PrevNS) {
6030   assert(*IsInline != PrevNS->isInline());
6031 
6032   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6033   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6034   // inline namespaces, with the intention of bringing names into namespace std.
6035   //
6036   // We support this just well enough to get that case working; this is not
6037   // sufficient to support reopening namespaces as inline in general.
6038   if (*IsInline && II && II->getName().startswith("__atomic") &&
6039       S.getSourceManager().isInSystemHeader(Loc)) {
6040     // Mark all prior declarations of the namespace as inline.
6041     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6042          NS = NS->getPreviousDecl())
6043       NS->setInline(*IsInline);
6044     // Patch up the lookup table for the containing namespace. This isn't really
6045     // correct, but it's good enough for this particular case.
6046     for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6047                                     E = PrevNS->decls_end(); I != E; ++I)
6048       if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6049         PrevNS->getParent()->makeDeclVisibleInContext(ND);
6050     return;
6051   }
6052 
6053   if (PrevNS->isInline())
6054     // The user probably just forgot the 'inline', so suggest that it
6055     // be added back.
6056     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6057       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6058   else
6059     S.Diag(Loc, diag::err_inline_namespace_mismatch)
6060       << IsInline;
6061 
6062   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6063   *IsInline = PrevNS->isInline();
6064 }
6065 
6066 /// ActOnStartNamespaceDef - This is called at the start of a namespace
6067 /// definition.
6068 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
6069                                    SourceLocation InlineLoc,
6070                                    SourceLocation NamespaceLoc,
6071                                    SourceLocation IdentLoc,
6072                                    IdentifierInfo *II,
6073                                    SourceLocation LBrace,
6074                                    AttributeList *AttrList) {
6075   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6076   // For anonymous namespace, take the location of the left brace.
6077   SourceLocation Loc = II ? IdentLoc : LBrace;
6078   bool IsInline = InlineLoc.isValid();
6079   bool IsInvalid = false;
6080   bool IsStd = false;
6081   bool AddToKnown = false;
6082   Scope *DeclRegionScope = NamespcScope->getParent();
6083 
6084   NamespaceDecl *PrevNS = 0;
6085   if (II) {
6086     // C++ [namespace.def]p2:
6087     //   The identifier in an original-namespace-definition shall not
6088     //   have been previously defined in the declarative region in
6089     //   which the original-namespace-definition appears. The
6090     //   identifier in an original-namespace-definition is the name of
6091     //   the namespace. Subsequently in that declarative region, it is
6092     //   treated as an original-namespace-name.
6093     //
6094     // Since namespace names are unique in their scope, and we don't
6095     // look through using directives, just look for any ordinary names.
6096 
6097     const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
6098     Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6099     Decl::IDNS_Namespace;
6100     NamedDecl *PrevDecl = 0;
6101     DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6102     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6103          ++I) {
6104       if ((*I)->getIdentifierNamespace() & IDNS) {
6105         PrevDecl = *I;
6106         break;
6107       }
6108     }
6109 
6110     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6111 
6112     if (PrevNS) {
6113       // This is an extended namespace definition.
6114       if (IsInline != PrevNS->isInline())
6115         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6116                                         &IsInline, PrevNS);
6117     } else if (PrevDecl) {
6118       // This is an invalid name redefinition.
6119       Diag(Loc, diag::err_redefinition_different_kind)
6120         << II;
6121       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6122       IsInvalid = true;
6123       // Continue on to push Namespc as current DeclContext and return it.
6124     } else if (II->isStr("std") &&
6125                CurContext->getRedeclContext()->isTranslationUnit()) {
6126       // This is the first "real" definition of the namespace "std", so update
6127       // our cache of the "std" namespace to point at this definition.
6128       PrevNS = getStdNamespace();
6129       IsStd = true;
6130       AddToKnown = !IsInline;
6131     } else {
6132       // We've seen this namespace for the first time.
6133       AddToKnown = !IsInline;
6134     }
6135   } else {
6136     // Anonymous namespaces.
6137 
6138     // Determine whether the parent already has an anonymous namespace.
6139     DeclContext *Parent = CurContext->getRedeclContext();
6140     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6141       PrevNS = TU->getAnonymousNamespace();
6142     } else {
6143       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
6144       PrevNS = ND->getAnonymousNamespace();
6145     }
6146 
6147     if (PrevNS && IsInline != PrevNS->isInline())
6148       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6149                                       &IsInline, PrevNS);
6150   }
6151 
6152   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6153                                                  StartLoc, Loc, II, PrevNS);
6154   if (IsInvalid)
6155     Namespc->setInvalidDecl();
6156 
6157   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
6158 
6159   // FIXME: Should we be merging attributes?
6160   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
6161     PushNamespaceVisibilityAttr(Attr, Loc);
6162 
6163   if (IsStd)
6164     StdNamespace = Namespc;
6165   if (AddToKnown)
6166     KnownNamespaces[Namespc] = false;
6167 
6168   if (II) {
6169     PushOnScopeChains(Namespc, DeclRegionScope);
6170   } else {
6171     // Link the anonymous namespace into its parent.
6172     DeclContext *Parent = CurContext->getRedeclContext();
6173     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6174       TU->setAnonymousNamespace(Namespc);
6175     } else {
6176       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
6177     }
6178 
6179     CurContext->addDecl(Namespc);
6180 
6181     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
6182     //   behaves as if it were replaced by
6183     //     namespace unique { /* empty body */ }
6184     //     using namespace unique;
6185     //     namespace unique { namespace-body }
6186     //   where all occurrences of 'unique' in a translation unit are
6187     //   replaced by the same identifier and this identifier differs
6188     //   from all other identifiers in the entire program.
6189 
6190     // We just create the namespace with an empty name and then add an
6191     // implicit using declaration, just like the standard suggests.
6192     //
6193     // CodeGen enforces the "universally unique" aspect by giving all
6194     // declarations semantically contained within an anonymous
6195     // namespace internal linkage.
6196 
6197     if (!PrevNS) {
6198       UsingDirectiveDecl* UD
6199         = UsingDirectiveDecl::Create(Context, Parent,
6200                                      /* 'using' */ LBrace,
6201                                      /* 'namespace' */ SourceLocation(),
6202                                      /* qualifier */ NestedNameSpecifierLoc(),
6203                                      /* identifier */ SourceLocation(),
6204                                      Namespc,
6205                                      /* Ancestor */ Parent);
6206       UD->setImplicit();
6207       Parent->addDecl(UD);
6208     }
6209   }
6210 
6211   ActOnDocumentableDecl(Namespc);
6212 
6213   // Although we could have an invalid decl (i.e. the namespace name is a
6214   // redefinition), push it as current DeclContext and try to continue parsing.
6215   // FIXME: We should be able to push Namespc here, so that the each DeclContext
6216   // for the namespace has the declarations that showed up in that particular
6217   // namespace definition.
6218   PushDeclContext(NamespcScope, Namespc);
6219   return Namespc;
6220 }
6221 
6222 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6223 /// is a namespace alias, returns the namespace it points to.
6224 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6225   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6226     return AD->getNamespace();
6227   return dyn_cast_or_null<NamespaceDecl>(D);
6228 }
6229 
6230 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
6231 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
6232 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
6233   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6234   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
6235   Namespc->setRBraceLoc(RBrace);
6236   PopDeclContext();
6237   if (Namespc->hasAttr<VisibilityAttr>())
6238     PopPragmaVisibility(true, RBrace);
6239 }
6240 
6241 CXXRecordDecl *Sema::getStdBadAlloc() const {
6242   return cast_or_null<CXXRecordDecl>(
6243                                   StdBadAlloc.get(Context.getExternalSource()));
6244 }
6245 
6246 NamespaceDecl *Sema::getStdNamespace() const {
6247   return cast_or_null<NamespaceDecl>(
6248                                  StdNamespace.get(Context.getExternalSource()));
6249 }
6250 
6251 /// \brief Retrieve the special "std" namespace, which may require us to
6252 /// implicitly define the namespace.
6253 NamespaceDecl *Sema::getOrCreateStdNamespace() {
6254   if (!StdNamespace) {
6255     // The "std" namespace has not yet been defined, so build one implicitly.
6256     StdNamespace = NamespaceDecl::Create(Context,
6257                                          Context.getTranslationUnitDecl(),
6258                                          /*Inline=*/false,
6259                                          SourceLocation(), SourceLocation(),
6260                                          &PP.getIdentifierTable().get("std"),
6261                                          /*PrevDecl=*/0);
6262     getStdNamespace()->setImplicit(true);
6263   }
6264 
6265   return getStdNamespace();
6266 }
6267 
6268 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
6269   assert(getLangOpts().CPlusPlus &&
6270          "Looking for std::initializer_list outside of C++.");
6271 
6272   // We're looking for implicit instantiations of
6273   // template <typename E> class std::initializer_list.
6274 
6275   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6276     return false;
6277 
6278   ClassTemplateDecl *Template = 0;
6279   const TemplateArgument *Arguments = 0;
6280 
6281   if (const RecordType *RT = Ty->getAs<RecordType>()) {
6282 
6283     ClassTemplateSpecializationDecl *Specialization =
6284         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6285     if (!Specialization)
6286       return false;
6287 
6288     Template = Specialization->getSpecializedTemplate();
6289     Arguments = Specialization->getTemplateArgs().data();
6290   } else if (const TemplateSpecializationType *TST =
6291                  Ty->getAs<TemplateSpecializationType>()) {
6292     Template = dyn_cast_or_null<ClassTemplateDecl>(
6293         TST->getTemplateName().getAsTemplateDecl());
6294     Arguments = TST->getArgs();
6295   }
6296   if (!Template)
6297     return false;
6298 
6299   if (!StdInitializerList) {
6300     // Haven't recognized std::initializer_list yet, maybe this is it.
6301     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6302     if (TemplateClass->getIdentifier() !=
6303             &PP.getIdentifierTable().get("initializer_list") ||
6304         !getStdNamespace()->InEnclosingNamespaceSetOf(
6305             TemplateClass->getDeclContext()))
6306       return false;
6307     // This is a template called std::initializer_list, but is it the right
6308     // template?
6309     TemplateParameterList *Params = Template->getTemplateParameters();
6310     if (Params->getMinRequiredArguments() != 1)
6311       return false;
6312     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6313       return false;
6314 
6315     // It's the right template.
6316     StdInitializerList = Template;
6317   }
6318 
6319   if (Template != StdInitializerList)
6320     return false;
6321 
6322   // This is an instance of std::initializer_list. Find the argument type.
6323   if (Element)
6324     *Element = Arguments[0].getAsType();
6325   return true;
6326 }
6327 
6328 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6329   NamespaceDecl *Std = S.getStdNamespace();
6330   if (!Std) {
6331     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6332     return 0;
6333   }
6334 
6335   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6336                       Loc, Sema::LookupOrdinaryName);
6337   if (!S.LookupQualifiedName(Result, Std)) {
6338     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6339     return 0;
6340   }
6341   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6342   if (!Template) {
6343     Result.suppressDiagnostics();
6344     // We found something weird. Complain about the first thing we found.
6345     NamedDecl *Found = *Result.begin();
6346     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6347     return 0;
6348   }
6349 
6350   // We found some template called std::initializer_list. Now verify that it's
6351   // correct.
6352   TemplateParameterList *Params = Template->getTemplateParameters();
6353   if (Params->getMinRequiredArguments() != 1 ||
6354       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6355     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6356     return 0;
6357   }
6358 
6359   return Template;
6360 }
6361 
6362 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6363   if (!StdInitializerList) {
6364     StdInitializerList = LookupStdInitializerList(*this, Loc);
6365     if (!StdInitializerList)
6366       return QualType();
6367   }
6368 
6369   TemplateArgumentListInfo Args(Loc, Loc);
6370   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6371                                        Context.getTrivialTypeSourceInfo(Element,
6372                                                                         Loc)));
6373   return Context.getCanonicalType(
6374       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6375 }
6376 
6377 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6378   // C++ [dcl.init.list]p2:
6379   //   A constructor is an initializer-list constructor if its first parameter
6380   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
6381   //   std::initializer_list<E> for some type E, and either there are no other
6382   //   parameters or else all other parameters have default arguments.
6383   if (Ctor->getNumParams() < 1 ||
6384       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6385     return false;
6386 
6387   QualType ArgType = Ctor->getParamDecl(0)->getType();
6388   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6389     ArgType = RT->getPointeeType().getUnqualifiedType();
6390 
6391   return isStdInitializerList(ArgType, 0);
6392 }
6393 
6394 /// \brief Determine whether a using statement is in a context where it will be
6395 /// apply in all contexts.
6396 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6397   switch (CurContext->getDeclKind()) {
6398     case Decl::TranslationUnit:
6399       return true;
6400     case Decl::LinkageSpec:
6401       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6402     default:
6403       return false;
6404   }
6405 }
6406 
6407 namespace {
6408 
6409 // Callback to only accept typo corrections that are namespaces.
6410 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6411  public:
6412   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6413     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6414       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6415     }
6416     return false;
6417   }
6418 };
6419 
6420 }
6421 
6422 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6423                                        CXXScopeSpec &SS,
6424                                        SourceLocation IdentLoc,
6425                                        IdentifierInfo *Ident) {
6426   NamespaceValidatorCCC Validator;
6427   R.clear();
6428   if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
6429                                                R.getLookupKind(), Sc, &SS,
6430                                                Validator)) {
6431     std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6432     std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
6433     if (DeclContext *DC = S.computeDeclContext(SS, false))
6434       S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6435         << Ident << DC << CorrectedQuotedStr << SS.getRange()
6436         << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
6437                                         CorrectedStr);
6438     else
6439       S.Diag(IdentLoc, diag::err_using_directive_suggest)
6440         << Ident << CorrectedQuotedStr
6441         << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
6442 
6443     S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6444          diag::note_namespace_defined_here) << CorrectedQuotedStr;
6445 
6446     R.addDecl(Corrected.getCorrectionDecl());
6447     return true;
6448   }
6449   return false;
6450 }
6451 
6452 Decl *Sema::ActOnUsingDirective(Scope *S,
6453                                           SourceLocation UsingLoc,
6454                                           SourceLocation NamespcLoc,
6455                                           CXXScopeSpec &SS,
6456                                           SourceLocation IdentLoc,
6457                                           IdentifierInfo *NamespcName,
6458                                           AttributeList *AttrList) {
6459   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6460   assert(NamespcName && "Invalid NamespcName.");
6461   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
6462 
6463   // This can only happen along a recovery path.
6464   while (S->getFlags() & Scope::TemplateParamScope)
6465     S = S->getParent();
6466   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
6467 
6468   UsingDirectiveDecl *UDir = 0;
6469   NestedNameSpecifier *Qualifier = 0;
6470   if (SS.isSet())
6471     Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6472 
6473   // Lookup namespace name.
6474   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6475   LookupParsedName(R, S, &SS);
6476   if (R.isAmbiguous())
6477     return 0;
6478 
6479   if (R.empty()) {
6480     R.clear();
6481     // Allow "using namespace std;" or "using namespace ::std;" even if
6482     // "std" hasn't been defined yet, for GCC compatibility.
6483     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6484         NamespcName->isStr("std")) {
6485       Diag(IdentLoc, diag::ext_using_undefined_std);
6486       R.addDecl(getOrCreateStdNamespace());
6487       R.resolveKind();
6488     }
6489     // Otherwise, attempt typo correction.
6490     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
6491   }
6492 
6493   if (!R.empty()) {
6494     NamedDecl *Named = R.getFoundDecl();
6495     assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6496         && "expected namespace decl");
6497     // C++ [namespace.udir]p1:
6498     //   A using-directive specifies that the names in the nominated
6499     //   namespace can be used in the scope in which the
6500     //   using-directive appears after the using-directive. During
6501     //   unqualified name lookup (3.4.1), the names appear as if they
6502     //   were declared in the nearest enclosing namespace which
6503     //   contains both the using-directive and the nominated
6504     //   namespace. [Note: in this context, "contains" means "contains
6505     //   directly or indirectly". ]
6506 
6507     // Find enclosing context containing both using-directive and
6508     // nominated namespace.
6509     NamespaceDecl *NS = getNamespaceDecl(Named);
6510     DeclContext *CommonAncestor = cast<DeclContext>(NS);
6511     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6512       CommonAncestor = CommonAncestor->getParent();
6513 
6514     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
6515                                       SS.getWithLocInContext(Context),
6516                                       IdentLoc, Named, CommonAncestor);
6517 
6518     if (IsUsingDirectiveInToplevelContext(CurContext) &&
6519         !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
6520       Diag(IdentLoc, diag::warn_using_directive_in_header);
6521     }
6522 
6523     PushUsingDirective(S, UDir);
6524   } else {
6525     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
6526   }
6527 
6528   if (UDir)
6529     ProcessDeclAttributeList(S, UDir, AttrList);
6530 
6531   return UDir;
6532 }
6533 
6534 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
6535   // If the scope has an associated entity and the using directive is at
6536   // namespace or translation unit scope, add the UsingDirectiveDecl into
6537   // its lookup structure so qualified name lookup can find it.
6538   DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6539   if (Ctx && !Ctx->isFunctionOrMethod())
6540     Ctx->addDecl(UDir);
6541   else
6542     // Otherwise, it is at block sope. The using-directives will affect lookup
6543     // only to the end of the scope.
6544     S->PushUsingDirective(UDir);
6545 }
6546 
6547 
6548 Decl *Sema::ActOnUsingDeclaration(Scope *S,
6549                                   AccessSpecifier AS,
6550                                   bool HasUsingKeyword,
6551                                   SourceLocation UsingLoc,
6552                                   CXXScopeSpec &SS,
6553                                   UnqualifiedId &Name,
6554                                   AttributeList *AttrList,
6555                                   bool IsTypeName,
6556                                   SourceLocation TypenameLoc) {
6557   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
6558 
6559   switch (Name.getKind()) {
6560   case UnqualifiedId::IK_ImplicitSelfParam:
6561   case UnqualifiedId::IK_Identifier:
6562   case UnqualifiedId::IK_OperatorFunctionId:
6563   case UnqualifiedId::IK_LiteralOperatorId:
6564   case UnqualifiedId::IK_ConversionFunctionId:
6565     break;
6566 
6567   case UnqualifiedId::IK_ConstructorName:
6568   case UnqualifiedId::IK_ConstructorTemplateId:
6569     // C++11 inheriting constructors.
6570     Diag(Name.getLocStart(),
6571          getLangOpts().CPlusPlus11 ?
6572            diag::warn_cxx98_compat_using_decl_constructor :
6573            diag::err_using_decl_constructor)
6574       << SS.getRange();
6575 
6576     if (getLangOpts().CPlusPlus11) break;
6577 
6578     return 0;
6579 
6580   case UnqualifiedId::IK_DestructorName:
6581     Diag(Name.getLocStart(), diag::err_using_decl_destructor)
6582       << SS.getRange();
6583     return 0;
6584 
6585   case UnqualifiedId::IK_TemplateId:
6586     Diag(Name.getLocStart(), diag::err_using_decl_template_id)
6587       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
6588     return 0;
6589   }
6590 
6591   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6592   DeclarationName TargetName = TargetNameInfo.getName();
6593   if (!TargetName)
6594     return 0;
6595 
6596   // Warn about access declarations.
6597   // TODO: store that the declaration was written without 'using' and
6598   // talk about access decls instead of using decls in the
6599   // diagnostics.
6600   if (!HasUsingKeyword) {
6601     UsingLoc = Name.getLocStart();
6602 
6603     Diag(UsingLoc, diag::warn_access_decl_deprecated)
6604       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
6605   }
6606 
6607   if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6608       DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6609     return 0;
6610 
6611   NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
6612                                         TargetNameInfo, AttrList,
6613                                         /* IsInstantiation */ false,
6614                                         IsTypeName, TypenameLoc);
6615   if (UD)
6616     PushOnScopeChains(UD, S, /*AddToContext*/ false);
6617 
6618   return UD;
6619 }
6620 
6621 /// \brief Determine whether a using declaration considers the given
6622 /// declarations as "equivalent", e.g., if they are redeclarations of
6623 /// the same entity or are both typedefs of the same type.
6624 static bool
6625 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6626                          bool &SuppressRedeclaration) {
6627   if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6628     SuppressRedeclaration = false;
6629     return true;
6630   }
6631 
6632   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6633     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
6634       SuppressRedeclaration = true;
6635       return Context.hasSameType(TD1->getUnderlyingType(),
6636                                  TD2->getUnderlyingType());
6637     }
6638 
6639   return false;
6640 }
6641 
6642 
6643 /// Determines whether to create a using shadow decl for a particular
6644 /// decl, given the set of decls existing prior to this using lookup.
6645 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6646                                 const LookupResult &Previous) {
6647   // Diagnose finding a decl which is not from a base class of the
6648   // current class.  We do this now because there are cases where this
6649   // function will silently decide not to build a shadow decl, which
6650   // will pre-empt further diagnostics.
6651   //
6652   // We don't need to do this in C++0x because we do the check once on
6653   // the qualifier.
6654   //
6655   // FIXME: diagnose the following if we care enough:
6656   //   struct A { int foo; };
6657   //   struct B : A { using A::foo; };
6658   //   template <class T> struct C : A {};
6659   //   template <class T> struct D : C<T> { using B::foo; } // <---
6660   // This is invalid (during instantiation) in C++03 because B::foo
6661   // resolves to the using decl in B, which is not a base class of D<T>.
6662   // We can't diagnose it immediately because C<T> is an unknown
6663   // specialization.  The UsingShadowDecl in D<T> then points directly
6664   // to A::foo, which will look well-formed when we instantiate.
6665   // The right solution is to not collapse the shadow-decl chain.
6666   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
6667     DeclContext *OrigDC = Orig->getDeclContext();
6668 
6669     // Handle enums and anonymous structs.
6670     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6671     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6672     while (OrigRec->isAnonymousStructOrUnion())
6673       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6674 
6675     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6676       if (OrigDC == CurContext) {
6677         Diag(Using->getLocation(),
6678              diag::err_using_decl_nested_name_specifier_is_current_class)
6679           << Using->getQualifierLoc().getSourceRange();
6680         Diag(Orig->getLocation(), diag::note_using_decl_target);
6681         return true;
6682       }
6683 
6684       Diag(Using->getQualifierLoc().getBeginLoc(),
6685            diag::err_using_decl_nested_name_specifier_is_not_base_class)
6686         << Using->getQualifier()
6687         << cast<CXXRecordDecl>(CurContext)
6688         << Using->getQualifierLoc().getSourceRange();
6689       Diag(Orig->getLocation(), diag::note_using_decl_target);
6690       return true;
6691     }
6692   }
6693 
6694   if (Previous.empty()) return false;
6695 
6696   NamedDecl *Target = Orig;
6697   if (isa<UsingShadowDecl>(Target))
6698     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6699 
6700   // If the target happens to be one of the previous declarations, we
6701   // don't have a conflict.
6702   //
6703   // FIXME: but we might be increasing its access, in which case we
6704   // should redeclare it.
6705   NamedDecl *NonTag = 0, *Tag = 0;
6706   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6707          I != E; ++I) {
6708     NamedDecl *D = (*I)->getUnderlyingDecl();
6709     bool Result;
6710     if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6711       return Result;
6712 
6713     (isa<TagDecl>(D) ? Tag : NonTag) = D;
6714   }
6715 
6716   if (Target->isFunctionOrFunctionTemplate()) {
6717     FunctionDecl *FD;
6718     if (isa<FunctionTemplateDecl>(Target))
6719       FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6720     else
6721       FD = cast<FunctionDecl>(Target);
6722 
6723     NamedDecl *OldDecl = 0;
6724     switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
6725     case Ovl_Overload:
6726       return false;
6727 
6728     case Ovl_NonFunction:
6729       Diag(Using->getLocation(), diag::err_using_decl_conflict);
6730       break;
6731 
6732     // We found a decl with the exact signature.
6733     case Ovl_Match:
6734       // If we're in a record, we want to hide the target, so we
6735       // return true (without a diagnostic) to tell the caller not to
6736       // build a shadow decl.
6737       if (CurContext->isRecord())
6738         return true;
6739 
6740       // If we're not in a record, this is an error.
6741       Diag(Using->getLocation(), diag::err_using_decl_conflict);
6742       break;
6743     }
6744 
6745     Diag(Target->getLocation(), diag::note_using_decl_target);
6746     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6747     return true;
6748   }
6749 
6750   // Target is not a function.
6751 
6752   if (isa<TagDecl>(Target)) {
6753     // No conflict between a tag and a non-tag.
6754     if (!Tag) return false;
6755 
6756     Diag(Using->getLocation(), diag::err_using_decl_conflict);
6757     Diag(Target->getLocation(), diag::note_using_decl_target);
6758     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6759     return true;
6760   }
6761 
6762   // No conflict between a tag and a non-tag.
6763   if (!NonTag) return false;
6764 
6765   Diag(Using->getLocation(), diag::err_using_decl_conflict);
6766   Diag(Target->getLocation(), diag::note_using_decl_target);
6767   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6768   return true;
6769 }
6770 
6771 /// Builds a shadow declaration corresponding to a 'using' declaration.
6772 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
6773                                             UsingDecl *UD,
6774                                             NamedDecl *Orig) {
6775 
6776   // If we resolved to another shadow declaration, just coalesce them.
6777   NamedDecl *Target = Orig;
6778   if (isa<UsingShadowDecl>(Target)) {
6779     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6780     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
6781   }
6782 
6783   UsingShadowDecl *Shadow
6784     = UsingShadowDecl::Create(Context, CurContext,
6785                               UD->getLocation(), UD, Target);
6786   UD->addShadowDecl(Shadow);
6787 
6788   Shadow->setAccess(UD->getAccess());
6789   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6790     Shadow->setInvalidDecl();
6791 
6792   if (S)
6793     PushOnScopeChains(Shadow, S);
6794   else
6795     CurContext->addDecl(Shadow);
6796 
6797 
6798   return Shadow;
6799 }
6800 
6801 /// Hides a using shadow declaration.  This is required by the current
6802 /// using-decl implementation when a resolvable using declaration in a
6803 /// class is followed by a declaration which would hide or override
6804 /// one or more of the using decl's targets; for example:
6805 ///
6806 ///   struct Base { void foo(int); };
6807 ///   struct Derived : Base {
6808 ///     using Base::foo;
6809 ///     void foo(int);
6810 ///   };
6811 ///
6812 /// The governing language is C++03 [namespace.udecl]p12:
6813 ///
6814 ///   When a using-declaration brings names from a base class into a
6815 ///   derived class scope, member functions in the derived class
6816 ///   override and/or hide member functions with the same name and
6817 ///   parameter types in a base class (rather than conflicting).
6818 ///
6819 /// There are two ways to implement this:
6820 ///   (1) optimistically create shadow decls when they're not hidden
6821 ///       by existing declarations, or
6822 ///   (2) don't create any shadow decls (or at least don't make them
6823 ///       visible) until we've fully parsed/instantiated the class.
6824 /// The problem with (1) is that we might have to retroactively remove
6825 /// a shadow decl, which requires several O(n) operations because the
6826 /// decl structures are (very reasonably) not designed for removal.
6827 /// (2) avoids this but is very fiddly and phase-dependent.
6828 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
6829   if (Shadow->getDeclName().getNameKind() ==
6830         DeclarationName::CXXConversionFunctionName)
6831     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6832 
6833   // Remove it from the DeclContext...
6834   Shadow->getDeclContext()->removeDecl(Shadow);
6835 
6836   // ...and the scope, if applicable...
6837   if (S) {
6838     S->RemoveDecl(Shadow);
6839     IdResolver.RemoveDecl(Shadow);
6840   }
6841 
6842   // ...and the using decl.
6843   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6844 
6845   // TODO: complain somehow if Shadow was used.  It shouldn't
6846   // be possible for this to happen, because...?
6847 }
6848 
6849 /// Builds a using declaration.
6850 ///
6851 /// \param IsInstantiation - Whether this call arises from an
6852 ///   instantiation of an unresolved using declaration.  We treat
6853 ///   the lookup differently for these declarations.
6854 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6855                                        SourceLocation UsingLoc,
6856                                        CXXScopeSpec &SS,
6857                                        const DeclarationNameInfo &NameInfo,
6858                                        AttributeList *AttrList,
6859                                        bool IsInstantiation,
6860                                        bool IsTypeName,
6861                                        SourceLocation TypenameLoc) {
6862   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6863   SourceLocation IdentLoc = NameInfo.getLoc();
6864   assert(IdentLoc.isValid() && "Invalid TargetName location.");
6865 
6866   // FIXME: We ignore attributes for now.
6867 
6868   if (SS.isEmpty()) {
6869     Diag(IdentLoc, diag::err_using_requires_qualname);
6870     return 0;
6871   }
6872 
6873   // Do the redeclaration lookup in the current scope.
6874   LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
6875                         ForRedeclaration);
6876   Previous.setHideTags(false);
6877   if (S) {
6878     LookupName(Previous, S);
6879 
6880     // It is really dumb that we have to do this.
6881     LookupResult::Filter F = Previous.makeFilter();
6882     while (F.hasNext()) {
6883       NamedDecl *D = F.next();
6884       if (!isDeclInScope(D, CurContext, S))
6885         F.erase();
6886     }
6887     F.done();
6888   } else {
6889     assert(IsInstantiation && "no scope in non-instantiation");
6890     assert(CurContext->isRecord() && "scope not record in instantiation");
6891     LookupQualifiedName(Previous, CurContext);
6892   }
6893 
6894   // Check for invalid redeclarations.
6895   if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6896     return 0;
6897 
6898   // Check for bad qualifiers.
6899   if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6900     return 0;
6901 
6902   DeclContext *LookupContext = computeDeclContext(SS);
6903   NamedDecl *D;
6904   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
6905   if (!LookupContext) {
6906     if (IsTypeName) {
6907       // FIXME: not all declaration name kinds are legal here
6908       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6909                                               UsingLoc, TypenameLoc,
6910                                               QualifierLoc,
6911                                               IdentLoc, NameInfo.getName());
6912     } else {
6913       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6914                                            QualifierLoc, NameInfo);
6915     }
6916   } else {
6917     D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6918                           NameInfo, IsTypeName);
6919   }
6920   D->setAccess(AS);
6921   CurContext->addDecl(D);
6922 
6923   if (!LookupContext) return D;
6924   UsingDecl *UD = cast<UsingDecl>(D);
6925 
6926   if (RequireCompleteDeclContext(SS, LookupContext)) {
6927     UD->setInvalidDecl();
6928     return UD;
6929   }
6930 
6931   // The normal rules do not apply to inheriting constructor declarations.
6932   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
6933     if (CheckInheritingConstructorUsingDecl(UD))
6934       UD->setInvalidDecl();
6935     return UD;
6936   }
6937 
6938   // Otherwise, look up the target name.
6939 
6940   LookupResult R(*this, NameInfo, LookupOrdinaryName);
6941 
6942   // Unlike most lookups, we don't always want to hide tag
6943   // declarations: tag names are visible through the using declaration
6944   // even if hidden by ordinary names, *except* in a dependent context
6945   // where it's important for the sanity of two-phase lookup.
6946   if (!IsInstantiation)
6947     R.setHideTags(false);
6948 
6949   // For the purposes of this lookup, we have a base object type
6950   // equal to that of the current context.
6951   if (CurContext->isRecord()) {
6952     R.setBaseObjectType(
6953                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6954   }
6955 
6956   LookupQualifiedName(R, LookupContext);
6957 
6958   if (R.empty()) {
6959     Diag(IdentLoc, diag::err_no_member)
6960       << NameInfo.getName() << LookupContext << SS.getRange();
6961     UD->setInvalidDecl();
6962     return UD;
6963   }
6964 
6965   if (R.isAmbiguous()) {
6966     UD->setInvalidDecl();
6967     return UD;
6968   }
6969 
6970   if (IsTypeName) {
6971     // If we asked for a typename and got a non-type decl, error out.
6972     if (!R.getAsSingle<TypeDecl>()) {
6973       Diag(IdentLoc, diag::err_using_typename_non_type);
6974       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6975         Diag((*I)->getUnderlyingDecl()->getLocation(),
6976              diag::note_using_decl_target);
6977       UD->setInvalidDecl();
6978       return UD;
6979     }
6980   } else {
6981     // If we asked for a non-typename and we got a type, error out,
6982     // but only if this is an instantiation of an unresolved using
6983     // decl.  Otherwise just silently find the type name.
6984     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
6985       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6986       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
6987       UD->setInvalidDecl();
6988       return UD;
6989     }
6990   }
6991 
6992   // C++0x N2914 [namespace.udecl]p6:
6993   // A using-declaration shall not name a namespace.
6994   if (R.getAsSingle<NamespaceDecl>()) {
6995     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6996       << SS.getRange();
6997     UD->setInvalidDecl();
6998     return UD;
6999   }
7000 
7001   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7002     if (!CheckUsingShadowDecl(UD, *I, Previous))
7003       BuildUsingShadowDecl(S, UD, *I);
7004   }
7005 
7006   return UD;
7007 }
7008 
7009 /// Additional checks for a using declaration referring to a constructor name.
7010 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
7011   assert(!UD->isTypeName() && "expecting a constructor name");
7012 
7013   const Type *SourceType = UD->getQualifier()->getAsType();
7014   assert(SourceType &&
7015          "Using decl naming constructor doesn't have type in scope spec.");
7016   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7017 
7018   // Check whether the named type is a direct base class.
7019   CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7020   CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7021   for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7022        BaseIt != BaseE; ++BaseIt) {
7023     CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7024     if (CanonicalSourceType == BaseType)
7025       break;
7026     if (BaseIt->getType()->isDependentType())
7027       break;
7028   }
7029 
7030   if (BaseIt == BaseE) {
7031     // Did not find SourceType in the bases.
7032     Diag(UD->getUsingLocation(),
7033          diag::err_using_decl_constructor_not_in_direct_base)
7034       << UD->getNameInfo().getSourceRange()
7035       << QualType(SourceType, 0) << TargetClass;
7036     return true;
7037   }
7038 
7039   if (!CurContext->isDependentContext())
7040     BaseIt->setInheritConstructors();
7041 
7042   return false;
7043 }
7044 
7045 /// Checks that the given using declaration is not an invalid
7046 /// redeclaration.  Note that this is checking only for the using decl
7047 /// itself, not for any ill-formedness among the UsingShadowDecls.
7048 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7049                                        bool isTypeName,
7050                                        const CXXScopeSpec &SS,
7051                                        SourceLocation NameLoc,
7052                                        const LookupResult &Prev) {
7053   // C++03 [namespace.udecl]p8:
7054   // C++0x [namespace.udecl]p10:
7055   //   A using-declaration is a declaration and can therefore be used
7056   //   repeatedly where (and only where) multiple declarations are
7057   //   allowed.
7058   //
7059   // That's in non-member contexts.
7060   if (!CurContext->getRedeclContext()->isRecord())
7061     return false;
7062 
7063   NestedNameSpecifier *Qual
7064     = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7065 
7066   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7067     NamedDecl *D = *I;
7068 
7069     bool DTypename;
7070     NestedNameSpecifier *DQual;
7071     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7072       DTypename = UD->isTypeName();
7073       DQual = UD->getQualifier();
7074     } else if (UnresolvedUsingValueDecl *UD
7075                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7076       DTypename = false;
7077       DQual = UD->getQualifier();
7078     } else if (UnresolvedUsingTypenameDecl *UD
7079                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7080       DTypename = true;
7081       DQual = UD->getQualifier();
7082     } else continue;
7083 
7084     // using decls differ if one says 'typename' and the other doesn't.
7085     // FIXME: non-dependent using decls?
7086     if (isTypeName != DTypename) continue;
7087 
7088     // using decls differ if they name different scopes (but note that
7089     // template instantiation can cause this check to trigger when it
7090     // didn't before instantiation).
7091     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7092         Context.getCanonicalNestedNameSpecifier(DQual))
7093       continue;
7094 
7095     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
7096     Diag(D->getLocation(), diag::note_using_decl) << 1;
7097     return true;
7098   }
7099 
7100   return false;
7101 }
7102 
7103 
7104 /// Checks that the given nested-name qualifier used in a using decl
7105 /// in the current context is appropriately related to the current
7106 /// scope.  If an error is found, diagnoses it and returns true.
7107 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7108                                    const CXXScopeSpec &SS,
7109                                    SourceLocation NameLoc) {
7110   DeclContext *NamedContext = computeDeclContext(SS);
7111 
7112   if (!CurContext->isRecord()) {
7113     // C++03 [namespace.udecl]p3:
7114     // C++0x [namespace.udecl]p8:
7115     //   A using-declaration for a class member shall be a member-declaration.
7116 
7117     // If we weren't able to compute a valid scope, it must be a
7118     // dependent class scope.
7119     if (!NamedContext || NamedContext->isRecord()) {
7120       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7121         << SS.getRange();
7122       return true;
7123     }
7124 
7125     // Otherwise, everything is known to be fine.
7126     return false;
7127   }
7128 
7129   // The current scope is a record.
7130 
7131   // If the named context is dependent, we can't decide much.
7132   if (!NamedContext) {
7133     // FIXME: in C++0x, we can diagnose if we can prove that the
7134     // nested-name-specifier does not refer to a base class, which is
7135     // still possible in some cases.
7136 
7137     // Otherwise we have to conservatively report that things might be
7138     // okay.
7139     return false;
7140   }
7141 
7142   if (!NamedContext->isRecord()) {
7143     // Ideally this would point at the last name in the specifier,
7144     // but we don't have that level of source info.
7145     Diag(SS.getRange().getBegin(),
7146          diag::err_using_decl_nested_name_specifier_is_not_class)
7147       << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7148     return true;
7149   }
7150 
7151   if (!NamedContext->isDependentContext() &&
7152       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7153     return true;
7154 
7155   if (getLangOpts().CPlusPlus11) {
7156     // C++0x [namespace.udecl]p3:
7157     //   In a using-declaration used as a member-declaration, the
7158     //   nested-name-specifier shall name a base class of the class
7159     //   being defined.
7160 
7161     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7162                                  cast<CXXRecordDecl>(NamedContext))) {
7163       if (CurContext == NamedContext) {
7164         Diag(NameLoc,
7165              diag::err_using_decl_nested_name_specifier_is_current_class)
7166           << SS.getRange();
7167         return true;
7168       }
7169 
7170       Diag(SS.getRange().getBegin(),
7171            diag::err_using_decl_nested_name_specifier_is_not_base_class)
7172         << (NestedNameSpecifier*) SS.getScopeRep()
7173         << cast<CXXRecordDecl>(CurContext)
7174         << SS.getRange();
7175       return true;
7176     }
7177 
7178     return false;
7179   }
7180 
7181   // C++03 [namespace.udecl]p4:
7182   //   A using-declaration used as a member-declaration shall refer
7183   //   to a member of a base class of the class being defined [etc.].
7184 
7185   // Salient point: SS doesn't have to name a base class as long as
7186   // lookup only finds members from base classes.  Therefore we can
7187   // diagnose here only if we can prove that that can't happen,
7188   // i.e. if the class hierarchies provably don't intersect.
7189 
7190   // TODO: it would be nice if "definitely valid" results were cached
7191   // in the UsingDecl and UsingShadowDecl so that these checks didn't
7192   // need to be repeated.
7193 
7194   struct UserData {
7195     llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
7196 
7197     static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7198       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7199       Data->Bases.insert(Base);
7200       return true;
7201     }
7202 
7203     bool hasDependentBases(const CXXRecordDecl *Class) {
7204       return !Class->forallBases(collect, this);
7205     }
7206 
7207     /// Returns true if the base is dependent or is one of the
7208     /// accumulated base classes.
7209     static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7210       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7211       return !Data->Bases.count(Base);
7212     }
7213 
7214     bool mightShareBases(const CXXRecordDecl *Class) {
7215       return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7216     }
7217   };
7218 
7219   UserData Data;
7220 
7221   // Returns false if we find a dependent base.
7222   if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7223     return false;
7224 
7225   // Returns false if the class has a dependent base or if it or one
7226   // of its bases is present in the base set of the current context.
7227   if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7228     return false;
7229 
7230   Diag(SS.getRange().getBegin(),
7231        diag::err_using_decl_nested_name_specifier_is_not_base_class)
7232     << (NestedNameSpecifier*) SS.getScopeRep()
7233     << cast<CXXRecordDecl>(CurContext)
7234     << SS.getRange();
7235 
7236   return true;
7237 }
7238 
7239 Decl *Sema::ActOnAliasDeclaration(Scope *S,
7240                                   AccessSpecifier AS,
7241                                   MultiTemplateParamsArg TemplateParamLists,
7242                                   SourceLocation UsingLoc,
7243                                   UnqualifiedId &Name,
7244                                   AttributeList *AttrList,
7245                                   TypeResult Type) {
7246   // Skip up to the relevant declaration scope.
7247   while (S->getFlags() & Scope::TemplateParamScope)
7248     S = S->getParent();
7249   assert((S->getFlags() & Scope::DeclScope) &&
7250          "got alias-declaration outside of declaration scope");
7251 
7252   if (Type.isInvalid())
7253     return 0;
7254 
7255   bool Invalid = false;
7256   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7257   TypeSourceInfo *TInfo = 0;
7258   GetTypeFromParser(Type.get(), &TInfo);
7259 
7260   if (DiagnoseClassNameShadow(CurContext, NameInfo))
7261     return 0;
7262 
7263   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
7264                                       UPPC_DeclarationType)) {
7265     Invalid = true;
7266     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7267                                              TInfo->getTypeLoc().getBeginLoc());
7268   }
7269 
7270   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7271   LookupName(Previous, S);
7272 
7273   // Warn about shadowing the name of a template parameter.
7274   if (Previous.isSingleResult() &&
7275       Previous.getFoundDecl()->isTemplateParameter()) {
7276     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
7277     Previous.clear();
7278   }
7279 
7280   assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7281          "name in alias declaration must be an identifier");
7282   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7283                                                Name.StartLocation,
7284                                                Name.Identifier, TInfo);
7285 
7286   NewTD->setAccess(AS);
7287 
7288   if (Invalid)
7289     NewTD->setInvalidDecl();
7290 
7291   ProcessDeclAttributeList(S, NewTD, AttrList);
7292 
7293   CheckTypedefForVariablyModifiedType(S, NewTD);
7294   Invalid |= NewTD->isInvalidDecl();
7295 
7296   bool Redeclaration = false;
7297 
7298   NamedDecl *NewND;
7299   if (TemplateParamLists.size()) {
7300     TypeAliasTemplateDecl *OldDecl = 0;
7301     TemplateParameterList *OldTemplateParams = 0;
7302 
7303     if (TemplateParamLists.size() != 1) {
7304       Diag(UsingLoc, diag::err_alias_template_extra_headers)
7305         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7306          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
7307     }
7308     TemplateParameterList *TemplateParams = TemplateParamLists[0];
7309 
7310     // Only consider previous declarations in the same scope.
7311     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7312                          /*ExplicitInstantiationOrSpecialization*/false);
7313     if (!Previous.empty()) {
7314       Redeclaration = true;
7315 
7316       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7317       if (!OldDecl && !Invalid) {
7318         Diag(UsingLoc, diag::err_redefinition_different_kind)
7319           << Name.Identifier;
7320 
7321         NamedDecl *OldD = Previous.getRepresentativeDecl();
7322         if (OldD->getLocation().isValid())
7323           Diag(OldD->getLocation(), diag::note_previous_definition);
7324 
7325         Invalid = true;
7326       }
7327 
7328       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7329         if (TemplateParameterListsAreEqual(TemplateParams,
7330                                            OldDecl->getTemplateParameters(),
7331                                            /*Complain=*/true,
7332                                            TPL_TemplateMatch))
7333           OldTemplateParams = OldDecl->getTemplateParameters();
7334         else
7335           Invalid = true;
7336 
7337         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7338         if (!Invalid &&
7339             !Context.hasSameType(OldTD->getUnderlyingType(),
7340                                  NewTD->getUnderlyingType())) {
7341           // FIXME: The C++0x standard does not clearly say this is ill-formed,
7342           // but we can't reasonably accept it.
7343           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7344             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7345           if (OldTD->getLocation().isValid())
7346             Diag(OldTD->getLocation(), diag::note_previous_definition);
7347           Invalid = true;
7348         }
7349       }
7350     }
7351 
7352     // Merge any previous default template arguments into our parameters,
7353     // and check the parameter list.
7354     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7355                                    TPC_TypeAliasTemplate))
7356       return 0;
7357 
7358     TypeAliasTemplateDecl *NewDecl =
7359       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7360                                     Name.Identifier, TemplateParams,
7361                                     NewTD);
7362 
7363     NewDecl->setAccess(AS);
7364 
7365     if (Invalid)
7366       NewDecl->setInvalidDecl();
7367     else if (OldDecl)
7368       NewDecl->setPreviousDeclaration(OldDecl);
7369 
7370     NewND = NewDecl;
7371   } else {
7372     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7373     NewND = NewTD;
7374   }
7375 
7376   if (!Redeclaration)
7377     PushOnScopeChains(NewND, S);
7378 
7379   ActOnDocumentableDecl(NewND);
7380   return NewND;
7381 }
7382 
7383 Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
7384                                              SourceLocation NamespaceLoc,
7385                                              SourceLocation AliasLoc,
7386                                              IdentifierInfo *Alias,
7387                                              CXXScopeSpec &SS,
7388                                              SourceLocation IdentLoc,
7389                                              IdentifierInfo *Ident) {
7390 
7391   // Lookup the namespace name.
7392   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7393   LookupParsedName(R, S, &SS);
7394 
7395   // Check if we have a previous declaration with the same name.
7396   NamedDecl *PrevDecl
7397     = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7398                        ForRedeclaration);
7399   if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7400     PrevDecl = 0;
7401 
7402   if (PrevDecl) {
7403     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
7404       // We already have an alias with the same name that points to the same
7405       // namespace, so don't create a new one.
7406       // FIXME: At some point, we'll want to create the (redundant)
7407       // declaration to maintain better source information.
7408       if (!R.isAmbiguous() && !R.empty() &&
7409           AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
7410         return 0;
7411     }
7412 
7413     unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7414       diag::err_redefinition_different_kind;
7415     Diag(AliasLoc, DiagID) << Alias;
7416     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
7417     return 0;
7418   }
7419 
7420   if (R.isAmbiguous())
7421     return 0;
7422 
7423   if (R.empty()) {
7424     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
7425       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
7426       return 0;
7427     }
7428   }
7429 
7430   NamespaceAliasDecl *AliasDecl =
7431     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
7432                                Alias, SS.getWithLocInContext(Context),
7433                                IdentLoc, R.getFoundDecl());
7434 
7435   PushOnScopeChains(AliasDecl, S);
7436   return AliasDecl;
7437 }
7438 
7439 Sema::ImplicitExceptionSpecification
7440 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7441                                                CXXMethodDecl *MD) {
7442   CXXRecordDecl *ClassDecl = MD->getParent();
7443 
7444   // C++ [except.spec]p14:
7445   //   An implicitly declared special member function (Clause 12) shall have an
7446   //   exception-specification. [...]
7447   ImplicitExceptionSpecification ExceptSpec(*this);
7448   if (ClassDecl->isInvalidDecl())
7449     return ExceptSpec;
7450 
7451   // Direct base-class constructors.
7452   for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7453                                        BEnd = ClassDecl->bases_end();
7454        B != BEnd; ++B) {
7455     if (B->isVirtual()) // Handled below.
7456       continue;
7457 
7458     if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7459       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7460       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7461       // If this is a deleted function, add it anyway. This might be conformant
7462       // with the standard. This might not. I'm not sure. It might not matter.
7463       if (Constructor)
7464         ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7465     }
7466   }
7467 
7468   // Virtual base-class constructors.
7469   for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7470                                        BEnd = ClassDecl->vbases_end();
7471        B != BEnd; ++B) {
7472     if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7473       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7474       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7475       // If this is a deleted function, add it anyway. This might be conformant
7476       // with the standard. This might not. I'm not sure. It might not matter.
7477       if (Constructor)
7478         ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7479     }
7480   }
7481 
7482   // Field constructors.
7483   for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7484                                FEnd = ClassDecl->field_end();
7485        F != FEnd; ++F) {
7486     if (F->hasInClassInitializer()) {
7487       if (Expr *E = F->getInClassInitializer())
7488         ExceptSpec.CalledExpr(E);
7489       else if (!F->isInvalidDecl())
7490         // DR1351:
7491         //   If the brace-or-equal-initializer of a non-static data member
7492         //   invokes a defaulted default constructor of its class or of an
7493         //   enclosing class in a potentially evaluated subexpression, the
7494         //   program is ill-formed.
7495         //
7496         // This resolution is unworkable: the exception specification of the
7497         // default constructor can be needed in an unevaluated context, in
7498         // particular, in the operand of a noexcept-expression, and we can be
7499         // unable to compute an exception specification for an enclosed class.
7500         //
7501         // We do not allow an in-class initializer to require the evaluation
7502         // of the exception specification for any in-class initializer whose
7503         // definition is not lexically complete.
7504         Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
7505     } else if (const RecordType *RecordTy
7506               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7507       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7508       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7509       // If this is a deleted function, add it anyway. This might be conformant
7510       // with the standard. This might not. I'm not sure. It might not matter.
7511       // In particular, the problem is that this function never gets called. It
7512       // might just be ill-formed because this function attempts to refer to
7513       // a deleted function here.
7514       if (Constructor)
7515         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7516     }
7517   }
7518 
7519   return ExceptSpec;
7520 }
7521 
7522 Sema::ImplicitExceptionSpecification
7523 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
7524   CXXRecordDecl *ClassDecl = CD->getParent();
7525 
7526   // C++ [except.spec]p14:
7527   //   An inheriting constructor [...] shall have an exception-specification. [...]
7528   ImplicitExceptionSpecification ExceptSpec(*this);
7529   if (ClassDecl->isInvalidDecl())
7530     return ExceptSpec;
7531 
7532   // Inherited constructor.
7533   const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
7534   const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
7535   // FIXME: Copying or moving the parameters could add extra exceptions to the
7536   // set, as could the default arguments for the inherited constructor. This
7537   // will be addressed when we implement the resolution of core issue 1351.
7538   ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
7539 
7540   // Direct base-class constructors.
7541   for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7542                                        BEnd = ClassDecl->bases_end();
7543        B != BEnd; ++B) {
7544     if (B->isVirtual()) // Handled below.
7545       continue;
7546 
7547     if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7548       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7549       if (BaseClassDecl == InheritedDecl)
7550         continue;
7551       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7552       if (Constructor)
7553         ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7554     }
7555   }
7556 
7557   // Virtual base-class constructors.
7558   for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7559                                        BEnd = ClassDecl->vbases_end();
7560        B != BEnd; ++B) {
7561     if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7562       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7563       if (BaseClassDecl == InheritedDecl)
7564         continue;
7565       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7566       if (Constructor)
7567         ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7568     }
7569   }
7570 
7571   // Field constructors.
7572   for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7573                                FEnd = ClassDecl->field_end();
7574        F != FEnd; ++F) {
7575     if (F->hasInClassInitializer()) {
7576       if (Expr *E = F->getInClassInitializer())
7577         ExceptSpec.CalledExpr(E);
7578       else if (!F->isInvalidDecl())
7579         Diag(CD->getLocation(),
7580              diag::err_in_class_initializer_references_def_ctor) << CD;
7581     } else if (const RecordType *RecordTy
7582               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7583       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7584       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7585       if (Constructor)
7586         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7587     }
7588   }
7589 
7590   return ExceptSpec;
7591 }
7592 
7593 namespace {
7594 /// RAII object to register a special member as being currently declared.
7595 struct DeclaringSpecialMember {
7596   Sema &S;
7597   Sema::SpecialMemberDecl D;
7598   bool WasAlreadyBeingDeclared;
7599 
7600   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7601     : S(S), D(RD, CSM) {
7602     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7603     if (WasAlreadyBeingDeclared)
7604       // This almost never happens, but if it does, ensure that our cache
7605       // doesn't contain a stale result.
7606       S.SpecialMemberCache.clear();
7607 
7608     // FIXME: Register a note to be produced if we encounter an error while
7609     // declaring the special member.
7610   }
7611   ~DeclaringSpecialMember() {
7612     if (!WasAlreadyBeingDeclared)
7613       S.SpecialMembersBeingDeclared.erase(D);
7614   }
7615 
7616   /// \brief Are we already trying to declare this special member?
7617   bool isAlreadyBeingDeclared() const {
7618     return WasAlreadyBeingDeclared;
7619   }
7620 };
7621 }
7622 
7623 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7624                                                      CXXRecordDecl *ClassDecl) {
7625   // C++ [class.ctor]p5:
7626   //   A default constructor for a class X is a constructor of class X
7627   //   that can be called without an argument. If there is no
7628   //   user-declared constructor for class X, a default constructor is
7629   //   implicitly declared. An implicitly-declared default constructor
7630   //   is an inline public member of its class.
7631   assert(ClassDecl->needsImplicitDefaultConstructor() &&
7632          "Should not build implicit default constructor!");
7633 
7634   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7635   if (DSM.isAlreadyBeingDeclared())
7636     return 0;
7637 
7638   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7639                                                      CXXDefaultConstructor,
7640                                                      false);
7641 
7642   // Create the actual constructor declaration.
7643   CanQualType ClassType
7644     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
7645   SourceLocation ClassLoc = ClassDecl->getLocation();
7646   DeclarationName Name
7647     = Context.DeclarationNames.getCXXConstructorName(ClassType);
7648   DeclarationNameInfo NameInfo(Name, ClassLoc);
7649   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
7650       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
7651       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
7652       Constexpr);
7653   DefaultCon->setAccess(AS_public);
7654   DefaultCon->setDefaulted();
7655   DefaultCon->setImplicit();
7656 
7657   // Build an exception specification pointing back at this constructor.
7658   FunctionProtoType::ExtProtoInfo EPI;
7659   EPI.ExceptionSpecType = EST_Unevaluated;
7660   EPI.ExceptionSpecDecl = DefaultCon;
7661   DefaultCon->setType(Context.getFunctionType(Context.VoidTy,
7662                                               ArrayRef<QualType>(),
7663                                               EPI));
7664 
7665   // We don't need to use SpecialMemberIsTrivial here; triviality for default
7666   // constructors is easy to compute.
7667   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7668 
7669   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
7670     SetDeclDeleted(DefaultCon, ClassLoc);
7671 
7672   // Note that we have declared this constructor.
7673   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
7674 
7675   if (Scope *S = getScopeForContext(ClassDecl))
7676     PushOnScopeChains(DefaultCon, S, false);
7677   ClassDecl->addDecl(DefaultCon);
7678 
7679   return DefaultCon;
7680 }
7681 
7682 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7683                                             CXXConstructorDecl *Constructor) {
7684   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
7685           !Constructor->doesThisDeclarationHaveABody() &&
7686           !Constructor->isDeleted()) &&
7687     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
7688 
7689   CXXRecordDecl *ClassDecl = Constructor->getParent();
7690   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
7691 
7692   SynthesizedFunctionScope Scope(*this, Constructor);
7693   DiagnosticErrorTrap Trap(Diags);
7694   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
7695       Trap.hasErrorOccurred()) {
7696     Diag(CurrentLocation, diag::note_member_synthesized_at)
7697       << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
7698     Constructor->setInvalidDecl();
7699     return;
7700   }
7701 
7702   SourceLocation Loc = Constructor->getLocation();
7703   Constructor->setBody(new (Context) CompoundStmt(Loc));
7704 
7705   Constructor->setUsed();
7706   MarkVTableUsed(CurrentLocation, ClassDecl);
7707 
7708   if (ASTMutationListener *L = getASTMutationListener()) {
7709     L->CompletedImplicitDefinition(Constructor);
7710   }
7711 }
7712 
7713 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
7714   // Check that any explicitly-defaulted methods have exception specifications
7715   // compatible with their implicit exception specifications.
7716   CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
7717 }
7718 
7719 namespace {
7720 /// Information on inheriting constructors to declare.
7721 class InheritingConstructorInfo {
7722 public:
7723   InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
7724       : SemaRef(SemaRef), Derived(Derived) {
7725     // Mark the constructors that we already have in the derived class.
7726     //
7727     // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7728     //   unless there is a user-declared constructor with the same signature in
7729     //   the class where the using-declaration appears.
7730     visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
7731   }
7732 
7733   void inheritAll(CXXRecordDecl *RD) {
7734     visitAll(RD, &InheritingConstructorInfo::inherit);
7735   }
7736 
7737 private:
7738   /// Information about an inheriting constructor.
7739   struct InheritingConstructor {
7740     InheritingConstructor()
7741       : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
7742 
7743     /// If \c true, a constructor with this signature is already declared
7744     /// in the derived class.
7745     bool DeclaredInDerived;
7746 
7747     /// The constructor which is inherited.
7748     const CXXConstructorDecl *BaseCtor;
7749 
7750     /// The derived constructor we declared.
7751     CXXConstructorDecl *DerivedCtor;
7752   };
7753 
7754   /// Inheriting constructors with a given canonical type. There can be at
7755   /// most one such non-template constructor, and any number of templated
7756   /// constructors.
7757   struct InheritingConstructorsForType {
7758     InheritingConstructor NonTemplate;
7759     llvm::SmallVector<
7760       std::pair<TemplateParameterList*, InheritingConstructor>, 4> Templates;
7761 
7762     InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
7763       if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
7764         TemplateParameterList *ParamList = FTD->getTemplateParameters();
7765         for (unsigned I = 0, N = Templates.size(); I != N; ++I)
7766           if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
7767                                                false, S.TPL_TemplateMatch))
7768             return Templates[I].second;
7769         Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
7770         return Templates.back().second;
7771       }
7772 
7773       return NonTemplate;
7774     }
7775   };
7776 
7777   /// Get or create the inheriting constructor record for a constructor.
7778   InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
7779                                   QualType CtorType) {
7780     return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
7781         .getEntry(SemaRef, Ctor);
7782   }
7783 
7784   typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
7785 
7786   /// Process all constructors for a class.
7787   void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
7788     for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
7789                                       CtorE = RD->ctor_end();
7790          CtorIt != CtorE; ++CtorIt)
7791       (this->*Callback)(*CtorIt);
7792     for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
7793              I(RD->decls_begin()), E(RD->decls_end());
7794          I != E; ++I) {
7795       const FunctionDecl *FD = (*I)->getTemplatedDecl();
7796       if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
7797         (this->*Callback)(CD);
7798     }
7799   }
7800 
7801   /// Note that a constructor (or constructor template) was declared in Derived.
7802   void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
7803     getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
7804   }
7805 
7806   /// Inherit a single constructor.
7807   void inherit(const CXXConstructorDecl *Ctor) {
7808     const FunctionProtoType *CtorType =
7809         Ctor->getType()->castAs<FunctionProtoType>();
7810     ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
7811     FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
7812 
7813     SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
7814 
7815     // Core issue (no number yet): the ellipsis is always discarded.
7816     if (EPI.Variadic) {
7817       SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
7818       SemaRef.Diag(Ctor->getLocation(),
7819                    diag::note_using_decl_constructor_ellipsis);
7820       EPI.Variadic = false;
7821     }
7822 
7823     // Declare a constructor for each number of parameters.
7824     //
7825     // C++11 [class.inhctor]p1:
7826     //   The candidate set of inherited constructors from the class X named in
7827     //   the using-declaration consists of [... modulo defects ...] for each
7828     //   constructor or constructor template of X, the set of constructors or
7829     //   constructor templates that results from omitting any ellipsis parameter
7830     //   specification and successively omitting parameters with a default
7831     //   argument from the end of the parameter-type-list
7832     unsigned MinParams = minParamsToInherit(Ctor);
7833     unsigned Params = Ctor->getNumParams();
7834     if (Params >= MinParams) {
7835       do
7836         declareCtor(UsingLoc, Ctor,
7837                     SemaRef.Context.getFunctionType(
7838                         Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
7839       while (Params > MinParams &&
7840              Ctor->getParamDecl(--Params)->hasDefaultArg());
7841     }
7842   }
7843 
7844   /// Find the using-declaration which specified that we should inherit the
7845   /// constructors of \p Base.
7846   SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
7847     // No fancy lookup required; just look for the base constructor name
7848     // directly within the derived class.
7849     ASTContext &Context = SemaRef.Context;
7850     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
7851         Context.getCanonicalType(Context.getRecordType(Base)));
7852     DeclContext::lookup_const_result Decls = Derived->lookup(Name);
7853     return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
7854   }
7855 
7856   unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
7857     // C++11 [class.inhctor]p3:
7858     //   [F]or each constructor template in the candidate set of inherited
7859     //   constructors, a constructor template is implicitly declared
7860     if (Ctor->getDescribedFunctionTemplate())
7861       return 0;
7862 
7863     //   For each non-template constructor in the candidate set of inherited
7864     //   constructors other than a constructor having no parameters or a
7865     //   copy/move constructor having a single parameter, a constructor is
7866     //   implicitly declared [...]
7867     if (Ctor->getNumParams() == 0)
7868       return 1;
7869     if (Ctor->isCopyOrMoveConstructor())
7870       return 2;
7871 
7872     // Per discussion on core reflector, never inherit a constructor which
7873     // would become a default, copy, or move constructor of Derived either.
7874     const ParmVarDecl *PD = Ctor->getParamDecl(0);
7875     const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
7876     return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
7877   }
7878 
7879   /// Declare a single inheriting constructor, inheriting the specified
7880   /// constructor, with the given type.
7881   void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
7882                    QualType DerivedType) {
7883     InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
7884 
7885     // C++11 [class.inhctor]p3:
7886     //   ... a constructor is implicitly declared with the same constructor
7887     //   characteristics unless there is a user-declared constructor with
7888     //   the same signature in the class where the using-declaration appears
7889     if (Entry.DeclaredInDerived)
7890       return;
7891 
7892     // C++11 [class.inhctor]p7:
7893     //   If two using-declarations declare inheriting constructors with the
7894     //   same signature, the program is ill-formed
7895     if (Entry.DerivedCtor) {
7896       if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
7897         // Only diagnose this once per constructor.
7898         if (Entry.DerivedCtor->isInvalidDecl())
7899           return;
7900         Entry.DerivedCtor->setInvalidDecl();
7901 
7902         SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7903         SemaRef.Diag(BaseCtor->getLocation(),
7904                      diag::note_using_decl_constructor_conflict_current_ctor);
7905         SemaRef.Diag(Entry.BaseCtor->getLocation(),
7906                      diag::note_using_decl_constructor_conflict_previous_ctor);
7907         SemaRef.Diag(Entry.DerivedCtor->getLocation(),
7908                      diag::note_using_decl_constructor_conflict_previous_using);
7909       } else {
7910         // Core issue (no number): if the same inheriting constructor is
7911         // produced by multiple base class constructors from the same base
7912         // class, the inheriting constructor is defined as deleted.
7913         SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
7914       }
7915 
7916       return;
7917     }
7918 
7919     ASTContext &Context = SemaRef.Context;
7920     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
7921         Context.getCanonicalType(Context.getRecordType(Derived)));
7922     DeclarationNameInfo NameInfo(Name, UsingLoc);
7923 
7924     TemplateParameterList *TemplateParams = 0;
7925     if (const FunctionTemplateDecl *FTD =
7926             BaseCtor->getDescribedFunctionTemplate()) {
7927       TemplateParams = FTD->getTemplateParameters();
7928       // We're reusing template parameters from a different DeclContext. This
7929       // is questionable at best, but works out because the template depth in
7930       // both places is guaranteed to be 0.
7931       // FIXME: Rebuild the template parameters in the new context, and
7932       // transform the function type to refer to them.
7933     }
7934 
7935     // Build type source info pointing at the using-declaration. This is
7936     // required by template instantiation.
7937     TypeSourceInfo *TInfo =
7938         Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
7939     FunctionProtoTypeLoc ProtoLoc =
7940         TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
7941 
7942     CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
7943         Context, Derived, UsingLoc, NameInfo, DerivedType,
7944         TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
7945         /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
7946 
7947     // Build an unevaluated exception specification for this constructor.
7948     const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
7949     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7950     EPI.ExceptionSpecType = EST_Unevaluated;
7951     EPI.ExceptionSpecDecl = DerivedCtor;
7952     DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
7953                                                  FPT->getArgTypes(), EPI));
7954 
7955     // Build the parameter declarations.
7956     SmallVector<ParmVarDecl *, 16> ParamDecls;
7957     for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
7958       TypeSourceInfo *TInfo =
7959           Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
7960       ParmVarDecl *PD = ParmVarDecl::Create(
7961           Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
7962           FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
7963       PD->setScopeInfo(0, I);
7964       PD->setImplicit();
7965       ParamDecls.push_back(PD);
7966       ProtoLoc.setArg(I, PD);
7967     }
7968 
7969     // Set up the new constructor.
7970     DerivedCtor->setAccess(BaseCtor->getAccess());
7971     DerivedCtor->setParams(ParamDecls);
7972     DerivedCtor->setInheritedConstructor(BaseCtor);
7973     if (BaseCtor->isDeleted())
7974       SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
7975 
7976     // If this is a constructor template, build the template declaration.
7977     if (TemplateParams) {
7978       FunctionTemplateDecl *DerivedTemplate =
7979           FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
7980                                        TemplateParams, DerivedCtor);
7981       DerivedTemplate->setAccess(BaseCtor->getAccess());
7982       DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
7983       Derived->addDecl(DerivedTemplate);
7984     } else {
7985       Derived->addDecl(DerivedCtor);
7986     }
7987 
7988     Entry.BaseCtor = BaseCtor;
7989     Entry.DerivedCtor = DerivedCtor;
7990   }
7991 
7992   Sema &SemaRef;
7993   CXXRecordDecl *Derived;
7994   typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
7995   MapType Map;
7996 };
7997 }
7998 
7999 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8000   // Defer declaring the inheriting constructors until the class is
8001   // instantiated.
8002   if (ClassDecl->isDependentContext())
8003     return;
8004 
8005   // Find base classes from which we might inherit constructors.
8006   SmallVector<CXXRecordDecl*, 4> InheritedBases;
8007   for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8008                                           BaseE = ClassDecl->bases_end();
8009        BaseIt != BaseE; ++BaseIt)
8010     if (BaseIt->getInheritConstructors())
8011       InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
8012 
8013   // Go no further if we're not inheriting any constructors.
8014   if (InheritedBases.empty())
8015     return;
8016 
8017   // Declare the inherited constructors.
8018   InheritingConstructorInfo ICI(*this, ClassDecl);
8019   for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8020     ICI.inheritAll(InheritedBases[I]);
8021 }
8022 
8023 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8024                                        CXXConstructorDecl *Constructor) {
8025   CXXRecordDecl *ClassDecl = Constructor->getParent();
8026   assert(Constructor->getInheritedConstructor() &&
8027          !Constructor->doesThisDeclarationHaveABody() &&
8028          !Constructor->isDeleted());
8029 
8030   SynthesizedFunctionScope Scope(*this, Constructor);
8031   DiagnosticErrorTrap Trap(Diags);
8032   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8033       Trap.hasErrorOccurred()) {
8034     Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8035       << Context.getTagDeclType(ClassDecl);
8036     Constructor->setInvalidDecl();
8037     return;
8038   }
8039 
8040   SourceLocation Loc = Constructor->getLocation();
8041   Constructor->setBody(new (Context) CompoundStmt(Loc));
8042 
8043   Constructor->setUsed();
8044   MarkVTableUsed(CurrentLocation, ClassDecl);
8045 
8046   if (ASTMutationListener *L = getASTMutationListener()) {
8047     L->CompletedImplicitDefinition(Constructor);
8048   }
8049 }
8050 
8051 
8052 Sema::ImplicitExceptionSpecification
8053 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8054   CXXRecordDecl *ClassDecl = MD->getParent();
8055 
8056   // C++ [except.spec]p14:
8057   //   An implicitly declared special member function (Clause 12) shall have
8058   //   an exception-specification.
8059   ImplicitExceptionSpecification ExceptSpec(*this);
8060   if (ClassDecl->isInvalidDecl())
8061     return ExceptSpec;
8062 
8063   // Direct base-class destructors.
8064   for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8065                                        BEnd = ClassDecl->bases_end();
8066        B != BEnd; ++B) {
8067     if (B->isVirtual()) // Handled below.
8068       continue;
8069 
8070     if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
8071       ExceptSpec.CalledDecl(B->getLocStart(),
8072                    LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
8073   }
8074 
8075   // Virtual base-class destructors.
8076   for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8077                                        BEnd = ClassDecl->vbases_end();
8078        B != BEnd; ++B) {
8079     if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
8080       ExceptSpec.CalledDecl(B->getLocStart(),
8081                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
8082   }
8083 
8084   // Field destructors.
8085   for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8086                                FEnd = ClassDecl->field_end();
8087        F != FEnd; ++F) {
8088     if (const RecordType *RecordTy
8089         = Context.getBaseElementType(F->getType())->getAs<RecordType>())
8090       ExceptSpec.CalledDecl(F->getLocation(),
8091                   LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
8092   }
8093 
8094   return ExceptSpec;
8095 }
8096 
8097 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8098   // C++ [class.dtor]p2:
8099   //   If a class has no user-declared destructor, a destructor is
8100   //   declared implicitly. An implicitly-declared destructor is an
8101   //   inline public member of its class.
8102   assert(ClassDecl->needsImplicitDestructor());
8103 
8104   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8105   if (DSM.isAlreadyBeingDeclared())
8106     return 0;
8107 
8108   // Create the actual destructor declaration.
8109   CanQualType ClassType
8110     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8111   SourceLocation ClassLoc = ClassDecl->getLocation();
8112   DeclarationName Name
8113     = Context.DeclarationNames.getCXXDestructorName(ClassType);
8114   DeclarationNameInfo NameInfo(Name, ClassLoc);
8115   CXXDestructorDecl *Destructor
8116       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8117                                   QualType(), 0, /*isInline=*/true,
8118                                   /*isImplicitlyDeclared=*/true);
8119   Destructor->setAccess(AS_public);
8120   Destructor->setDefaulted();
8121   Destructor->setImplicit();
8122 
8123   // Build an exception specification pointing back at this destructor.
8124   FunctionProtoType::ExtProtoInfo EPI;
8125   EPI.ExceptionSpecType = EST_Unevaluated;
8126   EPI.ExceptionSpecDecl = Destructor;
8127   Destructor->setType(Context.getFunctionType(Context.VoidTy,
8128                                               ArrayRef<QualType>(),
8129                                               EPI));
8130 
8131   AddOverriddenMethods(ClassDecl, Destructor);
8132 
8133   // We don't need to use SpecialMemberIsTrivial here; triviality for
8134   // destructors is easy to compute.
8135   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8136 
8137   if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
8138     SetDeclDeleted(Destructor, ClassLoc);
8139 
8140   // Note that we have declared this destructor.
8141   ++ASTContext::NumImplicitDestructorsDeclared;
8142 
8143   // Introduce this destructor into its scope.
8144   if (Scope *S = getScopeForContext(ClassDecl))
8145     PushOnScopeChains(Destructor, S, false);
8146   ClassDecl->addDecl(Destructor);
8147 
8148   return Destructor;
8149 }
8150 
8151 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
8152                                     CXXDestructorDecl *Destructor) {
8153   assert((Destructor->isDefaulted() &&
8154           !Destructor->doesThisDeclarationHaveABody() &&
8155           !Destructor->isDeleted()) &&
8156          "DefineImplicitDestructor - call it for implicit default dtor");
8157   CXXRecordDecl *ClassDecl = Destructor->getParent();
8158   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
8159 
8160   if (Destructor->isInvalidDecl())
8161     return;
8162 
8163   SynthesizedFunctionScope Scope(*this, Destructor);
8164 
8165   DiagnosticErrorTrap Trap(Diags);
8166   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8167                                          Destructor->getParent());
8168 
8169   if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
8170     Diag(CurrentLocation, diag::note_member_synthesized_at)
8171       << CXXDestructor << Context.getTagDeclType(ClassDecl);
8172 
8173     Destructor->setInvalidDecl();
8174     return;
8175   }
8176 
8177   SourceLocation Loc = Destructor->getLocation();
8178   Destructor->setBody(new (Context) CompoundStmt(Loc));
8179   Destructor->setImplicitlyDefined(true);
8180   Destructor->setUsed();
8181   MarkVTableUsed(CurrentLocation, ClassDecl);
8182 
8183   if (ASTMutationListener *L = getASTMutationListener()) {
8184     L->CompletedImplicitDefinition(Destructor);
8185   }
8186 }
8187 
8188 /// \brief Perform any semantic analysis which needs to be delayed until all
8189 /// pending class member declarations have been parsed.
8190 void Sema::ActOnFinishCXXMemberDecls() {
8191   // If the context is an invalid C++ class, just suppress these checks.
8192   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8193     if (Record->isInvalidDecl()) {
8194       DelayedDestructorExceptionSpecChecks.clear();
8195       return;
8196     }
8197   }
8198 
8199   // Perform any deferred checking of exception specifications for virtual
8200   // destructors.
8201   for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
8202        i != e; ++i) {
8203     const CXXDestructorDecl *Dtor =
8204         DelayedDestructorExceptionSpecChecks[i].first;
8205     assert(!Dtor->getParent()->isDependentType() &&
8206            "Should not ever add destructors of templates into the list.");
8207     CheckOverridingFunctionExceptionSpec(Dtor,
8208         DelayedDestructorExceptionSpecChecks[i].second);
8209   }
8210   DelayedDestructorExceptionSpecChecks.clear();
8211 }
8212 
8213 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8214                                          CXXDestructorDecl *Destructor) {
8215   assert(getLangOpts().CPlusPlus11 &&
8216          "adjusting dtor exception specs was introduced in c++11");
8217 
8218   // C++11 [class.dtor]p3:
8219   //   A declaration of a destructor that does not have an exception-
8220   //   specification is implicitly considered to have the same exception-
8221   //   specification as an implicit declaration.
8222   const FunctionProtoType *DtorType = Destructor->getType()->
8223                                         getAs<FunctionProtoType>();
8224   if (DtorType->hasExceptionSpec())
8225     return;
8226 
8227   // Replace the destructor's type, building off the existing one. Fortunately,
8228   // the only thing of interest in the destructor type is its extended info.
8229   // The return and arguments are fixed.
8230   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8231   EPI.ExceptionSpecType = EST_Unevaluated;
8232   EPI.ExceptionSpecDecl = Destructor;
8233   Destructor->setType(Context.getFunctionType(Context.VoidTy,
8234                                               ArrayRef<QualType>(),
8235                                               EPI));
8236 
8237   // FIXME: If the destructor has a body that could throw, and the newly created
8238   // spec doesn't allow exceptions, we should emit a warning, because this
8239   // change in behavior can break conforming C++03 programs at runtime.
8240   // However, we don't have a body or an exception specification yet, so it
8241   // needs to be done somewhere else.
8242 }
8243 
8244 /// When generating a defaulted copy or move assignment operator, if a field
8245 /// should be copied with __builtin_memcpy rather than via explicit assignments,
8246 /// do so. This optimization only applies for arrays of scalars, and for arrays
8247 /// of class type where the selected copy/move-assignment operator is trivial.
8248 static StmtResult
8249 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
8250                            Expr *To, Expr *From) {
8251   // Compute the size of the memory buffer to be copied.
8252   QualType SizeType = S.Context.getSizeType();
8253   llvm::APInt Size(S.Context.getTypeSize(SizeType),
8254                    S.Context.getTypeSizeInChars(T).getQuantity());
8255 
8256   // Take the address of the field references for "from" and "to". We
8257   // directly construct UnaryOperators here because semantic analysis
8258   // does not permit us to take the address of an xvalue.
8259   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8260                          S.Context.getPointerType(From->getType()),
8261                          VK_RValue, OK_Ordinary, Loc);
8262   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8263                        S.Context.getPointerType(To->getType()),
8264                        VK_RValue, OK_Ordinary, Loc);
8265 
8266   const Type *E = T->getBaseElementTypeUnsafe();
8267   bool NeedsCollectableMemCpy =
8268     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8269 
8270   // Create a reference to the __builtin_objc_memmove_collectable function
8271   StringRef MemCpyName = NeedsCollectableMemCpy ?
8272     "__builtin_objc_memmove_collectable" :
8273     "__builtin_memcpy";
8274   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8275                  Sema::LookupOrdinaryName);
8276   S.LookupName(R, S.TUScope, true);
8277 
8278   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8279   if (!MemCpy)
8280     // Something went horribly wrong earlier, and we will have complained
8281     // about it.
8282     return StmtError();
8283 
8284   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8285                                             VK_RValue, Loc, 0);
8286   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8287 
8288   Expr *CallArgs[] = {
8289     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8290   };
8291   ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8292                                     Loc, CallArgs, Loc);
8293 
8294   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8295   return S.Owned(Call.takeAs<Stmt>());
8296 }
8297 
8298 /// \brief Builds a statement that copies/moves the given entity from \p From to
8299 /// \c To.
8300 ///
8301 /// This routine is used to copy/move the members of a class with an
8302 /// implicitly-declared copy/move assignment operator. When the entities being
8303 /// copied are arrays, this routine builds for loops to copy them.
8304 ///
8305 /// \param S The Sema object used for type-checking.
8306 ///
8307 /// \param Loc The location where the implicit copy/move is being generated.
8308 ///
8309 /// \param T The type of the expressions being copied/moved. Both expressions
8310 /// must have this type.
8311 ///
8312 /// \param To The expression we are copying/moving to.
8313 ///
8314 /// \param From The expression we are copying/moving from.
8315 ///
8316 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
8317 /// Otherwise, it's a non-static member subobject.
8318 ///
8319 /// \param Copying Whether we're copying or moving.
8320 ///
8321 /// \param Depth Internal parameter recording the depth of the recursion.
8322 ///
8323 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8324 /// if a memcpy should be used instead.
8325 static StmtResult
8326 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8327                                  Expr *To, Expr *From,
8328                                  bool CopyingBaseSubobject, bool Copying,
8329                                  unsigned Depth = 0) {
8330   // C++11 [class.copy]p28:
8331   //   Each subobject is assigned in the manner appropriate to its type:
8332   //
8333   //     - if the subobject is of class type, as if by a call to operator= with
8334   //       the subobject as the object expression and the corresponding
8335   //       subobject of x as a single function argument (as if by explicit
8336   //       qualification; that is, ignoring any possible virtual overriding
8337   //       functions in more derived classes);
8338   //
8339   // C++03 [class.copy]p13:
8340   //     - if the subobject is of class type, the copy assignment operator for
8341   //       the class is used (as if by explicit qualification; that is,
8342   //       ignoring any possible virtual overriding functions in more derived
8343   //       classes);
8344   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8345     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8346 
8347     // Look for operator=.
8348     DeclarationName Name
8349       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8350     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8351     S.LookupQualifiedName(OpLookup, ClassDecl, false);
8352 
8353     // Prior to C++11, filter out any result that isn't a copy/move-assignment
8354     // operator.
8355     if (!S.getLangOpts().CPlusPlus11) {
8356       LookupResult::Filter F = OpLookup.makeFilter();
8357       while (F.hasNext()) {
8358         NamedDecl *D = F.next();
8359         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8360           if (Method->isCopyAssignmentOperator() ||
8361               (!Copying && Method->isMoveAssignmentOperator()))
8362             continue;
8363 
8364         F.erase();
8365       }
8366       F.done();
8367     }
8368 
8369     // Suppress the protected check (C++ [class.protected]) for each of the
8370     // assignment operators we found. This strange dance is required when
8371     // we're assigning via a base classes's copy-assignment operator. To
8372     // ensure that we're getting the right base class subobject (without
8373     // ambiguities), we need to cast "this" to that subobject type; to
8374     // ensure that we don't go through the virtual call mechanism, we need
8375     // to qualify the operator= name with the base class (see below). However,
8376     // this means that if the base class has a protected copy assignment
8377     // operator, the protected member access check will fail. So, we
8378     // rewrite "protected" access to "public" access in this case, since we
8379     // know by construction that we're calling from a derived class.
8380     if (CopyingBaseSubobject) {
8381       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8382            L != LEnd; ++L) {
8383         if (L.getAccess() == AS_protected)
8384           L.setAccess(AS_public);
8385       }
8386     }
8387 
8388     // Create the nested-name-specifier that will be used to qualify the
8389     // reference to operator=; this is required to suppress the virtual
8390     // call mechanism.
8391     CXXScopeSpec SS;
8392     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
8393     SS.MakeTrivial(S.Context,
8394                    NestedNameSpecifier::Create(S.Context, 0, false,
8395                                                CanonicalT),
8396                    Loc);
8397 
8398     // Create the reference to operator=.
8399     ExprResult OpEqualRef
8400       = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
8401                                    /*TemplateKWLoc=*/SourceLocation(),
8402                                    /*FirstQualifierInScope=*/0,
8403                                    OpLookup,
8404                                    /*TemplateArgs=*/0,
8405                                    /*SuppressQualifierCheck=*/true);
8406     if (OpEqualRef.isInvalid())
8407       return StmtError();
8408 
8409     // Build the call to the assignment operator.
8410 
8411     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
8412                                                   OpEqualRef.takeAs<Expr>(),
8413                                                   Loc, &From, 1, Loc);
8414     if (Call.isInvalid())
8415       return StmtError();
8416 
8417     // If we built a call to a trivial 'operator=' while copying an array,
8418     // bail out. We'll replace the whole shebang with a memcpy.
8419     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8420     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8421       return StmtResult((Stmt*)0);
8422 
8423     // Convert to an expression-statement, and clean up any produced
8424     // temporaries.
8425     return S.ActOnExprStmt(Call);
8426   }
8427 
8428   //     - if the subobject is of scalar type, the built-in assignment
8429   //       operator is used.
8430   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
8431   if (!ArrayTy) {
8432     ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
8433     if (Assignment.isInvalid())
8434       return StmtError();
8435     return S.ActOnExprStmt(Assignment);
8436   }
8437 
8438   //     - if the subobject is an array, each element is assigned, in the
8439   //       manner appropriate to the element type;
8440 
8441   // Construct a loop over the array bounds, e.g.,
8442   //
8443   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8444   //
8445   // that will copy each of the array elements.
8446   QualType SizeType = S.Context.getSizeType();
8447 
8448   // Create the iteration variable.
8449   IdentifierInfo *IterationVarName = 0;
8450   {
8451     SmallString<8> Str;
8452     llvm::raw_svector_ostream OS(Str);
8453     OS << "__i" << Depth;
8454     IterationVarName = &S.Context.Idents.get(OS.str());
8455   }
8456   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
8457                                           IterationVarName, SizeType,
8458                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
8459                                           SC_None);
8460 
8461   // Initialize the iteration variable to zero.
8462   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8463   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8464 
8465   // Create a reference to the iteration variable; we'll use this several
8466   // times throughout.
8467   Expr *IterationVarRef
8468     = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
8469   assert(IterationVarRef && "Reference to invented variable cannot fail!");
8470   Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8471   assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8472 
8473   // Create the DeclStmt that holds the iteration variable.
8474   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
8475 
8476   // Subscript the "from" and "to" expressions with the iteration variable.
8477   From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
8478                                                          IterationVarRefRVal,
8479                                                          Loc));
8480   To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
8481                                                        IterationVarRefRVal,
8482                                                        Loc));
8483   if (!Copying) // Cast to rvalue
8484     From = CastForMoving(S, From);
8485 
8486   // Build the copy/move for an individual element of the array.
8487   StmtResult Copy =
8488     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8489                                      To, From, CopyingBaseSubobject,
8490                                      Copying, Depth + 1);
8491   // Bail out if copying fails or if we determined that we should use memcpy.
8492   if (Copy.isInvalid() || !Copy.get())
8493     return Copy;
8494 
8495   // Create the comparison against the array bound.
8496   llvm::APInt Upper
8497     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8498   Expr *Comparison
8499     = new (S.Context) BinaryOperator(IterationVarRefRVal,
8500                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8501                                      BO_NE, S.Context.BoolTy,
8502                                      VK_RValue, OK_Ordinary, Loc, false);
8503 
8504   // Create the pre-increment of the iteration variable.
8505   Expr *Increment
8506     = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8507                                     VK_LValue, OK_Ordinary, Loc);
8508 
8509   // Construct the loop that copies all elements of this array.
8510   return S.ActOnForStmt(Loc, Loc, InitStmt,
8511                         S.MakeFullExpr(Comparison),
8512                         0, S.MakeFullDiscardedValueExpr(Increment),
8513                         Loc, Copy.take());
8514 }
8515 
8516 static StmtResult
8517 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8518                       Expr *To, Expr *From,
8519                       bool CopyingBaseSubobject, bool Copying) {
8520   // Maybe we should use a memcpy?
8521   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8522       T.isTriviallyCopyableType(S.Context))
8523     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8524 
8525   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8526                                                      CopyingBaseSubobject,
8527                                                      Copying, 0));
8528 
8529   // If we ended up picking a trivial assignment operator for an array of a
8530   // non-trivially-copyable class type, just emit a memcpy.
8531   if (!Result.isInvalid() && !Result.get())
8532     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8533 
8534   return Result;
8535 }
8536 
8537 Sema::ImplicitExceptionSpecification
8538 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8539   CXXRecordDecl *ClassDecl = MD->getParent();
8540 
8541   ImplicitExceptionSpecification ExceptSpec(*this);
8542   if (ClassDecl->isInvalidDecl())
8543     return ExceptSpec;
8544 
8545   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8546   assert(T->getNumArgs() == 1 && "not a copy assignment op");
8547   unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8548 
8549   // C++ [except.spec]p14:
8550   //   An implicitly declared special member function (Clause 12) shall have an
8551   //   exception-specification. [...]
8552 
8553   // It is unspecified whether or not an implicit copy assignment operator
8554   // attempts to deduplicate calls to assignment operators of virtual bases are
8555   // made. As such, this exception specification is effectively unspecified.
8556   // Based on a similar decision made for constness in C++0x, we're erring on
8557   // the side of assuming such calls to be made regardless of whether they
8558   // actually happen.
8559   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8560                                        BaseEnd = ClassDecl->bases_end();
8561        Base != BaseEnd; ++Base) {
8562     if (Base->isVirtual())
8563       continue;
8564 
8565     CXXRecordDecl *BaseClassDecl
8566       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8567     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8568                                                             ArgQuals, false, 0))
8569       ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
8570   }
8571 
8572   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8573                                        BaseEnd = ClassDecl->vbases_end();
8574        Base != BaseEnd; ++Base) {
8575     CXXRecordDecl *BaseClassDecl
8576       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8577     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8578                                                             ArgQuals, false, 0))
8579       ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
8580   }
8581 
8582   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8583                                   FieldEnd = ClassDecl->field_end();
8584        Field != FieldEnd;
8585        ++Field) {
8586     QualType FieldType = Context.getBaseElementType(Field->getType());
8587     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8588       if (CXXMethodDecl *CopyAssign =
8589           LookupCopyingAssignment(FieldClassDecl,
8590                                   ArgQuals | FieldType.getCVRQualifiers(),
8591                                   false, 0))
8592         ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
8593     }
8594   }
8595 
8596   return ExceptSpec;
8597 }
8598 
8599 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8600   // Note: The following rules are largely analoguous to the copy
8601   // constructor rules. Note that virtual bases are not taken into account
8602   // for determining the argument type of the operator. Note also that
8603   // operators taking an object instead of a reference are allowed.
8604   assert(ClassDecl->needsImplicitCopyAssignment());
8605 
8606   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8607   if (DSM.isAlreadyBeingDeclared())
8608     return 0;
8609 
8610   QualType ArgType = Context.getTypeDeclType(ClassDecl);
8611   QualType RetType = Context.getLValueReferenceType(ArgType);
8612   if (ClassDecl->implicitCopyAssignmentHasConstParam())
8613     ArgType = ArgType.withConst();
8614   ArgType = Context.getLValueReferenceType(ArgType);
8615 
8616   //   An implicitly-declared copy assignment operator is an inline public
8617   //   member of its class.
8618   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8619   SourceLocation ClassLoc = ClassDecl->getLocation();
8620   DeclarationNameInfo NameInfo(Name, ClassLoc);
8621   CXXMethodDecl *CopyAssignment
8622     = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
8623                             /*TInfo=*/0,
8624                             /*StorageClass=*/SC_None,
8625                             /*isInline=*/true, /*isConstexpr=*/false,
8626                             SourceLocation());
8627   CopyAssignment->setAccess(AS_public);
8628   CopyAssignment->setDefaulted();
8629   CopyAssignment->setImplicit();
8630 
8631   // Build an exception specification pointing back at this member.
8632   FunctionProtoType::ExtProtoInfo EPI;
8633   EPI.ExceptionSpecType = EST_Unevaluated;
8634   EPI.ExceptionSpecDecl = CopyAssignment;
8635   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
8636 
8637   // Add the parameter to the operator.
8638   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
8639                                                ClassLoc, ClassLoc, /*Id=*/0,
8640                                                ArgType, /*TInfo=*/0,
8641                                                SC_None, 0);
8642   CopyAssignment->setParams(FromParam);
8643 
8644   AddOverriddenMethods(ClassDecl, CopyAssignment);
8645 
8646   CopyAssignment->setTrivial(
8647     ClassDecl->needsOverloadResolutionForCopyAssignment()
8648       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8649       : ClassDecl->hasTrivialCopyAssignment());
8650 
8651   // C++0x [class.copy]p19:
8652   //   ....  If the class definition does not explicitly declare a copy
8653   //   assignment operator, there is no user-declared move constructor, and
8654   //   there is no user-declared move assignment operator, a copy assignment
8655   //   operator is implicitly declared as defaulted.
8656   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
8657     SetDeclDeleted(CopyAssignment, ClassLoc);
8658 
8659   // Note that we have added this copy-assignment operator.
8660   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8661 
8662   if (Scope *S = getScopeForContext(ClassDecl))
8663     PushOnScopeChains(CopyAssignment, S, false);
8664   ClassDecl->addDecl(CopyAssignment);
8665 
8666   return CopyAssignment;
8667 }
8668 
8669 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8670                                         CXXMethodDecl *CopyAssignOperator) {
8671   assert((CopyAssignOperator->isDefaulted() &&
8672           CopyAssignOperator->isOverloadedOperator() &&
8673           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
8674           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8675           !CopyAssignOperator->isDeleted()) &&
8676          "DefineImplicitCopyAssignment called for wrong function");
8677 
8678   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8679 
8680   if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8681     CopyAssignOperator->setInvalidDecl();
8682     return;
8683   }
8684 
8685   CopyAssignOperator->setUsed();
8686 
8687   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
8688   DiagnosticErrorTrap Trap(Diags);
8689 
8690   // C++0x [class.copy]p30:
8691   //   The implicitly-defined or explicitly-defaulted copy assignment operator
8692   //   for a non-union class X performs memberwise copy assignment of its
8693   //   subobjects. The direct base classes of X are assigned first, in the
8694   //   order of their declaration in the base-specifier-list, and then the
8695   //   immediate non-static data members of X are assigned, in the order in
8696   //   which they were declared in the class definition.
8697 
8698   // The statements that form the synthesized function body.
8699   SmallVector<Stmt*, 8> Statements;
8700 
8701   // The parameter for the "other" object, which we are copying from.
8702   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8703   Qualifiers OtherQuals = Other->getType().getQualifiers();
8704   QualType OtherRefType = Other->getType();
8705   if (const LValueReferenceType *OtherRef
8706                                 = OtherRefType->getAs<LValueReferenceType>()) {
8707     OtherRefType = OtherRef->getPointeeType();
8708     OtherQuals = OtherRefType.getQualifiers();
8709   }
8710 
8711   // Our location for everything implicitly-generated.
8712   SourceLocation Loc = CopyAssignOperator->getLocation();
8713 
8714   // Construct a reference to the "other" object. We'll be using this
8715   // throughout the generated ASTs.
8716   Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8717   assert(OtherRef && "Reference to parameter cannot fail!");
8718 
8719   // Construct the "this" pointer. We'll be using this throughout the generated
8720   // ASTs.
8721   Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8722   assert(This && "Reference to this cannot fail!");
8723 
8724   // Assign base classes.
8725   bool Invalid = false;
8726   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8727        E = ClassDecl->bases_end(); Base != E; ++Base) {
8728     // Form the assignment:
8729     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8730     QualType BaseType = Base->getType().getUnqualifiedType();
8731     if (!BaseType->isRecordType()) {
8732       Invalid = true;
8733       continue;
8734     }
8735 
8736     CXXCastPath BasePath;
8737     BasePath.push_back(Base);
8738 
8739     // Construct the "from" expression, which is an implicit cast to the
8740     // appropriately-qualified base type.
8741     Expr *From = OtherRef;
8742     From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8743                              CK_UncheckedDerivedToBase,
8744                              VK_LValue, &BasePath).take();
8745 
8746     // Dereference "this".
8747     ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8748 
8749     // Implicitly cast "this" to the appropriately-qualified base type.
8750     To = ImpCastExprToType(To.take(),
8751                            Context.getCVRQualifiedType(BaseType,
8752                                      CopyAssignOperator->getTypeQualifiers()),
8753                            CK_UncheckedDerivedToBase,
8754                            VK_LValue, &BasePath);
8755 
8756     // Build the copy.
8757     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
8758                                             To.get(), From,
8759                                             /*CopyingBaseSubobject=*/true,
8760                                             /*Copying=*/true);
8761     if (Copy.isInvalid()) {
8762       Diag(CurrentLocation, diag::note_member_synthesized_at)
8763         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8764       CopyAssignOperator->setInvalidDecl();
8765       return;
8766     }
8767 
8768     // Success! Record the copy.
8769     Statements.push_back(Copy.takeAs<Expr>());
8770   }
8771 
8772   // Assign non-static members.
8773   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8774                                   FieldEnd = ClassDecl->field_end();
8775        Field != FieldEnd; ++Field) {
8776     if (Field->isUnnamedBitfield())
8777       continue;
8778 
8779     // Check for members of reference type; we can't copy those.
8780     if (Field->getType()->isReferenceType()) {
8781       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8782         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8783       Diag(Field->getLocation(), diag::note_declared_at);
8784       Diag(CurrentLocation, diag::note_member_synthesized_at)
8785         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8786       Invalid = true;
8787       continue;
8788     }
8789 
8790     // Check for members of const-qualified, non-class type.
8791     QualType BaseType = Context.getBaseElementType(Field->getType());
8792     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8793       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8794         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8795       Diag(Field->getLocation(), diag::note_declared_at);
8796       Diag(CurrentLocation, diag::note_member_synthesized_at)
8797         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8798       Invalid = true;
8799       continue;
8800     }
8801 
8802     // Suppress assigning zero-width bitfields.
8803     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8804       continue;
8805 
8806     QualType FieldType = Field->getType().getNonReferenceType();
8807     if (FieldType->isIncompleteArrayType()) {
8808       assert(ClassDecl->hasFlexibleArrayMember() &&
8809              "Incomplete array type is not valid");
8810       continue;
8811     }
8812 
8813     // Build references to the field in the object we're copying from and to.
8814     CXXScopeSpec SS; // Intentionally empty
8815     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8816                               LookupMemberName);
8817     MemberLookup.addDecl(*Field);
8818     MemberLookup.resolveKind();
8819     ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8820                                                Loc, /*IsArrow=*/false,
8821                                                SS, SourceLocation(), 0,
8822                                                MemberLookup, 0);
8823     ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8824                                              Loc, /*IsArrow=*/true,
8825                                              SS, SourceLocation(), 0,
8826                                              MemberLookup, 0);
8827     assert(!From.isInvalid() && "Implicit field reference cannot fail");
8828     assert(!To.isInvalid() && "Implicit field reference cannot fail");
8829 
8830     // Build the copy of this field.
8831     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
8832                                             To.get(), From.get(),
8833                                             /*CopyingBaseSubobject=*/false,
8834                                             /*Copying=*/true);
8835     if (Copy.isInvalid()) {
8836       Diag(CurrentLocation, diag::note_member_synthesized_at)
8837         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8838       CopyAssignOperator->setInvalidDecl();
8839       return;
8840     }
8841 
8842     // Success! Record the copy.
8843     Statements.push_back(Copy.takeAs<Stmt>());
8844   }
8845 
8846   if (!Invalid) {
8847     // Add a "return *this;"
8848     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8849 
8850     StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8851     if (Return.isInvalid())
8852       Invalid = true;
8853     else {
8854       Statements.push_back(Return.takeAs<Stmt>());
8855 
8856       if (Trap.hasErrorOccurred()) {
8857         Diag(CurrentLocation, diag::note_member_synthesized_at)
8858           << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8859         Invalid = true;
8860       }
8861     }
8862   }
8863 
8864   if (Invalid) {
8865     CopyAssignOperator->setInvalidDecl();
8866     return;
8867   }
8868 
8869   StmtResult Body;
8870   {
8871     CompoundScopeRAII CompoundScope(*this);
8872     Body = ActOnCompoundStmt(Loc, Loc, Statements,
8873                              /*isStmtExpr=*/false);
8874     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8875   }
8876   CopyAssignOperator->setBody(Body.takeAs<Stmt>());
8877 
8878   if (ASTMutationListener *L = getASTMutationListener()) {
8879     L->CompletedImplicitDefinition(CopyAssignOperator);
8880   }
8881 }
8882 
8883 Sema::ImplicitExceptionSpecification
8884 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
8885   CXXRecordDecl *ClassDecl = MD->getParent();
8886 
8887   ImplicitExceptionSpecification ExceptSpec(*this);
8888   if (ClassDecl->isInvalidDecl())
8889     return ExceptSpec;
8890 
8891   // C++0x [except.spec]p14:
8892   //   An implicitly declared special member function (Clause 12) shall have an
8893   //   exception-specification. [...]
8894 
8895   // It is unspecified whether or not an implicit move assignment operator
8896   // attempts to deduplicate calls to assignment operators of virtual bases are
8897   // made. As such, this exception specification is effectively unspecified.
8898   // Based on a similar decision made for constness in C++0x, we're erring on
8899   // the side of assuming such calls to be made regardless of whether they
8900   // actually happen.
8901   // Note that a move constructor is not implicitly declared when there are
8902   // virtual bases, but it can still be user-declared and explicitly defaulted.
8903   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8904                                        BaseEnd = ClassDecl->bases_end();
8905        Base != BaseEnd; ++Base) {
8906     if (Base->isVirtual())
8907       continue;
8908 
8909     CXXRecordDecl *BaseClassDecl
8910       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8911     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8912                                                            0, false, 0))
8913       ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
8914   }
8915 
8916   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8917                                        BaseEnd = ClassDecl->vbases_end();
8918        Base != BaseEnd; ++Base) {
8919     CXXRecordDecl *BaseClassDecl
8920       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8921     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8922                                                            0, false, 0))
8923       ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
8924   }
8925 
8926   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8927                                   FieldEnd = ClassDecl->field_end();
8928        Field != FieldEnd;
8929        ++Field) {
8930     QualType FieldType = Context.getBaseElementType(Field->getType());
8931     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8932       if (CXXMethodDecl *MoveAssign =
8933               LookupMovingAssignment(FieldClassDecl,
8934                                      FieldType.getCVRQualifiers(),
8935                                      false, 0))
8936         ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
8937     }
8938   }
8939 
8940   return ExceptSpec;
8941 }
8942 
8943 /// Determine whether the class type has any direct or indirect virtual base
8944 /// classes which have a non-trivial move assignment operator.
8945 static bool
8946 hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
8947   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8948                                           BaseEnd = ClassDecl->vbases_end();
8949        Base != BaseEnd; ++Base) {
8950     CXXRecordDecl *BaseClass =
8951         cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8952 
8953     // Try to declare the move assignment. If it would be deleted, then the
8954     // class does not have a non-trivial move assignment.
8955     if (BaseClass->needsImplicitMoveAssignment())
8956       S.DeclareImplicitMoveAssignment(BaseClass);
8957 
8958     if (BaseClass->hasNonTrivialMoveAssignment())
8959       return true;
8960   }
8961 
8962   return false;
8963 }
8964 
8965 /// Determine whether the given type either has a move constructor or is
8966 /// trivially copyable.
8967 static bool
8968 hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8969   Type = S.Context.getBaseElementType(Type);
8970 
8971   // FIXME: Technically, non-trivially-copyable non-class types, such as
8972   // reference types, are supposed to return false here, but that appears
8973   // to be a standard defect.
8974   CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
8975   if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
8976     return true;
8977 
8978   if (Type.isTriviallyCopyableType(S.Context))
8979     return true;
8980 
8981   if (IsConstructor) {
8982     // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
8983     // give the right answer.
8984     if (ClassDecl->needsImplicitMoveConstructor())
8985       S.DeclareImplicitMoveConstructor(ClassDecl);
8986     return ClassDecl->hasMoveConstructor();
8987   }
8988 
8989   // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
8990   // give the right answer.
8991   if (ClassDecl->needsImplicitMoveAssignment())
8992     S.DeclareImplicitMoveAssignment(ClassDecl);
8993   return ClassDecl->hasMoveAssignment();
8994 }
8995 
8996 /// Determine whether all non-static data members and direct or virtual bases
8997 /// of class \p ClassDecl have either a move operation, or are trivially
8998 /// copyable.
8999 static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
9000                                             bool IsConstructor) {
9001   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9002                                           BaseEnd = ClassDecl->bases_end();
9003        Base != BaseEnd; ++Base) {
9004     if (Base->isVirtual())
9005       continue;
9006 
9007     if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9008       return false;
9009   }
9010 
9011   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9012                                           BaseEnd = ClassDecl->vbases_end();
9013        Base != BaseEnd; ++Base) {
9014     if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9015       return false;
9016   }
9017 
9018   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9019                                      FieldEnd = ClassDecl->field_end();
9020        Field != FieldEnd; ++Field) {
9021     if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
9022       return false;
9023   }
9024 
9025   return true;
9026 }
9027 
9028 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
9029   // C++11 [class.copy]p20:
9030   //   If the definition of a class X does not explicitly declare a move
9031   //   assignment operator, one will be implicitly declared as defaulted
9032   //   if and only if:
9033   //
9034   //   - [first 4 bullets]
9035   assert(ClassDecl->needsImplicitMoveAssignment());
9036 
9037   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9038   if (DSM.isAlreadyBeingDeclared())
9039     return 0;
9040 
9041   // [Checked after we build the declaration]
9042   //   - the move assignment operator would not be implicitly defined as
9043   //     deleted,
9044 
9045   // [DR1402]:
9046   //   - X has no direct or indirect virtual base class with a non-trivial
9047   //     move assignment operator, and
9048   //   - each of X's non-static data members and direct or virtual base classes
9049   //     has a type that either has a move assignment operator or is trivially
9050   //     copyable.
9051   if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
9052       !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
9053     ClassDecl->setFailedImplicitMoveAssignment();
9054     return 0;
9055   }
9056 
9057   // Note: The following rules are largely analoguous to the move
9058   // constructor rules.
9059 
9060   QualType ArgType = Context.getTypeDeclType(ClassDecl);
9061   QualType RetType = Context.getLValueReferenceType(ArgType);
9062   ArgType = Context.getRValueReferenceType(ArgType);
9063 
9064   //   An implicitly-declared move assignment operator is an inline public
9065   //   member of its class.
9066   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9067   SourceLocation ClassLoc = ClassDecl->getLocation();
9068   DeclarationNameInfo NameInfo(Name, ClassLoc);
9069   CXXMethodDecl *MoveAssignment
9070     = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9071                             /*TInfo=*/0,
9072                             /*StorageClass=*/SC_None,
9073                             /*isInline=*/true,
9074                             /*isConstexpr=*/false,
9075                             SourceLocation());
9076   MoveAssignment->setAccess(AS_public);
9077   MoveAssignment->setDefaulted();
9078   MoveAssignment->setImplicit();
9079 
9080   // Build an exception specification pointing back at this member.
9081   FunctionProtoType::ExtProtoInfo EPI;
9082   EPI.ExceptionSpecType = EST_Unevaluated;
9083   EPI.ExceptionSpecDecl = MoveAssignment;
9084   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
9085 
9086   // Add the parameter to the operator.
9087   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9088                                                ClassLoc, ClassLoc, /*Id=*/0,
9089                                                ArgType, /*TInfo=*/0,
9090                                                SC_None, 0);
9091   MoveAssignment->setParams(FromParam);
9092 
9093   AddOverriddenMethods(ClassDecl, MoveAssignment);
9094 
9095   MoveAssignment->setTrivial(
9096     ClassDecl->needsOverloadResolutionForMoveAssignment()
9097       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9098       : ClassDecl->hasTrivialMoveAssignment());
9099 
9100   // C++0x [class.copy]p9:
9101   //   If the definition of a class X does not explicitly declare a move
9102   //   assignment operator, one will be implicitly declared as defaulted if and
9103   //   only if:
9104   //   [...]
9105   //   - the move assignment operator would not be implicitly defined as
9106   //     deleted.
9107   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
9108     // Cache this result so that we don't try to generate this over and over
9109     // on every lookup, leaking memory and wasting time.
9110     ClassDecl->setFailedImplicitMoveAssignment();
9111     return 0;
9112   }
9113 
9114   // Note that we have added this copy-assignment operator.
9115   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9116 
9117   if (Scope *S = getScopeForContext(ClassDecl))
9118     PushOnScopeChains(MoveAssignment, S, false);
9119   ClassDecl->addDecl(MoveAssignment);
9120 
9121   return MoveAssignment;
9122 }
9123 
9124 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9125                                         CXXMethodDecl *MoveAssignOperator) {
9126   assert((MoveAssignOperator->isDefaulted() &&
9127           MoveAssignOperator->isOverloadedOperator() &&
9128           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
9129           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9130           !MoveAssignOperator->isDeleted()) &&
9131          "DefineImplicitMoveAssignment called for wrong function");
9132 
9133   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9134 
9135   if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9136     MoveAssignOperator->setInvalidDecl();
9137     return;
9138   }
9139 
9140   MoveAssignOperator->setUsed();
9141 
9142   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
9143   DiagnosticErrorTrap Trap(Diags);
9144 
9145   // C++0x [class.copy]p28:
9146   //   The implicitly-defined or move assignment operator for a non-union class
9147   //   X performs memberwise move assignment of its subobjects. The direct base
9148   //   classes of X are assigned first, in the order of their declaration in the
9149   //   base-specifier-list, and then the immediate non-static data members of X
9150   //   are assigned, in the order in which they were declared in the class
9151   //   definition.
9152 
9153   // The statements that form the synthesized function body.
9154   SmallVector<Stmt*, 8> Statements;
9155 
9156   // The parameter for the "other" object, which we are move from.
9157   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9158   QualType OtherRefType = Other->getType()->
9159       getAs<RValueReferenceType>()->getPointeeType();
9160   assert(OtherRefType.getQualifiers() == 0 &&
9161          "Bad argument type of defaulted move assignment");
9162 
9163   // Our location for everything implicitly-generated.
9164   SourceLocation Loc = MoveAssignOperator->getLocation();
9165 
9166   // Construct a reference to the "other" object. We'll be using this
9167   // throughout the generated ASTs.
9168   Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
9169   assert(OtherRef && "Reference to parameter cannot fail!");
9170   // Cast to rvalue.
9171   OtherRef = CastForMoving(*this, OtherRef);
9172 
9173   // Construct the "this" pointer. We'll be using this throughout the generated
9174   // ASTs.
9175   Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
9176   assert(This && "Reference to this cannot fail!");
9177 
9178   // Assign base classes.
9179   bool Invalid = false;
9180   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9181        E = ClassDecl->bases_end(); Base != E; ++Base) {
9182     // Form the assignment:
9183     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9184     QualType BaseType = Base->getType().getUnqualifiedType();
9185     if (!BaseType->isRecordType()) {
9186       Invalid = true;
9187       continue;
9188     }
9189 
9190     CXXCastPath BasePath;
9191     BasePath.push_back(Base);
9192 
9193     // Construct the "from" expression, which is an implicit cast to the
9194     // appropriately-qualified base type.
9195     Expr *From = OtherRef;
9196     From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
9197                              VK_XValue, &BasePath).take();
9198 
9199     // Dereference "this".
9200     ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9201 
9202     // Implicitly cast "this" to the appropriately-qualified base type.
9203     To = ImpCastExprToType(To.take(),
9204                            Context.getCVRQualifiedType(BaseType,
9205                                      MoveAssignOperator->getTypeQualifiers()),
9206                            CK_UncheckedDerivedToBase,
9207                            VK_LValue, &BasePath);
9208 
9209     // Build the move.
9210     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
9211                                             To.get(), From,
9212                                             /*CopyingBaseSubobject=*/true,
9213                                             /*Copying=*/false);
9214     if (Move.isInvalid()) {
9215       Diag(CurrentLocation, diag::note_member_synthesized_at)
9216         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9217       MoveAssignOperator->setInvalidDecl();
9218       return;
9219     }
9220 
9221     // Success! Record the move.
9222     Statements.push_back(Move.takeAs<Expr>());
9223   }
9224 
9225   // Assign non-static members.
9226   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9227                                   FieldEnd = ClassDecl->field_end();
9228        Field != FieldEnd; ++Field) {
9229     if (Field->isUnnamedBitfield())
9230       continue;
9231 
9232     // Check for members of reference type; we can't move those.
9233     if (Field->getType()->isReferenceType()) {
9234       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9235         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9236       Diag(Field->getLocation(), diag::note_declared_at);
9237       Diag(CurrentLocation, diag::note_member_synthesized_at)
9238         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9239       Invalid = true;
9240       continue;
9241     }
9242 
9243     // Check for members of const-qualified, non-class type.
9244     QualType BaseType = Context.getBaseElementType(Field->getType());
9245     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9246       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9247         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9248       Diag(Field->getLocation(), diag::note_declared_at);
9249       Diag(CurrentLocation, diag::note_member_synthesized_at)
9250         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9251       Invalid = true;
9252       continue;
9253     }
9254 
9255     // Suppress assigning zero-width bitfields.
9256     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9257       continue;
9258 
9259     QualType FieldType = Field->getType().getNonReferenceType();
9260     if (FieldType->isIncompleteArrayType()) {
9261       assert(ClassDecl->hasFlexibleArrayMember() &&
9262              "Incomplete array type is not valid");
9263       continue;
9264     }
9265 
9266     // Build references to the field in the object we're copying from and to.
9267     CXXScopeSpec SS; // Intentionally empty
9268     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9269                               LookupMemberName);
9270     MemberLookup.addDecl(*Field);
9271     MemberLookup.resolveKind();
9272     ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
9273                                                Loc, /*IsArrow=*/false,
9274                                                SS, SourceLocation(), 0,
9275                                                MemberLookup, 0);
9276     ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
9277                                              Loc, /*IsArrow=*/true,
9278                                              SS, SourceLocation(), 0,
9279                                              MemberLookup, 0);
9280     assert(!From.isInvalid() && "Implicit field reference cannot fail");
9281     assert(!To.isInvalid() && "Implicit field reference cannot fail");
9282 
9283     assert(!From.get()->isLValue() && // could be xvalue or prvalue
9284         "Member reference with rvalue base must be rvalue except for reference "
9285         "members, which aren't allowed for move assignment.");
9286 
9287     // Build the move of this field.
9288     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
9289                                             To.get(), From.get(),
9290                                             /*CopyingBaseSubobject=*/false,
9291                                             /*Copying=*/false);
9292     if (Move.isInvalid()) {
9293       Diag(CurrentLocation, diag::note_member_synthesized_at)
9294         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9295       MoveAssignOperator->setInvalidDecl();
9296       return;
9297     }
9298 
9299     // Success! Record the copy.
9300     Statements.push_back(Move.takeAs<Stmt>());
9301   }
9302 
9303   if (!Invalid) {
9304     // Add a "return *this;"
9305     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9306 
9307     StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9308     if (Return.isInvalid())
9309       Invalid = true;
9310     else {
9311       Statements.push_back(Return.takeAs<Stmt>());
9312 
9313       if (Trap.hasErrorOccurred()) {
9314         Diag(CurrentLocation, diag::note_member_synthesized_at)
9315           << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9316         Invalid = true;
9317       }
9318     }
9319   }
9320 
9321   if (Invalid) {
9322     MoveAssignOperator->setInvalidDecl();
9323     return;
9324   }
9325 
9326   StmtResult Body;
9327   {
9328     CompoundScopeRAII CompoundScope(*this);
9329     Body = ActOnCompoundStmt(Loc, Loc, Statements,
9330                              /*isStmtExpr=*/false);
9331     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9332   }
9333   MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9334 
9335   if (ASTMutationListener *L = getASTMutationListener()) {
9336     L->CompletedImplicitDefinition(MoveAssignOperator);
9337   }
9338 }
9339 
9340 Sema::ImplicitExceptionSpecification
9341 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9342   CXXRecordDecl *ClassDecl = MD->getParent();
9343 
9344   ImplicitExceptionSpecification ExceptSpec(*this);
9345   if (ClassDecl->isInvalidDecl())
9346     return ExceptSpec;
9347 
9348   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9349   assert(T->getNumArgs() >= 1 && "not a copy ctor");
9350   unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9351 
9352   // C++ [except.spec]p14:
9353   //   An implicitly declared special member function (Clause 12) shall have an
9354   //   exception-specification. [...]
9355   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9356                                        BaseEnd = ClassDecl->bases_end();
9357        Base != BaseEnd;
9358        ++Base) {
9359     // Virtual bases are handled below.
9360     if (Base->isVirtual())
9361       continue;
9362 
9363     CXXRecordDecl *BaseClassDecl
9364       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9365     if (CXXConstructorDecl *CopyConstructor =
9366           LookupCopyingConstructor(BaseClassDecl, Quals))
9367       ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
9368   }
9369   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9370                                        BaseEnd = ClassDecl->vbases_end();
9371        Base != BaseEnd;
9372        ++Base) {
9373     CXXRecordDecl *BaseClassDecl
9374       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9375     if (CXXConstructorDecl *CopyConstructor =
9376           LookupCopyingConstructor(BaseClassDecl, Quals))
9377       ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
9378   }
9379   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9380                                   FieldEnd = ClassDecl->field_end();
9381        Field != FieldEnd;
9382        ++Field) {
9383     QualType FieldType = Context.getBaseElementType(Field->getType());
9384     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9385       if (CXXConstructorDecl *CopyConstructor =
9386               LookupCopyingConstructor(FieldClassDecl,
9387                                        Quals | FieldType.getCVRQualifiers()))
9388       ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
9389     }
9390   }
9391 
9392   return ExceptSpec;
9393 }
9394 
9395 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9396                                                     CXXRecordDecl *ClassDecl) {
9397   // C++ [class.copy]p4:
9398   //   If the class definition does not explicitly declare a copy
9399   //   constructor, one is declared implicitly.
9400   assert(ClassDecl->needsImplicitCopyConstructor());
9401 
9402   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9403   if (DSM.isAlreadyBeingDeclared())
9404     return 0;
9405 
9406   QualType ClassType = Context.getTypeDeclType(ClassDecl);
9407   QualType ArgType = ClassType;
9408   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
9409   if (Const)
9410     ArgType = ArgType.withConst();
9411   ArgType = Context.getLValueReferenceType(ArgType);
9412 
9413   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9414                                                      CXXCopyConstructor,
9415                                                      Const);
9416 
9417   DeclarationName Name
9418     = Context.DeclarationNames.getCXXConstructorName(
9419                                            Context.getCanonicalType(ClassType));
9420   SourceLocation ClassLoc = ClassDecl->getLocation();
9421   DeclarationNameInfo NameInfo(Name, ClassLoc);
9422 
9423   //   An implicitly-declared copy constructor is an inline public
9424   //   member of its class.
9425   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
9426       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
9427       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
9428       Constexpr);
9429   CopyConstructor->setAccess(AS_public);
9430   CopyConstructor->setDefaulted();
9431 
9432   // Build an exception specification pointing back at this member.
9433   FunctionProtoType::ExtProtoInfo EPI;
9434   EPI.ExceptionSpecType = EST_Unevaluated;
9435   EPI.ExceptionSpecDecl = CopyConstructor;
9436   CopyConstructor->setType(
9437       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
9438 
9439   // Add the parameter to the constructor.
9440   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
9441                                                ClassLoc, ClassLoc,
9442                                                /*IdentifierInfo=*/0,
9443                                                ArgType, /*TInfo=*/0,
9444                                                SC_None, 0);
9445   CopyConstructor->setParams(FromParam);
9446 
9447   CopyConstructor->setTrivial(
9448     ClassDecl->needsOverloadResolutionForCopyConstructor()
9449       ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9450       : ClassDecl->hasTrivialCopyConstructor());
9451 
9452   // C++11 [class.copy]p8:
9453   //   ... If the class definition does not explicitly declare a copy
9454   //   constructor, there is no user-declared move constructor, and there is no
9455   //   user-declared move assignment operator, a copy constructor is implicitly
9456   //   declared as defaulted.
9457   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
9458     SetDeclDeleted(CopyConstructor, ClassLoc);
9459 
9460   // Note that we have declared this constructor.
9461   ++ASTContext::NumImplicitCopyConstructorsDeclared;
9462 
9463   if (Scope *S = getScopeForContext(ClassDecl))
9464     PushOnScopeChains(CopyConstructor, S, false);
9465   ClassDecl->addDecl(CopyConstructor);
9466 
9467   return CopyConstructor;
9468 }
9469 
9470 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
9471                                    CXXConstructorDecl *CopyConstructor) {
9472   assert((CopyConstructor->isDefaulted() &&
9473           CopyConstructor->isCopyConstructor() &&
9474           !CopyConstructor->doesThisDeclarationHaveABody() &&
9475           !CopyConstructor->isDeleted()) &&
9476          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
9477 
9478   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
9479   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
9480 
9481   SynthesizedFunctionScope Scope(*this, CopyConstructor);
9482   DiagnosticErrorTrap Trap(Diags);
9483 
9484   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
9485       Trap.hasErrorOccurred()) {
9486     Diag(CurrentLocation, diag::note_member_synthesized_at)
9487       << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
9488     CopyConstructor->setInvalidDecl();
9489   }  else {
9490     Sema::CompoundScopeRAII CompoundScope(*this);
9491     CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9492                                                CopyConstructor->getLocation(),
9493                                                MultiStmtArg(),
9494                                                /*isStmtExpr=*/false)
9495                                                               .takeAs<Stmt>());
9496     CopyConstructor->setImplicitlyDefined(true);
9497   }
9498 
9499   CopyConstructor->setUsed();
9500   if (ASTMutationListener *L = getASTMutationListener()) {
9501     L->CompletedImplicitDefinition(CopyConstructor);
9502   }
9503 }
9504 
9505 Sema::ImplicitExceptionSpecification
9506 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9507   CXXRecordDecl *ClassDecl = MD->getParent();
9508 
9509   // C++ [except.spec]p14:
9510   //   An implicitly declared special member function (Clause 12) shall have an
9511   //   exception-specification. [...]
9512   ImplicitExceptionSpecification ExceptSpec(*this);
9513   if (ClassDecl->isInvalidDecl())
9514     return ExceptSpec;
9515 
9516   // Direct base-class constructors.
9517   for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9518                                        BEnd = ClassDecl->bases_end();
9519        B != BEnd; ++B) {
9520     if (B->isVirtual()) // Handled below.
9521       continue;
9522 
9523     if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9524       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
9525       CXXConstructorDecl *Constructor =
9526           LookupMovingConstructor(BaseClassDecl, 0);
9527       // If this is a deleted function, add it anyway. This might be conformant
9528       // with the standard. This might not. I'm not sure. It might not matter.
9529       if (Constructor)
9530         ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
9531     }
9532   }
9533 
9534   // Virtual base-class constructors.
9535   for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9536                                        BEnd = ClassDecl->vbases_end();
9537        B != BEnd; ++B) {
9538     if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9539       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
9540       CXXConstructorDecl *Constructor =
9541           LookupMovingConstructor(BaseClassDecl, 0);
9542       // If this is a deleted function, add it anyway. This might be conformant
9543       // with the standard. This might not. I'm not sure. It might not matter.
9544       if (Constructor)
9545         ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
9546     }
9547   }
9548 
9549   // Field constructors.
9550   for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9551                                FEnd = ClassDecl->field_end();
9552        F != FEnd; ++F) {
9553     QualType FieldType = Context.getBaseElementType(F->getType());
9554     if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9555       CXXConstructorDecl *Constructor =
9556           LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
9557       // If this is a deleted function, add it anyway. This might be conformant
9558       // with the standard. This might not. I'm not sure. It might not matter.
9559       // In particular, the problem is that this function never gets called. It
9560       // might just be ill-formed because this function attempts to refer to
9561       // a deleted function here.
9562       if (Constructor)
9563         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
9564     }
9565   }
9566 
9567   return ExceptSpec;
9568 }
9569 
9570 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9571                                                     CXXRecordDecl *ClassDecl) {
9572   // C++11 [class.copy]p9:
9573   //   If the definition of a class X does not explicitly declare a move
9574   //   constructor, one will be implicitly declared as defaulted if and only if:
9575   //
9576   //   - [first 4 bullets]
9577   assert(ClassDecl->needsImplicitMoveConstructor());
9578 
9579   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9580   if (DSM.isAlreadyBeingDeclared())
9581     return 0;
9582 
9583   // [Checked after we build the declaration]
9584   //   - the move assignment operator would not be implicitly defined as
9585   //     deleted,
9586 
9587   // [DR1402]:
9588   //   - each of X's non-static data members and direct or virtual base classes
9589   //     has a type that either has a move constructor or is trivially copyable.
9590   if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9591     ClassDecl->setFailedImplicitMoveConstructor();
9592     return 0;
9593   }
9594 
9595   QualType ClassType = Context.getTypeDeclType(ClassDecl);
9596   QualType ArgType = Context.getRValueReferenceType(ClassType);
9597 
9598   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9599                                                      CXXMoveConstructor,
9600                                                      false);
9601 
9602   DeclarationName Name
9603     = Context.DeclarationNames.getCXXConstructorName(
9604                                            Context.getCanonicalType(ClassType));
9605   SourceLocation ClassLoc = ClassDecl->getLocation();
9606   DeclarationNameInfo NameInfo(Name, ClassLoc);
9607 
9608   // C++0x [class.copy]p11:
9609   //   An implicitly-declared copy/move constructor is an inline public
9610   //   member of its class.
9611   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
9612       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
9613       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
9614       Constexpr);
9615   MoveConstructor->setAccess(AS_public);
9616   MoveConstructor->setDefaulted();
9617 
9618   // Build an exception specification pointing back at this member.
9619   FunctionProtoType::ExtProtoInfo EPI;
9620   EPI.ExceptionSpecType = EST_Unevaluated;
9621   EPI.ExceptionSpecDecl = MoveConstructor;
9622   MoveConstructor->setType(
9623       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
9624 
9625   // Add the parameter to the constructor.
9626   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9627                                                ClassLoc, ClassLoc,
9628                                                /*IdentifierInfo=*/0,
9629                                                ArgType, /*TInfo=*/0,
9630                                                SC_None, 0);
9631   MoveConstructor->setParams(FromParam);
9632 
9633   MoveConstructor->setTrivial(
9634     ClassDecl->needsOverloadResolutionForMoveConstructor()
9635       ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9636       : ClassDecl->hasTrivialMoveConstructor());
9637 
9638   // C++0x [class.copy]p9:
9639   //   If the definition of a class X does not explicitly declare a move
9640   //   constructor, one will be implicitly declared as defaulted if and only if:
9641   //   [...]
9642   //   - the move constructor would not be implicitly defined as deleted.
9643   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
9644     // Cache this result so that we don't try to generate this over and over
9645     // on every lookup, leaking memory and wasting time.
9646     ClassDecl->setFailedImplicitMoveConstructor();
9647     return 0;
9648   }
9649 
9650   // Note that we have declared this constructor.
9651   ++ASTContext::NumImplicitMoveConstructorsDeclared;
9652 
9653   if (Scope *S = getScopeForContext(ClassDecl))
9654     PushOnScopeChains(MoveConstructor, S, false);
9655   ClassDecl->addDecl(MoveConstructor);
9656 
9657   return MoveConstructor;
9658 }
9659 
9660 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9661                                    CXXConstructorDecl *MoveConstructor) {
9662   assert((MoveConstructor->isDefaulted() &&
9663           MoveConstructor->isMoveConstructor() &&
9664           !MoveConstructor->doesThisDeclarationHaveABody() &&
9665           !MoveConstructor->isDeleted()) &&
9666          "DefineImplicitMoveConstructor - call it for implicit move ctor");
9667 
9668   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9669   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9670 
9671   SynthesizedFunctionScope Scope(*this, MoveConstructor);
9672   DiagnosticErrorTrap Trap(Diags);
9673 
9674   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
9675       Trap.hasErrorOccurred()) {
9676     Diag(CurrentLocation, diag::note_member_synthesized_at)
9677       << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9678     MoveConstructor->setInvalidDecl();
9679   }  else {
9680     Sema::CompoundScopeRAII CompoundScope(*this);
9681     MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9682                                                MoveConstructor->getLocation(),
9683                                                MultiStmtArg(),
9684                                                /*isStmtExpr=*/false)
9685                                                               .takeAs<Stmt>());
9686     MoveConstructor->setImplicitlyDefined(true);
9687   }
9688 
9689   MoveConstructor->setUsed();
9690 
9691   if (ASTMutationListener *L = getASTMutationListener()) {
9692     L->CompletedImplicitDefinition(MoveConstructor);
9693   }
9694 }
9695 
9696 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9697   return FD->isDeleted() &&
9698          (FD->isDefaulted() || FD->isImplicit()) &&
9699          isa<CXXMethodDecl>(FD);
9700 }
9701 
9702 /// \brief Mark the call operator of the given lambda closure type as "used".
9703 static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9704   CXXMethodDecl *CallOperator
9705     = cast<CXXMethodDecl>(
9706         Lambda->lookup(
9707           S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
9708   CallOperator->setReferenced();
9709   CallOperator->setUsed();
9710 }
9711 
9712 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9713        SourceLocation CurrentLocation,
9714        CXXConversionDecl *Conv)
9715 {
9716   CXXRecordDecl *Lambda = Conv->getParent();
9717 
9718   // Make sure that the lambda call operator is marked used.
9719   markLambdaCallOperatorUsed(*this, Lambda);
9720 
9721   Conv->setUsed();
9722 
9723   SynthesizedFunctionScope Scope(*this, Conv);
9724   DiagnosticErrorTrap Trap(Diags);
9725 
9726   // Return the address of the __invoke function.
9727   DeclarationName InvokeName = &Context.Idents.get("__invoke");
9728   CXXMethodDecl *Invoke
9729     = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
9730   Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9731                                        VK_LValue, Conv->getLocation()).take();
9732   assert(FunctionRef && "Can't refer to __invoke function?");
9733   Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
9734   Conv->setBody(new (Context) CompoundStmt(Context, Return,
9735                                            Conv->getLocation(),
9736                                            Conv->getLocation()));
9737 
9738   // Fill in the __invoke function with a dummy implementation. IR generation
9739   // will fill in the actual details.
9740   Invoke->setUsed();
9741   Invoke->setReferenced();
9742   Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
9743 
9744   if (ASTMutationListener *L = getASTMutationListener()) {
9745     L->CompletedImplicitDefinition(Conv);
9746     L->CompletedImplicitDefinition(Invoke);
9747   }
9748 }
9749 
9750 void Sema::DefineImplicitLambdaToBlockPointerConversion(
9751        SourceLocation CurrentLocation,
9752        CXXConversionDecl *Conv)
9753 {
9754   Conv->setUsed();
9755 
9756   SynthesizedFunctionScope Scope(*this, Conv);
9757   DiagnosticErrorTrap Trap(Diags);
9758 
9759   // Copy-initialize the lambda object as needed to capture it.
9760   Expr *This = ActOnCXXThis(CurrentLocation).take();
9761   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
9762 
9763   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9764                                                         Conv->getLocation(),
9765                                                         Conv, DerefThis);
9766 
9767   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9768   // behavior.  Note that only the general conversion function does this
9769   // (since it's unusable otherwise); in the case where we inline the
9770   // block literal, it has block literal lifetime semantics.
9771   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
9772     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9773                                           CK_CopyAndAutoreleaseBlockObject,
9774                                           BuildBlock.get(), 0, VK_RValue);
9775 
9776   if (BuildBlock.isInvalid()) {
9777     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9778     Conv->setInvalidDecl();
9779     return;
9780   }
9781 
9782   // Create the return statement that returns the block from the conversion
9783   // function.
9784   StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
9785   if (Return.isInvalid()) {
9786     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9787     Conv->setInvalidDecl();
9788     return;
9789   }
9790 
9791   // Set the body of the conversion function.
9792   Stmt *ReturnS = Return.take();
9793   Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
9794                                            Conv->getLocation(),
9795                                            Conv->getLocation()));
9796 
9797   // We're done; notify the mutation listener, if any.
9798   if (ASTMutationListener *L = getASTMutationListener()) {
9799     L->CompletedImplicitDefinition(Conv);
9800   }
9801 }
9802 
9803 /// \brief Determine whether the given list arguments contains exactly one
9804 /// "real" (non-default) argument.
9805 static bool hasOneRealArgument(MultiExprArg Args) {
9806   switch (Args.size()) {
9807   case 0:
9808     return false;
9809 
9810   default:
9811     if (!Args[1]->isDefaultArgument())
9812       return false;
9813 
9814     // fall through
9815   case 1:
9816     return !Args[0]->isDefaultArgument();
9817   }
9818 
9819   return false;
9820 }
9821 
9822 ExprResult
9823 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9824                             CXXConstructorDecl *Constructor,
9825                             MultiExprArg ExprArgs,
9826                             bool HadMultipleCandidates,
9827                             bool IsListInitialization,
9828                             bool RequiresZeroInit,
9829                             unsigned ConstructKind,
9830                             SourceRange ParenRange) {
9831   bool Elidable = false;
9832 
9833   // C++0x [class.copy]p34:
9834   //   When certain criteria are met, an implementation is allowed to
9835   //   omit the copy/move construction of a class object, even if the
9836   //   copy/move constructor and/or destructor for the object have
9837   //   side effects. [...]
9838   //     - when a temporary class object that has not been bound to a
9839   //       reference (12.2) would be copied/moved to a class object
9840   //       with the same cv-unqualified type, the copy/move operation
9841   //       can be omitted by constructing the temporary object
9842   //       directly into the target of the omitted copy/move
9843   if (ConstructKind == CXXConstructExpr::CK_Complete &&
9844       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
9845     Expr *SubExpr = ExprArgs[0];
9846     Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
9847   }
9848 
9849   return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
9850                                Elidable, ExprArgs, HadMultipleCandidates,
9851                                IsListInitialization, RequiresZeroInit,
9852                                ConstructKind, ParenRange);
9853 }
9854 
9855 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
9856 /// including handling of its default argument expressions.
9857 ExprResult
9858 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9859                             CXXConstructorDecl *Constructor, bool Elidable,
9860                             MultiExprArg ExprArgs,
9861                             bool HadMultipleCandidates,
9862                             bool IsListInitialization,
9863                             bool RequiresZeroInit,
9864                             unsigned ConstructKind,
9865                             SourceRange ParenRange) {
9866   MarkFunctionReferenced(ConstructLoc, Constructor);
9867   return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
9868                                         Constructor, Elidable, ExprArgs,
9869                                         HadMultipleCandidates,
9870                                         IsListInitialization, RequiresZeroInit,
9871               static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9872                                         ParenRange));
9873 }
9874 
9875 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
9876   if (VD->isInvalidDecl()) return;
9877 
9878   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
9879   if (ClassDecl->isInvalidDecl()) return;
9880   if (ClassDecl->hasIrrelevantDestructor()) return;
9881   if (ClassDecl->isDependentContext()) return;
9882 
9883   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
9884   MarkFunctionReferenced(VD->getLocation(), Destructor);
9885   CheckDestructorAccess(VD->getLocation(), Destructor,
9886                         PDiag(diag::err_access_dtor_var)
9887                         << VD->getDeclName()
9888                         << VD->getType());
9889   DiagnoseUseOfDecl(Destructor, VD->getLocation());
9890 
9891   if (!VD->hasGlobalStorage()) return;
9892 
9893   // Emit warning for non-trivial dtor in global scope (a real global,
9894   // class-static, function-static).
9895   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9896 
9897   // TODO: this should be re-enabled for static locals by !CXAAtExit
9898   if (!VD->isStaticLocal())
9899     Diag(VD->getLocation(), diag::warn_global_destructor);
9900 }
9901 
9902 /// \brief Given a constructor and the set of arguments provided for the
9903 /// constructor, convert the arguments and add any required default arguments
9904 /// to form a proper call to this constructor.
9905 ///
9906 /// \returns true if an error occurred, false otherwise.
9907 bool
9908 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9909                               MultiExprArg ArgsPtr,
9910                               SourceLocation Loc,
9911                               SmallVectorImpl<Expr*> &ConvertedArgs,
9912                               bool AllowExplicit,
9913                               bool IsListInitialization) {
9914   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9915   unsigned NumArgs = ArgsPtr.size();
9916   Expr **Args = ArgsPtr.data();
9917 
9918   const FunctionProtoType *Proto
9919     = Constructor->getType()->getAs<FunctionProtoType>();
9920   assert(Proto && "Constructor without a prototype?");
9921   unsigned NumArgsInProto = Proto->getNumArgs();
9922 
9923   // If too few arguments are available, we'll fill in the rest with defaults.
9924   if (NumArgs < NumArgsInProto)
9925     ConvertedArgs.reserve(NumArgsInProto);
9926   else
9927     ConvertedArgs.reserve(NumArgs);
9928 
9929   VariadicCallType CallType =
9930     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
9931   SmallVector<Expr *, 8> AllArgs;
9932   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9933                                         Proto, 0, Args, NumArgs, AllArgs,
9934                                         CallType, AllowExplicit,
9935                                         IsListInitialization);
9936   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
9937 
9938   DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9939 
9940   CheckConstructorCall(Constructor,
9941                        llvm::makeArrayRef<const Expr *>(AllArgs.data(),
9942                                                         AllArgs.size()),
9943                        Proto, Loc);
9944 
9945   return Invalid;
9946 }
9947 
9948 static inline bool
9949 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9950                                        const FunctionDecl *FnDecl) {
9951   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
9952   if (isa<NamespaceDecl>(DC)) {
9953     return SemaRef.Diag(FnDecl->getLocation(),
9954                         diag::err_operator_new_delete_declared_in_namespace)
9955       << FnDecl->getDeclName();
9956   }
9957 
9958   if (isa<TranslationUnitDecl>(DC) &&
9959       FnDecl->getStorageClass() == SC_Static) {
9960     return SemaRef.Diag(FnDecl->getLocation(),
9961                         diag::err_operator_new_delete_declared_static)
9962       << FnDecl->getDeclName();
9963   }
9964 
9965   return false;
9966 }
9967 
9968 static inline bool
9969 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9970                             CanQualType ExpectedResultType,
9971                             CanQualType ExpectedFirstParamType,
9972                             unsigned DependentParamTypeDiag,
9973                             unsigned InvalidParamTypeDiag) {
9974   QualType ResultType =
9975     FnDecl->getType()->getAs<FunctionType>()->getResultType();
9976 
9977   // Check that the result type is not dependent.
9978   if (ResultType->isDependentType())
9979     return SemaRef.Diag(FnDecl->getLocation(),
9980                         diag::err_operator_new_delete_dependent_result_type)
9981     << FnDecl->getDeclName() << ExpectedResultType;
9982 
9983   // Check that the result type is what we expect.
9984   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9985     return SemaRef.Diag(FnDecl->getLocation(),
9986                         diag::err_operator_new_delete_invalid_result_type)
9987     << FnDecl->getDeclName() << ExpectedResultType;
9988 
9989   // A function template must have at least 2 parameters.
9990   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9991     return SemaRef.Diag(FnDecl->getLocation(),
9992                       diag::err_operator_new_delete_template_too_few_parameters)
9993         << FnDecl->getDeclName();
9994 
9995   // The function decl must have at least 1 parameter.
9996   if (FnDecl->getNumParams() == 0)
9997     return SemaRef.Diag(FnDecl->getLocation(),
9998                         diag::err_operator_new_delete_too_few_parameters)
9999       << FnDecl->getDeclName();
10000 
10001   // Check the first parameter type is not dependent.
10002   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10003   if (FirstParamType->isDependentType())
10004     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10005       << FnDecl->getDeclName() << ExpectedFirstParamType;
10006 
10007   // Check that the first parameter type is what we expect.
10008   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
10009       ExpectedFirstParamType)
10010     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10011     << FnDecl->getDeclName() << ExpectedFirstParamType;
10012 
10013   return false;
10014 }
10015 
10016 static bool
10017 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
10018   // C++ [basic.stc.dynamic.allocation]p1:
10019   //   A program is ill-formed if an allocation function is declared in a
10020   //   namespace scope other than global scope or declared static in global
10021   //   scope.
10022   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10023     return true;
10024 
10025   CanQualType SizeTy =
10026     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10027 
10028   // C++ [basic.stc.dynamic.allocation]p1:
10029   //  The return type shall be void*. The first parameter shall have type
10030   //  std::size_t.
10031   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10032                                   SizeTy,
10033                                   diag::err_operator_new_dependent_param_type,
10034                                   diag::err_operator_new_param_type))
10035     return true;
10036 
10037   // C++ [basic.stc.dynamic.allocation]p1:
10038   //  The first parameter shall not have an associated default argument.
10039   if (FnDecl->getParamDecl(0)->hasDefaultArg())
10040     return SemaRef.Diag(FnDecl->getLocation(),
10041                         diag::err_operator_new_default_arg)
10042       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10043 
10044   return false;
10045 }
10046 
10047 static bool
10048 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
10049   // C++ [basic.stc.dynamic.deallocation]p1:
10050   //   A program is ill-formed if deallocation functions are declared in a
10051   //   namespace scope other than global scope or declared static in global
10052   //   scope.
10053   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10054     return true;
10055 
10056   // C++ [basic.stc.dynamic.deallocation]p2:
10057   //   Each deallocation function shall return void and its first parameter
10058   //   shall be void*.
10059   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10060                                   SemaRef.Context.VoidPtrTy,
10061                                  diag::err_operator_delete_dependent_param_type,
10062                                  diag::err_operator_delete_param_type))
10063     return true;
10064 
10065   return false;
10066 }
10067 
10068 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
10069 /// of this overloaded operator is well-formed. If so, returns false;
10070 /// otherwise, emits appropriate diagnostics and returns true.
10071 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
10072   assert(FnDecl && FnDecl->isOverloadedOperator() &&
10073          "Expected an overloaded operator declaration");
10074 
10075   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10076 
10077   // C++ [over.oper]p5:
10078   //   The allocation and deallocation functions, operator new,
10079   //   operator new[], operator delete and operator delete[], are
10080   //   described completely in 3.7.3. The attributes and restrictions
10081   //   found in the rest of this subclause do not apply to them unless
10082   //   explicitly stated in 3.7.3.
10083   if (Op == OO_Delete || Op == OO_Array_Delete)
10084     return CheckOperatorDeleteDeclaration(*this, FnDecl);
10085 
10086   if (Op == OO_New || Op == OO_Array_New)
10087     return CheckOperatorNewDeclaration(*this, FnDecl);
10088 
10089   // C++ [over.oper]p6:
10090   //   An operator function shall either be a non-static member
10091   //   function or be a non-member function and have at least one
10092   //   parameter whose type is a class, a reference to a class, an
10093   //   enumeration, or a reference to an enumeration.
10094   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10095     if (MethodDecl->isStatic())
10096       return Diag(FnDecl->getLocation(),
10097                   diag::err_operator_overload_static) << FnDecl->getDeclName();
10098   } else {
10099     bool ClassOrEnumParam = false;
10100     for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10101                                    ParamEnd = FnDecl->param_end();
10102          Param != ParamEnd; ++Param) {
10103       QualType ParamType = (*Param)->getType().getNonReferenceType();
10104       if (ParamType->isDependentType() || ParamType->isRecordType() ||
10105           ParamType->isEnumeralType()) {
10106         ClassOrEnumParam = true;
10107         break;
10108       }
10109     }
10110 
10111     if (!ClassOrEnumParam)
10112       return Diag(FnDecl->getLocation(),
10113                   diag::err_operator_overload_needs_class_or_enum)
10114         << FnDecl->getDeclName();
10115   }
10116 
10117   // C++ [over.oper]p8:
10118   //   An operator function cannot have default arguments (8.3.6),
10119   //   except where explicitly stated below.
10120   //
10121   // Only the function-call operator allows default arguments
10122   // (C++ [over.call]p1).
10123   if (Op != OO_Call) {
10124     for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10125          Param != FnDecl->param_end(); ++Param) {
10126       if ((*Param)->hasDefaultArg())
10127         return Diag((*Param)->getLocation(),
10128                     diag::err_operator_overload_default_arg)
10129           << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
10130     }
10131   }
10132 
10133   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10134     { false, false, false }
10135 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10136     , { Unary, Binary, MemberOnly }
10137 #include "clang/Basic/OperatorKinds.def"
10138   };
10139 
10140   bool CanBeUnaryOperator = OperatorUses[Op][0];
10141   bool CanBeBinaryOperator = OperatorUses[Op][1];
10142   bool MustBeMemberOperator = OperatorUses[Op][2];
10143 
10144   // C++ [over.oper]p8:
10145   //   [...] Operator functions cannot have more or fewer parameters
10146   //   than the number required for the corresponding operator, as
10147   //   described in the rest of this subclause.
10148   unsigned NumParams = FnDecl->getNumParams()
10149                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
10150   if (Op != OO_Call &&
10151       ((NumParams == 1 && !CanBeUnaryOperator) ||
10152        (NumParams == 2 && !CanBeBinaryOperator) ||
10153        (NumParams < 1) || (NumParams > 2))) {
10154     // We have the wrong number of parameters.
10155     unsigned ErrorKind;
10156     if (CanBeUnaryOperator && CanBeBinaryOperator) {
10157       ErrorKind = 2;  // 2 -> unary or binary.
10158     } else if (CanBeUnaryOperator) {
10159       ErrorKind = 0;  // 0 -> unary
10160     } else {
10161       assert(CanBeBinaryOperator &&
10162              "All non-call overloaded operators are unary or binary!");
10163       ErrorKind = 1;  // 1 -> binary
10164     }
10165 
10166     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
10167       << FnDecl->getDeclName() << NumParams << ErrorKind;
10168   }
10169 
10170   // Overloaded operators other than operator() cannot be variadic.
10171   if (Op != OO_Call &&
10172       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
10173     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
10174       << FnDecl->getDeclName();
10175   }
10176 
10177   // Some operators must be non-static member functions.
10178   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10179     return Diag(FnDecl->getLocation(),
10180                 diag::err_operator_overload_must_be_member)
10181       << FnDecl->getDeclName();
10182   }
10183 
10184   // C++ [over.inc]p1:
10185   //   The user-defined function called operator++ implements the
10186   //   prefix and postfix ++ operator. If this function is a member
10187   //   function with no parameters, or a non-member function with one
10188   //   parameter of class or enumeration type, it defines the prefix
10189   //   increment operator ++ for objects of that type. If the function
10190   //   is a member function with one parameter (which shall be of type
10191   //   int) or a non-member function with two parameters (the second
10192   //   of which shall be of type int), it defines the postfix
10193   //   increment operator ++ for objects of that type.
10194   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10195     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10196     bool ParamIsInt = false;
10197     if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
10198       ParamIsInt = BT->getKind() == BuiltinType::Int;
10199 
10200     if (!ParamIsInt)
10201       return Diag(LastParam->getLocation(),
10202                   diag::err_operator_overload_post_incdec_must_be_int)
10203         << LastParam->getType() << (Op == OO_MinusMinus);
10204   }
10205 
10206   return false;
10207 }
10208 
10209 /// CheckLiteralOperatorDeclaration - Check whether the declaration
10210 /// of this literal operator function is well-formed. If so, returns
10211 /// false; otherwise, emits appropriate diagnostics and returns true.
10212 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
10213   if (isa<CXXMethodDecl>(FnDecl)) {
10214     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10215       << FnDecl->getDeclName();
10216     return true;
10217   }
10218 
10219   if (FnDecl->isExternC()) {
10220     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10221     return true;
10222   }
10223 
10224   bool Valid = false;
10225 
10226   // This might be the definition of a literal operator template.
10227   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10228   // This might be a specialization of a literal operator template.
10229   if (!TpDecl)
10230     TpDecl = FnDecl->getPrimaryTemplate();
10231 
10232   // template <char...> type operator "" name() is the only valid template
10233   // signature, and the only valid signature with no parameters.
10234   if (TpDecl) {
10235     if (FnDecl->param_size() == 0) {
10236       // Must have only one template parameter
10237       TemplateParameterList *Params = TpDecl->getTemplateParameters();
10238       if (Params->size() == 1) {
10239         NonTypeTemplateParmDecl *PmDecl =
10240           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
10241 
10242         // The template parameter must be a char parameter pack.
10243         if (PmDecl && PmDecl->isTemplateParameterPack() &&
10244             Context.hasSameType(PmDecl->getType(), Context.CharTy))
10245           Valid = true;
10246       }
10247     }
10248   } else if (FnDecl->param_size()) {
10249     // Check the first parameter
10250     FunctionDecl::param_iterator Param = FnDecl->param_begin();
10251 
10252     QualType T = (*Param)->getType().getUnqualifiedType();
10253 
10254     // unsigned long long int, long double, and any character type are allowed
10255     // as the only parameters.
10256     if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10257         Context.hasSameType(T, Context.LongDoubleTy) ||
10258         Context.hasSameType(T, Context.CharTy) ||
10259         Context.hasSameType(T, Context.WCharTy) ||
10260         Context.hasSameType(T, Context.Char16Ty) ||
10261         Context.hasSameType(T, Context.Char32Ty)) {
10262       if (++Param == FnDecl->param_end())
10263         Valid = true;
10264       goto FinishedParams;
10265     }
10266 
10267     // Otherwise it must be a pointer to const; let's strip those qualifiers.
10268     const PointerType *PT = T->getAs<PointerType>();
10269     if (!PT)
10270       goto FinishedParams;
10271     T = PT->getPointeeType();
10272     if (!T.isConstQualified() || T.isVolatileQualified())
10273       goto FinishedParams;
10274     T = T.getUnqualifiedType();
10275 
10276     // Move on to the second parameter;
10277     ++Param;
10278 
10279     // If there is no second parameter, the first must be a const char *
10280     if (Param == FnDecl->param_end()) {
10281       if (Context.hasSameType(T, Context.CharTy))
10282         Valid = true;
10283       goto FinishedParams;
10284     }
10285 
10286     // const char *, const wchar_t*, const char16_t*, and const char32_t*
10287     // are allowed as the first parameter to a two-parameter function
10288     if (!(Context.hasSameType(T, Context.CharTy) ||
10289           Context.hasSameType(T, Context.WCharTy) ||
10290           Context.hasSameType(T, Context.Char16Ty) ||
10291           Context.hasSameType(T, Context.Char32Ty)))
10292       goto FinishedParams;
10293 
10294     // The second and final parameter must be an std::size_t
10295     T = (*Param)->getType().getUnqualifiedType();
10296     if (Context.hasSameType(T, Context.getSizeType()) &&
10297         ++Param == FnDecl->param_end())
10298       Valid = true;
10299   }
10300 
10301   // FIXME: This diagnostic is absolutely terrible.
10302 FinishedParams:
10303   if (!Valid) {
10304     Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10305       << FnDecl->getDeclName();
10306     return true;
10307   }
10308 
10309   // A parameter-declaration-clause containing a default argument is not
10310   // equivalent to any of the permitted forms.
10311   for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10312                                     ParamEnd = FnDecl->param_end();
10313        Param != ParamEnd; ++Param) {
10314     if ((*Param)->hasDefaultArg()) {
10315       Diag((*Param)->getDefaultArgRange().getBegin(),
10316            diag::err_literal_operator_default_argument)
10317         << (*Param)->getDefaultArgRange();
10318       break;
10319     }
10320   }
10321 
10322   StringRef LiteralName
10323     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10324   if (LiteralName[0] != '_') {
10325     // C++11 [usrlit.suffix]p1:
10326     //   Literal suffix identifiers that do not start with an underscore
10327     //   are reserved for future standardization.
10328     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
10329   }
10330 
10331   return false;
10332 }
10333 
10334 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10335 /// linkage specification, including the language and (if present)
10336 /// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10337 /// the location of the language string literal, which is provided
10338 /// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10339 /// the '{' brace. Otherwise, this linkage specification does not
10340 /// have any braces.
10341 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10342                                            SourceLocation LangLoc,
10343                                            StringRef Lang,
10344                                            SourceLocation LBraceLoc) {
10345   LinkageSpecDecl::LanguageIDs Language;
10346   if (Lang == "\"C\"")
10347     Language = LinkageSpecDecl::lang_c;
10348   else if (Lang == "\"C++\"")
10349     Language = LinkageSpecDecl::lang_cxx;
10350   else {
10351     Diag(LangLoc, diag::err_bad_language);
10352     return 0;
10353   }
10354 
10355   // FIXME: Add all the various semantics of linkage specifications
10356 
10357   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
10358                                                ExternLoc, LangLoc, Language);
10359   CurContext->addDecl(D);
10360   PushDeclContext(S, D);
10361   return D;
10362 }
10363 
10364 /// ActOnFinishLinkageSpecification - Complete the definition of
10365 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
10366 /// valid, it's the position of the closing '}' brace in a linkage
10367 /// specification that uses braces.
10368 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
10369                                             Decl *LinkageSpec,
10370                                             SourceLocation RBraceLoc) {
10371   if (LinkageSpec) {
10372     if (RBraceLoc.isValid()) {
10373       LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10374       LSDecl->setRBraceLoc(RBraceLoc);
10375     }
10376     PopDeclContext();
10377   }
10378   return LinkageSpec;
10379 }
10380 
10381 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10382                                   AttributeList *AttrList,
10383                                   SourceLocation SemiLoc) {
10384   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10385   // Attribute declarations appertain to empty declaration so we handle
10386   // them here.
10387   if (AttrList)
10388     ProcessDeclAttributeList(S, ED, AttrList);
10389 
10390   CurContext->addDecl(ED);
10391   return ED;
10392 }
10393 
10394 /// \brief Perform semantic analysis for the variable declaration that
10395 /// occurs within a C++ catch clause, returning the newly-created
10396 /// variable.
10397 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
10398                                          TypeSourceInfo *TInfo,
10399                                          SourceLocation StartLoc,
10400                                          SourceLocation Loc,
10401                                          IdentifierInfo *Name) {
10402   bool Invalid = false;
10403   QualType ExDeclType = TInfo->getType();
10404 
10405   // Arrays and functions decay.
10406   if (ExDeclType->isArrayType())
10407     ExDeclType = Context.getArrayDecayedType(ExDeclType);
10408   else if (ExDeclType->isFunctionType())
10409     ExDeclType = Context.getPointerType(ExDeclType);
10410 
10411   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10412   // The exception-declaration shall not denote a pointer or reference to an
10413   // incomplete type, other than [cv] void*.
10414   // N2844 forbids rvalue references.
10415   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
10416     Diag(Loc, diag::err_catch_rvalue_ref);
10417     Invalid = true;
10418   }
10419 
10420   QualType BaseType = ExDeclType;
10421   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
10422   unsigned DK = diag::err_catch_incomplete;
10423   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
10424     BaseType = Ptr->getPointeeType();
10425     Mode = 1;
10426     DK = diag::err_catch_incomplete_ptr;
10427   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
10428     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
10429     BaseType = Ref->getPointeeType();
10430     Mode = 2;
10431     DK = diag::err_catch_incomplete_ref;
10432   }
10433   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
10434       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
10435     Invalid = true;
10436 
10437   if (!Invalid && !ExDeclType->isDependentType() &&
10438       RequireNonAbstractType(Loc, ExDeclType,
10439                              diag::err_abstract_type_in_decl,
10440                              AbstractVariableType))
10441     Invalid = true;
10442 
10443   // Only the non-fragile NeXT runtime currently supports C++ catches
10444   // of ObjC types, and no runtime supports catching ObjC types by value.
10445   if (!Invalid && getLangOpts().ObjC1) {
10446     QualType T = ExDeclType;
10447     if (const ReferenceType *RT = T->getAs<ReferenceType>())
10448       T = RT->getPointeeType();
10449 
10450     if (T->isObjCObjectType()) {
10451       Diag(Loc, diag::err_objc_object_catch);
10452       Invalid = true;
10453     } else if (T->isObjCObjectPointerType()) {
10454       // FIXME: should this be a test for macosx-fragile specifically?
10455       if (getLangOpts().ObjCRuntime.isFragile())
10456         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
10457     }
10458   }
10459 
10460   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
10461                                     ExDeclType, TInfo, SC_None);
10462   ExDecl->setExceptionVariable(true);
10463 
10464   // In ARC, infer 'retaining' for variables of retainable type.
10465   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
10466     Invalid = true;
10467 
10468   if (!Invalid && !ExDeclType->isDependentType()) {
10469     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
10470       // Insulate this from anything else we might currently be parsing.
10471       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10472 
10473       // C++ [except.handle]p16:
10474       //   The object declared in an exception-declaration or, if the
10475       //   exception-declaration does not specify a name, a temporary (12.2) is
10476       //   copy-initialized (8.5) from the exception object. [...]
10477       //   The object is destroyed when the handler exits, after the destruction
10478       //   of any automatic objects initialized within the handler.
10479       //
10480       // We just pretend to initialize the object with itself, then make sure
10481       // it can be destroyed later.
10482       QualType initType = ExDeclType;
10483 
10484       InitializedEntity entity =
10485         InitializedEntity::InitializeVariable(ExDecl);
10486       InitializationKind initKind =
10487         InitializationKind::CreateCopy(Loc, SourceLocation());
10488 
10489       Expr *opaqueValue =
10490         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
10491       InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
10492       ExprResult result = sequence.Perform(*this, entity, initKind,
10493                                            MultiExprArg(&opaqueValue, 1));
10494       if (result.isInvalid())
10495         Invalid = true;
10496       else {
10497         // If the constructor used was non-trivial, set this as the
10498         // "initializer".
10499         CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10500         if (!construct->getConstructor()->isTrivial()) {
10501           Expr *init = MaybeCreateExprWithCleanups(construct);
10502           ExDecl->setInit(init);
10503         }
10504 
10505         // And make sure it's destructable.
10506         FinalizeVarWithDestructor(ExDecl, recordType);
10507       }
10508     }
10509   }
10510 
10511   if (Invalid)
10512     ExDecl->setInvalidDecl();
10513 
10514   return ExDecl;
10515 }
10516 
10517 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10518 /// handler.
10519 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
10520   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10521   bool Invalid = D.isInvalidType();
10522 
10523   // Check for unexpanded parameter packs.
10524   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10525                                       UPPC_ExceptionType)) {
10526     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10527                                              D.getIdentifierLoc());
10528     Invalid = true;
10529   }
10530 
10531   IdentifierInfo *II = D.getIdentifier();
10532   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
10533                                              LookupOrdinaryName,
10534                                              ForRedeclaration)) {
10535     // The scope should be freshly made just for us. There is just no way
10536     // it contains any previous declaration.
10537     assert(!S->isDeclScope(PrevDecl));
10538     if (PrevDecl->isTemplateParameter()) {
10539       // Maybe we will complain about the shadowed template parameter.
10540       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
10541       PrevDecl = 0;
10542     }
10543   }
10544 
10545   if (D.getCXXScopeSpec().isSet() && !Invalid) {
10546     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10547       << D.getCXXScopeSpec().getRange();
10548     Invalid = true;
10549   }
10550 
10551   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
10552                                               D.getLocStart(),
10553                                               D.getIdentifierLoc(),
10554                                               D.getIdentifier());
10555   if (Invalid)
10556     ExDecl->setInvalidDecl();
10557 
10558   // Add the exception declaration into this scope.
10559   if (II)
10560     PushOnScopeChains(ExDecl, S);
10561   else
10562     CurContext->addDecl(ExDecl);
10563 
10564   ProcessDeclAttributes(S, ExDecl, D);
10565   return ExDecl;
10566 }
10567 
10568 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10569                                          Expr *AssertExpr,
10570                                          Expr *AssertMessageExpr,
10571                                          SourceLocation RParenLoc) {
10572   StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
10573 
10574   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10575     return 0;
10576 
10577   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10578                                       AssertMessage, RParenLoc, false);
10579 }
10580 
10581 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10582                                          Expr *AssertExpr,
10583                                          StringLiteral *AssertMessage,
10584                                          SourceLocation RParenLoc,
10585                                          bool Failed) {
10586   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10587       !Failed) {
10588     // In a static_assert-declaration, the constant-expression shall be a
10589     // constant expression that can be contextually converted to bool.
10590     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10591     if (Converted.isInvalid())
10592       Failed = true;
10593 
10594     llvm::APSInt Cond;
10595     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
10596           diag::err_static_assert_expression_is_not_constant,
10597           /*AllowFold=*/false).isInvalid())
10598       Failed = true;
10599 
10600     if (!Failed && !Cond) {
10601       SmallString<256> MsgBuffer;
10602       llvm::raw_svector_ostream Msg(MsgBuffer);
10603       AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
10604       Diag(StaticAssertLoc, diag::err_static_assert_failed)
10605         << Msg.str() << AssertExpr->getSourceRange();
10606       Failed = true;
10607     }
10608   }
10609 
10610   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
10611                                         AssertExpr, AssertMessage, RParenLoc,
10612                                         Failed);
10613 
10614   CurContext->addDecl(Decl);
10615   return Decl;
10616 }
10617 
10618 /// \brief Perform semantic analysis of the given friend type declaration.
10619 ///
10620 /// \returns A friend declaration that.
10621 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
10622                                       SourceLocation FriendLoc,
10623                                       TypeSourceInfo *TSInfo) {
10624   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10625 
10626   QualType T = TSInfo->getType();
10627   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
10628 
10629   // C++03 [class.friend]p2:
10630   //   An elaborated-type-specifier shall be used in a friend declaration
10631   //   for a class.*
10632   //
10633   //   * The class-key of the elaborated-type-specifier is required.
10634   if (!ActiveTemplateInstantiations.empty()) {
10635     // Do not complain about the form of friend template types during
10636     // template instantiation; we will already have complained when the
10637     // template was declared.
10638   } else {
10639     if (!T->isElaboratedTypeSpecifier()) {
10640       // If we evaluated the type to a record type, suggest putting
10641       // a tag in front.
10642       if (const RecordType *RT = T->getAs<RecordType>()) {
10643         RecordDecl *RD = RT->getDecl();
10644 
10645         std::string InsertionText = std::string(" ") + RD->getKindName();
10646 
10647         Diag(TypeRange.getBegin(),
10648              getLangOpts().CPlusPlus11 ?
10649                diag::warn_cxx98_compat_unelaborated_friend_type :
10650                diag::ext_unelaborated_friend_type)
10651           << (unsigned) RD->getTagKind()
10652           << T
10653           << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10654                                         InsertionText);
10655       } else {
10656         Diag(FriendLoc,
10657              getLangOpts().CPlusPlus11 ?
10658                diag::warn_cxx98_compat_nonclass_type_friend :
10659                diag::ext_nonclass_type_friend)
10660           << T
10661           << TypeRange;
10662       }
10663     } else if (T->getAs<EnumType>()) {
10664       Diag(FriendLoc,
10665            getLangOpts().CPlusPlus11 ?
10666              diag::warn_cxx98_compat_enum_friend :
10667              diag::ext_enum_friend)
10668         << T
10669         << TypeRange;
10670     }
10671 
10672     // C++11 [class.friend]p3:
10673     //   A friend declaration that does not declare a function shall have one
10674     //   of the following forms:
10675     //     friend elaborated-type-specifier ;
10676     //     friend simple-type-specifier ;
10677     //     friend typename-specifier ;
10678     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
10679       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10680   }
10681 
10682   //   If the type specifier in a friend declaration designates a (possibly
10683   //   cv-qualified) class type, that class is declared as a friend; otherwise,
10684   //   the friend declaration is ignored.
10685   return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
10686 }
10687 
10688 /// Handle a friend tag declaration where the scope specifier was
10689 /// templated.
10690 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10691                                     unsigned TagSpec, SourceLocation TagLoc,
10692                                     CXXScopeSpec &SS,
10693                                     IdentifierInfo *Name,
10694                                     SourceLocation NameLoc,
10695                                     AttributeList *Attr,
10696                                     MultiTemplateParamsArg TempParamLists) {
10697   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10698 
10699   bool isExplicitSpecialization = false;
10700   bool Invalid = false;
10701 
10702   if (TemplateParameterList *TemplateParams
10703         = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
10704                                                   TempParamLists.data(),
10705                                                   TempParamLists.size(),
10706                                                   /*friend*/ true,
10707                                                   isExplicitSpecialization,
10708                                                   Invalid)) {
10709     if (TemplateParams->size() > 0) {
10710       // This is a declaration of a class template.
10711       if (Invalid)
10712         return 0;
10713 
10714       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10715                                 SS, Name, NameLoc, Attr,
10716                                 TemplateParams, AS_public,
10717                                 /*ModulePrivateLoc=*/SourceLocation(),
10718                                 TempParamLists.size() - 1,
10719                                 TempParamLists.data()).take();
10720     } else {
10721       // The "template<>" header is extraneous.
10722       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10723         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10724       isExplicitSpecialization = true;
10725     }
10726   }
10727 
10728   if (Invalid) return 0;
10729 
10730   bool isAllExplicitSpecializations = true;
10731   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
10732     if (TempParamLists[I]->size()) {
10733       isAllExplicitSpecializations = false;
10734       break;
10735     }
10736   }
10737 
10738   // FIXME: don't ignore attributes.
10739 
10740   // If it's explicit specializations all the way down, just forget
10741   // about the template header and build an appropriate non-templated
10742   // friend.  TODO: for source fidelity, remember the headers.
10743   if (isAllExplicitSpecializations) {
10744     if (SS.isEmpty()) {
10745       bool Owned = false;
10746       bool IsDependent = false;
10747       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10748                       Attr, AS_public,
10749                       /*ModulePrivateLoc=*/SourceLocation(),
10750                       MultiTemplateParamsArg(), Owned, IsDependent,
10751                       /*ScopedEnumKWLoc=*/SourceLocation(),
10752                       /*ScopedEnumUsesClassTag=*/false,
10753                       /*UnderlyingType=*/TypeResult());
10754     }
10755 
10756     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10757     ElaboratedTypeKeyword Keyword
10758       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10759     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
10760                                    *Name, NameLoc);
10761     if (T.isNull())
10762       return 0;
10763 
10764     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10765     if (isa<DependentNameType>(T)) {
10766       DependentNameTypeLoc TL =
10767           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
10768       TL.setElaboratedKeywordLoc(TagLoc);
10769       TL.setQualifierLoc(QualifierLoc);
10770       TL.setNameLoc(NameLoc);
10771     } else {
10772       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
10773       TL.setElaboratedKeywordLoc(TagLoc);
10774       TL.setQualifierLoc(QualifierLoc);
10775       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
10776     }
10777 
10778     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10779                                             TSI, FriendLoc, TempParamLists);
10780     Friend->setAccess(AS_public);
10781     CurContext->addDecl(Friend);
10782     return Friend;
10783   }
10784 
10785   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10786 
10787 
10788 
10789   // Handle the case of a templated-scope friend class.  e.g.
10790   //   template <class T> class A<T>::B;
10791   // FIXME: we don't support these right now.
10792   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10793   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10794   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10795   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
10796   TL.setElaboratedKeywordLoc(TagLoc);
10797   TL.setQualifierLoc(SS.getWithLocInContext(Context));
10798   TL.setNameLoc(NameLoc);
10799 
10800   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10801                                           TSI, FriendLoc, TempParamLists);
10802   Friend->setAccess(AS_public);
10803   Friend->setUnsupportedFriend(true);
10804   CurContext->addDecl(Friend);
10805   return Friend;
10806 }
10807 
10808 
10809 /// Handle a friend type declaration.  This works in tandem with
10810 /// ActOnTag.
10811 ///
10812 /// Notes on friend class templates:
10813 ///
10814 /// We generally treat friend class declarations as if they were
10815 /// declaring a class.  So, for example, the elaborated type specifier
10816 /// in a friend declaration is required to obey the restrictions of a
10817 /// class-head (i.e. no typedefs in the scope chain), template
10818 /// parameters are required to match up with simple template-ids, &c.
10819 /// However, unlike when declaring a template specialization, it's
10820 /// okay to refer to a template specialization without an empty
10821 /// template parameter declaration, e.g.
10822 ///   friend class A<T>::B<unsigned>;
10823 /// We permit this as a special case; if there are any template
10824 /// parameters present at all, require proper matching, i.e.
10825 ///   template <> template \<class T> friend class A<int>::B;
10826 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
10827                                 MultiTemplateParamsArg TempParams) {
10828   SourceLocation Loc = DS.getLocStart();
10829 
10830   assert(DS.isFriendSpecified());
10831   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10832 
10833   // Try to convert the decl specifier to a type.  This works for
10834   // friend templates because ActOnTag never produces a ClassTemplateDecl
10835   // for a TUK_Friend.
10836   Declarator TheDeclarator(DS, Declarator::MemberContext);
10837   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10838   QualType T = TSI->getType();
10839   if (TheDeclarator.isInvalidType())
10840     return 0;
10841 
10842   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10843     return 0;
10844 
10845   // This is definitely an error in C++98.  It's probably meant to
10846   // be forbidden in C++0x, too, but the specification is just
10847   // poorly written.
10848   //
10849   // The problem is with declarations like the following:
10850   //   template <T> friend A<T>::foo;
10851   // where deciding whether a class C is a friend or not now hinges
10852   // on whether there exists an instantiation of A that causes
10853   // 'foo' to equal C.  There are restrictions on class-heads
10854   // (which we declare (by fiat) elaborated friend declarations to
10855   // be) that makes this tractable.
10856   //
10857   // FIXME: handle "template <> friend class A<T>;", which
10858   // is possibly well-formed?  Who even knows?
10859   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
10860     Diag(Loc, diag::err_tagless_friend_type_template)
10861       << DS.getSourceRange();
10862     return 0;
10863   }
10864 
10865   // C++98 [class.friend]p1: A friend of a class is a function
10866   //   or class that is not a member of the class . . .
10867   // This is fixed in DR77, which just barely didn't make the C++03
10868   // deadline.  It's also a very silly restriction that seriously
10869   // affects inner classes and which nobody else seems to implement;
10870   // thus we never diagnose it, not even in -pedantic.
10871   //
10872   // But note that we could warn about it: it's always useless to
10873   // friend one of your own members (it's not, however, worthless to
10874   // friend a member of an arbitrary specialization of your template).
10875 
10876   Decl *D;
10877   if (unsigned NumTempParamLists = TempParams.size())
10878     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
10879                                    NumTempParamLists,
10880                                    TempParams.data(),
10881                                    TSI,
10882                                    DS.getFriendSpecLoc());
10883   else
10884     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
10885 
10886   if (!D)
10887     return 0;
10888 
10889   D->setAccess(AS_public);
10890   CurContext->addDecl(D);
10891 
10892   return D;
10893 }
10894 
10895 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
10896                                         MultiTemplateParamsArg TemplateParams) {
10897   const DeclSpec &DS = D.getDeclSpec();
10898 
10899   assert(DS.isFriendSpecified());
10900   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10901 
10902   SourceLocation Loc = D.getIdentifierLoc();
10903   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10904 
10905   // C++ [class.friend]p1
10906   //   A friend of a class is a function or class....
10907   // Note that this sees through typedefs, which is intended.
10908   // It *doesn't* see through dependent types, which is correct
10909   // according to [temp.arg.type]p3:
10910   //   If a declaration acquires a function type through a
10911   //   type dependent on a template-parameter and this causes
10912   //   a declaration that does not use the syntactic form of a
10913   //   function declarator to have a function type, the program
10914   //   is ill-formed.
10915   if (!TInfo->getType()->isFunctionType()) {
10916     Diag(Loc, diag::err_unexpected_friend);
10917 
10918     // It might be worthwhile to try to recover by creating an
10919     // appropriate declaration.
10920     return 0;
10921   }
10922 
10923   // C++ [namespace.memdef]p3
10924   //  - If a friend declaration in a non-local class first declares a
10925   //    class or function, the friend class or function is a member
10926   //    of the innermost enclosing namespace.
10927   //  - The name of the friend is not found by simple name lookup
10928   //    until a matching declaration is provided in that namespace
10929   //    scope (either before or after the class declaration granting
10930   //    friendship).
10931   //  - If a friend function is called, its name may be found by the
10932   //    name lookup that considers functions from namespaces and
10933   //    classes associated with the types of the function arguments.
10934   //  - When looking for a prior declaration of a class or a function
10935   //    declared as a friend, scopes outside the innermost enclosing
10936   //    namespace scope are not considered.
10937 
10938   CXXScopeSpec &SS = D.getCXXScopeSpec();
10939   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10940   DeclarationName Name = NameInfo.getName();
10941   assert(Name);
10942 
10943   // Check for unexpanded parameter packs.
10944   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10945       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10946       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10947     return 0;
10948 
10949   // The context we found the declaration in, or in which we should
10950   // create the declaration.
10951   DeclContext *DC;
10952   Scope *DCScope = S;
10953   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10954                         ForRedeclaration);
10955 
10956   // FIXME: there are different rules in local classes
10957 
10958   // There are four cases here.
10959   //   - There's no scope specifier, in which case we just go to the
10960   //     appropriate scope and look for a function or function template
10961   //     there as appropriate.
10962   // Recover from invalid scope qualifiers as if they just weren't there.
10963   if (SS.isInvalid() || !SS.isSet()) {
10964     // C++0x [namespace.memdef]p3:
10965     //   If the name in a friend declaration is neither qualified nor
10966     //   a template-id and the declaration is a function or an
10967     //   elaborated-type-specifier, the lookup to determine whether
10968     //   the entity has been previously declared shall not consider
10969     //   any scopes outside the innermost enclosing namespace.
10970     // C++0x [class.friend]p11:
10971     //   If a friend declaration appears in a local class and the name
10972     //   specified is an unqualified name, a prior declaration is
10973     //   looked up without considering scopes that are outside the
10974     //   innermost enclosing non-class scope. For a friend function
10975     //   declaration, if there is no prior declaration, the program is
10976     //   ill-formed.
10977     bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
10978     bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
10979 
10980     // Find the appropriate context according to the above.
10981     DC = CurContext;
10982     while (true) {
10983       // Skip class contexts.  If someone can cite chapter and verse
10984       // for this behavior, that would be nice --- it's what GCC and
10985       // EDG do, and it seems like a reasonable intent, but the spec
10986       // really only says that checks for unqualified existing
10987       // declarations should stop at the nearest enclosing namespace,
10988       // not that they should only consider the nearest enclosing
10989       // namespace.
10990       while (DC->isRecord() || DC->isTransparentContext())
10991         DC = DC->getParent();
10992 
10993       LookupQualifiedName(Previous, DC);
10994 
10995       // TODO: decide what we think about using declarations.
10996       if (isLocal || !Previous.empty())
10997         break;
10998 
10999       if (isTemplateId) {
11000         if (isa<TranslationUnitDecl>(DC)) break;
11001       } else {
11002         if (DC->isFileContext()) break;
11003       }
11004       DC = DC->getParent();
11005     }
11006 
11007     DCScope = getScopeForDeclContext(S, DC);
11008 
11009     // C++ [class.friend]p6:
11010     //   A function can be defined in a friend declaration of a class if and
11011     //   only if the class is a non-local class (9.8), the function name is
11012     //   unqualified, and the function has namespace scope.
11013     if (isLocal && D.isFunctionDefinition()) {
11014       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11015     }
11016 
11017   //   - There's a non-dependent scope specifier, in which case we
11018   //     compute it and do a previous lookup there for a function
11019   //     or function template.
11020   } else if (!SS.getScopeRep()->isDependent()) {
11021     DC = computeDeclContext(SS);
11022     if (!DC) return 0;
11023 
11024     if (RequireCompleteDeclContext(SS, DC)) return 0;
11025 
11026     LookupQualifiedName(Previous, DC);
11027 
11028     // Ignore things found implicitly in the wrong scope.
11029     // TODO: better diagnostics for this case.  Suggesting the right
11030     // qualified scope would be nice...
11031     LookupResult::Filter F = Previous.makeFilter();
11032     while (F.hasNext()) {
11033       NamedDecl *D = F.next();
11034       if (!DC->InEnclosingNamespaceSetOf(
11035               D->getDeclContext()->getRedeclContext()))
11036         F.erase();
11037     }
11038     F.done();
11039 
11040     if (Previous.empty()) {
11041       D.setInvalidType();
11042       Diag(Loc, diag::err_qualified_friend_not_found)
11043           << Name << TInfo->getType();
11044       return 0;
11045     }
11046 
11047     // C++ [class.friend]p1: A friend of a class is a function or
11048     //   class that is not a member of the class . . .
11049     if (DC->Equals(CurContext))
11050       Diag(DS.getFriendSpecLoc(),
11051            getLangOpts().CPlusPlus11 ?
11052              diag::warn_cxx98_compat_friend_is_member :
11053              diag::err_friend_is_member);
11054 
11055     if (D.isFunctionDefinition()) {
11056       // C++ [class.friend]p6:
11057       //   A function can be defined in a friend declaration of a class if and
11058       //   only if the class is a non-local class (9.8), the function name is
11059       //   unqualified, and the function has namespace scope.
11060       SemaDiagnosticBuilder DB
11061         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11062 
11063       DB << SS.getScopeRep();
11064       if (DC->isFileContext())
11065         DB << FixItHint::CreateRemoval(SS.getRange());
11066       SS.clear();
11067     }
11068 
11069   //   - There's a scope specifier that does not match any template
11070   //     parameter lists, in which case we use some arbitrary context,
11071   //     create a method or method template, and wait for instantiation.
11072   //   - There's a scope specifier that does match some template
11073   //     parameter lists, which we don't handle right now.
11074   } else {
11075     if (D.isFunctionDefinition()) {
11076       // C++ [class.friend]p6:
11077       //   A function can be defined in a friend declaration of a class if and
11078       //   only if the class is a non-local class (9.8), the function name is
11079       //   unqualified, and the function has namespace scope.
11080       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11081         << SS.getScopeRep();
11082     }
11083 
11084     DC = CurContext;
11085     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
11086   }
11087 
11088   if (!DC->isRecord()) {
11089     // This implies that it has to be an operator or function.
11090     if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11091         D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11092         D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
11093       Diag(Loc, diag::err_introducing_special_friend) <<
11094         (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11095          D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
11096       return 0;
11097     }
11098   }
11099 
11100   // FIXME: This is an egregious hack to cope with cases where the scope stack
11101   // does not contain the declaration context, i.e., in an out-of-line
11102   // definition of a class.
11103   Scope FakeDCScope(S, Scope::DeclScope, Diags);
11104   if (!DCScope) {
11105     FakeDCScope.setEntity(DC);
11106     DCScope = &FakeDCScope;
11107   }
11108 
11109   bool AddToScope = true;
11110   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
11111                                           TemplateParams, AddToScope);
11112   if (!ND) return 0;
11113 
11114   assert(ND->getDeclContext() == DC);
11115   assert(ND->getLexicalDeclContext() == CurContext);
11116 
11117   // Add the function declaration to the appropriate lookup tables,
11118   // adjusting the redeclarations list as necessary.  We don't
11119   // want to do this yet if the friending class is dependent.
11120   //
11121   // Also update the scope-based lookup if the target context's
11122   // lookup context is in lexical scope.
11123   if (!CurContext->isDependentContext()) {
11124     DC = DC->getRedeclContext();
11125     DC->makeDeclVisibleInContext(ND);
11126     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11127       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
11128   }
11129 
11130   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
11131                                        D.getIdentifierLoc(), ND,
11132                                        DS.getFriendSpecLoc());
11133   FrD->setAccess(AS_public);
11134   CurContext->addDecl(FrD);
11135 
11136   if (ND->isInvalidDecl()) {
11137     FrD->setInvalidDecl();
11138   } else {
11139     if (DC->isRecord()) CheckFriendAccess(ND);
11140 
11141     FunctionDecl *FD;
11142     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11143       FD = FTD->getTemplatedDecl();
11144     else
11145       FD = cast<FunctionDecl>(ND);
11146 
11147     // Mark templated-scope function declarations as unsupported.
11148     if (FD->getNumTemplateParameterLists())
11149       FrD->setUnsupportedFriend(true);
11150   }
11151 
11152   return ND;
11153 }
11154 
11155 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11156   AdjustDeclIfTemplate(Dcl);
11157 
11158   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
11159   if (!Fn) {
11160     Diag(DelLoc, diag::err_deleted_non_function);
11161     return;
11162   }
11163 
11164   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
11165     // Don't consider the implicit declaration we generate for explicit
11166     // specializations. FIXME: Do not generate these implicit declarations.
11167     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11168         || Prev->getPreviousDecl()) && !Prev->isDefined()) {
11169       Diag(DelLoc, diag::err_deleted_decl_not_first);
11170       Diag(Prev->getLocation(), diag::note_previous_declaration);
11171     }
11172     // If the declaration wasn't the first, we delete the function anyway for
11173     // recovery.
11174     Fn = Fn->getCanonicalDecl();
11175   }
11176 
11177   if (Fn->isDeleted())
11178     return;
11179 
11180   // See if we're deleting a function which is already known to override a
11181   // non-deleted virtual function.
11182   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11183     bool IssuedDiagnostic = false;
11184     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11185                                         E = MD->end_overridden_methods();
11186          I != E; ++I) {
11187       if (!(*MD->begin_overridden_methods())->isDeleted()) {
11188         if (!IssuedDiagnostic) {
11189           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11190           IssuedDiagnostic = true;
11191         }
11192         Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11193       }
11194     }
11195   }
11196 
11197   Fn->setDeletedAsWritten();
11198 }
11199 
11200 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
11201   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
11202 
11203   if (MD) {
11204     if (MD->getParent()->isDependentType()) {
11205       MD->setDefaulted();
11206       MD->setExplicitlyDefaulted();
11207       return;
11208     }
11209 
11210     CXXSpecialMember Member = getSpecialMember(MD);
11211     if (Member == CXXInvalid) {
11212       Diag(DefaultLoc, diag::err_default_special_members);
11213       return;
11214     }
11215 
11216     MD->setDefaulted();
11217     MD->setExplicitlyDefaulted();
11218 
11219     // If this definition appears within the record, do the checking when
11220     // the record is complete.
11221     const FunctionDecl *Primary = MD;
11222     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
11223       // Find the uninstantiated declaration that actually had the '= default'
11224       // on it.
11225       Pattern->isDefined(Primary);
11226 
11227     // If the method was defaulted on its first declaration, we will have
11228     // already performed the checking in CheckCompletedCXXClass. Such a
11229     // declaration doesn't trigger an implicit definition.
11230     if (Primary == Primary->getCanonicalDecl())
11231       return;
11232 
11233     CheckExplicitlyDefaultedSpecialMember(MD);
11234 
11235     // The exception specification is needed because we are defining the
11236     // function.
11237     ResolveExceptionSpec(DefaultLoc,
11238                          MD->getType()->castAs<FunctionProtoType>());
11239 
11240     switch (Member) {
11241     case CXXDefaultConstructor: {
11242       CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
11243       if (!CD->isInvalidDecl())
11244         DefineImplicitDefaultConstructor(DefaultLoc, CD);
11245       break;
11246     }
11247 
11248     case CXXCopyConstructor: {
11249       CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
11250       if (!CD->isInvalidDecl())
11251         DefineImplicitCopyConstructor(DefaultLoc, CD);
11252       break;
11253     }
11254 
11255     case CXXCopyAssignment: {
11256       if (!MD->isInvalidDecl())
11257         DefineImplicitCopyAssignment(DefaultLoc, MD);
11258       break;
11259     }
11260 
11261     case CXXDestructor: {
11262       CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
11263       if (!DD->isInvalidDecl())
11264         DefineImplicitDestructor(DefaultLoc, DD);
11265       break;
11266     }
11267 
11268     case CXXMoveConstructor: {
11269       CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
11270       if (!CD->isInvalidDecl())
11271         DefineImplicitMoveConstructor(DefaultLoc, CD);
11272       break;
11273     }
11274 
11275     case CXXMoveAssignment: {
11276       if (!MD->isInvalidDecl())
11277         DefineImplicitMoveAssignment(DefaultLoc, MD);
11278       break;
11279     }
11280 
11281     case CXXInvalid:
11282       llvm_unreachable("Invalid special member.");
11283     }
11284   } else {
11285     Diag(DefaultLoc, diag::err_default_special_members);
11286   }
11287 }
11288 
11289 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
11290   for (Stmt::child_range CI = S->children(); CI; ++CI) {
11291     Stmt *SubStmt = *CI;
11292     if (!SubStmt)
11293       continue;
11294     if (isa<ReturnStmt>(SubStmt))
11295       Self.Diag(SubStmt->getLocStart(),
11296            diag::err_return_in_constructor_handler);
11297     if (!isa<Expr>(SubStmt))
11298       SearchForReturnInStmt(Self, SubStmt);
11299   }
11300 }
11301 
11302 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11303   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11304     CXXCatchStmt *Handler = TryBlock->getHandler(I);
11305     SearchForReturnInStmt(*this, Handler);
11306   }
11307 }
11308 
11309 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
11310                                              const CXXMethodDecl *Old) {
11311   const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11312   const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11313 
11314   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11315 
11316   // If the calling conventions match, everything is fine
11317   if (NewCC == OldCC)
11318     return false;
11319 
11320   // If either of the calling conventions are set to "default", we need to pick
11321   // something more sensible based on the target. This supports code where the
11322   // one method explicitly sets thiscall, and another has no explicit calling
11323   // convention.
11324   CallingConv Default =
11325     Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
11326   if (NewCC == CC_Default)
11327     NewCC = Default;
11328   if (OldCC == CC_Default)
11329     OldCC = Default;
11330 
11331   // If the calling conventions still don't match, then report the error
11332   if (NewCC != OldCC) {
11333     Diag(New->getLocation(),
11334          diag::err_conflicting_overriding_cc_attributes)
11335       << New->getDeclName() << New->getType() << Old->getType();
11336     Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11337     return true;
11338   }
11339 
11340   return false;
11341 }
11342 
11343 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
11344                                              const CXXMethodDecl *Old) {
11345   QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11346   QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
11347 
11348   if (Context.hasSameType(NewTy, OldTy) ||
11349       NewTy->isDependentType() || OldTy->isDependentType())
11350     return false;
11351 
11352   // Check if the return types are covariant
11353   QualType NewClassTy, OldClassTy;
11354 
11355   /// Both types must be pointers or references to classes.
11356   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11357     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
11358       NewClassTy = NewPT->getPointeeType();
11359       OldClassTy = OldPT->getPointeeType();
11360     }
11361   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11362     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11363       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11364         NewClassTy = NewRT->getPointeeType();
11365         OldClassTy = OldRT->getPointeeType();
11366       }
11367     }
11368   }
11369 
11370   // The return types aren't either both pointers or references to a class type.
11371   if (NewClassTy.isNull()) {
11372     Diag(New->getLocation(),
11373          diag::err_different_return_type_for_overriding_virtual_function)
11374       << New->getDeclName() << NewTy << OldTy;
11375     Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11376 
11377     return true;
11378   }
11379 
11380   // C++ [class.virtual]p6:
11381   //   If the return type of D::f differs from the return type of B::f, the
11382   //   class type in the return type of D::f shall be complete at the point of
11383   //   declaration of D::f or shall be the class type D.
11384   if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11385     if (!RT->isBeingDefined() &&
11386         RequireCompleteType(New->getLocation(), NewClassTy,
11387                             diag::err_covariant_return_incomplete,
11388                             New->getDeclName()))
11389     return true;
11390   }
11391 
11392   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
11393     // Check if the new class derives from the old class.
11394     if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11395       Diag(New->getLocation(),
11396            diag::err_covariant_return_not_derived)
11397       << New->getDeclName() << NewTy << OldTy;
11398       Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11399       return true;
11400     }
11401 
11402     // Check if we the conversion from derived to base is valid.
11403     if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
11404                     diag::err_covariant_return_inaccessible_base,
11405                     diag::err_covariant_return_ambiguous_derived_to_base_conv,
11406                     // FIXME: Should this point to the return type?
11407                     New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
11408       // FIXME: this note won't trigger for delayed access control
11409       // diagnostics, and it's impossible to get an undelayed error
11410       // here from access control during the original parse because
11411       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
11412       Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11413       return true;
11414     }
11415   }
11416 
11417   // The qualifiers of the return types must be the same.
11418   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
11419     Diag(New->getLocation(),
11420          diag::err_covariant_return_type_different_qualifications)
11421     << New->getDeclName() << NewTy << OldTy;
11422     Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11423     return true;
11424   };
11425 
11426 
11427   // The new class type must have the same or less qualifiers as the old type.
11428   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11429     Diag(New->getLocation(),
11430          diag::err_covariant_return_type_class_type_more_qualified)
11431     << New->getDeclName() << NewTy << OldTy;
11432     Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11433     return true;
11434   };
11435 
11436   return false;
11437 }
11438 
11439 /// \brief Mark the given method pure.
11440 ///
11441 /// \param Method the method to be marked pure.
11442 ///
11443 /// \param InitRange the source range that covers the "0" initializer.
11444 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
11445   SourceLocation EndLoc = InitRange.getEnd();
11446   if (EndLoc.isValid())
11447     Method->setRangeEnd(EndLoc);
11448 
11449   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11450     Method->setPure();
11451     return false;
11452   }
11453 
11454   if (!Method->isInvalidDecl())
11455     Diag(Method->getLocation(), diag::err_non_virtual_pure)
11456       << Method->getDeclName() << InitRange;
11457   return true;
11458 }
11459 
11460 /// \brief Determine whether the given declaration is a static data member.
11461 static bool isStaticDataMember(Decl *D) {
11462   VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11463   if (!Var)
11464     return false;
11465 
11466   return Var->isStaticDataMember();
11467 }
11468 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11469 /// an initializer for the out-of-line declaration 'Dcl'.  The scope
11470 /// is a fresh scope pushed for just this purpose.
11471 ///
11472 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11473 /// static data member of class X, names should be looked up in the scope of
11474 /// class X.
11475 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
11476   // If there is no declaration, there was an error parsing it.
11477   if (D == 0 || D->isInvalidDecl()) return;
11478 
11479   // We should only get called for declarations with scope specifiers, like:
11480   //   int foo::bar;
11481   assert(D->isOutOfLine());
11482   EnterDeclaratorContext(S, D->getDeclContext());
11483 
11484   // If we are parsing the initializer for a static data member, push a
11485   // new expression evaluation context that is associated with this static
11486   // data member.
11487   if (isStaticDataMember(D))
11488     PushExpressionEvaluationContext(PotentiallyEvaluated, D);
11489 }
11490 
11491 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
11492 /// initializer for the out-of-line declaration 'D'.
11493 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
11494   // If there is no declaration, there was an error parsing it.
11495   if (D == 0 || D->isInvalidDecl()) return;
11496 
11497   if (isStaticDataMember(D))
11498     PopExpressionEvaluationContext();
11499 
11500   assert(D->isOutOfLine());
11501   ExitDeclaratorContext(S);
11502 }
11503 
11504 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11505 /// C++ if/switch/while/for statement.
11506 /// e.g: "if (int x = f()) {...}"
11507 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
11508   // C++ 6.4p2:
11509   // The declarator shall not specify a function or an array.
11510   // The type-specifier-seq shall not contain typedef and shall not declare a
11511   // new class or enumeration.
11512   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11513          "Parser allowed 'typedef' as storage class of condition decl.");
11514 
11515   Decl *Dcl = ActOnDeclarator(S, D);
11516   if (!Dcl)
11517     return true;
11518 
11519   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11520     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
11521       << D.getSourceRange();
11522     return true;
11523   }
11524 
11525   return Dcl;
11526 }
11527 
11528 void Sema::LoadExternalVTableUses() {
11529   if (!ExternalSource)
11530     return;
11531 
11532   SmallVector<ExternalVTableUse, 4> VTables;
11533   ExternalSource->ReadUsedVTables(VTables);
11534   SmallVector<VTableUse, 4> NewUses;
11535   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11536     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11537       = VTablesUsed.find(VTables[I].Record);
11538     // Even if a definition wasn't required before, it may be required now.
11539     if (Pos != VTablesUsed.end()) {
11540       if (!Pos->second && VTables[I].DefinitionRequired)
11541         Pos->second = true;
11542       continue;
11543     }
11544 
11545     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11546     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11547   }
11548 
11549   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11550 }
11551 
11552 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11553                           bool DefinitionRequired) {
11554   // Ignore any vtable uses in unevaluated operands or for classes that do
11555   // not have a vtable.
11556   if (!Class->isDynamicClass() || Class->isDependentContext() ||
11557       CurContext->isDependentContext() ||
11558       ExprEvalContexts.back().Context == Unevaluated)
11559     return;
11560 
11561   // Try to insert this class into the map.
11562   LoadExternalVTableUses();
11563   Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11564   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11565     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11566   if (!Pos.second) {
11567     // If we already had an entry, check to see if we are promoting this vtable
11568     // to required a definition. If so, we need to reappend to the VTableUses
11569     // list, since we may have already processed the first entry.
11570     if (DefinitionRequired && !Pos.first->second) {
11571       Pos.first->second = true;
11572     } else {
11573       // Otherwise, we can early exit.
11574       return;
11575     }
11576   }
11577 
11578   // Local classes need to have their virtual members marked
11579   // immediately. For all other classes, we mark their virtual members
11580   // at the end of the translation unit.
11581   if (Class->isLocalClass())
11582     MarkVirtualMembersReferenced(Loc, Class);
11583   else
11584     VTableUses.push_back(std::make_pair(Class, Loc));
11585 }
11586 
11587 bool Sema::DefineUsedVTables() {
11588   LoadExternalVTableUses();
11589   if (VTableUses.empty())
11590     return false;
11591 
11592   // Note: The VTableUses vector could grow as a result of marking
11593   // the members of a class as "used", so we check the size each
11594   // time through the loop and prefer indices (which are stable) to
11595   // iterators (which are not).
11596   bool DefinedAnything = false;
11597   for (unsigned I = 0; I != VTableUses.size(); ++I) {
11598     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
11599     if (!Class)
11600       continue;
11601 
11602     SourceLocation Loc = VTableUses[I].second;
11603 
11604     bool DefineVTable = true;
11605 
11606     // If this class has a key function, but that key function is
11607     // defined in another translation unit, we don't need to emit the
11608     // vtable even though we're using it.
11609     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
11610     if (KeyFunction && !KeyFunction->hasBody()) {
11611       switch (KeyFunction->getTemplateSpecializationKind()) {
11612       case TSK_Undeclared:
11613       case TSK_ExplicitSpecialization:
11614       case TSK_ExplicitInstantiationDeclaration:
11615         // The key function is in another translation unit.
11616         DefineVTable = false;
11617         break;
11618 
11619       case TSK_ExplicitInstantiationDefinition:
11620       case TSK_ImplicitInstantiation:
11621         // We will be instantiating the key function.
11622         break;
11623       }
11624     } else if (!KeyFunction) {
11625       // If we have a class with no key function that is the subject
11626       // of an explicit instantiation declaration, suppress the
11627       // vtable; it will live with the explicit instantiation
11628       // definition.
11629       bool IsExplicitInstantiationDeclaration
11630         = Class->getTemplateSpecializationKind()
11631                                       == TSK_ExplicitInstantiationDeclaration;
11632       for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11633                                  REnd = Class->redecls_end();
11634            R != REnd; ++R) {
11635         TemplateSpecializationKind TSK
11636           = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11637         if (TSK == TSK_ExplicitInstantiationDeclaration)
11638           IsExplicitInstantiationDeclaration = true;
11639         else if (TSK == TSK_ExplicitInstantiationDefinition) {
11640           IsExplicitInstantiationDeclaration = false;
11641           break;
11642         }
11643       }
11644 
11645       if (IsExplicitInstantiationDeclaration)
11646         DefineVTable = false;
11647     }
11648 
11649     // The exception specifications for all virtual members may be needed even
11650     // if we are not providing an authoritative form of the vtable in this TU.
11651     // We may choose to emit it available_externally anyway.
11652     if (!DefineVTable) {
11653       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11654       continue;
11655     }
11656 
11657     // Mark all of the virtual members of this class as referenced, so
11658     // that we can build a vtable. Then, tell the AST consumer that a
11659     // vtable for this class is required.
11660     DefinedAnything = true;
11661     MarkVirtualMembersReferenced(Loc, Class);
11662     CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11663     Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11664 
11665     // Optionally warn if we're emitting a weak vtable.
11666     if (Class->hasExternalLinkage() &&
11667         Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
11668       const FunctionDecl *KeyFunctionDef = 0;
11669       if (!KeyFunction ||
11670           (KeyFunction->hasBody(KeyFunctionDef) &&
11671            KeyFunctionDef->isInlined()))
11672         Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11673              TSK_ExplicitInstantiationDefinition
11674              ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11675           << Class;
11676     }
11677   }
11678   VTableUses.clear();
11679 
11680   return DefinedAnything;
11681 }
11682 
11683 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
11684                                                  const CXXRecordDecl *RD) {
11685   for (CXXRecordDecl::method_iterator I = RD->method_begin(),
11686                                       E = RD->method_end(); I != E; ++I)
11687     if ((*I)->isVirtual() && !(*I)->isPure())
11688       ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
11689 }
11690 
11691 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
11692                                         const CXXRecordDecl *RD) {
11693   // Mark all functions which will appear in RD's vtable as used.
11694   CXXFinalOverriderMap FinalOverriders;
11695   RD->getFinalOverriders(FinalOverriders);
11696   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
11697                                             E = FinalOverriders.end();
11698        I != E; ++I) {
11699     for (OverridingMethods::const_iterator OI = I->second.begin(),
11700                                            OE = I->second.end();
11701          OI != OE; ++OI) {
11702       assert(OI->second.size() > 0 && "no final overrider");
11703       CXXMethodDecl *Overrider = OI->second.front().Method;
11704 
11705       // C++ [basic.def.odr]p2:
11706       //   [...] A virtual member function is used if it is not pure. [...]
11707       if (!Overrider->isPure())
11708         MarkFunctionReferenced(Loc, Overrider);
11709     }
11710   }
11711 
11712   // Only classes that have virtual bases need a VTT.
11713   if (RD->getNumVBases() == 0)
11714     return;
11715 
11716   for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11717            e = RD->bases_end(); i != e; ++i) {
11718     const CXXRecordDecl *Base =
11719         cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
11720     if (Base->getNumVBases() == 0)
11721       continue;
11722     MarkVirtualMembersReferenced(Loc, Base);
11723   }
11724 }
11725 
11726 /// SetIvarInitializers - This routine builds initialization ASTs for the
11727 /// Objective-C implementation whose ivars need be initialized.
11728 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
11729   if (!getLangOpts().CPlusPlus)
11730     return;
11731   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
11732     SmallVector<ObjCIvarDecl*, 8> ivars;
11733     CollectIvarsToConstructOrDestruct(OID, ivars);
11734     if (ivars.empty())
11735       return;
11736     SmallVector<CXXCtorInitializer*, 32> AllToInit;
11737     for (unsigned i = 0; i < ivars.size(); i++) {
11738       FieldDecl *Field = ivars[i];
11739       if (Field->isInvalidDecl())
11740         continue;
11741 
11742       CXXCtorInitializer *Member;
11743       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
11744       InitializationKind InitKind =
11745         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
11746 
11747       InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
11748       ExprResult MemberInit =
11749         InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
11750       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
11751       // Note, MemberInit could actually come back empty if no initialization
11752       // is required (e.g., because it would call a trivial default constructor)
11753       if (!MemberInit.get() || MemberInit.isInvalid())
11754         continue;
11755 
11756       Member =
11757         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
11758                                          SourceLocation(),
11759                                          MemberInit.takeAs<Expr>(),
11760                                          SourceLocation());
11761       AllToInit.push_back(Member);
11762 
11763       // Be sure that the destructor is accessible and is marked as referenced.
11764       if (const RecordType *RecordTy
11765                   = Context.getBaseElementType(Field->getType())
11766                                                         ->getAs<RecordType>()) {
11767                     CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
11768         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
11769           MarkFunctionReferenced(Field->getLocation(), Destructor);
11770           CheckDestructorAccess(Field->getLocation(), Destructor,
11771                             PDiag(diag::err_access_dtor_ivar)
11772                               << Context.getBaseElementType(Field->getType()));
11773         }
11774       }
11775     }
11776     ObjCImplementation->setIvarInitializers(Context,
11777                                             AllToInit.data(), AllToInit.size());
11778   }
11779 }
11780 
11781 static
11782 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11783                            llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11784                            llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11785                            llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11786                            Sema &S) {
11787   llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11788                                                    CE = Current.end();
11789   if (Ctor->isInvalidDecl())
11790     return;
11791 
11792   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
11793 
11794   // Target may not be determinable yet, for instance if this is a dependent
11795   // call in an uninstantiated template.
11796   if (Target) {
11797     const FunctionDecl *FNTarget = 0;
11798     (void)Target->hasBody(FNTarget);
11799     Target = const_cast<CXXConstructorDecl*>(
11800       cast_or_null<CXXConstructorDecl>(FNTarget));
11801   }
11802 
11803   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11804                      // Avoid dereferencing a null pointer here.
11805                      *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11806 
11807   if (!Current.insert(Canonical))
11808     return;
11809 
11810   // We know that beyond here, we aren't chaining into a cycle.
11811   if (!Target || !Target->isDelegatingConstructor() ||
11812       Target->isInvalidDecl() || Valid.count(TCanonical)) {
11813     for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11814       Valid.insert(*CI);
11815     Current.clear();
11816   // We've hit a cycle.
11817   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11818              Current.count(TCanonical)) {
11819     // If we haven't diagnosed this cycle yet, do so now.
11820     if (!Invalid.count(TCanonical)) {
11821       S.Diag((*Ctor->init_begin())->getSourceLocation(),
11822              diag::warn_delegating_ctor_cycle)
11823         << Ctor;
11824 
11825       // Don't add a note for a function delegating directly to itself.
11826       if (TCanonical != Canonical)
11827         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11828 
11829       CXXConstructorDecl *C = Target;
11830       while (C->getCanonicalDecl() != Canonical) {
11831         const FunctionDecl *FNTarget = 0;
11832         (void)C->getTargetConstructor()->hasBody(FNTarget);
11833         assert(FNTarget && "Ctor cycle through bodiless function");
11834 
11835         C = const_cast<CXXConstructorDecl*>(
11836           cast<CXXConstructorDecl>(FNTarget));
11837         S.Diag(C->getLocation(), diag::note_which_delegates_to);
11838       }
11839     }
11840 
11841     for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11842       Invalid.insert(*CI);
11843     Current.clear();
11844   } else {
11845     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11846   }
11847 }
11848 
11849 
11850 void Sema::CheckDelegatingCtorCycles() {
11851   llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11852 
11853   llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11854                                                    CE = Current.end();
11855 
11856   for (DelegatingCtorDeclsType::iterator
11857          I = DelegatingCtorDecls.begin(ExternalSource),
11858          E = DelegatingCtorDecls.end();
11859        I != E; ++I)
11860     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
11861 
11862   for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11863     (*CI)->setInvalidDecl();
11864 }
11865 
11866 namespace {
11867   /// \brief AST visitor that finds references to the 'this' expression.
11868   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
11869     Sema &S;
11870 
11871   public:
11872     explicit FindCXXThisExpr(Sema &S) : S(S) { }
11873 
11874     bool VisitCXXThisExpr(CXXThisExpr *E) {
11875       S.Diag(E->getLocation(), diag::err_this_static_member_func)
11876         << E->isImplicit();
11877       return false;
11878     }
11879   };
11880 }
11881 
11882 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
11883   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11884   if (!TSInfo)
11885     return false;
11886 
11887   TypeLoc TL = TSInfo->getTypeLoc();
11888   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
11889   if (!ProtoTL)
11890     return false;
11891 
11892   // C++11 [expr.prim.general]p3:
11893   //   [The expression this] shall not appear before the optional
11894   //   cv-qualifier-seq and it shall not appear within the declaration of a
11895   //   static member function (although its type and value category are defined
11896   //   within a static member function as they are within a non-static member
11897   //   function). [ Note: this is because declaration matching does not occur
11898   //  until the complete declarator is known. - end note ]
11899   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
11900   FindCXXThisExpr Finder(*this);
11901 
11902   // If the return type came after the cv-qualifier-seq, check it now.
11903   if (Proto->hasTrailingReturn() &&
11904       !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
11905     return true;
11906 
11907   // Check the exception specification.
11908   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
11909     return true;
11910 
11911   return checkThisInStaticMemberFunctionAttributes(Method);
11912 }
11913 
11914 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
11915   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11916   if (!TSInfo)
11917     return false;
11918 
11919   TypeLoc TL = TSInfo->getTypeLoc();
11920   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
11921   if (!ProtoTL)
11922     return false;
11923 
11924   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
11925   FindCXXThisExpr Finder(*this);
11926 
11927   switch (Proto->getExceptionSpecType()) {
11928   case EST_Uninstantiated:
11929   case EST_Unevaluated:
11930   case EST_BasicNoexcept:
11931   case EST_DynamicNone:
11932   case EST_MSAny:
11933   case EST_None:
11934     break;
11935 
11936   case EST_ComputedNoexcept:
11937     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
11938       return true;
11939 
11940   case EST_Dynamic:
11941     for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
11942          EEnd = Proto->exception_end();
11943          E != EEnd; ++E) {
11944       if (!Finder.TraverseType(*E))
11945         return true;
11946     }
11947     break;
11948   }
11949 
11950   return false;
11951 }
11952 
11953 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
11954   FindCXXThisExpr Finder(*this);
11955 
11956   // Check attributes.
11957   for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
11958        A != AEnd; ++A) {
11959     // FIXME: This should be emitted by tblgen.
11960     Expr *Arg = 0;
11961     ArrayRef<Expr *> Args;
11962     if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
11963       Arg = G->getArg();
11964     else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
11965       Arg = G->getArg();
11966     else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
11967       Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
11968     else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
11969       Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
11970     else if (ExclusiveLockFunctionAttr *ELF
11971                = dyn_cast<ExclusiveLockFunctionAttr>(*A))
11972       Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
11973     else if (SharedLockFunctionAttr *SLF
11974                = dyn_cast<SharedLockFunctionAttr>(*A))
11975       Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
11976     else if (ExclusiveTrylockFunctionAttr *ETLF
11977                = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
11978       Arg = ETLF->getSuccessValue();
11979       Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
11980     } else if (SharedTrylockFunctionAttr *STLF
11981                  = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
11982       Arg = STLF->getSuccessValue();
11983       Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
11984     } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
11985       Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
11986     else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
11987       Arg = LR->getArg();
11988     else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
11989       Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
11990     else if (ExclusiveLocksRequiredAttr *ELR
11991                = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
11992       Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
11993     else if (SharedLocksRequiredAttr *SLR
11994                = dyn_cast<SharedLocksRequiredAttr>(*A))
11995       Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
11996 
11997     if (Arg && !Finder.TraverseStmt(Arg))
11998       return true;
11999 
12000     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12001       if (!Finder.TraverseStmt(Args[I]))
12002         return true;
12003     }
12004   }
12005 
12006   return false;
12007 }
12008 
12009 void
12010 Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12011                                   ArrayRef<ParsedType> DynamicExceptions,
12012                                   ArrayRef<SourceRange> DynamicExceptionRanges,
12013                                   Expr *NoexceptExpr,
12014                                   SmallVectorImpl<QualType> &Exceptions,
12015                                   FunctionProtoType::ExtProtoInfo &EPI) {
12016   Exceptions.clear();
12017   EPI.ExceptionSpecType = EST;
12018   if (EST == EST_Dynamic) {
12019     Exceptions.reserve(DynamicExceptions.size());
12020     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12021       // FIXME: Preserve type source info.
12022       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12023 
12024       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12025       collectUnexpandedParameterPacks(ET, Unexpanded);
12026       if (!Unexpanded.empty()) {
12027         DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12028                                          UPPC_ExceptionType,
12029                                          Unexpanded);
12030         continue;
12031       }
12032 
12033       // Check that the type is valid for an exception spec, and
12034       // drop it if not.
12035       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12036         Exceptions.push_back(ET);
12037     }
12038     EPI.NumExceptions = Exceptions.size();
12039     EPI.Exceptions = Exceptions.data();
12040     return;
12041   }
12042 
12043   if (EST == EST_ComputedNoexcept) {
12044     // If an error occurred, there's no expression here.
12045     if (NoexceptExpr) {
12046       assert((NoexceptExpr->isTypeDependent() ||
12047               NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12048               Context.BoolTy) &&
12049              "Parser should have made sure that the expression is boolean");
12050       if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12051         EPI.ExceptionSpecType = EST_BasicNoexcept;
12052         return;
12053       }
12054 
12055       if (!NoexceptExpr->isValueDependent())
12056         NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
12057                          diag::err_noexcept_needs_constant_expression,
12058                          /*AllowFold*/ false).take();
12059       EPI.NoexceptExpr = NoexceptExpr;
12060     }
12061     return;
12062   }
12063 }
12064 
12065 /// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12066 Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12067   // Implicitly declared functions (e.g. copy constructors) are
12068   // __host__ __device__
12069   if (D->isImplicit())
12070     return CFT_HostDevice;
12071 
12072   if (D->hasAttr<CUDAGlobalAttr>())
12073     return CFT_Global;
12074 
12075   if (D->hasAttr<CUDADeviceAttr>()) {
12076     if (D->hasAttr<CUDAHostAttr>())
12077       return CFT_HostDevice;
12078     else
12079       return CFT_Device;
12080   }
12081 
12082   return CFT_Host;
12083 }
12084 
12085 bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12086                            CUDAFunctionTarget CalleeTarget) {
12087   // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12088   // Callable from the device only."
12089   if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12090     return true;
12091 
12092   // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12093   // Callable from the host only."
12094   // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12095   // Callable from the host only."
12096   if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12097       (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12098     return true;
12099 
12100   if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12101     return true;
12102 
12103   return false;
12104 }
12105 
12106 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12107 ///
12108 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12109                                        SourceLocation DeclStart,
12110                                        Declarator &D, Expr *BitWidth,
12111                                        InClassInitStyle InitStyle,
12112                                        AccessSpecifier AS,
12113                                        AttributeList *MSPropertyAttr) {
12114   IdentifierInfo *II = D.getIdentifier();
12115   if (!II) {
12116     Diag(DeclStart, diag::err_anonymous_property);
12117     return NULL;
12118   }
12119   SourceLocation Loc = D.getIdentifierLoc();
12120 
12121   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12122   QualType T = TInfo->getType();
12123   if (getLangOpts().CPlusPlus) {
12124     CheckExtraCXXDefaultArguments(D);
12125 
12126     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12127                                         UPPC_DataMemberType)) {
12128       D.setInvalidType();
12129       T = Context.IntTy;
12130       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12131     }
12132   }
12133 
12134   DiagnoseFunctionSpecifiers(D.getDeclSpec());
12135 
12136   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12137     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12138          diag::err_invalid_thread)
12139       << DeclSpec::getSpecifierName(TSCS);
12140 
12141   // Check to see if this name was declared as a member previously
12142   NamedDecl *PrevDecl = 0;
12143   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12144   LookupName(Previous, S);
12145   switch (Previous.getResultKind()) {
12146   case LookupResult::Found:
12147   case LookupResult::FoundUnresolvedValue:
12148     PrevDecl = Previous.getAsSingle<NamedDecl>();
12149     break;
12150 
12151   case LookupResult::FoundOverloaded:
12152     PrevDecl = Previous.getRepresentativeDecl();
12153     break;
12154 
12155   case LookupResult::NotFound:
12156   case LookupResult::NotFoundInCurrentInstantiation:
12157   case LookupResult::Ambiguous:
12158     break;
12159   }
12160 
12161   if (PrevDecl && PrevDecl->isTemplateParameter()) {
12162     // Maybe we will complain about the shadowed template parameter.
12163     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12164     // Just pretend that we didn't see the previous declaration.
12165     PrevDecl = 0;
12166   }
12167 
12168   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12169     PrevDecl = 0;
12170 
12171   SourceLocation TSSL = D.getLocStart();
12172   MSPropertyDecl *NewPD;
12173   const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12174   NewPD = new (Context) MSPropertyDecl(Record, Loc,
12175                                        II, T, TInfo, TSSL,
12176                                        Data.GetterId, Data.SetterId);
12177   ProcessDeclAttributes(TUScope, NewPD, D);
12178   NewPD->setAccess(AS);
12179 
12180   if (NewPD->isInvalidDecl())
12181     Record->setInvalidDecl();
12182 
12183   if (D.getDeclSpec().isModulePrivateSpecified())
12184     NewPD->setModulePrivate();
12185 
12186   if (NewPD->isInvalidDecl() && PrevDecl) {
12187     // Don't introduce NewFD into scope; there's already something
12188     // with the same name in the same scope.
12189   } else if (II) {
12190     PushOnScopeChains(NewPD, S);
12191   } else
12192     Record->addDecl(NewPD);
12193 
12194   return NewPD;
12195 }
12196