SemaDeclCXX.cpp revision ff331c15729f7d4439d253c97f4d60f2a7ffd0c6
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 "Sema.h"
15#include "SemaInit.h"
16#include "Lookup.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/CharUnits.h"
20#include "clang/AST/CXXInheritance.h"
21#include "clang/AST/DeclVisitor.h"
22#include "clang/AST/RecordLayout.h"
23#include "clang/AST/StmtVisitor.h"
24#include "clang/AST/TypeLoc.h"
25#include "clang/AST/TypeOrdering.h"
26#include "clang/Parse/DeclSpec.h"
27#include "clang/Parse/Template.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "clang/Lex/Preprocessor.h"
30#include "llvm/ADT/STLExtras.h"
31#include <map>
32#include <set>
33
34using namespace clang;
35
36//===----------------------------------------------------------------------===//
37// CheckDefaultArgumentVisitor
38//===----------------------------------------------------------------------===//
39
40namespace {
41  /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
42  /// the default argument of a parameter to determine whether it
43  /// contains any ill-formed subexpressions. For example, this will
44  /// diagnose the use of local variables or parameters within the
45  /// default argument expression.
46  class CheckDefaultArgumentVisitor
47    : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
48    Expr *DefaultArg;
49    Sema *S;
50
51  public:
52    CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
53      : DefaultArg(defarg), S(s) {}
54
55    bool VisitExpr(Expr *Node);
56    bool VisitDeclRefExpr(DeclRefExpr *DRE);
57    bool VisitCXXThisExpr(CXXThisExpr *ThisE);
58  };
59
60  /// VisitExpr - Visit all of the children of this expression.
61  bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
62    bool IsInvalid = false;
63    for (Stmt::child_iterator I = Node->child_begin(),
64         E = Node->child_end(); I != E; ++I)
65      IsInvalid |= Visit(*I);
66    return IsInvalid;
67  }
68
69  /// VisitDeclRefExpr - Visit a reference to a declaration, to
70  /// determine whether this declaration can be used in the default
71  /// argument expression.
72  bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
73    NamedDecl *Decl = DRE->getDecl();
74    if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
75      // C++ [dcl.fct.default]p9
76      //   Default arguments are evaluated each time the function is
77      //   called. The order of evaluation of function arguments is
78      //   unspecified. Consequently, parameters of a function shall not
79      //   be used in default argument expressions, even if they are not
80      //   evaluated. Parameters of a function declared before a default
81      //   argument expression are in scope and can hide namespace and
82      //   class member names.
83      return S->Diag(DRE->getSourceRange().getBegin(),
84                     diag::err_param_default_argument_references_param)
85         << Param->getDeclName() << DefaultArg->getSourceRange();
86    } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
87      // C++ [dcl.fct.default]p7
88      //   Local variables shall not be used in default argument
89      //   expressions.
90      if (VDecl->isBlockVarDecl())
91        return S->Diag(DRE->getSourceRange().getBegin(),
92                       diag::err_param_default_argument_references_local)
93          << VDecl->getDeclName() << DefaultArg->getSourceRange();
94    }
95
96    return false;
97  }
98
99  /// VisitCXXThisExpr - Visit a C++ "this" expression.
100  bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
101    // C++ [dcl.fct.default]p8:
102    //   The keyword this shall not be used in a default argument of a
103    //   member function.
104    return S->Diag(ThisE->getSourceRange().getBegin(),
105                   diag::err_param_default_argument_references_this)
106               << ThisE->getSourceRange();
107  }
108}
109
110bool
111Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
112                              SourceLocation EqualLoc) {
113  if (RequireCompleteType(Param->getLocation(), Param->getType(),
114                          diag::err_typecheck_decl_incomplete_type)) {
115    Param->setInvalidDecl();
116    return true;
117  }
118
119  Expr *Arg = (Expr *)DefaultArg.get();
120
121  // C++ [dcl.fct.default]p5
122  //   A default argument expression is implicitly converted (clause
123  //   4) to the parameter type. The default argument expression has
124  //   the same semantic constraints as the initializer expression in
125  //   a declaration of a variable of the parameter type, using the
126  //   copy-initialization semantics (8.5).
127  InitializedEntity Entity = InitializedEntity::InitializeParameter(Param);
128  InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
129                                                           EqualLoc);
130  InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
131  OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
132                                          MultiExprArg(*this, (void**)&Arg, 1));
133  if (Result.isInvalid())
134    return true;
135  Arg = Result.takeAs<Expr>();
136
137  Arg = MaybeCreateCXXExprWithTemporaries(Arg);
138
139  // Okay: add the default argument to the parameter
140  Param->setDefaultArg(Arg);
141
142  DefaultArg.release();
143
144  return false;
145}
146
147/// ActOnParamDefaultArgument - Check whether the default argument
148/// provided for a function parameter is well-formed. If so, attach it
149/// to the parameter declaration.
150void
151Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
152                                ExprArg defarg) {
153  if (!param || !defarg.get())
154    return;
155
156  ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
157  UnparsedDefaultArgLocs.erase(Param);
158
159  ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
160
161  // Default arguments are only permitted in C++
162  if (!getLangOptions().CPlusPlus) {
163    Diag(EqualLoc, diag::err_param_default_argument)
164      << DefaultArg->getSourceRange();
165    Param->setInvalidDecl();
166    return;
167  }
168
169  // Check that the default argument is well-formed
170  CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
171  if (DefaultArgChecker.Visit(DefaultArg.get())) {
172    Param->setInvalidDecl();
173    return;
174  }
175
176  SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
177}
178
179/// ActOnParamUnparsedDefaultArgument - We've seen a default
180/// argument for a function parameter, but we can't parse it yet
181/// because we're inside a class definition. Note that this default
182/// argument will be parsed later.
183void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
184                                             SourceLocation EqualLoc,
185                                             SourceLocation ArgLoc) {
186  if (!param)
187    return;
188
189  ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
190  if (Param)
191    Param->setUnparsedDefaultArg();
192
193  UnparsedDefaultArgLocs[Param] = ArgLoc;
194}
195
196/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
197/// the default argument for the parameter param failed.
198void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
199  if (!param)
200    return;
201
202  ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
203
204  Param->setInvalidDecl();
205
206  UnparsedDefaultArgLocs.erase(Param);
207}
208
209/// CheckExtraCXXDefaultArguments - Check for any extra default
210/// arguments in the declarator, which is not a function declaration
211/// or definition and therefore is not permitted to have default
212/// arguments. This routine should be invoked for every declarator
213/// that is not a function declaration or definition.
214void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
215  // C++ [dcl.fct.default]p3
216  //   A default argument expression shall be specified only in the
217  //   parameter-declaration-clause of a function declaration or in a
218  //   template-parameter (14.1). It shall not be specified for a
219  //   parameter pack. If it is specified in a
220  //   parameter-declaration-clause, it shall not occur within a
221  //   declarator or abstract-declarator of a parameter-declaration.
222  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
223    DeclaratorChunk &chunk = D.getTypeObject(i);
224    if (chunk.Kind == DeclaratorChunk::Function) {
225      for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
226        ParmVarDecl *Param =
227          cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
228        if (Param->hasUnparsedDefaultArg()) {
229          CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
230          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
231            << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
232          delete Toks;
233          chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
234        } else if (Param->getDefaultArg()) {
235          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
236            << Param->getDefaultArg()->getSourceRange();
237          Param->setDefaultArg(0);
238        }
239      }
240    }
241  }
242}
243
244// MergeCXXFunctionDecl - Merge two declarations of the same C++
245// function, once we already know that they have the same
246// type. Subroutine of MergeFunctionDecl. Returns true if there was an
247// error, false otherwise.
248bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
249  bool Invalid = false;
250
251  // C++ [dcl.fct.default]p4:
252  //   For non-template functions, default arguments can be added in
253  //   later declarations of a function in the same
254  //   scope. Declarations in different scopes have completely
255  //   distinct sets of default arguments. That is, declarations in
256  //   inner scopes do not acquire default arguments from
257  //   declarations in outer scopes, and vice versa. In a given
258  //   function declaration, all parameters subsequent to a
259  //   parameter with a default argument shall have default
260  //   arguments supplied in this or previous declarations. A
261  //   default argument shall not be redefined by a later
262  //   declaration (not even to the same value).
263  //
264  // C++ [dcl.fct.default]p6:
265  //   Except for member functions of class templates, the default arguments
266  //   in a member function definition that appears outside of the class
267  //   definition are added to the set of default arguments provided by the
268  //   member function declaration in the class definition.
269  for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
270    ParmVarDecl *OldParam = Old->getParamDecl(p);
271    ParmVarDecl *NewParam = New->getParamDecl(p);
272
273    if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
274      // FIXME: If we knew where the '=' was, we could easily provide a fix-it
275      // hint here. Alternatively, we could walk the type-source information
276      // for NewParam to find the last source location in the type... but it
277      // isn't worth the effort right now. This is the kind of test case that
278      // is hard to get right:
279
280      //   int f(int);
281      //   void g(int (*fp)(int) = f);
282      //   void g(int (*fp)(int) = &f);
283      Diag(NewParam->getLocation(),
284           diag::err_param_default_argument_redefinition)
285        << NewParam->getDefaultArgRange();
286
287      // Look for the function declaration where the default argument was
288      // actually written, which may be a declaration prior to Old.
289      for (FunctionDecl *Older = Old->getPreviousDeclaration();
290           Older; Older = Older->getPreviousDeclaration()) {
291        if (!Older->getParamDecl(p)->hasDefaultArg())
292          break;
293
294        OldParam = Older->getParamDecl(p);
295      }
296
297      Diag(OldParam->getLocation(), diag::note_previous_definition)
298        << OldParam->getDefaultArgRange();
299      Invalid = true;
300    } else if (OldParam->hasDefaultArg()) {
301      // Merge the old default argument into the new parameter.
302      // It's important to use getInit() here;  getDefaultArg()
303      // strips off any top-level CXXExprWithTemporaries.
304      NewParam->setHasInheritedDefaultArg();
305      if (OldParam->hasUninstantiatedDefaultArg())
306        NewParam->setUninstantiatedDefaultArg(
307                                      OldParam->getUninstantiatedDefaultArg());
308      else
309        NewParam->setDefaultArg(OldParam->getInit());
310    } else if (NewParam->hasDefaultArg()) {
311      if (New->getDescribedFunctionTemplate()) {
312        // Paragraph 4, quoted above, only applies to non-template functions.
313        Diag(NewParam->getLocation(),
314             diag::err_param_default_argument_template_redecl)
315          << NewParam->getDefaultArgRange();
316        Diag(Old->getLocation(), diag::note_template_prev_declaration)
317          << false;
318      } else if (New->getTemplateSpecializationKind()
319                   != TSK_ImplicitInstantiation &&
320                 New->getTemplateSpecializationKind() != TSK_Undeclared) {
321        // C++ [temp.expr.spec]p21:
322        //   Default function arguments shall not be specified in a declaration
323        //   or a definition for one of the following explicit specializations:
324        //     - the explicit specialization of a function template;
325        //     - the explicit specialization of a member function template;
326        //     - the explicit specialization of a member function of a class
327        //       template where the class template specialization to which the
328        //       member function specialization belongs is implicitly
329        //       instantiated.
330        Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
331          << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
332          << New->getDeclName()
333          << NewParam->getDefaultArgRange();
334      } else if (New->getDeclContext()->isDependentContext()) {
335        // C++ [dcl.fct.default]p6 (DR217):
336        //   Default arguments for a member function of a class template shall
337        //   be specified on the initial declaration of the member function
338        //   within the class template.
339        //
340        // Reading the tea leaves a bit in DR217 and its reference to DR205
341        // leads me to the conclusion that one cannot add default function
342        // arguments for an out-of-line definition of a member function of a
343        // dependent type.
344        int WhichKind = 2;
345        if (CXXRecordDecl *Record
346              = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
347          if (Record->getDescribedClassTemplate())
348            WhichKind = 0;
349          else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
350            WhichKind = 1;
351          else
352            WhichKind = 2;
353        }
354
355        Diag(NewParam->getLocation(),
356             diag::err_param_default_argument_member_template_redecl)
357          << WhichKind
358          << NewParam->getDefaultArgRange();
359      }
360    }
361  }
362
363  if (CheckEquivalentExceptionSpec(Old, New))
364    Invalid = true;
365
366  return Invalid;
367}
368
369/// CheckCXXDefaultArguments - Verify that the default arguments for a
370/// function declaration are well-formed according to C++
371/// [dcl.fct.default].
372void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
373  unsigned NumParams = FD->getNumParams();
374  unsigned p;
375
376  // Find first parameter with a default argument
377  for (p = 0; p < NumParams; ++p) {
378    ParmVarDecl *Param = FD->getParamDecl(p);
379    if (Param->hasDefaultArg())
380      break;
381  }
382
383  // C++ [dcl.fct.default]p4:
384  //   In a given function declaration, all parameters
385  //   subsequent to a parameter with a default argument shall
386  //   have default arguments supplied in this or previous
387  //   declarations. A default argument shall not be redefined
388  //   by a later declaration (not even to the same value).
389  unsigned LastMissingDefaultArg = 0;
390  for (; p < NumParams; ++p) {
391    ParmVarDecl *Param = FD->getParamDecl(p);
392    if (!Param->hasDefaultArg()) {
393      if (Param->isInvalidDecl())
394        /* We already complained about this parameter. */;
395      else if (Param->getIdentifier())
396        Diag(Param->getLocation(),
397             diag::err_param_default_argument_missing_name)
398          << Param->getIdentifier();
399      else
400        Diag(Param->getLocation(),
401             diag::err_param_default_argument_missing);
402
403      LastMissingDefaultArg = p;
404    }
405  }
406
407  if (LastMissingDefaultArg > 0) {
408    // Some default arguments were missing. Clear out all of the
409    // default arguments up to (and including) the last missing
410    // default argument, so that we leave the function parameters
411    // in a semantically valid state.
412    for (p = 0; p <= LastMissingDefaultArg; ++p) {
413      ParmVarDecl *Param = FD->getParamDecl(p);
414      if (Param->hasDefaultArg()) {
415        Param->setDefaultArg(0);
416      }
417    }
418  }
419}
420
421/// isCurrentClassName - Determine whether the identifier II is the
422/// name of the class type currently being defined. In the case of
423/// nested classes, this will only return true if II is the name of
424/// the innermost class.
425bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
426                              const CXXScopeSpec *SS) {
427  assert(getLangOptions().CPlusPlus && "No class names in C!");
428
429  CXXRecordDecl *CurDecl;
430  if (SS && SS->isSet() && !SS->isInvalid()) {
431    DeclContext *DC = computeDeclContext(*SS, true);
432    CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
433  } else
434    CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
435
436  if (CurDecl && CurDecl->getIdentifier())
437    return &II == CurDecl->getIdentifier();
438  else
439    return false;
440}
441
442/// \brief Check the validity of a C++ base class specifier.
443///
444/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
445/// and returns NULL otherwise.
446CXXBaseSpecifier *
447Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
448                         SourceRange SpecifierRange,
449                         bool Virtual, AccessSpecifier Access,
450                         QualType BaseType,
451                         SourceLocation BaseLoc) {
452  // C++ [class.union]p1:
453  //   A union shall not have base classes.
454  if (Class->isUnion()) {
455    Diag(Class->getLocation(), diag::err_base_clause_on_union)
456      << SpecifierRange;
457    return 0;
458  }
459
460  if (BaseType->isDependentType())
461    return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
462                                Class->getTagKind() == TTK_Class,
463                                Access, BaseType);
464
465  // Base specifiers must be record types.
466  if (!BaseType->isRecordType()) {
467    Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
468    return 0;
469  }
470
471  // C++ [class.union]p1:
472  //   A union shall not be used as a base class.
473  if (BaseType->isUnionType()) {
474    Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
475    return 0;
476  }
477
478  // C++ [class.derived]p2:
479  //   The class-name in a base-specifier shall not be an incompletely
480  //   defined class.
481  if (RequireCompleteType(BaseLoc, BaseType,
482                          PDiag(diag::err_incomplete_base_class)
483                            << SpecifierRange))
484    return 0;
485
486  // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
487  RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
488  assert(BaseDecl && "Record type has no declaration");
489  BaseDecl = BaseDecl->getDefinition();
490  assert(BaseDecl && "Base type is not incomplete, but has no definition");
491  CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
492  assert(CXXBaseDecl && "Base type is not a C++ type");
493
494  // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
495  if (CXXBaseDecl->hasAttr<FinalAttr>()) {
496    Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
497    Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
498      << BaseType;
499    return 0;
500  }
501
502  SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual);
503
504  // Create the base specifier.
505  return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
506                              Class->getTagKind() == TTK_Class,
507                              Access, BaseType);
508}
509
510void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class,
511                                          const CXXRecordDecl *BaseClass,
512                                          bool BaseIsVirtual) {
513  // A class with a non-empty base class is not empty.
514  // FIXME: Standard ref?
515  if (!BaseClass->isEmpty())
516    Class->setEmpty(false);
517
518  // C++ [class.virtual]p1:
519  //   A class that [...] inherits a virtual function is called a polymorphic
520  //   class.
521  if (BaseClass->isPolymorphic())
522    Class->setPolymorphic(true);
523
524  // C++ [dcl.init.aggr]p1:
525  //   An aggregate is [...] a class with [...] no base classes [...].
526  Class->setAggregate(false);
527
528  // C++ [class]p4:
529  //   A POD-struct is an aggregate class...
530  Class->setPOD(false);
531
532  if (BaseIsVirtual) {
533    // C++ [class.ctor]p5:
534    //   A constructor is trivial if its class has no virtual base classes.
535    Class->setHasTrivialConstructor(false);
536
537    // C++ [class.copy]p6:
538    //   A copy constructor is trivial if its class has no virtual base classes.
539    Class->setHasTrivialCopyConstructor(false);
540
541    // C++ [class.copy]p11:
542    //   A copy assignment operator is trivial if its class has no virtual
543    //   base classes.
544    Class->setHasTrivialCopyAssignment(false);
545
546    // C++0x [meta.unary.prop] is_empty:
547    //    T is a class type, but not a union type, with ... no virtual base
548    //    classes
549    Class->setEmpty(false);
550  } else {
551    // C++ [class.ctor]p5:
552    //   A constructor is trivial if all the direct base classes of its
553    //   class have trivial constructors.
554    if (!BaseClass->hasTrivialConstructor())
555      Class->setHasTrivialConstructor(false);
556
557    // C++ [class.copy]p6:
558    //   A copy constructor is trivial if all the direct base classes of its
559    //   class have trivial copy constructors.
560    if (!BaseClass->hasTrivialCopyConstructor())
561      Class->setHasTrivialCopyConstructor(false);
562
563    // C++ [class.copy]p11:
564    //   A copy assignment operator is trivial if all the direct base classes
565    //   of its class have trivial copy assignment operators.
566    if (!BaseClass->hasTrivialCopyAssignment())
567      Class->setHasTrivialCopyAssignment(false);
568  }
569
570  // C++ [class.ctor]p3:
571  //   A destructor is trivial if all the direct base classes of its class
572  //   have trivial destructors.
573  if (!BaseClass->hasTrivialDestructor())
574    Class->setHasTrivialDestructor(false);
575}
576
577/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
578/// one entry in the base class list of a class specifier, for
579/// example:
580///    class foo : public bar, virtual private baz {
581/// 'public bar' and 'virtual private baz' are each base-specifiers.
582Sema::BaseResult
583Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
584                         bool Virtual, AccessSpecifier Access,
585                         TypeTy *basetype, SourceLocation BaseLoc) {
586  if (!classdecl)
587    return true;
588
589  AdjustDeclIfTemplate(classdecl);
590  CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl.getAs<Decl>());
591  if (!Class)
592    return true;
593
594  QualType BaseType = GetTypeFromParser(basetype);
595  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
596                                                      Virtual, Access,
597                                                      BaseType, BaseLoc))
598    return BaseSpec;
599
600  return true;
601}
602
603/// \brief Performs the actual work of attaching the given base class
604/// specifiers to a C++ class.
605bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
606                                unsigned NumBases) {
607 if (NumBases == 0)
608    return false;
609
610  // Used to keep track of which base types we have already seen, so
611  // that we can properly diagnose redundant direct base types. Note
612  // that the key is always the unqualified canonical type of the base
613  // class.
614  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
615
616  // Copy non-redundant base specifiers into permanent storage.
617  unsigned NumGoodBases = 0;
618  bool Invalid = false;
619  for (unsigned idx = 0; idx < NumBases; ++idx) {
620    QualType NewBaseType
621      = Context.getCanonicalType(Bases[idx]->getType());
622    NewBaseType = NewBaseType.getLocalUnqualifiedType();
623    if (!Class->hasObjectMember()) {
624      if (const RecordType *FDTTy =
625            NewBaseType.getTypePtr()->getAs<RecordType>())
626        if (FDTTy->getDecl()->hasObjectMember())
627          Class->setHasObjectMember(true);
628    }
629
630    if (KnownBaseTypes[NewBaseType]) {
631      // C++ [class.mi]p3:
632      //   A class shall not be specified as a direct base class of a
633      //   derived class more than once.
634      Diag(Bases[idx]->getSourceRange().getBegin(),
635           diag::err_duplicate_base_class)
636        << KnownBaseTypes[NewBaseType]->getType()
637        << Bases[idx]->getSourceRange();
638
639      // Delete the duplicate base class specifier; we're going to
640      // overwrite its pointer later.
641      Context.Deallocate(Bases[idx]);
642
643      Invalid = true;
644    } else {
645      // Okay, add this new base class.
646      KnownBaseTypes[NewBaseType] = Bases[idx];
647      Bases[NumGoodBases++] = Bases[idx];
648    }
649  }
650
651  // Attach the remaining base class specifiers to the derived class.
652  Class->setBases(Bases, NumGoodBases);
653
654  // Delete the remaining (good) base class specifiers, since their
655  // data has been copied into the CXXRecordDecl.
656  for (unsigned idx = 0; idx < NumGoodBases; ++idx)
657    Context.Deallocate(Bases[idx]);
658
659  return Invalid;
660}
661
662/// ActOnBaseSpecifiers - Attach the given base specifiers to the
663/// class, after checking whether there are any duplicate base
664/// classes.
665void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
666                               unsigned NumBases) {
667  if (!ClassDecl || !Bases || !NumBases)
668    return;
669
670  AdjustDeclIfTemplate(ClassDecl);
671  AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
672                       (CXXBaseSpecifier**)(Bases), NumBases);
673}
674
675static CXXRecordDecl *GetClassForType(QualType T) {
676  if (const RecordType *RT = T->getAs<RecordType>())
677    return cast<CXXRecordDecl>(RT->getDecl());
678  else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
679    return ICT->getDecl();
680  else
681    return 0;
682}
683
684/// \brief Determine whether the type \p Derived is a C++ class that is
685/// derived from the type \p Base.
686bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
687  if (!getLangOptions().CPlusPlus)
688    return false;
689
690  CXXRecordDecl *DerivedRD = GetClassForType(Derived);
691  if (!DerivedRD)
692    return false;
693
694  CXXRecordDecl *BaseRD = GetClassForType(Base);
695  if (!BaseRD)
696    return false;
697
698  // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
699  return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
700}
701
702/// \brief Determine whether the type \p Derived is a C++ class that is
703/// derived from the type \p Base.
704bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
705  if (!getLangOptions().CPlusPlus)
706    return false;
707
708  CXXRecordDecl *DerivedRD = GetClassForType(Derived);
709  if (!DerivedRD)
710    return false;
711
712  CXXRecordDecl *BaseRD = GetClassForType(Base);
713  if (!BaseRD)
714    return false;
715
716  return DerivedRD->isDerivedFrom(BaseRD, Paths);
717}
718
719void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
720                              CXXBaseSpecifierArray &BasePathArray) {
721  assert(BasePathArray.empty() && "Base path array must be empty!");
722  assert(Paths.isRecordingPaths() && "Must record paths!");
723
724  const CXXBasePath &Path = Paths.front();
725
726  // We first go backward and check if we have a virtual base.
727  // FIXME: It would be better if CXXBasePath had the base specifier for
728  // the nearest virtual base.
729  unsigned Start = 0;
730  for (unsigned I = Path.size(); I != 0; --I) {
731    if (Path[I - 1].Base->isVirtual()) {
732      Start = I - 1;
733      break;
734    }
735  }
736
737  // Now add all bases.
738  for (unsigned I = Start, E = Path.size(); I != E; ++I)
739    BasePathArray.push_back(Path[I].Base);
740}
741
742/// \brief Determine whether the given base path includes a virtual
743/// base class.
744bool Sema::BasePathInvolvesVirtualBase(const CXXBaseSpecifierArray &BasePath) {
745  for (CXXBaseSpecifierArray::iterator B = BasePath.begin(),
746                                    BEnd = BasePath.end();
747       B != BEnd; ++B)
748    if ((*B)->isVirtual())
749      return true;
750
751  return false;
752}
753
754/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
755/// conversion (where Derived and Base are class types) is
756/// well-formed, meaning that the conversion is unambiguous (and
757/// that all of the base classes are accessible). Returns true
758/// and emits a diagnostic if the code is ill-formed, returns false
759/// otherwise. Loc is the location where this routine should point to
760/// if there is an error, and Range is the source range to highlight
761/// if there is an error.
762bool
763Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
764                                   unsigned InaccessibleBaseID,
765                                   unsigned AmbigiousBaseConvID,
766                                   SourceLocation Loc, SourceRange Range,
767                                   DeclarationName Name,
768                                   CXXBaseSpecifierArray *BasePath) {
769  // First, determine whether the path from Derived to Base is
770  // ambiguous. This is slightly more expensive than checking whether
771  // the Derived to Base conversion exists, because here we need to
772  // explore multiple paths to determine if there is an ambiguity.
773  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
774                     /*DetectVirtual=*/false);
775  bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
776  assert(DerivationOkay &&
777         "Can only be used with a derived-to-base conversion");
778  (void)DerivationOkay;
779
780  if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
781    if (InaccessibleBaseID) {
782      // Check that the base class can be accessed.
783      switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
784                                   InaccessibleBaseID)) {
785        case AR_inaccessible:
786          return true;
787        case AR_accessible:
788        case AR_dependent:
789        case AR_delayed:
790          break;
791      }
792    }
793
794    // Build a base path if necessary.
795    if (BasePath)
796      BuildBasePathArray(Paths, *BasePath);
797    return false;
798  }
799
800  // We know that the derived-to-base conversion is ambiguous, and
801  // we're going to produce a diagnostic. Perform the derived-to-base
802  // search just one more time to compute all of the possible paths so
803  // that we can print them out. This is more expensive than any of
804  // the previous derived-to-base checks we've done, but at this point
805  // performance isn't as much of an issue.
806  Paths.clear();
807  Paths.setRecordingPaths(true);
808  bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
809  assert(StillOkay && "Can only be used with a derived-to-base conversion");
810  (void)StillOkay;
811
812  // Build up a textual representation of the ambiguous paths, e.g.,
813  // D -> B -> A, that will be used to illustrate the ambiguous
814  // conversions in the diagnostic. We only print one of the paths
815  // to each base class subobject.
816  std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
817
818  Diag(Loc, AmbigiousBaseConvID)
819  << Derived << Base << PathDisplayStr << Range << Name;
820  return true;
821}
822
823bool
824Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
825                                   SourceLocation Loc, SourceRange Range,
826                                   CXXBaseSpecifierArray *BasePath,
827                                   bool IgnoreAccess) {
828  return CheckDerivedToBaseConversion(Derived, Base,
829                                      IgnoreAccess ? 0
830                                       : diag::err_upcast_to_inaccessible_base,
831                                      diag::err_ambiguous_derived_to_base_conv,
832                                      Loc, Range, DeclarationName(),
833                                      BasePath);
834}
835
836
837/// @brief Builds a string representing ambiguous paths from a
838/// specific derived class to different subobjects of the same base
839/// class.
840///
841/// This function builds a string that can be used in error messages
842/// to show the different paths that one can take through the
843/// inheritance hierarchy to go from the derived class to different
844/// subobjects of a base class. The result looks something like this:
845/// @code
846/// struct D -> struct B -> struct A
847/// struct D -> struct C -> struct A
848/// @endcode
849std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
850  std::string PathDisplayStr;
851  std::set<unsigned> DisplayedPaths;
852  for (CXXBasePaths::paths_iterator Path = Paths.begin();
853       Path != Paths.end(); ++Path) {
854    if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
855      // We haven't displayed a path to this particular base
856      // class subobject yet.
857      PathDisplayStr += "\n    ";
858      PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
859      for (CXXBasePath::const_iterator Element = Path->begin();
860           Element != Path->end(); ++Element)
861        PathDisplayStr += " -> " + Element->Base->getType().getAsString();
862    }
863  }
864
865  return PathDisplayStr;
866}
867
868//===----------------------------------------------------------------------===//
869// C++ class member Handling
870//===----------------------------------------------------------------------===//
871
872/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
873Sema::DeclPtrTy
874Sema::ActOnAccessSpecifier(AccessSpecifier Access,
875                           SourceLocation ASLoc, SourceLocation ColonLoc) {
876  assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
877  AccessSpecDecl* ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
878                                                  ASLoc, ColonLoc);
879  CurContext->addHiddenDecl(ASDecl);
880  return DeclPtrTy::make(ASDecl);
881}
882
883/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
884/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
885/// bitfield width if there is one and 'InitExpr' specifies the initializer if
886/// any.
887Sema::DeclPtrTy
888Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
889                               MultiTemplateParamsArg TemplateParameterLists,
890                               ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
891                               bool Deleted) {
892  const DeclSpec &DS = D.getDeclSpec();
893  DeclarationName Name = GetNameForDeclarator(D);
894  Expr *BitWidth = static_cast<Expr*>(BW);
895  Expr *Init = static_cast<Expr*>(InitExpr);
896  SourceLocation Loc = D.getIdentifierLoc();
897
898  assert(isa<CXXRecordDecl>(CurContext));
899  assert(!DS.isFriendSpecified());
900
901  bool isFunc = false;
902  if (D.isFunctionDeclarator())
903    isFunc = true;
904  else if (D.getNumTypeObjects() == 0 &&
905           D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
906    QualType TDType = GetTypeFromParser(DS.getTypeRep());
907    isFunc = TDType->isFunctionType();
908  }
909
910  // C++ 9.2p6: A member shall not be declared to have automatic storage
911  // duration (auto, register) or with the extern storage-class-specifier.
912  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
913  // data members and cannot be applied to names declared const or static,
914  // and cannot be applied to reference members.
915  switch (DS.getStorageClassSpec()) {
916    case DeclSpec::SCS_unspecified:
917    case DeclSpec::SCS_typedef:
918    case DeclSpec::SCS_static:
919      // FALL THROUGH.
920      break;
921    case DeclSpec::SCS_mutable:
922      if (isFunc) {
923        if (DS.getStorageClassSpecLoc().isValid())
924          Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
925        else
926          Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
927
928        // FIXME: It would be nicer if the keyword was ignored only for this
929        // declarator. Otherwise we could get follow-up errors.
930        D.getMutableDeclSpec().ClearStorageClassSpecs();
931      }
932      break;
933    default:
934      if (DS.getStorageClassSpecLoc().isValid())
935        Diag(DS.getStorageClassSpecLoc(),
936             diag::err_storageclass_invalid_for_member);
937      else
938        Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
939      D.getMutableDeclSpec().ClearStorageClassSpecs();
940  }
941
942  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
943                       DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
944                      !isFunc);
945
946  Decl *Member;
947  if (isInstField) {
948    // FIXME: Check for template parameters!
949    Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
950                         AS);
951    assert(Member && "HandleField never returns null");
952  } else {
953    Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
954               .getAs<Decl>();
955    if (!Member) {
956      if (BitWidth) DeleteExpr(BitWidth);
957      return DeclPtrTy();
958    }
959
960    // Non-instance-fields can't have a bitfield.
961    if (BitWidth) {
962      if (Member->isInvalidDecl()) {
963        // don't emit another diagnostic.
964      } else if (isa<VarDecl>(Member)) {
965        // C++ 9.6p3: A bit-field shall not be a static member.
966        // "static member 'A' cannot be a bit-field"
967        Diag(Loc, diag::err_static_not_bitfield)
968          << Name << BitWidth->getSourceRange();
969      } else if (isa<TypedefDecl>(Member)) {
970        // "typedef member 'x' cannot be a bit-field"
971        Diag(Loc, diag::err_typedef_not_bitfield)
972          << Name << BitWidth->getSourceRange();
973      } else {
974        // A function typedef ("typedef int f(); f a;").
975        // C++ 9.6p3: A bit-field shall have integral or enumeration type.
976        Diag(Loc, diag::err_not_integral_type_bitfield)
977          << Name << cast<ValueDecl>(Member)->getType()
978          << BitWidth->getSourceRange();
979      }
980
981      DeleteExpr(BitWidth);
982      BitWidth = 0;
983      Member->setInvalidDecl();
984    }
985
986    Member->setAccess(AS);
987
988    // If we have declared a member function template, set the access of the
989    // templated declaration as well.
990    if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
991      FunTmpl->getTemplatedDecl()->setAccess(AS);
992  }
993
994  assert((Name || isInstField) && "No identifier for non-field ?");
995
996  if (Init)
997    AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
998  if (Deleted) // FIXME: Source location is not very good.
999    SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
1000
1001  if (isInstField) {
1002    FieldCollector->Add(cast<FieldDecl>(Member));
1003    return DeclPtrTy();
1004  }
1005  return DeclPtrTy::make(Member);
1006}
1007
1008/// \brief Find the direct and/or virtual base specifiers that
1009/// correspond to the given base type, for use in base initialization
1010/// within a constructor.
1011static bool FindBaseInitializer(Sema &SemaRef,
1012                                CXXRecordDecl *ClassDecl,
1013                                QualType BaseType,
1014                                const CXXBaseSpecifier *&DirectBaseSpec,
1015                                const CXXBaseSpecifier *&VirtualBaseSpec) {
1016  // First, check for a direct base class.
1017  DirectBaseSpec = 0;
1018  for (CXXRecordDecl::base_class_const_iterator Base
1019         = ClassDecl->bases_begin();
1020       Base != ClassDecl->bases_end(); ++Base) {
1021    if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1022      // We found a direct base of this type. That's what we're
1023      // initializing.
1024      DirectBaseSpec = &*Base;
1025      break;
1026    }
1027  }
1028
1029  // Check for a virtual base class.
1030  // FIXME: We might be able to short-circuit this if we know in advance that
1031  // there are no virtual bases.
1032  VirtualBaseSpec = 0;
1033  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1034    // We haven't found a base yet; search the class hierarchy for a
1035    // virtual base class.
1036    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1037                       /*DetectVirtual=*/false);
1038    if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1039                              BaseType, Paths)) {
1040      for (CXXBasePaths::paths_iterator Path = Paths.begin();
1041           Path != Paths.end(); ++Path) {
1042        if (Path->back().Base->isVirtual()) {
1043          VirtualBaseSpec = Path->back().Base;
1044          break;
1045        }
1046      }
1047    }
1048  }
1049
1050  return DirectBaseSpec || VirtualBaseSpec;
1051}
1052
1053/// ActOnMemInitializer - Handle a C++ member initializer.
1054Sema::MemInitResult
1055Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
1056                          Scope *S,
1057                          CXXScopeSpec &SS,
1058                          IdentifierInfo *MemberOrBase,
1059                          TypeTy *TemplateTypeTy,
1060                          SourceLocation IdLoc,
1061                          SourceLocation LParenLoc,
1062                          ExprTy **Args, unsigned NumArgs,
1063                          SourceLocation *CommaLocs,
1064                          SourceLocation RParenLoc) {
1065  if (!ConstructorD)
1066    return true;
1067
1068  AdjustDeclIfTemplate(ConstructorD);
1069
1070  CXXConstructorDecl *Constructor
1071    = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
1072  if (!Constructor) {
1073    // The user wrote a constructor initializer on a function that is
1074    // not a C++ constructor. Ignore the error for now, because we may
1075    // have more member initializers coming; we'll diagnose it just
1076    // once in ActOnMemInitializers.
1077    return true;
1078  }
1079
1080  CXXRecordDecl *ClassDecl = Constructor->getParent();
1081
1082  // C++ [class.base.init]p2:
1083  //   Names in a mem-initializer-id are looked up in the scope of the
1084  //   constructor’s class and, if not found in that scope, are looked
1085  //   up in the scope containing the constructor’s
1086  //   definition. [Note: if the constructor’s class contains a member
1087  //   with the same name as a direct or virtual base class of the
1088  //   class, a mem-initializer-id naming the member or base class and
1089  //   composed of a single identifier refers to the class member. A
1090  //   mem-initializer-id for the hidden base class may be specified
1091  //   using a qualified name. ]
1092  if (!SS.getScopeRep() && !TemplateTypeTy) {
1093    // Look for a member, first.
1094    FieldDecl *Member = 0;
1095    DeclContext::lookup_result Result
1096      = ClassDecl->lookup(MemberOrBase);
1097    if (Result.first != Result.second)
1098      Member = dyn_cast<FieldDecl>(*Result.first);
1099
1100    // FIXME: Handle members of an anonymous union.
1101
1102    if (Member)
1103      return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1104                                    LParenLoc, RParenLoc);
1105  }
1106  // It didn't name a member, so see if it names a class.
1107  QualType BaseType;
1108  TypeSourceInfo *TInfo = 0;
1109
1110  if (TemplateTypeTy) {
1111    BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
1112  } else {
1113    LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1114    LookupParsedName(R, S, &SS);
1115
1116    TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1117    if (!TyD) {
1118      if (R.isAmbiguous()) return true;
1119
1120      // We don't want access-control diagnostics here.
1121      R.suppressDiagnostics();
1122
1123      if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1124        bool NotUnknownSpecialization = false;
1125        DeclContext *DC = computeDeclContext(SS, false);
1126        if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1127          NotUnknownSpecialization = !Record->hasAnyDependentBases();
1128
1129        if (!NotUnknownSpecialization) {
1130          // When the scope specifier can refer to a member of an unknown
1131          // specialization, we take it as a type name.
1132          BaseType = CheckTypenameType(ETK_None,
1133                                       (NestedNameSpecifier *)SS.getScopeRep(),
1134                                       *MemberOrBase, SourceLocation(),
1135                                       SS.getRange(), IdLoc);
1136          if (BaseType.isNull())
1137            return true;
1138
1139          R.clear();
1140          R.setLookupName(MemberOrBase);
1141        }
1142      }
1143
1144      // If no results were found, try to correct typos.
1145      if (R.empty() && BaseType.isNull() &&
1146          CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1147          R.isSingleResult()) {
1148        if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
1149          if (Member->getDeclContext()->getLookupContext()->Equals(ClassDecl)) {
1150            // We have found a non-static data member with a similar
1151            // name to what was typed; complain and initialize that
1152            // member.
1153            Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1154              << MemberOrBase << true << R.getLookupName()
1155              << FixItHint::CreateReplacement(R.getNameLoc(),
1156                                              R.getLookupName().getAsString());
1157            Diag(Member->getLocation(), diag::note_previous_decl)
1158              << Member->getDeclName();
1159
1160            return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1161                                          LParenLoc, RParenLoc);
1162          }
1163        } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1164          const CXXBaseSpecifier *DirectBaseSpec;
1165          const CXXBaseSpecifier *VirtualBaseSpec;
1166          if (FindBaseInitializer(*this, ClassDecl,
1167                                  Context.getTypeDeclType(Type),
1168                                  DirectBaseSpec, VirtualBaseSpec)) {
1169            // We have found a direct or virtual base class with a
1170            // similar name to what was typed; complain and initialize
1171            // that base class.
1172            Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1173              << MemberOrBase << false << R.getLookupName()
1174              << FixItHint::CreateReplacement(R.getNameLoc(),
1175                                              R.getLookupName().getAsString());
1176
1177            const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1178                                                             : VirtualBaseSpec;
1179            Diag(BaseSpec->getSourceRange().getBegin(),
1180                 diag::note_base_class_specified_here)
1181              << BaseSpec->getType()
1182              << BaseSpec->getSourceRange();
1183
1184            TyD = Type;
1185          }
1186        }
1187      }
1188
1189      if (!TyD && BaseType.isNull()) {
1190        Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1191          << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1192        return true;
1193      }
1194    }
1195
1196    if (BaseType.isNull()) {
1197      BaseType = Context.getTypeDeclType(TyD);
1198      if (SS.isSet()) {
1199        NestedNameSpecifier *Qualifier =
1200          static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1201
1202        // FIXME: preserve source range information
1203        BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
1204      }
1205    }
1206  }
1207
1208  if (!TInfo)
1209    TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
1210
1211  return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
1212                              LParenLoc, RParenLoc, ClassDecl);
1213}
1214
1215/// Checks an initializer expression for use of uninitialized fields, such as
1216/// containing the field that is being initialized. Returns true if there is an
1217/// uninitialized field was used an updates the SourceLocation parameter; false
1218/// otherwise.
1219static bool InitExprContainsUninitializedFields(const Stmt *S,
1220                                                const FieldDecl *LhsField,
1221                                                SourceLocation *L) {
1222  if (isa<CallExpr>(S)) {
1223    // Do not descend into function calls or constructors, as the use
1224    // of an uninitialized field may be valid. One would have to inspect
1225    // the contents of the function/ctor to determine if it is safe or not.
1226    // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1227    // may be safe, depending on what the function/ctor does.
1228    return false;
1229  }
1230  if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1231    const NamedDecl *RhsField = ME->getMemberDecl();
1232    if (RhsField == LhsField) {
1233      // Initializing a field with itself. Throw a warning.
1234      // But wait; there are exceptions!
1235      // Exception #1:  The field may not belong to this record.
1236      // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1237      const Expr *base = ME->getBase();
1238      if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1239        // Even though the field matches, it does not belong to this record.
1240        return false;
1241      }
1242      // None of the exceptions triggered; return true to indicate an
1243      // uninitialized field was used.
1244      *L = ME->getMemberLoc();
1245      return true;
1246    }
1247  }
1248  for (Stmt::const_child_iterator it = S->child_begin(), e = S->child_end();
1249       it != e; ++it) {
1250    if (!*it) {
1251      // An expression such as 'member(arg ?: "")' may trigger this.
1252      continue;
1253    }
1254    if (InitExprContainsUninitializedFields(*it, LhsField, L))
1255      return true;
1256  }
1257  return false;
1258}
1259
1260Sema::MemInitResult
1261Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1262                             unsigned NumArgs, SourceLocation IdLoc,
1263                             SourceLocation LParenLoc,
1264                             SourceLocation RParenLoc) {
1265  // Diagnose value-uses of fields to initialize themselves, e.g.
1266  //   foo(foo)
1267  // where foo is not also a parameter to the constructor.
1268  // TODO: implement -Wuninitialized and fold this into that framework.
1269  for (unsigned i = 0; i < NumArgs; ++i) {
1270    SourceLocation L;
1271    if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1272      // FIXME: Return true in the case when other fields are used before being
1273      // uninitialized. For example, let this field be the i'th field. When
1274      // initializing the i'th field, throw a warning if any of the >= i'th
1275      // fields are used, as they are not yet initialized.
1276      // Right now we are only handling the case where the i'th field uses
1277      // itself in its initializer.
1278      Diag(L, diag::warn_field_is_uninit);
1279    }
1280  }
1281
1282  bool HasDependentArg = false;
1283  for (unsigned i = 0; i < NumArgs; i++)
1284    HasDependentArg |= Args[i]->isTypeDependent();
1285
1286  if (Member->getType()->isDependentType() || HasDependentArg) {
1287    // Can't check initialization for a member of dependent type or when
1288    // any of the arguments are type-dependent expressions.
1289    OwningExprResult Init
1290      = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1291                                          RParenLoc));
1292
1293    // Erase any temporaries within this evaluation context; we're not
1294    // going to track them in the AST, since we'll be rebuilding the
1295    // ASTs during template instantiation.
1296    ExprTemporaries.erase(
1297              ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1298                          ExprTemporaries.end());
1299
1300    return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1301                                                    LParenLoc,
1302                                                    Init.takeAs<Expr>(),
1303                                                    RParenLoc);
1304
1305  }
1306
1307  if (Member->isInvalidDecl())
1308    return true;
1309
1310  // Initialize the member.
1311  InitializedEntity MemberEntity =
1312    InitializedEntity::InitializeMember(Member, 0);
1313  InitializationKind Kind =
1314    InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1315
1316  InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1317
1318  OwningExprResult MemberInit =
1319    InitSeq.Perform(*this, MemberEntity, Kind,
1320                    MultiExprArg(*this, (void**)Args, NumArgs), 0);
1321  if (MemberInit.isInvalid())
1322    return true;
1323
1324  // C++0x [class.base.init]p7:
1325  //   The initialization of each base and member constitutes a
1326  //   full-expression.
1327  MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1328  if (MemberInit.isInvalid())
1329    return true;
1330
1331  // If we are in a dependent context, template instantiation will
1332  // perform this type-checking again. Just save the arguments that we
1333  // received in a ParenListExpr.
1334  // FIXME: This isn't quite ideal, since our ASTs don't capture all
1335  // of the information that we have about the member
1336  // initializer. However, deconstructing the ASTs is a dicey process,
1337  // and this approach is far more likely to get the corner cases right.
1338  if (CurContext->isDependentContext()) {
1339    // Bump the reference count of all of the arguments.
1340    for (unsigned I = 0; I != NumArgs; ++I)
1341      Args[I]->Retain();
1342
1343    OwningExprResult Init
1344      = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1345                                          RParenLoc));
1346    return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1347                                                    LParenLoc,
1348                                                    Init.takeAs<Expr>(),
1349                                                    RParenLoc);
1350  }
1351
1352  return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1353                                                  LParenLoc,
1354                                                  MemberInit.takeAs<Expr>(),
1355                                                  RParenLoc);
1356}
1357
1358Sema::MemInitResult
1359Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
1360                           Expr **Args, unsigned NumArgs,
1361                           SourceLocation LParenLoc, SourceLocation RParenLoc,
1362                           CXXRecordDecl *ClassDecl) {
1363  bool HasDependentArg = false;
1364  for (unsigned i = 0; i < NumArgs; i++)
1365    HasDependentArg |= Args[i]->isTypeDependent();
1366
1367  SourceLocation BaseLoc
1368    = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1369
1370  if (!BaseType->isDependentType() && !BaseType->isRecordType())
1371    return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1372             << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1373
1374  // C++ [class.base.init]p2:
1375  //   [...] Unless the mem-initializer-id names a nonstatic data
1376  //   member of the constructor’s class or a direct or virtual base
1377  //   of that class, the mem-initializer is ill-formed. A
1378  //   mem-initializer-list can initialize a base class using any
1379  //   name that denotes that base class type.
1380  bool Dependent = BaseType->isDependentType() || HasDependentArg;
1381
1382  // Check for direct and virtual base classes.
1383  const CXXBaseSpecifier *DirectBaseSpec = 0;
1384  const CXXBaseSpecifier *VirtualBaseSpec = 0;
1385  if (!Dependent) {
1386    FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1387                        VirtualBaseSpec);
1388
1389    // C++ [base.class.init]p2:
1390    // Unless the mem-initializer-id names a nonstatic data member of the
1391    // constructor's class or a direct or virtual base of that class, the
1392    // mem-initializer is ill-formed.
1393    if (!DirectBaseSpec && !VirtualBaseSpec) {
1394      // If the class has any dependent bases, then it's possible that
1395      // one of those types will resolve to the same type as
1396      // BaseType. Therefore, just treat this as a dependent base
1397      // class initialization.  FIXME: Should we try to check the
1398      // initialization anyway? It seems odd.
1399      if (ClassDecl->hasAnyDependentBases())
1400        Dependent = true;
1401      else
1402        return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1403          << BaseType << Context.getTypeDeclType(ClassDecl)
1404          << BaseTInfo->getTypeLoc().getLocalSourceRange();
1405    }
1406  }
1407
1408  if (Dependent) {
1409    // Can't check initialization for a base of dependent type or when
1410    // any of the arguments are type-dependent expressions.
1411    OwningExprResult BaseInit
1412      = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1413                                          RParenLoc));
1414
1415    // Erase any temporaries within this evaluation context; we're not
1416    // going to track them in the AST, since we'll be rebuilding the
1417    // ASTs during template instantiation.
1418    ExprTemporaries.erase(
1419              ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1420                          ExprTemporaries.end());
1421
1422    return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1423                                                    /*IsVirtual=*/false,
1424                                                    LParenLoc,
1425                                                    BaseInit.takeAs<Expr>(),
1426                                                    RParenLoc);
1427  }
1428
1429  // C++ [base.class.init]p2:
1430  //   If a mem-initializer-id is ambiguous because it designates both
1431  //   a direct non-virtual base class and an inherited virtual base
1432  //   class, the mem-initializer is ill-formed.
1433  if (DirectBaseSpec && VirtualBaseSpec)
1434    return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
1435      << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1436
1437  CXXBaseSpecifier *BaseSpec
1438    = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1439  if (!BaseSpec)
1440    BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1441
1442  // Initialize the base.
1443  InitializedEntity BaseEntity =
1444    InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
1445  InitializationKind Kind =
1446    InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1447
1448  InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1449
1450  OwningExprResult BaseInit =
1451    InitSeq.Perform(*this, BaseEntity, Kind,
1452                    MultiExprArg(*this, (void**)Args, NumArgs), 0);
1453  if (BaseInit.isInvalid())
1454    return true;
1455
1456  // C++0x [class.base.init]p7:
1457  //   The initialization of each base and member constitutes a
1458  //   full-expression.
1459  BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1460  if (BaseInit.isInvalid())
1461    return true;
1462
1463  // If we are in a dependent context, template instantiation will
1464  // perform this type-checking again. Just save the arguments that we
1465  // received in a ParenListExpr.
1466  // FIXME: This isn't quite ideal, since our ASTs don't capture all
1467  // of the information that we have about the base
1468  // initializer. However, deconstructing the ASTs is a dicey process,
1469  // and this approach is far more likely to get the corner cases right.
1470  if (CurContext->isDependentContext()) {
1471    // Bump the reference count of all of the arguments.
1472    for (unsigned I = 0; I != NumArgs; ++I)
1473      Args[I]->Retain();
1474
1475    OwningExprResult Init
1476      = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1477                                          RParenLoc));
1478    return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1479                                                    BaseSpec->isVirtual(),
1480                                                    LParenLoc,
1481                                                    Init.takeAs<Expr>(),
1482                                                    RParenLoc);
1483  }
1484
1485  return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1486                                                  BaseSpec->isVirtual(),
1487                                                  LParenLoc,
1488                                                  BaseInit.takeAs<Expr>(),
1489                                                  RParenLoc);
1490}
1491
1492/// ImplicitInitializerKind - How an implicit base or member initializer should
1493/// initialize its base or member.
1494enum ImplicitInitializerKind {
1495  IIK_Default,
1496  IIK_Copy,
1497  IIK_Move
1498};
1499
1500static bool
1501BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
1502                             ImplicitInitializerKind ImplicitInitKind,
1503                             CXXBaseSpecifier *BaseSpec,
1504                             bool IsInheritedVirtualBase,
1505                             CXXBaseOrMemberInitializer *&CXXBaseInit) {
1506  InitializedEntity InitEntity
1507    = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1508                                        IsInheritedVirtualBase);
1509
1510  Sema::OwningExprResult BaseInit(SemaRef);
1511
1512  switch (ImplicitInitKind) {
1513  case IIK_Default: {
1514    InitializationKind InitKind
1515      = InitializationKind::CreateDefault(Constructor->getLocation());
1516    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1517    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1518                               Sema::MultiExprArg(SemaRef, 0, 0));
1519    break;
1520  }
1521
1522  case IIK_Copy: {
1523    ParmVarDecl *Param = Constructor->getParamDecl(0);
1524    QualType ParamType = Param->getType().getNonReferenceType();
1525
1526    Expr *CopyCtorArg =
1527      DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
1528                          Constructor->getLocation(), ParamType, 0);
1529
1530    // Cast to the base class to avoid ambiguities.
1531    QualType ArgTy =
1532      SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1533                                       ParamType.getQualifiers());
1534    SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
1535                              CastExpr::CK_UncheckedDerivedToBase,
1536                              ImplicitCastExpr::LValue,
1537                              CXXBaseSpecifierArray(BaseSpec));
1538
1539    InitializationKind InitKind
1540      = InitializationKind::CreateDirect(Constructor->getLocation(),
1541                                         SourceLocation(), SourceLocation());
1542    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1543                                   &CopyCtorArg, 1);
1544    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1545                               Sema::MultiExprArg(SemaRef,
1546                                                  (void**)&CopyCtorArg, 1));
1547    break;
1548  }
1549
1550  case IIK_Move:
1551    assert(false && "Unhandled initializer kind!");
1552  }
1553
1554  BaseInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1555  if (BaseInit.isInvalid())
1556    return true;
1557
1558  CXXBaseInit =
1559    new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1560               SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1561                                                        SourceLocation()),
1562                                             BaseSpec->isVirtual(),
1563                                             SourceLocation(),
1564                                             BaseInit.takeAs<Expr>(),
1565                                             SourceLocation());
1566
1567  return false;
1568}
1569
1570static bool
1571BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
1572                               ImplicitInitializerKind ImplicitInitKind,
1573                               FieldDecl *Field,
1574                               CXXBaseOrMemberInitializer *&CXXMemberInit) {
1575  if (Field->isInvalidDecl())
1576    return true;
1577
1578  SourceLocation Loc = Constructor->getLocation();
1579
1580  if (ImplicitInitKind == IIK_Copy) {
1581    ParmVarDecl *Param = Constructor->getParamDecl(0);
1582    QualType ParamType = Param->getType().getNonReferenceType();
1583
1584    Expr *MemberExprBase =
1585      DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
1586                          Loc, ParamType, 0);
1587
1588    // Build a reference to this field within the parameter.
1589    CXXScopeSpec SS;
1590    LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1591                              Sema::LookupMemberName);
1592    MemberLookup.addDecl(Field, AS_public);
1593    MemberLookup.resolveKind();
1594    Sema::OwningExprResult CopyCtorArg
1595      = SemaRef.BuildMemberReferenceExpr(SemaRef.Owned(MemberExprBase),
1596                                         ParamType, Loc,
1597                                         /*IsArrow=*/false,
1598                                         SS,
1599                                         /*FirstQualifierInScope=*/0,
1600                                         MemberLookup,
1601                                         /*TemplateArgs=*/0);
1602    if (CopyCtorArg.isInvalid())
1603      return true;
1604
1605    // When the field we are copying is an array, create index variables for
1606    // each dimension of the array. We use these index variables to subscript
1607    // the source array, and other clients (e.g., CodeGen) will perform the
1608    // necessary iteration with these index variables.
1609    llvm::SmallVector<VarDecl *, 4> IndexVariables;
1610    QualType BaseType = Field->getType();
1611    QualType SizeType = SemaRef.Context.getSizeType();
1612    while (const ConstantArrayType *Array
1613                          = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1614      // Create the iteration variable for this array index.
1615      IdentifierInfo *IterationVarName = 0;
1616      {
1617        llvm::SmallString<8> Str;
1618        llvm::raw_svector_ostream OS(Str);
1619        OS << "__i" << IndexVariables.size();
1620        IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1621      }
1622      VarDecl *IterationVar
1623        = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc,
1624                          IterationVarName, SizeType,
1625                        SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
1626                          VarDecl::None, VarDecl::None);
1627      IndexVariables.push_back(IterationVar);
1628
1629      // Create a reference to the iteration variable.
1630      Sema::OwningExprResult IterationVarRef
1631        = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, Loc);
1632      assert(!IterationVarRef.isInvalid() &&
1633             "Reference to invented variable cannot fail!");
1634
1635      // Subscript the array with this iteration variable.
1636      CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(move(CopyCtorArg),
1637                                                            Loc,
1638                                                          move(IterationVarRef),
1639                                                            Loc);
1640      if (CopyCtorArg.isInvalid())
1641        return true;
1642
1643      BaseType = Array->getElementType();
1644    }
1645
1646    // Construct the entity that we will be initializing. For an array, this
1647    // will be first element in the array, which may require several levels
1648    // of array-subscript entities.
1649    llvm::SmallVector<InitializedEntity, 4> Entities;
1650    Entities.reserve(1 + IndexVariables.size());
1651    Entities.push_back(InitializedEntity::InitializeMember(Field));
1652    for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1653      Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1654                                                              0,
1655                                                              Entities.back()));
1656
1657    // Direct-initialize to use the copy constructor.
1658    InitializationKind InitKind =
1659      InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1660
1661    Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1662    InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1663                                   &CopyCtorArgE, 1);
1664
1665    Sema::OwningExprResult MemberInit
1666      = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
1667                        Sema::MultiExprArg(SemaRef, (void**)&CopyCtorArgE, 1));
1668    MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1669    if (MemberInit.isInvalid())
1670      return true;
1671
1672    CXXMemberInit
1673      = CXXBaseOrMemberInitializer::Create(SemaRef.Context, Field, Loc, Loc,
1674                                           MemberInit.takeAs<Expr>(), Loc,
1675                                           IndexVariables.data(),
1676                                           IndexVariables.size());
1677    return false;
1678  }
1679
1680  assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1681
1682  QualType FieldBaseElementType =
1683    SemaRef.Context.getBaseElementType(Field->getType());
1684
1685  if (FieldBaseElementType->isRecordType()) {
1686    InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
1687    InitializationKind InitKind =
1688      InitializationKind::CreateDefault(Loc);
1689
1690    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1691    Sema::OwningExprResult MemberInit =
1692      InitSeq.Perform(SemaRef, InitEntity, InitKind,
1693                      Sema::MultiExprArg(SemaRef, 0, 0));
1694    MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1695    if (MemberInit.isInvalid())
1696      return true;
1697
1698    CXXMemberInit =
1699      new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1700                                                       Field, Loc, Loc,
1701                                                      MemberInit.takeAs<Expr>(),
1702                                                       Loc);
1703    return false;
1704  }
1705
1706  if (FieldBaseElementType->isReferenceType()) {
1707    SemaRef.Diag(Constructor->getLocation(),
1708                 diag::err_uninitialized_member_in_ctor)
1709    << (int)Constructor->isImplicit()
1710    << SemaRef.Context.getTagDeclType(Constructor->getParent())
1711    << 0 << Field->getDeclName();
1712    SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1713    return true;
1714  }
1715
1716  if (FieldBaseElementType.isConstQualified()) {
1717    SemaRef.Diag(Constructor->getLocation(),
1718                 diag::err_uninitialized_member_in_ctor)
1719    << (int)Constructor->isImplicit()
1720    << SemaRef.Context.getTagDeclType(Constructor->getParent())
1721    << 1 << Field->getDeclName();
1722    SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1723    return true;
1724  }
1725
1726  // Nothing to initialize.
1727  CXXMemberInit = 0;
1728  return false;
1729}
1730
1731namespace {
1732struct BaseAndFieldInfo {
1733  Sema &S;
1734  CXXConstructorDecl *Ctor;
1735  bool AnyErrorsInInits;
1736  ImplicitInitializerKind IIK;
1737  llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1738  llvm::SmallVector<CXXBaseOrMemberInitializer*, 8> AllToInit;
1739
1740  BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1741    : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1742    // FIXME: Handle implicit move constructors.
1743    if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1744      IIK = IIK_Copy;
1745    else
1746      IIK = IIK_Default;
1747  }
1748};
1749}
1750
1751static void RecordFieldInitializer(BaseAndFieldInfo &Info,
1752                                   FieldDecl *Top, FieldDecl *Field,
1753                                   CXXBaseOrMemberInitializer *Init) {
1754  // If the member doesn't need to be initialized, Init will still be null.
1755  if (!Init)
1756    return;
1757
1758  Info.AllToInit.push_back(Init);
1759  if (Field != Top) {
1760    Init->setMember(Top);
1761    Init->setAnonUnionMember(Field);
1762  }
1763}
1764
1765static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
1766                                    FieldDecl *Top, FieldDecl *Field) {
1767
1768  // Overwhelmingly common case: we have a direct initializer for this field.
1769  if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(Field)) {
1770    RecordFieldInitializer(Info, Top, Field, Init);
1771    return false;
1772  }
1773
1774  if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
1775    const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
1776    assert(FieldClassType && "anonymous struct/union without record type");
1777    CXXRecordDecl *FieldClassDecl
1778      = cast<CXXRecordDecl>(FieldClassType->getDecl());
1779
1780    // Even though union members never have non-trivial default
1781    // constructions in C++03, we still build member initializers for aggregate
1782    // record types which can be union members, and C++0x allows non-trivial
1783    // default constructors for union members, so we ensure that only one
1784    // member is initialized for these.
1785    if (FieldClassDecl->isUnion()) {
1786      // First check for an explicit initializer for one field.
1787      for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1788           EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1789        if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
1790          RecordFieldInitializer(Info, Top, *FA, Init);
1791
1792          // Once we've initialized a field of an anonymous union, the union
1793          // field in the class is also initialized, so exit immediately.
1794          return false;
1795        }
1796      }
1797
1798      // Fallthrough and construct a default initializer for the union as
1799      // a whole, which can call its default constructor if such a thing exists
1800      // (C++0x perhaps). FIXME: It's not clear that this is the correct
1801      // behavior going forward with C++0x, when anonymous unions there are
1802      // finalized, we should revisit this.
1803    } else {
1804      // For structs, we simply descend through to initialize all members where
1805      // necessary.
1806      for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1807           EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1808        if (CollectFieldInitializer(Info, Top, *FA))
1809          return true;
1810      }
1811    }
1812  }
1813
1814  // Don't try to build an implicit initializer if there were semantic
1815  // errors in any of the initializers (and therefore we might be
1816  // missing some that the user actually wrote).
1817  if (Info.AnyErrorsInInits)
1818    return false;
1819
1820  CXXBaseOrMemberInitializer *Init = 0;
1821  if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
1822    return true;
1823
1824  RecordFieldInitializer(Info, Top, Field, Init);
1825  return false;
1826}
1827
1828bool
1829Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
1830                                  CXXBaseOrMemberInitializer **Initializers,
1831                                  unsigned NumInitializers,
1832                                  bool AnyErrors) {
1833  if (Constructor->getDeclContext()->isDependentContext()) {
1834    // Just store the initializers as written, they will be checked during
1835    // instantiation.
1836    if (NumInitializers > 0) {
1837      Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1838      CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1839        new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1840      memcpy(baseOrMemberInitializers, Initializers,
1841             NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
1842      Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1843    }
1844
1845    return false;
1846  }
1847
1848  BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
1849
1850  // We need to build the initializer AST according to order of construction
1851  // and not what user specified in the Initializers list.
1852  CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
1853  if (!ClassDecl)
1854    return true;
1855
1856  bool HadError = false;
1857
1858  for (unsigned i = 0; i < NumInitializers; i++) {
1859    CXXBaseOrMemberInitializer *Member = Initializers[i];
1860
1861    if (Member->isBaseInitializer())
1862      Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1863    else
1864      Info.AllBaseFields[Member->getMember()] = Member;
1865  }
1866
1867  // Keep track of the direct virtual bases.
1868  llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
1869  for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
1870       E = ClassDecl->bases_end(); I != E; ++I) {
1871    if (I->isVirtual())
1872      DirectVBases.insert(I);
1873  }
1874
1875  // Push virtual bases before others.
1876  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1877       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1878
1879    if (CXXBaseOrMemberInitializer *Value
1880        = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1881      Info.AllToInit.push_back(Value);
1882    } else if (!AnyErrors) {
1883      bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
1884      CXXBaseOrMemberInitializer *CXXBaseInit;
1885      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
1886                                       VBase, IsInheritedVirtualBase,
1887                                       CXXBaseInit)) {
1888        HadError = true;
1889        continue;
1890      }
1891
1892      Info.AllToInit.push_back(CXXBaseInit);
1893    }
1894  }
1895
1896  // Non-virtual bases.
1897  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1898       E = ClassDecl->bases_end(); Base != E; ++Base) {
1899    // Virtuals are in the virtual base list and already constructed.
1900    if (Base->isVirtual())
1901      continue;
1902
1903    if (CXXBaseOrMemberInitializer *Value
1904          = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1905      Info.AllToInit.push_back(Value);
1906    } else if (!AnyErrors) {
1907      CXXBaseOrMemberInitializer *CXXBaseInit;
1908      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
1909                                       Base, /*IsInheritedVirtualBase=*/false,
1910                                       CXXBaseInit)) {
1911        HadError = true;
1912        continue;
1913      }
1914
1915      Info.AllToInit.push_back(CXXBaseInit);
1916    }
1917  }
1918
1919  // Fields.
1920  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1921       E = ClassDecl->field_end(); Field != E; ++Field) {
1922    if ((*Field)->getType()->isIncompleteArrayType()) {
1923      assert(ClassDecl->hasFlexibleArrayMember() &&
1924             "Incomplete array type is not valid");
1925      continue;
1926    }
1927    if (CollectFieldInitializer(Info, *Field, *Field))
1928      HadError = true;
1929  }
1930
1931  NumInitializers = Info.AllToInit.size();
1932  if (NumInitializers > 0) {
1933    Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1934    CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1935      new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1936    memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
1937           NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
1938    Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1939
1940    // Constructors implicitly reference the base and member
1941    // destructors.
1942    MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
1943                                           Constructor->getParent());
1944  }
1945
1946  return HadError;
1947}
1948
1949static void *GetKeyForTopLevelField(FieldDecl *Field) {
1950  // For anonymous unions, use the class declaration as the key.
1951  if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
1952    if (RT->getDecl()->isAnonymousStructOrUnion())
1953      return static_cast<void *>(RT->getDecl());
1954  }
1955  return static_cast<void *>(Field);
1956}
1957
1958static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
1959  return Context.getCanonicalType(BaseType).getTypePtr();
1960}
1961
1962static void *GetKeyForMember(ASTContext &Context,
1963                             CXXBaseOrMemberInitializer *Member,
1964                             bool MemberMaybeAnon = false) {
1965  if (!Member->isMemberInitializer())
1966    return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
1967
1968  // For fields injected into the class via declaration of an anonymous union,
1969  // use its anonymous union class declaration as the unique key.
1970  FieldDecl *Field = Member->getMember();
1971
1972  // After SetBaseOrMemberInitializers call, Field is the anonymous union
1973  // data member of the class. Data member used in the initializer list is
1974  // in AnonUnionMember field.
1975  if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1976    Field = Member->getAnonUnionMember();
1977
1978  // If the field is a member of an anonymous struct or union, our key
1979  // is the anonymous record decl that's a direct child of the class.
1980  RecordDecl *RD = Field->getParent();
1981  if (RD->isAnonymousStructOrUnion()) {
1982    while (true) {
1983      RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
1984      if (Parent->isAnonymousStructOrUnion())
1985        RD = Parent;
1986      else
1987        break;
1988    }
1989
1990    return static_cast<void *>(RD);
1991  }
1992
1993  return static_cast<void *>(Field);
1994}
1995
1996static void
1997DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
1998                                  const CXXConstructorDecl *Constructor,
1999                                  CXXBaseOrMemberInitializer **Inits,
2000                                  unsigned NumInits) {
2001  if (Constructor->getDeclContext()->isDependentContext())
2002    return;
2003
2004  if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order)
2005        == Diagnostic::Ignored)
2006    return;
2007
2008  // Build the list of bases and members in the order that they'll
2009  // actually be initialized.  The explicit initializers should be in
2010  // this same order but may be missing things.
2011  llvm::SmallVector<const void*, 32> IdealInitKeys;
2012
2013  const CXXRecordDecl *ClassDecl = Constructor->getParent();
2014
2015  // 1. Virtual bases.
2016  for (CXXRecordDecl::base_class_const_iterator VBase =
2017       ClassDecl->vbases_begin(),
2018       E = ClassDecl->vbases_end(); VBase != E; ++VBase)
2019    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
2020
2021  // 2. Non-virtual bases.
2022  for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
2023       E = ClassDecl->bases_end(); Base != E; ++Base) {
2024    if (Base->isVirtual())
2025      continue;
2026    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
2027  }
2028
2029  // 3. Direct fields.
2030  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2031       E = ClassDecl->field_end(); Field != E; ++Field)
2032    IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
2033
2034  unsigned NumIdealInits = IdealInitKeys.size();
2035  unsigned IdealIndex = 0;
2036
2037  CXXBaseOrMemberInitializer *PrevInit = 0;
2038  for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2039    CXXBaseOrMemberInitializer *Init = Inits[InitIndex];
2040    void *InitKey = GetKeyForMember(SemaRef.Context, Init, true);
2041
2042    // Scan forward to try to find this initializer in the idealized
2043    // initializers list.
2044    for (; IdealIndex != NumIdealInits; ++IdealIndex)
2045      if (InitKey == IdealInitKeys[IdealIndex])
2046        break;
2047
2048    // If we didn't find this initializer, it must be because we
2049    // scanned past it on a previous iteration.  That can only
2050    // happen if we're out of order;  emit a warning.
2051    if (IdealIndex == NumIdealInits && PrevInit) {
2052      Sema::SemaDiagnosticBuilder D =
2053        SemaRef.Diag(PrevInit->getSourceLocation(),
2054                     diag::warn_initializer_out_of_order);
2055
2056      if (PrevInit->isMemberInitializer())
2057        D << 0 << PrevInit->getMember()->getDeclName();
2058      else
2059        D << 1 << PrevInit->getBaseClassInfo()->getType();
2060
2061      if (Init->isMemberInitializer())
2062        D << 0 << Init->getMember()->getDeclName();
2063      else
2064        D << 1 << Init->getBaseClassInfo()->getType();
2065
2066      // Move back to the initializer's location in the ideal list.
2067      for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2068        if (InitKey == IdealInitKeys[IdealIndex])
2069          break;
2070
2071      assert(IdealIndex != NumIdealInits &&
2072             "initializer not found in initializer list");
2073    }
2074
2075    PrevInit = Init;
2076  }
2077}
2078
2079namespace {
2080bool CheckRedundantInit(Sema &S,
2081                        CXXBaseOrMemberInitializer *Init,
2082                        CXXBaseOrMemberInitializer *&PrevInit) {
2083  if (!PrevInit) {
2084    PrevInit = Init;
2085    return false;
2086  }
2087
2088  if (FieldDecl *Field = Init->getMember())
2089    S.Diag(Init->getSourceLocation(),
2090           diag::err_multiple_mem_initialization)
2091      << Field->getDeclName()
2092      << Init->getSourceRange();
2093  else {
2094    Type *BaseClass = Init->getBaseClass();
2095    assert(BaseClass && "neither field nor base");
2096    S.Diag(Init->getSourceLocation(),
2097           diag::err_multiple_base_initialization)
2098      << QualType(BaseClass, 0)
2099      << Init->getSourceRange();
2100  }
2101  S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2102    << 0 << PrevInit->getSourceRange();
2103
2104  return true;
2105}
2106
2107typedef std::pair<NamedDecl *, CXXBaseOrMemberInitializer *> UnionEntry;
2108typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2109
2110bool CheckRedundantUnionInit(Sema &S,
2111                             CXXBaseOrMemberInitializer *Init,
2112                             RedundantUnionMap &Unions) {
2113  FieldDecl *Field = Init->getMember();
2114  RecordDecl *Parent = Field->getParent();
2115  if (!Parent->isAnonymousStructOrUnion())
2116    return false;
2117
2118  NamedDecl *Child = Field;
2119  do {
2120    if (Parent->isUnion()) {
2121      UnionEntry &En = Unions[Parent];
2122      if (En.first && En.first != Child) {
2123        S.Diag(Init->getSourceLocation(),
2124               diag::err_multiple_mem_union_initialization)
2125          << Field->getDeclName()
2126          << Init->getSourceRange();
2127        S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2128          << 0 << En.second->getSourceRange();
2129        return true;
2130      } else if (!En.first) {
2131        En.first = Child;
2132        En.second = Init;
2133      }
2134    }
2135
2136    Child = Parent;
2137    Parent = cast<RecordDecl>(Parent->getDeclContext());
2138  } while (Parent->isAnonymousStructOrUnion());
2139
2140  return false;
2141}
2142}
2143
2144/// ActOnMemInitializers - Handle the member initializers for a constructor.
2145void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
2146                                SourceLocation ColonLoc,
2147                                MemInitTy **meminits, unsigned NumMemInits,
2148                                bool AnyErrors) {
2149  if (!ConstructorDecl)
2150    return;
2151
2152  AdjustDeclIfTemplate(ConstructorDecl);
2153
2154  CXXConstructorDecl *Constructor
2155    = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
2156
2157  if (!Constructor) {
2158    Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2159    return;
2160  }
2161
2162  CXXBaseOrMemberInitializer **MemInits =
2163    reinterpret_cast<CXXBaseOrMemberInitializer **>(meminits);
2164
2165  // Mapping for the duplicate initializers check.
2166  // For member initializers, this is keyed with a FieldDecl*.
2167  // For base initializers, this is keyed with a Type*.
2168  llvm::DenseMap<void*, CXXBaseOrMemberInitializer *> Members;
2169
2170  // Mapping for the inconsistent anonymous-union initializers check.
2171  RedundantUnionMap MemberUnions;
2172
2173  bool HadError = false;
2174  for (unsigned i = 0; i < NumMemInits; i++) {
2175    CXXBaseOrMemberInitializer *Init = MemInits[i];
2176
2177    // Set the source order index.
2178    Init->setSourceOrder(i);
2179
2180    if (Init->isMemberInitializer()) {
2181      FieldDecl *Field = Init->getMember();
2182      if (CheckRedundantInit(*this, Init, Members[Field]) ||
2183          CheckRedundantUnionInit(*this, Init, MemberUnions))
2184        HadError = true;
2185    } else {
2186      void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2187      if (CheckRedundantInit(*this, Init, Members[Key]))
2188        HadError = true;
2189    }
2190  }
2191
2192  if (HadError)
2193    return;
2194
2195  DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
2196
2197  SetBaseOrMemberInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
2198}
2199
2200void
2201Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2202                                             CXXRecordDecl *ClassDecl) {
2203  // Ignore dependent contexts.
2204  if (ClassDecl->isDependentContext())
2205    return;
2206
2207  // FIXME: all the access-control diagnostics are positioned on the
2208  // field/base declaration.  That's probably good; that said, the
2209  // user might reasonably want to know why the destructor is being
2210  // emitted, and we currently don't say.
2211
2212  // Non-static data members.
2213  for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2214       E = ClassDecl->field_end(); I != E; ++I) {
2215    FieldDecl *Field = *I;
2216    if (Field->isInvalidDecl())
2217      continue;
2218    QualType FieldType = Context.getBaseElementType(Field->getType());
2219
2220    const RecordType* RT = FieldType->getAs<RecordType>();
2221    if (!RT)
2222      continue;
2223
2224    CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2225    if (FieldClassDecl->hasTrivialDestructor())
2226      continue;
2227
2228    CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
2229    CheckDestructorAccess(Field->getLocation(), Dtor,
2230                          PDiag(diag::err_access_dtor_field)
2231                            << Field->getDeclName()
2232                            << FieldType);
2233
2234    MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
2235  }
2236
2237  llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2238
2239  // Bases.
2240  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2241       E = ClassDecl->bases_end(); Base != E; ++Base) {
2242    // Bases are always records in a well-formed non-dependent class.
2243    const RecordType *RT = Base->getType()->getAs<RecordType>();
2244
2245    // Remember direct virtual bases.
2246    if (Base->isVirtual())
2247      DirectVirtualBases.insert(RT);
2248
2249    // Ignore trivial destructors.
2250    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2251    if (BaseClassDecl->hasTrivialDestructor())
2252      continue;
2253
2254    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
2255
2256    // FIXME: caret should be on the start of the class name
2257    CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
2258                          PDiag(diag::err_access_dtor_base)
2259                            << Base->getType()
2260                            << Base->getSourceRange());
2261
2262    MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
2263  }
2264
2265  // Virtual bases.
2266  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2267       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2268
2269    // Bases are always records in a well-formed non-dependent class.
2270    const RecordType *RT = VBase->getType()->getAs<RecordType>();
2271
2272    // Ignore direct virtual bases.
2273    if (DirectVirtualBases.count(RT))
2274      continue;
2275
2276    // Ignore trivial destructors.
2277    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2278    if (BaseClassDecl->hasTrivialDestructor())
2279      continue;
2280
2281    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
2282    CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
2283                          PDiag(diag::err_access_dtor_vbase)
2284                            << VBase->getType());
2285
2286    MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
2287  }
2288}
2289
2290void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
2291  if (!CDtorDecl)
2292    return;
2293
2294  if (CXXConstructorDecl *Constructor
2295      = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
2296    SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
2297}
2298
2299bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2300                                  unsigned DiagID, AbstractDiagSelID SelID,
2301                                  const CXXRecordDecl *CurrentRD) {
2302  if (SelID == -1)
2303    return RequireNonAbstractType(Loc, T,
2304                                  PDiag(DiagID), CurrentRD);
2305  else
2306    return RequireNonAbstractType(Loc, T,
2307                                  PDiag(DiagID) << SelID, CurrentRD);
2308}
2309
2310bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2311                                  const PartialDiagnostic &PD,
2312                                  const CXXRecordDecl *CurrentRD) {
2313  if (!getLangOptions().CPlusPlus)
2314    return false;
2315
2316  if (const ArrayType *AT = Context.getAsArrayType(T))
2317    return RequireNonAbstractType(Loc, AT->getElementType(), PD,
2318                                  CurrentRD);
2319
2320  if (const PointerType *PT = T->getAs<PointerType>()) {
2321    // Find the innermost pointer type.
2322    while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
2323      PT = T;
2324
2325    if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
2326      return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
2327  }
2328
2329  const RecordType *RT = T->getAs<RecordType>();
2330  if (!RT)
2331    return false;
2332
2333  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2334
2335  if (CurrentRD && CurrentRD != RD)
2336    return false;
2337
2338  // FIXME: is this reasonable?  It matches current behavior, but....
2339  if (!RD->getDefinition())
2340    return false;
2341
2342  if (!RD->isAbstract())
2343    return false;
2344
2345  Diag(Loc, PD) << RD->getDeclName();
2346
2347  // Check if we've already emitted the list of pure virtual functions for this
2348  // class.
2349  if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
2350    return true;
2351
2352  CXXFinalOverriderMap FinalOverriders;
2353  RD->getFinalOverriders(FinalOverriders);
2354
2355  // Keep a set of seen pure methods so we won't diagnose the same method
2356  // more than once.
2357  llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2358
2359  for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2360                                   MEnd = FinalOverriders.end();
2361       M != MEnd;
2362       ++M) {
2363    for (OverridingMethods::iterator SO = M->second.begin(),
2364                                  SOEnd = M->second.end();
2365         SO != SOEnd; ++SO) {
2366      // C++ [class.abstract]p4:
2367      //   A class is abstract if it contains or inherits at least one
2368      //   pure virtual function for which the final overrider is pure
2369      //   virtual.
2370
2371      //
2372      if (SO->second.size() != 1)
2373        continue;
2374
2375      if (!SO->second.front().Method->isPure())
2376        continue;
2377
2378      if (!SeenPureMethods.insert(SO->second.front().Method))
2379        continue;
2380
2381      Diag(SO->second.front().Method->getLocation(),
2382           diag::note_pure_virtual_function)
2383        << SO->second.front().Method->getDeclName();
2384    }
2385  }
2386
2387  if (!PureVirtualClassDiagSet)
2388    PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2389  PureVirtualClassDiagSet->insert(RD);
2390
2391  return true;
2392}
2393
2394namespace {
2395  class AbstractClassUsageDiagnoser
2396    : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
2397    Sema &SemaRef;
2398    CXXRecordDecl *AbstractClass;
2399
2400    bool VisitDeclContext(const DeclContext *DC) {
2401      bool Invalid = false;
2402
2403      for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
2404           E = DC->decls_end(); I != E; ++I)
2405        Invalid |= Visit(*I);
2406
2407      return Invalid;
2408    }
2409
2410  public:
2411    AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
2412      : SemaRef(SemaRef), AbstractClass(ac) {
2413        Visit(SemaRef.Context.getTranslationUnitDecl());
2414    }
2415
2416    bool VisitFunctionDecl(const FunctionDecl *FD) {
2417      if (FD->isThisDeclarationADefinition()) {
2418        // No need to do the check if we're in a definition, because it requires
2419        // that the return/param types are complete.
2420        // because that requires
2421        return VisitDeclContext(FD);
2422      }
2423
2424      // Check the return type.
2425      QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
2426      bool Invalid =
2427        SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
2428                                       diag::err_abstract_type_in_decl,
2429                                       Sema::AbstractReturnType,
2430                                       AbstractClass);
2431
2432      for (FunctionDecl::param_const_iterator I = FD->param_begin(),
2433           E = FD->param_end(); I != E; ++I) {
2434        const ParmVarDecl *VD = *I;
2435        Invalid |=
2436          SemaRef.RequireNonAbstractType(VD->getLocation(),
2437                                         VD->getOriginalType(),
2438                                         diag::err_abstract_type_in_decl,
2439                                         Sema::AbstractParamType,
2440                                         AbstractClass);
2441      }
2442
2443      return Invalid;
2444    }
2445
2446    bool VisitDecl(const Decl* D) {
2447      if (const DeclContext *DC = dyn_cast<DeclContext>(D))
2448        return VisitDeclContext(DC);
2449
2450      return false;
2451    }
2452  };
2453}
2454
2455/// \brief Perform semantic checks on a class definition that has been
2456/// completing, introducing implicitly-declared members, checking for
2457/// abstract types, etc.
2458void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
2459  if (!Record || Record->isInvalidDecl())
2460    return;
2461
2462  if (!Record->isDependentType())
2463    AddImplicitlyDeclaredMembersToClass(Record);
2464
2465  if (Record->isInvalidDecl())
2466    return;
2467
2468  // Set access bits correctly on the directly-declared conversions.
2469  UnresolvedSetImpl *Convs = Record->getConversionFunctions();
2470  for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I)
2471    Convs->setAccess(I, (*I)->getAccess());
2472
2473  // Determine whether we need to check for final overriders. We do
2474  // this either when there are virtual base classes (in which case we
2475  // may end up finding multiple final overriders for a given virtual
2476  // function) or any of the base classes is abstract (in which case
2477  // we might detect that this class is abstract).
2478  bool CheckFinalOverriders = false;
2479  if (Record->isPolymorphic() && !Record->isInvalidDecl() &&
2480      !Record->isDependentType()) {
2481    if (Record->getNumVBases())
2482      CheckFinalOverriders = true;
2483    else if (!Record->isAbstract()) {
2484      for (CXXRecordDecl::base_class_const_iterator B = Record->bases_begin(),
2485                                                 BEnd = Record->bases_end();
2486           B != BEnd; ++B) {
2487        CXXRecordDecl *BaseDecl
2488          = cast<CXXRecordDecl>(B->getType()->getAs<RecordType>()->getDecl());
2489        if (BaseDecl->isAbstract()) {
2490          CheckFinalOverriders = true;
2491          break;
2492        }
2493      }
2494    }
2495  }
2496
2497  if (CheckFinalOverriders) {
2498    CXXFinalOverriderMap FinalOverriders;
2499    Record->getFinalOverriders(FinalOverriders);
2500
2501    for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2502                                     MEnd = FinalOverriders.end();
2503         M != MEnd; ++M) {
2504      for (OverridingMethods::iterator SO = M->second.begin(),
2505                                    SOEnd = M->second.end();
2506           SO != SOEnd; ++SO) {
2507        assert(SO->second.size() > 0 &&
2508               "All virtual functions have overridding virtual functions");
2509        if (SO->second.size() == 1) {
2510          // C++ [class.abstract]p4:
2511          //   A class is abstract if it contains or inherits at least one
2512          //   pure virtual function for which the final overrider is pure
2513          //   virtual.
2514          if (SO->second.front().Method->isPure())
2515            Record->setAbstract(true);
2516          continue;
2517        }
2518
2519        // C++ [class.virtual]p2:
2520        //   In a derived class, if a virtual member function of a base
2521        //   class subobject has more than one final overrider the
2522        //   program is ill-formed.
2523        Diag(Record->getLocation(), diag::err_multiple_final_overriders)
2524          << (NamedDecl *)M->first << Record;
2525        Diag(M->first->getLocation(), diag::note_overridden_virtual_function);
2526        for (OverridingMethods::overriding_iterator OM = SO->second.begin(),
2527                                                 OMEnd = SO->second.end();
2528             OM != OMEnd; ++OM)
2529          Diag(OM->Method->getLocation(), diag::note_final_overrider)
2530            << (NamedDecl *)M->first << OM->Method->getParent();
2531
2532        Record->setInvalidDecl();
2533      }
2534    }
2535  }
2536
2537  if (Record->isAbstract() && !Record->isInvalidDecl())
2538    (void)AbstractClassUsageDiagnoser(*this, Record);
2539
2540  // If this is not an aggregate type and has no user-declared constructor,
2541  // complain about any non-static data members of reference or const scalar
2542  // type, since they will never get initializers.
2543  if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2544      !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2545    bool Complained = false;
2546    for (RecordDecl::field_iterator F = Record->field_begin(),
2547                                 FEnd = Record->field_end();
2548         F != FEnd; ++F) {
2549      if (F->getType()->isReferenceType() ||
2550          (F->getType().isConstQualified() && F->getType()->isScalarType())) {
2551        if (!Complained) {
2552          Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2553            << Record->getTagKind() << Record;
2554          Complained = true;
2555        }
2556
2557        Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2558          << F->getType()->isReferenceType()
2559          << F->getDeclName();
2560      }
2561    }
2562  }
2563
2564  if (Record->isDynamicClass())
2565    DynamicClasses.push_back(Record);
2566}
2567
2568void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
2569                                             DeclPtrTy TagDecl,
2570                                             SourceLocation LBrac,
2571                                             SourceLocation RBrac,
2572                                             AttributeList *AttrList) {
2573  if (!TagDecl)
2574    return;
2575
2576  AdjustDeclIfTemplate(TagDecl);
2577
2578  ActOnFields(S, RLoc, TagDecl,
2579              (DeclPtrTy*)FieldCollector->getCurFields(),
2580              FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
2581
2582  CheckCompletedCXXClass(
2583                        dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
2584}
2585
2586namespace {
2587  /// \brief Helper class that collects exception specifications for
2588  /// implicitly-declared special member functions.
2589  class ImplicitExceptionSpecification {
2590    ASTContext &Context;
2591    bool AllowsAllExceptions;
2592    llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2593    llvm::SmallVector<QualType, 4> Exceptions;
2594
2595  public:
2596    explicit ImplicitExceptionSpecification(ASTContext &Context)
2597      : Context(Context), AllowsAllExceptions(false) { }
2598
2599    /// \brief Whether the special member function should have any
2600    /// exception specification at all.
2601    bool hasExceptionSpecification() const {
2602      return !AllowsAllExceptions;
2603    }
2604
2605    /// \brief Whether the special member function should have a
2606    /// throw(...) exception specification (a Microsoft extension).
2607    bool hasAnyExceptionSpecification() const {
2608      return false;
2609    }
2610
2611    /// \brief The number of exceptions in the exception specification.
2612    unsigned size() const { return Exceptions.size(); }
2613
2614    /// \brief The set of exceptions in the exception specification.
2615    const QualType *data() const { return Exceptions.data(); }
2616
2617    /// \brief Note that
2618    void CalledDecl(CXXMethodDecl *Method) {
2619      // If we already know that we allow all exceptions, do nothing.
2620      if (AllowsAllExceptions || !Method)
2621        return;
2622
2623      const FunctionProtoType *Proto
2624        = Method->getType()->getAs<FunctionProtoType>();
2625
2626      // If this function can throw any exceptions, make a note of that.
2627      if (!Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec()) {
2628        AllowsAllExceptions = true;
2629        ExceptionsSeen.clear();
2630        Exceptions.clear();
2631        return;
2632      }
2633
2634      // Record the exceptions in this function's exception specification.
2635      for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
2636                                              EEnd = Proto->exception_end();
2637           E != EEnd; ++E)
2638        if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
2639          Exceptions.push_back(*E);
2640    }
2641  };
2642}
2643
2644
2645/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2646/// special functions, such as the default constructor, copy
2647/// constructor, or destructor, to the given C++ class (C++
2648/// [special]p1).  This routine can only be executed just before the
2649/// definition of the class is complete.
2650void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
2651  if (!ClassDecl->hasUserDeclaredConstructor())
2652    ++ASTContext::NumImplicitDefaultConstructors;
2653
2654  if (!ClassDecl->hasUserDeclaredCopyConstructor())
2655    ++ASTContext::NumImplicitCopyConstructors;
2656
2657  if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2658    ++ASTContext::NumImplicitCopyAssignmentOperators;
2659
2660    // If we have a dynamic class, then the copy assignment operator may be
2661    // virtual, so we have to declare it immediately. This ensures that, e.g.,
2662    // it shows up in the right place in the vtable and that we diagnose
2663    // problems with the implicit exception specification.
2664    if (ClassDecl->isDynamicClass())
2665      DeclareImplicitCopyAssignment(ClassDecl);
2666  }
2667
2668  if (!ClassDecl->hasUserDeclaredDestructor()) {
2669    ++ASTContext::NumImplicitDestructors;
2670
2671    // If we have a dynamic class, then the destructor may be virtual, so we
2672    // have to declare the destructor immediately. This ensures that, e.g., it
2673    // shows up in the right place in the vtable and that we diagnose problems
2674    // with the implicit exception specification.
2675    if (ClassDecl->isDynamicClass())
2676      DeclareImplicitDestructor(ClassDecl);
2677  }
2678}
2679
2680void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
2681  Decl *D = TemplateD.getAs<Decl>();
2682  if (!D)
2683    return;
2684
2685  TemplateParameterList *Params = 0;
2686  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2687    Params = Template->getTemplateParameters();
2688  else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2689           = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2690    Params = PartialSpec->getTemplateParameters();
2691  else
2692    return;
2693
2694  for (TemplateParameterList::iterator Param = Params->begin(),
2695                                    ParamEnd = Params->end();
2696       Param != ParamEnd; ++Param) {
2697    NamedDecl *Named = cast<NamedDecl>(*Param);
2698    if (Named->getDeclName()) {
2699      S->AddDecl(DeclPtrTy::make(Named));
2700      IdResolver.AddDecl(Named);
2701    }
2702  }
2703}
2704
2705void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2706  if (!RecordD) return;
2707  AdjustDeclIfTemplate(RecordD);
2708  CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>());
2709  PushDeclContext(S, Record);
2710}
2711
2712void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2713  if (!RecordD) return;
2714  PopDeclContext();
2715}
2716
2717/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2718/// parsing a top-level (non-nested) C++ class, and we are now
2719/// parsing those parts of the given Method declaration that could
2720/// not be parsed earlier (C++ [class.mem]p2), such as default
2721/// arguments. This action should enter the scope of the given
2722/// Method declaration as if we had just parsed the qualified method
2723/// name. However, it should not bring the parameters into scope;
2724/// that will be performed by ActOnDelayedCXXMethodParameter.
2725void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
2726}
2727
2728/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2729/// C++ method declaration. We're (re-)introducing the given
2730/// function parameter into scope for use in parsing later parts of
2731/// the method declaration. For example, we could see an
2732/// ActOnParamDefaultArgument event for this parameter.
2733void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
2734  if (!ParamD)
2735    return;
2736
2737  ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
2738
2739  // If this parameter has an unparsed default argument, clear it out
2740  // to make way for the parsed default argument.
2741  if (Param->hasUnparsedDefaultArg())
2742    Param->setDefaultArg(0);
2743
2744  S->AddDecl(DeclPtrTy::make(Param));
2745  if (Param->getDeclName())
2746    IdResolver.AddDecl(Param);
2747}
2748
2749/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2750/// processing the delayed method declaration for Method. The method
2751/// declaration is now considered finished. There may be a separate
2752/// ActOnStartOfFunctionDef action later (not necessarily
2753/// immediately!) for this method, if it was also defined inside the
2754/// class body.
2755void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
2756  if (!MethodD)
2757    return;
2758
2759  AdjustDeclIfTemplate(MethodD);
2760
2761  FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
2762
2763  // Now that we have our default arguments, check the constructor
2764  // again. It could produce additional diagnostics or affect whether
2765  // the class has implicitly-declared destructors, among other
2766  // things.
2767  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2768    CheckConstructor(Constructor);
2769
2770  // Check the default arguments, which we may have added.
2771  if (!Method->isInvalidDecl())
2772    CheckCXXDefaultArguments(Method);
2773}
2774
2775/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
2776/// the well-formedness of the constructor declarator @p D with type @p
2777/// R. If there are any errors in the declarator, this routine will
2778/// emit diagnostics and set the invalid bit to true.  In any case, the type
2779/// will be updated to reflect a well-formed type for the constructor and
2780/// returned.
2781QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2782                                          FunctionDecl::StorageClass &SC) {
2783  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
2784
2785  // C++ [class.ctor]p3:
2786  //   A constructor shall not be virtual (10.3) or static (9.4). A
2787  //   constructor can be invoked for a const, volatile or const
2788  //   volatile object. A constructor shall not be declared const,
2789  //   volatile, or const volatile (9.3.2).
2790  if (isVirtual) {
2791    if (!D.isInvalidType())
2792      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2793        << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2794        << SourceRange(D.getIdentifierLoc());
2795    D.setInvalidType();
2796  }
2797  if (SC == FunctionDecl::Static) {
2798    if (!D.isInvalidType())
2799      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2800        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2801        << SourceRange(D.getIdentifierLoc());
2802    D.setInvalidType();
2803    SC = FunctionDecl::None;
2804  }
2805
2806  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2807  if (FTI.TypeQuals != 0) {
2808    if (FTI.TypeQuals & Qualifiers::Const)
2809      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2810        << "const" << SourceRange(D.getIdentifierLoc());
2811    if (FTI.TypeQuals & Qualifiers::Volatile)
2812      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2813        << "volatile" << SourceRange(D.getIdentifierLoc());
2814    if (FTI.TypeQuals & Qualifiers::Restrict)
2815      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2816        << "restrict" << SourceRange(D.getIdentifierLoc());
2817  }
2818
2819  // Rebuild the function type "R" without any type qualifiers (in
2820  // case any of the errors above fired) and with "void" as the
2821  // return type, since constructors don't have return types.
2822  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
2823  return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2824                                 Proto->getNumArgs(),
2825                                 Proto->isVariadic(), 0,
2826                                 Proto->hasExceptionSpec(),
2827                                 Proto->hasAnyExceptionSpec(),
2828                                 Proto->getNumExceptions(),
2829                                 Proto->exception_begin(),
2830                                 Proto->getExtInfo());
2831}
2832
2833/// CheckConstructor - Checks a fully-formed constructor for
2834/// well-formedness, issuing any diagnostics required. Returns true if
2835/// the constructor declarator is invalid.
2836void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
2837  CXXRecordDecl *ClassDecl
2838    = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2839  if (!ClassDecl)
2840    return Constructor->setInvalidDecl();
2841
2842  // C++ [class.copy]p3:
2843  //   A declaration of a constructor for a class X is ill-formed if
2844  //   its first parameter is of type (optionally cv-qualified) X and
2845  //   either there are no other parameters or else all other
2846  //   parameters have default arguments.
2847  if (!Constructor->isInvalidDecl() &&
2848      ((Constructor->getNumParams() == 1) ||
2849       (Constructor->getNumParams() > 1 &&
2850        Constructor->getParamDecl(1)->hasDefaultArg())) &&
2851      Constructor->getTemplateSpecializationKind()
2852                                              != TSK_ImplicitInstantiation) {
2853    QualType ParamType = Constructor->getParamDecl(0)->getType();
2854    QualType ClassTy = Context.getTagDeclType(ClassDecl);
2855    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
2856      SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2857      const char *ConstRef
2858        = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
2859                                                        : " const &";
2860      Diag(ParamLoc, diag::err_constructor_byvalue_arg)
2861        << FixItHint::CreateInsertion(ParamLoc, ConstRef);
2862
2863      // FIXME: Rather that making the constructor invalid, we should endeavor
2864      // to fix the type.
2865      Constructor->setInvalidDecl();
2866    }
2867  }
2868
2869  // Notify the class that we've added a constructor.  In principle we
2870  // don't need to do this for out-of-line declarations; in practice
2871  // we only instantiate the most recent declaration of a method, so
2872  // we have to call this for everything but friends.
2873  if (!Constructor->getFriendObjectKind())
2874    ClassDecl->addedConstructor(Context, Constructor);
2875}
2876
2877/// CheckDestructor - Checks a fully-formed destructor for well-formedness,
2878/// issuing any diagnostics required. Returns true on error.
2879bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
2880  CXXRecordDecl *RD = Destructor->getParent();
2881
2882  if (Destructor->isVirtual()) {
2883    SourceLocation Loc;
2884
2885    if (!Destructor->isImplicit())
2886      Loc = Destructor->getLocation();
2887    else
2888      Loc = RD->getLocation();
2889
2890    // If we have a virtual destructor, look up the deallocation function
2891    FunctionDecl *OperatorDelete = 0;
2892    DeclarationName Name =
2893    Context.DeclarationNames.getCXXOperatorName(OO_Delete);
2894    if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2895      return true;
2896
2897    MarkDeclarationReferenced(Loc, OperatorDelete);
2898
2899    Destructor->setOperatorDelete(OperatorDelete);
2900  }
2901
2902  return false;
2903}
2904
2905static inline bool
2906FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2907  return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2908          FTI.ArgInfo[0].Param &&
2909          FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2910}
2911
2912/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2913/// the well-formednes of the destructor declarator @p D with type @p
2914/// R. If there are any errors in the declarator, this routine will
2915/// emit diagnostics and set the declarator to invalid.  Even if this happens,
2916/// will be updated to reflect a well-formed type for the destructor and
2917/// returned.
2918QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
2919                                         FunctionDecl::StorageClass& SC) {
2920  // C++ [class.dtor]p1:
2921  //   [...] A typedef-name that names a class is a class-name
2922  //   (7.1.3); however, a typedef-name that names a class shall not
2923  //   be used as the identifier in the declarator for a destructor
2924  //   declaration.
2925  QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
2926  if (isa<TypedefType>(DeclaratorType))
2927    Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
2928      << DeclaratorType;
2929
2930  // C++ [class.dtor]p2:
2931  //   A destructor is used to destroy objects of its class type. A
2932  //   destructor takes no parameters, and no return type can be
2933  //   specified for it (not even void). The address of a destructor
2934  //   shall not be taken. A destructor shall not be static. A
2935  //   destructor can be invoked for a const, volatile or const
2936  //   volatile object. A destructor shall not be declared const,
2937  //   volatile or const volatile (9.3.2).
2938  if (SC == FunctionDecl::Static) {
2939    if (!D.isInvalidType())
2940      Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2941        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2942        << SourceRange(D.getIdentifierLoc())
2943        << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
2944
2945    SC = FunctionDecl::None;
2946  }
2947  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
2948    // Destructors don't have return types, but the parser will
2949    // happily parse something like:
2950    //
2951    //   class X {
2952    //     float ~X();
2953    //   };
2954    //
2955    // The return type will be eliminated later.
2956    Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2957      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2958      << SourceRange(D.getIdentifierLoc());
2959  }
2960
2961  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2962  if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
2963    if (FTI.TypeQuals & Qualifiers::Const)
2964      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2965        << "const" << SourceRange(D.getIdentifierLoc());
2966    if (FTI.TypeQuals & Qualifiers::Volatile)
2967      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2968        << "volatile" << SourceRange(D.getIdentifierLoc());
2969    if (FTI.TypeQuals & Qualifiers::Restrict)
2970      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2971        << "restrict" << SourceRange(D.getIdentifierLoc());
2972    D.setInvalidType();
2973  }
2974
2975  // Make sure we don't have any parameters.
2976  if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
2977    Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2978
2979    // Delete the parameters.
2980    FTI.freeArgs();
2981    D.setInvalidType();
2982  }
2983
2984  // Make sure the destructor isn't variadic.
2985  if (FTI.isVariadic) {
2986    Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
2987    D.setInvalidType();
2988  }
2989
2990  // Rebuild the function type "R" without any type qualifiers or
2991  // parameters (in case any of the errors above fired) and with
2992  // "void" as the return type, since destructors don't have return
2993  // types.
2994  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
2995  if (!Proto)
2996    return QualType();
2997
2998  return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0,
2999                                 Proto->hasExceptionSpec(),
3000                                 Proto->hasAnyExceptionSpec(),
3001                                 Proto->getNumExceptions(),
3002                                 Proto->exception_begin(),
3003                                 Proto->getExtInfo());
3004}
3005
3006/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3007/// well-formednes of the conversion function declarator @p D with
3008/// type @p R. If there are any errors in the declarator, this routine
3009/// will emit diagnostics and return true. Otherwise, it will return
3010/// false. Either way, the type @p R will be updated to reflect a
3011/// well-formed type for the conversion operator.
3012void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
3013                                     FunctionDecl::StorageClass& SC) {
3014  // C++ [class.conv.fct]p1:
3015  //   Neither parameter types nor return type can be specified. The
3016  //   type of a conversion function (8.3.5) is "function taking no
3017  //   parameter returning conversion-type-id."
3018  if (SC == FunctionDecl::Static) {
3019    if (!D.isInvalidType())
3020      Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3021        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3022        << SourceRange(D.getIdentifierLoc());
3023    D.setInvalidType();
3024    SC = FunctionDecl::None;
3025  }
3026
3027  QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3028
3029  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
3030    // Conversion functions don't have return types, but the parser will
3031    // happily parse something like:
3032    //
3033    //   class X {
3034    //     float operator bool();
3035    //   };
3036    //
3037    // The return type will be changed later anyway.
3038    Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3039      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3040      << SourceRange(D.getIdentifierLoc());
3041    D.setInvalidType();
3042  }
3043
3044  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3045
3046  // Make sure we don't have any parameters.
3047  if (Proto->getNumArgs() > 0) {
3048    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3049
3050    // Delete the parameters.
3051    D.getTypeObject(0).Fun.freeArgs();
3052    D.setInvalidType();
3053  } else if (Proto->isVariadic()) {
3054    Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
3055    D.setInvalidType();
3056  }
3057
3058  // Diagnose "&operator bool()" and other such nonsense.  This
3059  // is actually a gcc extension which we don't support.
3060  if (Proto->getResultType() != ConvType) {
3061    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3062      << Proto->getResultType();
3063    D.setInvalidType();
3064    ConvType = Proto->getResultType();
3065  }
3066
3067  // C++ [class.conv.fct]p4:
3068  //   The conversion-type-id shall not represent a function type nor
3069  //   an array type.
3070  if (ConvType->isArrayType()) {
3071    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3072    ConvType = Context.getPointerType(ConvType);
3073    D.setInvalidType();
3074  } else if (ConvType->isFunctionType()) {
3075    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3076    ConvType = Context.getPointerType(ConvType);
3077    D.setInvalidType();
3078  }
3079
3080  // Rebuild the function type "R" without any parameters (in case any
3081  // of the errors above fired) and with the conversion type as the
3082  // return type.
3083  if (D.isInvalidType()) {
3084    R = Context.getFunctionType(ConvType, 0, 0, false,
3085                                Proto->getTypeQuals(),
3086                                Proto->hasExceptionSpec(),
3087                                Proto->hasAnyExceptionSpec(),
3088                                Proto->getNumExceptions(),
3089                                Proto->exception_begin(),
3090                                Proto->getExtInfo());
3091  }
3092
3093  // C++0x explicit conversion operators.
3094  if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
3095    Diag(D.getDeclSpec().getExplicitSpecLoc(),
3096         diag::warn_explicit_conversion_functions)
3097      << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
3098}
3099
3100/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3101/// the declaration of the given C++ conversion function. This routine
3102/// is responsible for recording the conversion function in the C++
3103/// class, if possible.
3104Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
3105  assert(Conversion && "Expected to receive a conversion function declaration");
3106
3107  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
3108
3109  // Make sure we aren't redeclaring the conversion function.
3110  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
3111
3112  // C++ [class.conv.fct]p1:
3113  //   [...] A conversion function is never used to convert a
3114  //   (possibly cv-qualified) object to the (possibly cv-qualified)
3115  //   same object type (or a reference to it), to a (possibly
3116  //   cv-qualified) base class of that type (or a reference to it),
3117  //   or to (possibly cv-qualified) void.
3118  // FIXME: Suppress this warning if the conversion function ends up being a
3119  // virtual function that overrides a virtual function in a base class.
3120  QualType ClassType
3121    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
3122  if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
3123    ConvType = ConvTypeRef->getPointeeType();
3124  if (ConvType->isRecordType()) {
3125    ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3126    if (ConvType == ClassType)
3127      Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
3128        << ClassType;
3129    else if (IsDerivedFrom(ClassType, ConvType))
3130      Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
3131        <<  ClassType << ConvType;
3132  } else if (ConvType->isVoidType()) {
3133    Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
3134      << ClassType << ConvType;
3135  }
3136
3137  if (Conversion->getPrimaryTemplate()) {
3138    // ignore specializations
3139  } else if (Conversion->getPreviousDeclaration()) {
3140    if (FunctionTemplateDecl *ConversionTemplate
3141                                  = Conversion->getDescribedFunctionTemplate()) {
3142      if (ClassDecl->replaceConversion(
3143                                   ConversionTemplate->getPreviousDeclaration(),
3144                                       ConversionTemplate))
3145        return DeclPtrTy::make(ConversionTemplate);
3146    } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(),
3147                                            Conversion))
3148      return DeclPtrTy::make(Conversion);
3149    assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
3150  } else if (FunctionTemplateDecl *ConversionTemplate
3151               = Conversion->getDescribedFunctionTemplate())
3152    ClassDecl->addConversionFunction(ConversionTemplate);
3153  else
3154    ClassDecl->addConversionFunction(Conversion);
3155
3156  return DeclPtrTy::make(Conversion);
3157}
3158
3159//===----------------------------------------------------------------------===//
3160// Namespace Handling
3161//===----------------------------------------------------------------------===//
3162
3163/// ActOnStartNamespaceDef - This is called at the start of a namespace
3164/// definition.
3165Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
3166                                             SourceLocation IdentLoc,
3167                                             IdentifierInfo *II,
3168                                             SourceLocation LBrace,
3169                                             AttributeList *AttrList) {
3170  NamespaceDecl *Namespc =
3171      NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
3172  Namespc->setLBracLoc(LBrace);
3173
3174  Scope *DeclRegionScope = NamespcScope->getParent();
3175
3176  ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3177
3178  if (II) {
3179    // C++ [namespace.def]p2:
3180    // The identifier in an original-namespace-definition shall not have been
3181    // previously defined in the declarative region in which the
3182    // original-namespace-definition appears. The identifier in an
3183    // original-namespace-definition is the name of the namespace. Subsequently
3184    // in that declarative region, it is treated as an original-namespace-name.
3185
3186    NamedDecl *PrevDecl
3187      = LookupSingleName(DeclRegionScope, II, IdentLoc, LookupOrdinaryName,
3188                         ForRedeclaration);
3189
3190    if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3191      // This is an extended namespace definition.
3192      // Attach this namespace decl to the chain of extended namespace
3193      // definitions.
3194      OrigNS->setNextNamespace(Namespc);
3195      Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
3196
3197      // Remove the previous declaration from the scope.
3198      if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
3199        IdResolver.RemoveDecl(OrigNS);
3200        DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
3201      }
3202    } else if (PrevDecl) {
3203      // This is an invalid name redefinition.
3204      Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3205       << Namespc->getDeclName();
3206      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3207      Namespc->setInvalidDecl();
3208      // Continue on to push Namespc as current DeclContext and return it.
3209    } else if (II->isStr("std") &&
3210               CurContext->getLookupContext()->isTranslationUnit()) {
3211      // This is the first "real" definition of the namespace "std", so update
3212      // our cache of the "std" namespace to point at this definition.
3213      if (StdNamespace) {
3214        // We had already defined a dummy namespace "std". Link this new
3215        // namespace definition to the dummy namespace "std".
3216        StdNamespace->setNextNamespace(Namespc);
3217        StdNamespace->setLocation(IdentLoc);
3218        Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
3219      }
3220
3221      // Make our StdNamespace cache point at the first real definition of the
3222      // "std" namespace.
3223      StdNamespace = Namespc;
3224    }
3225
3226    PushOnScopeChains(Namespc, DeclRegionScope);
3227  } else {
3228    // Anonymous namespaces.
3229    assert(Namespc->isAnonymousNamespace());
3230
3231    // Link the anonymous namespace into its parent.
3232    NamespaceDecl *PrevDecl;
3233    DeclContext *Parent = CurContext->getLookupContext();
3234    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3235      PrevDecl = TU->getAnonymousNamespace();
3236      TU->setAnonymousNamespace(Namespc);
3237    } else {
3238      NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3239      PrevDecl = ND->getAnonymousNamespace();
3240      ND->setAnonymousNamespace(Namespc);
3241    }
3242
3243    // Link the anonymous namespace with its previous declaration.
3244    if (PrevDecl) {
3245      assert(PrevDecl->isAnonymousNamespace());
3246      assert(!PrevDecl->getNextNamespace());
3247      Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3248      PrevDecl->setNextNamespace(Namespc);
3249    }
3250
3251    CurContext->addDecl(Namespc);
3252
3253    // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
3254    //   behaves as if it were replaced by
3255    //     namespace unique { /* empty body */ }
3256    //     using namespace unique;
3257    //     namespace unique { namespace-body }
3258    //   where all occurrences of 'unique' in a translation unit are
3259    //   replaced by the same identifier and this identifier differs
3260    //   from all other identifiers in the entire program.
3261
3262    // We just create the namespace with an empty name and then add an
3263    // implicit using declaration, just like the standard suggests.
3264    //
3265    // CodeGen enforces the "universally unique" aspect by giving all
3266    // declarations semantically contained within an anonymous
3267    // namespace internal linkage.
3268
3269    if (!PrevDecl) {
3270      UsingDirectiveDecl* UD
3271        = UsingDirectiveDecl::Create(Context, CurContext,
3272                                     /* 'using' */ LBrace,
3273                                     /* 'namespace' */ SourceLocation(),
3274                                     /* qualifier */ SourceRange(),
3275                                     /* NNS */ NULL,
3276                                     /* identifier */ SourceLocation(),
3277                                     Namespc,
3278                                     /* Ancestor */ CurContext);
3279      UD->setImplicit();
3280      CurContext->addDecl(UD);
3281    }
3282  }
3283
3284  // Although we could have an invalid decl (i.e. the namespace name is a
3285  // redefinition), push it as current DeclContext and try to continue parsing.
3286  // FIXME: We should be able to push Namespc here, so that the each DeclContext
3287  // for the namespace has the declarations that showed up in that particular
3288  // namespace definition.
3289  PushDeclContext(NamespcScope, Namespc);
3290  return DeclPtrTy::make(Namespc);
3291}
3292
3293/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3294/// is a namespace alias, returns the namespace it points to.
3295static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3296  if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3297    return AD->getNamespace();
3298  return dyn_cast_or_null<NamespaceDecl>(D);
3299}
3300
3301/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3302/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
3303void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
3304  Decl *Dcl = D.getAs<Decl>();
3305  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3306  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3307  Namespc->setRBracLoc(RBrace);
3308  PopDeclContext();
3309}
3310
3311/// \brief Retrieve the special "std" namespace, which may require us to
3312/// implicitly define the namespace.
3313NamespaceDecl *Sema::getStdNamespace() {
3314  if (!StdNamespace) {
3315    // The "std" namespace has not yet been defined, so build one implicitly.
3316    StdNamespace = NamespaceDecl::Create(Context,
3317                                         Context.getTranslationUnitDecl(),
3318                                         SourceLocation(),
3319                                         &PP.getIdentifierTable().get("std"));
3320    StdNamespace->setImplicit(true);
3321  }
3322
3323  return StdNamespace;
3324}
3325
3326Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
3327                                          SourceLocation UsingLoc,
3328                                          SourceLocation NamespcLoc,
3329                                          CXXScopeSpec &SS,
3330                                          SourceLocation IdentLoc,
3331                                          IdentifierInfo *NamespcName,
3332                                          AttributeList *AttrList) {
3333  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3334  assert(NamespcName && "Invalid NamespcName.");
3335  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
3336  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
3337
3338  UsingDirectiveDecl *UDir = 0;
3339  NestedNameSpecifier *Qualifier = 0;
3340  if (SS.isSet())
3341    Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3342
3343  // Lookup namespace name.
3344  LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3345  LookupParsedName(R, S, &SS);
3346  if (R.isAmbiguous())
3347    return DeclPtrTy();
3348
3349  if (R.empty()) {
3350    // Allow "using namespace std;" or "using namespace ::std;" even if
3351    // "std" hasn't been defined yet, for GCC compatibility.
3352    if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3353        NamespcName->isStr("std")) {
3354      Diag(IdentLoc, diag::ext_using_undefined_std);
3355      R.addDecl(getStdNamespace());
3356      R.resolveKind();
3357    }
3358    // Otherwise, attempt typo correction.
3359    else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3360                                                       CTC_NoKeywords, 0)) {
3361      if (R.getAsSingle<NamespaceDecl>() ||
3362          R.getAsSingle<NamespaceAliasDecl>()) {
3363        if (DeclContext *DC = computeDeclContext(SS, false))
3364          Diag(IdentLoc, diag::err_using_directive_member_suggest)
3365            << NamespcName << DC << Corrected << SS.getRange()
3366            << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3367        else
3368          Diag(IdentLoc, diag::err_using_directive_suggest)
3369            << NamespcName << Corrected
3370            << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3371        Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3372          << Corrected;
3373
3374        NamespcName = Corrected.getAsIdentifierInfo();
3375      } else {
3376        R.clear();
3377        R.setLookupName(NamespcName);
3378      }
3379    }
3380  }
3381
3382  if (!R.empty()) {
3383    NamedDecl *Named = R.getFoundDecl();
3384    assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3385        && "expected namespace decl");
3386    // C++ [namespace.udir]p1:
3387    //   A using-directive specifies that the names in the nominated
3388    //   namespace can be used in the scope in which the
3389    //   using-directive appears after the using-directive. During
3390    //   unqualified name lookup (3.4.1), the names appear as if they
3391    //   were declared in the nearest enclosing namespace which
3392    //   contains both the using-directive and the nominated
3393    //   namespace. [Note: in this context, "contains" means "contains
3394    //   directly or indirectly". ]
3395
3396    // Find enclosing context containing both using-directive and
3397    // nominated namespace.
3398    NamespaceDecl *NS = getNamespaceDecl(Named);
3399    DeclContext *CommonAncestor = cast<DeclContext>(NS);
3400    while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3401      CommonAncestor = CommonAncestor->getParent();
3402
3403    UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
3404                                      SS.getRange(),
3405                                      (NestedNameSpecifier *)SS.getScopeRep(),
3406                                      IdentLoc, Named, CommonAncestor);
3407    PushUsingDirective(S, UDir);
3408  } else {
3409    Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
3410  }
3411
3412  // FIXME: We ignore attributes for now.
3413  delete AttrList;
3414  return DeclPtrTy::make(UDir);
3415}
3416
3417void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3418  // If scope has associated entity, then using directive is at namespace
3419  // or translation unit scope. We add UsingDirectiveDecls, into
3420  // it's lookup structure.
3421  if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
3422    Ctx->addDecl(UDir);
3423  else
3424    // Otherwise it is block-sope. using-directives will affect lookup
3425    // only to the end of scope.
3426    S->PushUsingDirective(DeclPtrTy::make(UDir));
3427}
3428
3429
3430Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
3431                                            AccessSpecifier AS,
3432                                            bool HasUsingKeyword,
3433                                            SourceLocation UsingLoc,
3434                                            CXXScopeSpec &SS,
3435                                            UnqualifiedId &Name,
3436                                            AttributeList *AttrList,
3437                                            bool IsTypeName,
3438                                            SourceLocation TypenameLoc) {
3439  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
3440
3441  switch (Name.getKind()) {
3442  case UnqualifiedId::IK_Identifier:
3443  case UnqualifiedId::IK_OperatorFunctionId:
3444  case UnqualifiedId::IK_LiteralOperatorId:
3445  case UnqualifiedId::IK_ConversionFunctionId:
3446    break;
3447
3448  case UnqualifiedId::IK_ConstructorName:
3449  case UnqualifiedId::IK_ConstructorTemplateId:
3450    // C++0x inherited constructors.
3451    if (getLangOptions().CPlusPlus0x) break;
3452
3453    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3454      << SS.getRange();
3455    return DeclPtrTy();
3456
3457  case UnqualifiedId::IK_DestructorName:
3458    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3459      << SS.getRange();
3460    return DeclPtrTy();
3461
3462  case UnqualifiedId::IK_TemplateId:
3463    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3464      << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
3465    return DeclPtrTy();
3466  }
3467
3468  DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
3469  if (!TargetName)
3470    return DeclPtrTy();
3471
3472  // Warn about using declarations.
3473  // TODO: store that the declaration was written without 'using' and
3474  // talk about access decls instead of using decls in the
3475  // diagnostics.
3476  if (!HasUsingKeyword) {
3477    UsingLoc = Name.getSourceRange().getBegin();
3478
3479    Diag(UsingLoc, diag::warn_access_decl_deprecated)
3480      << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
3481  }
3482
3483  NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
3484                                        Name.getSourceRange().getBegin(),
3485                                        TargetName, AttrList,
3486                                        /* IsInstantiation */ false,
3487                                        IsTypeName, TypenameLoc);
3488  if (UD)
3489    PushOnScopeChains(UD, S, /*AddToContext*/ false);
3490
3491  return DeclPtrTy::make(UD);
3492}
3493
3494/// \brief Determine whether a using declaration considers the given
3495/// declarations as "equivalent", e.g., if they are redeclarations of
3496/// the same entity or are both typedefs of the same type.
3497static bool
3498IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
3499                         bool &SuppressRedeclaration) {
3500  if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
3501    SuppressRedeclaration = false;
3502    return true;
3503  }
3504
3505  if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
3506    if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
3507      SuppressRedeclaration = true;
3508      return Context.hasSameType(TD1->getUnderlyingType(),
3509                                 TD2->getUnderlyingType());
3510    }
3511
3512  return false;
3513}
3514
3515
3516/// Determines whether to create a using shadow decl for a particular
3517/// decl, given the set of decls existing prior to this using lookup.
3518bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3519                                const LookupResult &Previous) {
3520  // Diagnose finding a decl which is not from a base class of the
3521  // current class.  We do this now because there are cases where this
3522  // function will silently decide not to build a shadow decl, which
3523  // will pre-empt further diagnostics.
3524  //
3525  // We don't need to do this in C++0x because we do the check once on
3526  // the qualifier.
3527  //
3528  // FIXME: diagnose the following if we care enough:
3529  //   struct A { int foo; };
3530  //   struct B : A { using A::foo; };
3531  //   template <class T> struct C : A {};
3532  //   template <class T> struct D : C<T> { using B::foo; } // <---
3533  // This is invalid (during instantiation) in C++03 because B::foo
3534  // resolves to the using decl in B, which is not a base class of D<T>.
3535  // We can't diagnose it immediately because C<T> is an unknown
3536  // specialization.  The UsingShadowDecl in D<T> then points directly
3537  // to A::foo, which will look well-formed when we instantiate.
3538  // The right solution is to not collapse the shadow-decl chain.
3539  if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3540    DeclContext *OrigDC = Orig->getDeclContext();
3541
3542    // Handle enums and anonymous structs.
3543    if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3544    CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3545    while (OrigRec->isAnonymousStructOrUnion())
3546      OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3547
3548    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3549      if (OrigDC == CurContext) {
3550        Diag(Using->getLocation(),
3551             diag::err_using_decl_nested_name_specifier_is_current_class)
3552          << Using->getNestedNameRange();
3553        Diag(Orig->getLocation(), diag::note_using_decl_target);
3554        return true;
3555      }
3556
3557      Diag(Using->getNestedNameRange().getBegin(),
3558           diag::err_using_decl_nested_name_specifier_is_not_base_class)
3559        << Using->getTargetNestedNameDecl()
3560        << cast<CXXRecordDecl>(CurContext)
3561        << Using->getNestedNameRange();
3562      Diag(Orig->getLocation(), diag::note_using_decl_target);
3563      return true;
3564    }
3565  }
3566
3567  if (Previous.empty()) return false;
3568
3569  NamedDecl *Target = Orig;
3570  if (isa<UsingShadowDecl>(Target))
3571    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3572
3573  // If the target happens to be one of the previous declarations, we
3574  // don't have a conflict.
3575  //
3576  // FIXME: but we might be increasing its access, in which case we
3577  // should redeclare it.
3578  NamedDecl *NonTag = 0, *Tag = 0;
3579  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3580         I != E; ++I) {
3581    NamedDecl *D = (*I)->getUnderlyingDecl();
3582    bool Result;
3583    if (IsEquivalentForUsingDecl(Context, D, Target, Result))
3584      return Result;
3585
3586    (isa<TagDecl>(D) ? Tag : NonTag) = D;
3587  }
3588
3589  if (Target->isFunctionOrFunctionTemplate()) {
3590    FunctionDecl *FD;
3591    if (isa<FunctionTemplateDecl>(Target))
3592      FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3593    else
3594      FD = cast<FunctionDecl>(Target);
3595
3596    NamedDecl *OldDecl = 0;
3597    switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
3598    case Ovl_Overload:
3599      return false;
3600
3601    case Ovl_NonFunction:
3602      Diag(Using->getLocation(), diag::err_using_decl_conflict);
3603      break;
3604
3605    // We found a decl with the exact signature.
3606    case Ovl_Match:
3607      // If we're in a record, we want to hide the target, so we
3608      // return true (without a diagnostic) to tell the caller not to
3609      // build a shadow decl.
3610      if (CurContext->isRecord())
3611        return true;
3612
3613      // If we're not in a record, this is an error.
3614      Diag(Using->getLocation(), diag::err_using_decl_conflict);
3615      break;
3616    }
3617
3618    Diag(Target->getLocation(), diag::note_using_decl_target);
3619    Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3620    return true;
3621  }
3622
3623  // Target is not a function.
3624
3625  if (isa<TagDecl>(Target)) {
3626    // No conflict between a tag and a non-tag.
3627    if (!Tag) return false;
3628
3629    Diag(Using->getLocation(), diag::err_using_decl_conflict);
3630    Diag(Target->getLocation(), diag::note_using_decl_target);
3631    Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3632    return true;
3633  }
3634
3635  // No conflict between a tag and a non-tag.
3636  if (!NonTag) return false;
3637
3638  Diag(Using->getLocation(), diag::err_using_decl_conflict);
3639  Diag(Target->getLocation(), diag::note_using_decl_target);
3640  Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3641  return true;
3642}
3643
3644/// Builds a shadow declaration corresponding to a 'using' declaration.
3645UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
3646                                            UsingDecl *UD,
3647                                            NamedDecl *Orig) {
3648
3649  // If we resolved to another shadow declaration, just coalesce them.
3650  NamedDecl *Target = Orig;
3651  if (isa<UsingShadowDecl>(Target)) {
3652    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3653    assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
3654  }
3655
3656  UsingShadowDecl *Shadow
3657    = UsingShadowDecl::Create(Context, CurContext,
3658                              UD->getLocation(), UD, Target);
3659  UD->addShadowDecl(Shadow);
3660
3661  if (S)
3662    PushOnScopeChains(Shadow, S);
3663  else
3664    CurContext->addDecl(Shadow);
3665  Shadow->setAccess(UD->getAccess());
3666
3667  // Register it as a conversion if appropriate.
3668  if (Shadow->getDeclName().getNameKind()
3669        == DeclarationName::CXXConversionFunctionName)
3670    cast<CXXRecordDecl>(CurContext)->addConversionFunction(Shadow);
3671
3672  if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3673    Shadow->setInvalidDecl();
3674
3675  return Shadow;
3676}
3677
3678/// Hides a using shadow declaration.  This is required by the current
3679/// using-decl implementation when a resolvable using declaration in a
3680/// class is followed by a declaration which would hide or override
3681/// one or more of the using decl's targets; for example:
3682///
3683///   struct Base { void foo(int); };
3684///   struct Derived : Base {
3685///     using Base::foo;
3686///     void foo(int);
3687///   };
3688///
3689/// The governing language is C++03 [namespace.udecl]p12:
3690///
3691///   When a using-declaration brings names from a base class into a
3692///   derived class scope, member functions in the derived class
3693///   override and/or hide member functions with the same name and
3694///   parameter types in a base class (rather than conflicting).
3695///
3696/// There are two ways to implement this:
3697///   (1) optimistically create shadow decls when they're not hidden
3698///       by existing declarations, or
3699///   (2) don't create any shadow decls (or at least don't make them
3700///       visible) until we've fully parsed/instantiated the class.
3701/// The problem with (1) is that we might have to retroactively remove
3702/// a shadow decl, which requires several O(n) operations because the
3703/// decl structures are (very reasonably) not designed for removal.
3704/// (2) avoids this but is very fiddly and phase-dependent.
3705void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
3706  if (Shadow->getDeclName().getNameKind() ==
3707        DeclarationName::CXXConversionFunctionName)
3708    cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3709
3710  // Remove it from the DeclContext...
3711  Shadow->getDeclContext()->removeDecl(Shadow);
3712
3713  // ...and the scope, if applicable...
3714  if (S) {
3715    S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow)));
3716    IdResolver.RemoveDecl(Shadow);
3717  }
3718
3719  // ...and the using decl.
3720  Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3721
3722  // TODO: complain somehow if Shadow was used.  It shouldn't
3723  // be possible for this to happen, because...?
3724}
3725
3726/// Builds a using declaration.
3727///
3728/// \param IsInstantiation - Whether this call arises from an
3729///   instantiation of an unresolved using declaration.  We treat
3730///   the lookup differently for these declarations.
3731NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3732                                       SourceLocation UsingLoc,
3733                                       CXXScopeSpec &SS,
3734                                       SourceLocation IdentLoc,
3735                                       DeclarationName Name,
3736                                       AttributeList *AttrList,
3737                                       bool IsInstantiation,
3738                                       bool IsTypeName,
3739                                       SourceLocation TypenameLoc) {
3740  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3741  assert(IdentLoc.isValid() && "Invalid TargetName location.");
3742
3743  // FIXME: We ignore attributes for now.
3744  delete AttrList;
3745
3746  if (SS.isEmpty()) {
3747    Diag(IdentLoc, diag::err_using_requires_qualname);
3748    return 0;
3749  }
3750
3751  // Do the redeclaration lookup in the current scope.
3752  LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName,
3753                        ForRedeclaration);
3754  Previous.setHideTags(false);
3755  if (S) {
3756    LookupName(Previous, S);
3757
3758    // It is really dumb that we have to do this.
3759    LookupResult::Filter F = Previous.makeFilter();
3760    while (F.hasNext()) {
3761      NamedDecl *D = F.next();
3762      if (!isDeclInScope(D, CurContext, S))
3763        F.erase();
3764    }
3765    F.done();
3766  } else {
3767    assert(IsInstantiation && "no scope in non-instantiation");
3768    assert(CurContext->isRecord() && "scope not record in instantiation");
3769    LookupQualifiedName(Previous, CurContext);
3770  }
3771
3772  NestedNameSpecifier *NNS =
3773    static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3774
3775  // Check for invalid redeclarations.
3776  if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3777    return 0;
3778
3779  // Check for bad qualifiers.
3780  if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3781    return 0;
3782
3783  DeclContext *LookupContext = computeDeclContext(SS);
3784  NamedDecl *D;
3785  if (!LookupContext) {
3786    if (IsTypeName) {
3787      // FIXME: not all declaration name kinds are legal here
3788      D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3789                                              UsingLoc, TypenameLoc,
3790                                              SS.getRange(), NNS,
3791                                              IdentLoc, Name);
3792    } else {
3793      D = UnresolvedUsingValueDecl::Create(Context, CurContext,
3794                                           UsingLoc, SS.getRange(), NNS,
3795                                           IdentLoc, Name);
3796    }
3797  } else {
3798    D = UsingDecl::Create(Context, CurContext, IdentLoc,
3799                          SS.getRange(), UsingLoc, NNS, Name,
3800                          IsTypeName);
3801  }
3802  D->setAccess(AS);
3803  CurContext->addDecl(D);
3804
3805  if (!LookupContext) return D;
3806  UsingDecl *UD = cast<UsingDecl>(D);
3807
3808  if (RequireCompleteDeclContext(SS, LookupContext)) {
3809    UD->setInvalidDecl();
3810    return UD;
3811  }
3812
3813  // Look up the target name.
3814
3815  LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
3816
3817  // Unlike most lookups, we don't always want to hide tag
3818  // declarations: tag names are visible through the using declaration
3819  // even if hidden by ordinary names, *except* in a dependent context
3820  // where it's important for the sanity of two-phase lookup.
3821  if (!IsInstantiation)
3822    R.setHideTags(false);
3823
3824  LookupQualifiedName(R, LookupContext);
3825
3826  if (R.empty()) {
3827    Diag(IdentLoc, diag::err_no_member)
3828      << Name << LookupContext << SS.getRange();
3829    UD->setInvalidDecl();
3830    return UD;
3831  }
3832
3833  if (R.isAmbiguous()) {
3834    UD->setInvalidDecl();
3835    return UD;
3836  }
3837
3838  if (IsTypeName) {
3839    // If we asked for a typename and got a non-type decl, error out.
3840    if (!R.getAsSingle<TypeDecl>()) {
3841      Diag(IdentLoc, diag::err_using_typename_non_type);
3842      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3843        Diag((*I)->getUnderlyingDecl()->getLocation(),
3844             diag::note_using_decl_target);
3845      UD->setInvalidDecl();
3846      return UD;
3847    }
3848  } else {
3849    // If we asked for a non-typename and we got a type, error out,
3850    // but only if this is an instantiation of an unresolved using
3851    // decl.  Otherwise just silently find the type name.
3852    if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
3853      Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3854      Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
3855      UD->setInvalidDecl();
3856      return UD;
3857    }
3858  }
3859
3860  // C++0x N2914 [namespace.udecl]p6:
3861  // A using-declaration shall not name a namespace.
3862  if (R.getAsSingle<NamespaceDecl>()) {
3863    Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3864      << SS.getRange();
3865    UD->setInvalidDecl();
3866    return UD;
3867  }
3868
3869  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3870    if (!CheckUsingShadowDecl(UD, *I, Previous))
3871      BuildUsingShadowDecl(S, UD, *I);
3872  }
3873
3874  return UD;
3875}
3876
3877/// Checks that the given using declaration is not an invalid
3878/// redeclaration.  Note that this is checking only for the using decl
3879/// itself, not for any ill-formedness among the UsingShadowDecls.
3880bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3881                                       bool isTypeName,
3882                                       const CXXScopeSpec &SS,
3883                                       SourceLocation NameLoc,
3884                                       const LookupResult &Prev) {
3885  // C++03 [namespace.udecl]p8:
3886  // C++0x [namespace.udecl]p10:
3887  //   A using-declaration is a declaration and can therefore be used
3888  //   repeatedly where (and only where) multiple declarations are
3889  //   allowed.
3890  //
3891  // That's in non-member contexts.
3892  if (!CurContext->getLookupContext()->isRecord())
3893    return false;
3894
3895  NestedNameSpecifier *Qual
3896    = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3897
3898  for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3899    NamedDecl *D = *I;
3900
3901    bool DTypename;
3902    NestedNameSpecifier *DQual;
3903    if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3904      DTypename = UD->isTypeName();
3905      DQual = UD->getTargetNestedNameDecl();
3906    } else if (UnresolvedUsingValueDecl *UD
3907                 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3908      DTypename = false;
3909      DQual = UD->getTargetNestedNameSpecifier();
3910    } else if (UnresolvedUsingTypenameDecl *UD
3911                 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3912      DTypename = true;
3913      DQual = UD->getTargetNestedNameSpecifier();
3914    } else continue;
3915
3916    // using decls differ if one says 'typename' and the other doesn't.
3917    // FIXME: non-dependent using decls?
3918    if (isTypeName != DTypename) continue;
3919
3920    // using decls differ if they name different scopes (but note that
3921    // template instantiation can cause this check to trigger when it
3922    // didn't before instantiation).
3923    if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3924        Context.getCanonicalNestedNameSpecifier(DQual))
3925      continue;
3926
3927    Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
3928    Diag(D->getLocation(), diag::note_using_decl) << 1;
3929    return true;
3930  }
3931
3932  return false;
3933}
3934
3935
3936/// Checks that the given nested-name qualifier used in a using decl
3937/// in the current context is appropriately related to the current
3938/// scope.  If an error is found, diagnoses it and returns true.
3939bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3940                                   const CXXScopeSpec &SS,
3941                                   SourceLocation NameLoc) {
3942  DeclContext *NamedContext = computeDeclContext(SS);
3943
3944  if (!CurContext->isRecord()) {
3945    // C++03 [namespace.udecl]p3:
3946    // C++0x [namespace.udecl]p8:
3947    //   A using-declaration for a class member shall be a member-declaration.
3948
3949    // If we weren't able to compute a valid scope, it must be a
3950    // dependent class scope.
3951    if (!NamedContext || NamedContext->isRecord()) {
3952      Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
3953        << SS.getRange();
3954      return true;
3955    }
3956
3957    // Otherwise, everything is known to be fine.
3958    return false;
3959  }
3960
3961  // The current scope is a record.
3962
3963  // If the named context is dependent, we can't decide much.
3964  if (!NamedContext) {
3965    // FIXME: in C++0x, we can diagnose if we can prove that the
3966    // nested-name-specifier does not refer to a base class, which is
3967    // still possible in some cases.
3968
3969    // Otherwise we have to conservatively report that things might be
3970    // okay.
3971    return false;
3972  }
3973
3974  if (!NamedContext->isRecord()) {
3975    // Ideally this would point at the last name in the specifier,
3976    // but we don't have that level of source info.
3977    Diag(SS.getRange().getBegin(),
3978         diag::err_using_decl_nested_name_specifier_is_not_class)
3979      << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
3980    return true;
3981  }
3982
3983  if (getLangOptions().CPlusPlus0x) {
3984    // C++0x [namespace.udecl]p3:
3985    //   In a using-declaration used as a member-declaration, the
3986    //   nested-name-specifier shall name a base class of the class
3987    //   being defined.
3988
3989    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
3990                                 cast<CXXRecordDecl>(NamedContext))) {
3991      if (CurContext == NamedContext) {
3992        Diag(NameLoc,
3993             diag::err_using_decl_nested_name_specifier_is_current_class)
3994          << SS.getRange();
3995        return true;
3996      }
3997
3998      Diag(SS.getRange().getBegin(),
3999           diag::err_using_decl_nested_name_specifier_is_not_base_class)
4000        << (NestedNameSpecifier*) SS.getScopeRep()
4001        << cast<CXXRecordDecl>(CurContext)
4002        << SS.getRange();
4003      return true;
4004    }
4005
4006    return false;
4007  }
4008
4009  // C++03 [namespace.udecl]p4:
4010  //   A using-declaration used as a member-declaration shall refer
4011  //   to a member of a base class of the class being defined [etc.].
4012
4013  // Salient point: SS doesn't have to name a base class as long as
4014  // lookup only finds members from base classes.  Therefore we can
4015  // diagnose here only if we can prove that that can't happen,
4016  // i.e. if the class hierarchies provably don't intersect.
4017
4018  // TODO: it would be nice if "definitely valid" results were cached
4019  // in the UsingDecl and UsingShadowDecl so that these checks didn't
4020  // need to be repeated.
4021
4022  struct UserData {
4023    llvm::DenseSet<const CXXRecordDecl*> Bases;
4024
4025    static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4026      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4027      Data->Bases.insert(Base);
4028      return true;
4029    }
4030
4031    bool hasDependentBases(const CXXRecordDecl *Class) {
4032      return !Class->forallBases(collect, this);
4033    }
4034
4035    /// Returns true if the base is dependent or is one of the
4036    /// accumulated base classes.
4037    static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4038      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4039      return !Data->Bases.count(Base);
4040    }
4041
4042    bool mightShareBases(const CXXRecordDecl *Class) {
4043      return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4044    }
4045  };
4046
4047  UserData Data;
4048
4049  // Returns false if we find a dependent base.
4050  if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4051    return false;
4052
4053  // Returns false if the class has a dependent base or if it or one
4054  // of its bases is present in the base set of the current context.
4055  if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4056    return false;
4057
4058  Diag(SS.getRange().getBegin(),
4059       diag::err_using_decl_nested_name_specifier_is_not_base_class)
4060    << (NestedNameSpecifier*) SS.getScopeRep()
4061    << cast<CXXRecordDecl>(CurContext)
4062    << SS.getRange();
4063
4064  return true;
4065}
4066
4067Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
4068                                             SourceLocation NamespaceLoc,
4069                                             SourceLocation AliasLoc,
4070                                             IdentifierInfo *Alias,
4071                                             CXXScopeSpec &SS,
4072                                             SourceLocation IdentLoc,
4073                                             IdentifierInfo *Ident) {
4074
4075  // Lookup the namespace name.
4076  LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4077  LookupParsedName(R, S, &SS);
4078
4079  // Check if we have a previous declaration with the same name.
4080  NamedDecl *PrevDecl
4081    = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4082                       ForRedeclaration);
4083  if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4084    PrevDecl = 0;
4085
4086  if (PrevDecl) {
4087    if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
4088      // We already have an alias with the same name that points to the same
4089      // namespace, so don't create a new one.
4090      // FIXME: At some point, we'll want to create the (redundant)
4091      // declaration to maintain better source information.
4092      if (!R.isAmbiguous() && !R.empty() &&
4093          AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
4094        return DeclPtrTy();
4095    }
4096
4097    unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4098      diag::err_redefinition_different_kind;
4099    Diag(AliasLoc, DiagID) << Alias;
4100    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4101    return DeclPtrTy();
4102  }
4103
4104  if (R.isAmbiguous())
4105    return DeclPtrTy();
4106
4107  if (R.empty()) {
4108    if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4109                                                CTC_NoKeywords, 0)) {
4110      if (R.getAsSingle<NamespaceDecl>() ||
4111          R.getAsSingle<NamespaceAliasDecl>()) {
4112        if (DeclContext *DC = computeDeclContext(SS, false))
4113          Diag(IdentLoc, diag::err_using_directive_member_suggest)
4114            << Ident << DC << Corrected << SS.getRange()
4115            << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4116        else
4117          Diag(IdentLoc, diag::err_using_directive_suggest)
4118            << Ident << Corrected
4119            << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4120
4121        Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4122          << Corrected;
4123
4124        Ident = Corrected.getAsIdentifierInfo();
4125      } else {
4126        R.clear();
4127        R.setLookupName(Ident);
4128      }
4129    }
4130
4131    if (R.empty()) {
4132      Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
4133      return DeclPtrTy();
4134    }
4135  }
4136
4137  NamespaceAliasDecl *AliasDecl =
4138    NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4139                               Alias, SS.getRange(),
4140                               (NestedNameSpecifier *)SS.getScopeRep(),
4141                               IdentLoc, R.getFoundDecl());
4142
4143  PushOnScopeChains(AliasDecl, S);
4144  return DeclPtrTy::make(AliasDecl);
4145}
4146
4147namespace {
4148  /// \brief Scoped object used to handle the state changes required in Sema
4149  /// to implicitly define the body of a C++ member function;
4150  class ImplicitlyDefinedFunctionScope {
4151    Sema &S;
4152    DeclContext *PreviousContext;
4153
4154  public:
4155    ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4156      : S(S), PreviousContext(S.CurContext)
4157    {
4158      S.CurContext = Method;
4159      S.PushFunctionScope();
4160      S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4161    }
4162
4163    ~ImplicitlyDefinedFunctionScope() {
4164      S.PopExpressionEvaluationContext();
4165      S.PopFunctionOrBlockScope();
4166      S.CurContext = PreviousContext;
4167    }
4168  };
4169}
4170
4171CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4172                                                     CXXRecordDecl *ClassDecl) {
4173  // C++ [class.ctor]p5:
4174  //   A default constructor for a class X is a constructor of class X
4175  //   that can be called without an argument. If there is no
4176  //   user-declared constructor for class X, a default constructor is
4177  //   implicitly declared. An implicitly-declared default constructor
4178  //   is an inline public member of its class.
4179  assert(!ClassDecl->hasUserDeclaredConstructor() &&
4180         "Should not build implicit default constructor!");
4181
4182  // C++ [except.spec]p14:
4183  //   An implicitly declared special member function (Clause 12) shall have an
4184  //   exception-specification. [...]
4185  ImplicitExceptionSpecification ExceptSpec(Context);
4186
4187  // Direct base-class destructors.
4188  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4189                                       BEnd = ClassDecl->bases_end();
4190       B != BEnd; ++B) {
4191    if (B->isVirtual()) // Handled below.
4192      continue;
4193
4194    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4195      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4196      if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4197        ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4198      else if (CXXConstructorDecl *Constructor
4199                                       = BaseClassDecl->getDefaultConstructor())
4200        ExceptSpec.CalledDecl(Constructor);
4201    }
4202  }
4203
4204  // Virtual base-class destructors.
4205  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4206                                       BEnd = ClassDecl->vbases_end();
4207       B != BEnd; ++B) {
4208    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4209      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4210      if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4211        ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4212      else if (CXXConstructorDecl *Constructor
4213                                       = BaseClassDecl->getDefaultConstructor())
4214        ExceptSpec.CalledDecl(Constructor);
4215    }
4216  }
4217
4218  // Field destructors.
4219  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4220                               FEnd = ClassDecl->field_end();
4221       F != FEnd; ++F) {
4222    if (const RecordType *RecordTy
4223              = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4224      CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4225      if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4226        ExceptSpec.CalledDecl(
4227                            DeclareImplicitDefaultConstructor(FieldClassDecl));
4228      else if (CXXConstructorDecl *Constructor
4229                                      = FieldClassDecl->getDefaultConstructor())
4230        ExceptSpec.CalledDecl(Constructor);
4231    }
4232  }
4233
4234
4235  // Create the actual constructor declaration.
4236  CanQualType ClassType
4237    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4238  DeclarationName Name
4239    = Context.DeclarationNames.getCXXConstructorName(ClassType);
4240  CXXConstructorDecl *DefaultCon
4241    = CXXConstructorDecl::Create(Context, ClassDecl,
4242                                 ClassDecl->getLocation(), Name,
4243                                 Context.getFunctionType(Context.VoidTy,
4244                                                         0, 0, false, 0,
4245                                       ExceptSpec.hasExceptionSpecification(),
4246                                     ExceptSpec.hasAnyExceptionSpecification(),
4247                                                         ExceptSpec.size(),
4248                                                         ExceptSpec.data(),
4249                                                       FunctionType::ExtInfo()),
4250                                 /*TInfo=*/0,
4251                                 /*isExplicit=*/false,
4252                                 /*isInline=*/true,
4253                                 /*isImplicitlyDeclared=*/true);
4254  DefaultCon->setAccess(AS_public);
4255  DefaultCon->setImplicit();
4256  DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
4257
4258  // Note that we have declared this constructor.
4259  ClassDecl->setDeclaredDefaultConstructor(true);
4260  ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4261
4262  if (Scope *S = getScopeForContext(ClassDecl))
4263    PushOnScopeChains(DefaultCon, S, false);
4264  ClassDecl->addDecl(DefaultCon);
4265
4266  return DefaultCon;
4267}
4268
4269void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4270                                            CXXConstructorDecl *Constructor) {
4271  assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
4272          !Constructor->isUsed(false)) &&
4273    "DefineImplicitDefaultConstructor - call it for implicit default ctor");
4274
4275  CXXRecordDecl *ClassDecl = Constructor->getParent();
4276  assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
4277
4278  ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
4279  ErrorTrap Trap(*this);
4280  if (SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
4281      Trap.hasErrorOccurred()) {
4282    Diag(CurrentLocation, diag::note_member_synthesized_at)
4283      << CXXConstructor << Context.getTagDeclType(ClassDecl);
4284    Constructor->setInvalidDecl();
4285  } else {
4286    Constructor->setUsed();
4287    MarkVTableUsed(CurrentLocation, ClassDecl);
4288  }
4289}
4290
4291CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
4292  // C++ [class.dtor]p2:
4293  //   If a class has no user-declared destructor, a destructor is
4294  //   declared implicitly. An implicitly-declared destructor is an
4295  //   inline public member of its class.
4296
4297  // C++ [except.spec]p14:
4298  //   An implicitly declared special member function (Clause 12) shall have
4299  //   an exception-specification.
4300  ImplicitExceptionSpecification ExceptSpec(Context);
4301
4302  // Direct base-class destructors.
4303  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4304                                       BEnd = ClassDecl->bases_end();
4305       B != BEnd; ++B) {
4306    if (B->isVirtual()) // Handled below.
4307      continue;
4308
4309    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4310      ExceptSpec.CalledDecl(
4311                    LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
4312  }
4313
4314  // Virtual base-class destructors.
4315  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4316                                       BEnd = ClassDecl->vbases_end();
4317       B != BEnd; ++B) {
4318    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4319      ExceptSpec.CalledDecl(
4320                    LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
4321  }
4322
4323  // Field destructors.
4324  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4325                               FEnd = ClassDecl->field_end();
4326       F != FEnd; ++F) {
4327    if (const RecordType *RecordTy
4328        = Context.getBaseElementType(F->getType())->getAs<RecordType>())
4329      ExceptSpec.CalledDecl(
4330                    LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
4331  }
4332
4333  // Create the actual destructor declaration.
4334  QualType Ty = Context.getFunctionType(Context.VoidTy,
4335                                        0, 0, false, 0,
4336                                        ExceptSpec.hasExceptionSpecification(),
4337                                    ExceptSpec.hasAnyExceptionSpecification(),
4338                                        ExceptSpec.size(),
4339                                        ExceptSpec.data(),
4340                                        FunctionType::ExtInfo());
4341
4342  CanQualType ClassType
4343    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4344  DeclarationName Name
4345    = Context.DeclarationNames.getCXXDestructorName(ClassType);
4346  CXXDestructorDecl *Destructor
4347    = CXXDestructorDecl::Create(Context, ClassDecl,
4348                                ClassDecl->getLocation(), Name, Ty,
4349                                /*isInline=*/true,
4350                                /*isImplicitlyDeclared=*/true);
4351  Destructor->setAccess(AS_public);
4352  Destructor->setImplicit();
4353  Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
4354
4355  // Note that we have declared this destructor.
4356  ClassDecl->setDeclaredDestructor(true);
4357  ++ASTContext::NumImplicitDestructorsDeclared;
4358
4359  // Introduce this destructor into its scope.
4360  if (Scope *S = getScopeForContext(ClassDecl))
4361    PushOnScopeChains(Destructor, S, false);
4362  ClassDecl->addDecl(Destructor);
4363
4364  // This could be uniqued if it ever proves significant.
4365  Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
4366
4367  AddOverriddenMethods(ClassDecl, Destructor);
4368
4369  return Destructor;
4370}
4371
4372void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
4373                                    CXXDestructorDecl *Destructor) {
4374  assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
4375         "DefineImplicitDestructor - call it for implicit default dtor");
4376  CXXRecordDecl *ClassDecl = Destructor->getParent();
4377  assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
4378
4379  if (Destructor->isInvalidDecl())
4380    return;
4381
4382  ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
4383
4384  ErrorTrap Trap(*this);
4385  MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4386                                         Destructor->getParent());
4387
4388  if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
4389    Diag(CurrentLocation, diag::note_member_synthesized_at)
4390      << CXXDestructor << Context.getTagDeclType(ClassDecl);
4391
4392    Destructor->setInvalidDecl();
4393    return;
4394  }
4395
4396  Destructor->setUsed();
4397  MarkVTableUsed(CurrentLocation, ClassDecl);
4398}
4399
4400/// \brief Builds a statement that copies the given entity from \p From to
4401/// \c To.
4402///
4403/// This routine is used to copy the members of a class with an
4404/// implicitly-declared copy assignment operator. When the entities being
4405/// copied are arrays, this routine builds for loops to copy them.
4406///
4407/// \param S The Sema object used for type-checking.
4408///
4409/// \param Loc The location where the implicit copy is being generated.
4410///
4411/// \param T The type of the expressions being copied. Both expressions must
4412/// have this type.
4413///
4414/// \param To The expression we are copying to.
4415///
4416/// \param From The expression we are copying from.
4417///
4418/// \param CopyingBaseSubobject Whether we're copying a base subobject.
4419/// Otherwise, it's a non-static member subobject.
4420///
4421/// \param Depth Internal parameter recording the depth of the recursion.
4422///
4423/// \returns A statement or a loop that copies the expressions.
4424static Sema::OwningStmtResult
4425BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
4426                      Sema::OwningExprResult To, Sema::OwningExprResult From,
4427                      bool CopyingBaseSubobject, unsigned Depth = 0) {
4428  typedef Sema::OwningStmtResult OwningStmtResult;
4429  typedef Sema::OwningExprResult OwningExprResult;
4430
4431  // C++0x [class.copy]p30:
4432  //   Each subobject is assigned in the manner appropriate to its type:
4433  //
4434  //     - if the subobject is of class type, the copy assignment operator
4435  //       for the class is used (as if by explicit qualification; that is,
4436  //       ignoring any possible virtual overriding functions in more derived
4437  //       classes);
4438  if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4439    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4440
4441    // Look for operator=.
4442    DeclarationName Name
4443      = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4444    LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4445    S.LookupQualifiedName(OpLookup, ClassDecl, false);
4446
4447    // Filter out any result that isn't a copy-assignment operator.
4448    LookupResult::Filter F = OpLookup.makeFilter();
4449    while (F.hasNext()) {
4450      NamedDecl *D = F.next();
4451      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4452        if (Method->isCopyAssignmentOperator())
4453          continue;
4454
4455      F.erase();
4456    }
4457    F.done();
4458
4459    // Suppress the protected check (C++ [class.protected]) for each of the
4460    // assignment operators we found. This strange dance is required when
4461    // we're assigning via a base classes's copy-assignment operator. To
4462    // ensure that we're getting the right base class subobject (without
4463    // ambiguities), we need to cast "this" to that subobject type; to
4464    // ensure that we don't go through the virtual call mechanism, we need
4465    // to qualify the operator= name with the base class (see below). However,
4466    // this means that if the base class has a protected copy assignment
4467    // operator, the protected member access check will fail. So, we
4468    // rewrite "protected" access to "public" access in this case, since we
4469    // know by construction that we're calling from a derived class.
4470    if (CopyingBaseSubobject) {
4471      for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
4472           L != LEnd; ++L) {
4473        if (L.getAccess() == AS_protected)
4474          L.setAccess(AS_public);
4475      }
4476    }
4477
4478    // Create the nested-name-specifier that will be used to qualify the
4479    // reference to operator=; this is required to suppress the virtual
4480    // call mechanism.
4481    CXXScopeSpec SS;
4482    SS.setRange(Loc);
4483    SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4484                                               T.getTypePtr()));
4485
4486    // Create the reference to operator=.
4487    OwningExprResult OpEqualRef
4488      = S.BuildMemberReferenceExpr(move(To), T, Loc, /*isArrow=*/false, SS,
4489                                   /*FirstQualifierInScope=*/0, OpLookup,
4490                                   /*TemplateArgs=*/0,
4491                                   /*SuppressQualifierCheck=*/true);
4492    if (OpEqualRef.isInvalid())
4493      return S.StmtError();
4494
4495    // Build the call to the assignment operator.
4496    Expr *FromE = From.takeAs<Expr>();
4497    OwningExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
4498                                                      OpEqualRef.takeAs<Expr>(),
4499                                                        Loc, &FromE, 1, 0, Loc);
4500    if (Call.isInvalid())
4501      return S.StmtError();
4502
4503    return S.Owned(Call.takeAs<Stmt>());
4504  }
4505
4506  //     - if the subobject is of scalar type, the built-in assignment
4507  //       operator is used.
4508  const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4509  if (!ArrayTy) {
4510    OwningExprResult Assignment = S.CreateBuiltinBinOp(Loc,
4511                                                       BinaryOperator::Assign,
4512                                                       To.takeAs<Expr>(),
4513                                                       From.takeAs<Expr>());
4514    if (Assignment.isInvalid())
4515      return S.StmtError();
4516
4517    return S.Owned(Assignment.takeAs<Stmt>());
4518  }
4519
4520  //     - if the subobject is an array, each element is assigned, in the
4521  //       manner appropriate to the element type;
4522
4523  // Construct a loop over the array bounds, e.g.,
4524  //
4525  //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4526  //
4527  // that will copy each of the array elements.
4528  QualType SizeType = S.Context.getSizeType();
4529
4530  // Create the iteration variable.
4531  IdentifierInfo *IterationVarName = 0;
4532  {
4533    llvm::SmallString<8> Str;
4534    llvm::raw_svector_ostream OS(Str);
4535    OS << "__i" << Depth;
4536    IterationVarName = &S.Context.Idents.get(OS.str());
4537  }
4538  VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4539                                          IterationVarName, SizeType,
4540                            S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
4541                                          VarDecl::None, VarDecl::None);
4542
4543  // Initialize the iteration variable to zero.
4544  llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
4545  IterationVar->setInit(new (S.Context) IntegerLiteral(Zero, SizeType, Loc));
4546
4547  // Create a reference to the iteration variable; we'll use this several
4548  // times throughout.
4549  Expr *IterationVarRef
4550    = S.BuildDeclRefExpr(IterationVar, SizeType, Loc).takeAs<Expr>();
4551  assert(IterationVarRef && "Reference to invented variable cannot fail!");
4552
4553  // Create the DeclStmt that holds the iteration variable.
4554  Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4555
4556  // Create the comparison against the array bound.
4557  llvm::APInt Upper = ArrayTy->getSize();
4558  Upper.zextOrTrunc(S.Context.getTypeSize(SizeType));
4559  OwningExprResult Comparison
4560    = S.Owned(new (S.Context) BinaryOperator(IterationVarRef->Retain(),
4561                           new (S.Context) IntegerLiteral(Upper, SizeType, Loc),
4562                                    BinaryOperator::NE, S.Context.BoolTy, Loc));
4563
4564  // Create the pre-increment of the iteration variable.
4565  OwningExprResult Increment
4566    = S.Owned(new (S.Context) UnaryOperator(IterationVarRef->Retain(),
4567                                            UnaryOperator::PreInc,
4568                                            SizeType, Loc));
4569
4570  // Subscript the "from" and "to" expressions with the iteration variable.
4571  From = S.CreateBuiltinArraySubscriptExpr(move(From), Loc,
4572                                           S.Owned(IterationVarRef->Retain()),
4573                                           Loc);
4574  To = S.CreateBuiltinArraySubscriptExpr(move(To), Loc,
4575                                         S.Owned(IterationVarRef->Retain()),
4576                                         Loc);
4577  assert(!From.isInvalid() && "Builtin subscripting can't fail!");
4578  assert(!To.isInvalid() && "Builtin subscripting can't fail!");
4579
4580  // Build the copy for an individual element of the array.
4581  OwningStmtResult Copy = BuildSingleCopyAssign(S, Loc,
4582                                                ArrayTy->getElementType(),
4583                                                move(To), move(From),
4584                                                CopyingBaseSubobject, Depth+1);
4585  if (Copy.isInvalid())
4586    return S.StmtError();
4587
4588  // Construct the loop that copies all elements of this array.
4589  return S.ActOnForStmt(Loc, Loc, S.Owned(InitStmt),
4590                        S.MakeFullExpr(Comparison),
4591                        Sema::DeclPtrTy(),
4592                        S.MakeFullExpr(Increment),
4593                        Loc, move(Copy));
4594}
4595
4596/// \brief Determine whether the given class has a copy assignment operator
4597/// that accepts a const-qualified argument.
4598static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
4599  CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
4600
4601  if (!Class->hasDeclaredCopyAssignment())
4602    S.DeclareImplicitCopyAssignment(Class);
4603
4604  QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
4605  DeclarationName OpName
4606    = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4607
4608  DeclContext::lookup_const_iterator Op, OpEnd;
4609  for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
4610    // C++ [class.copy]p9:
4611    //   A user-declared copy assignment operator is a non-static non-template
4612    //   member function of class X with exactly one parameter of type X, X&,
4613    //   const X&, volatile X& or const volatile X&.
4614    const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
4615    if (!Method)
4616      continue;
4617
4618    if (Method->isStatic())
4619      continue;
4620    if (Method->getPrimaryTemplate())
4621      continue;
4622    const FunctionProtoType *FnType =
4623    Method->getType()->getAs<FunctionProtoType>();
4624    assert(FnType && "Overloaded operator has no prototype.");
4625    // Don't assert on this; an invalid decl might have been left in the AST.
4626    if (FnType->getNumArgs() != 1 || FnType->isVariadic())
4627      continue;
4628    bool AcceptsConst = true;
4629    QualType ArgType = FnType->getArgType(0);
4630    if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
4631      ArgType = Ref->getPointeeType();
4632      // Is it a non-const lvalue reference?
4633      if (!ArgType.isConstQualified())
4634        AcceptsConst = false;
4635    }
4636    if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
4637      continue;
4638
4639    // We have a single argument of type cv X or cv X&, i.e. we've found the
4640    // copy assignment operator. Return whether it accepts const arguments.
4641    return AcceptsConst;
4642  }
4643  assert(Class->isInvalidDecl() &&
4644         "No copy assignment operator declared in valid code.");
4645  return false;
4646}
4647
4648CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
4649  // Note: The following rules are largely analoguous to the copy
4650  // constructor rules. Note that virtual bases are not taken into account
4651  // for determining the argument type of the operator. Note also that
4652  // operators taking an object instead of a reference are allowed.
4653
4654
4655  // C++ [class.copy]p10:
4656  //   If the class definition does not explicitly declare a copy
4657  //   assignment operator, one is declared implicitly.
4658  //   The implicitly-defined copy assignment operator for a class X
4659  //   will have the form
4660  //
4661  //       X& X::operator=(const X&)
4662  //
4663  //   if
4664  bool HasConstCopyAssignment = true;
4665
4666  //       -- each direct base class B of X has a copy assignment operator
4667  //          whose parameter is of type const B&, const volatile B& or B,
4668  //          and
4669  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4670                                       BaseEnd = ClassDecl->bases_end();
4671       HasConstCopyAssignment && Base != BaseEnd; ++Base) {
4672    assert(!Base->getType()->isDependentType() &&
4673           "Cannot generate implicit members for class with dependent bases.");
4674    const CXXRecordDecl *BaseClassDecl
4675      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
4676    HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
4677  }
4678
4679  //       -- for all the nonstatic data members of X that are of a class
4680  //          type M (or array thereof), each such class type has a copy
4681  //          assignment operator whose parameter is of type const M&,
4682  //          const volatile M& or M.
4683  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4684                                  FieldEnd = ClassDecl->field_end();
4685       HasConstCopyAssignment && Field != FieldEnd;
4686       ++Field) {
4687    QualType FieldType = Context.getBaseElementType((*Field)->getType());
4688    if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
4689      const CXXRecordDecl *FieldClassDecl
4690        = cast<CXXRecordDecl>(FieldClassType->getDecl());
4691      HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
4692    }
4693  }
4694
4695  //   Otherwise, the implicitly declared copy assignment operator will
4696  //   have the form
4697  //
4698  //       X& X::operator=(X&)
4699  QualType ArgType = Context.getTypeDeclType(ClassDecl);
4700  QualType RetType = Context.getLValueReferenceType(ArgType);
4701  if (HasConstCopyAssignment)
4702    ArgType = ArgType.withConst();
4703  ArgType = Context.getLValueReferenceType(ArgType);
4704
4705  // C++ [except.spec]p14:
4706  //   An implicitly declared special member function (Clause 12) shall have an
4707  //   exception-specification. [...]
4708  ImplicitExceptionSpecification ExceptSpec(Context);
4709  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4710                                       BaseEnd = ClassDecl->bases_end();
4711       Base != BaseEnd; ++Base) {
4712    CXXRecordDecl *BaseClassDecl
4713      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
4714
4715    if (!BaseClassDecl->hasDeclaredCopyAssignment())
4716      DeclareImplicitCopyAssignment(BaseClassDecl);
4717
4718    if (CXXMethodDecl *CopyAssign
4719           = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4720      ExceptSpec.CalledDecl(CopyAssign);
4721  }
4722  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4723                                  FieldEnd = ClassDecl->field_end();
4724       Field != FieldEnd;
4725       ++Field) {
4726    QualType FieldType = Context.getBaseElementType((*Field)->getType());
4727    if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
4728      CXXRecordDecl *FieldClassDecl
4729        = cast<CXXRecordDecl>(FieldClassType->getDecl());
4730
4731      if (!FieldClassDecl->hasDeclaredCopyAssignment())
4732        DeclareImplicitCopyAssignment(FieldClassDecl);
4733
4734      if (CXXMethodDecl *CopyAssign
4735            = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4736        ExceptSpec.CalledDecl(CopyAssign);
4737    }
4738  }
4739
4740  //   An implicitly-declared copy assignment operator is an inline public
4741  //   member of its class.
4742  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4743  CXXMethodDecl *CopyAssignment
4744    = CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
4745                            Context.getFunctionType(RetType, &ArgType, 1,
4746                                                    false, 0,
4747                                         ExceptSpec.hasExceptionSpecification(),
4748                                      ExceptSpec.hasAnyExceptionSpecification(),
4749                                                    ExceptSpec.size(),
4750                                                    ExceptSpec.data(),
4751                                                    FunctionType::ExtInfo()),
4752                            /*TInfo=*/0, /*isStatic=*/false,
4753                            /*StorageClassAsWritten=*/FunctionDecl::None,
4754                            /*isInline=*/true);
4755  CopyAssignment->setAccess(AS_public);
4756  CopyAssignment->setImplicit();
4757  CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
4758  CopyAssignment->setCopyAssignment(true);
4759
4760  // Add the parameter to the operator.
4761  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
4762                                               ClassDecl->getLocation(),
4763                                               /*Id=*/0,
4764                                               ArgType, /*TInfo=*/0,
4765                                               VarDecl::None,
4766                                               VarDecl::None, 0);
4767  CopyAssignment->setParams(&FromParam, 1);
4768
4769  // Note that we have added this copy-assignment operator.
4770  ClassDecl->setDeclaredCopyAssignment(true);
4771  ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
4772
4773  if (Scope *S = getScopeForContext(ClassDecl))
4774    PushOnScopeChains(CopyAssignment, S, false);
4775  ClassDecl->addDecl(CopyAssignment);
4776
4777  AddOverriddenMethods(ClassDecl, CopyAssignment);
4778  return CopyAssignment;
4779}
4780
4781void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4782                                        CXXMethodDecl *CopyAssignOperator) {
4783  assert((CopyAssignOperator->isImplicit() &&
4784          CopyAssignOperator->isOverloadedOperator() &&
4785          CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
4786          !CopyAssignOperator->isUsed(false)) &&
4787         "DefineImplicitCopyAssignment called for wrong function");
4788
4789  CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
4790
4791  if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
4792    CopyAssignOperator->setInvalidDecl();
4793    return;
4794  }
4795
4796  CopyAssignOperator->setUsed();
4797
4798  ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
4799  ErrorTrap Trap(*this);
4800
4801  // C++0x [class.copy]p30:
4802  //   The implicitly-defined or explicitly-defaulted copy assignment operator
4803  //   for a non-union class X performs memberwise copy assignment of its
4804  //   subobjects. The direct base classes of X are assigned first, in the
4805  //   order of their declaration in the base-specifier-list, and then the
4806  //   immediate non-static data members of X are assigned, in the order in
4807  //   which they were declared in the class definition.
4808
4809  // The statements that form the synthesized function body.
4810  ASTOwningVector<&ActionBase::DeleteStmt> Statements(*this);
4811
4812  // The parameter for the "other" object, which we are copying from.
4813  ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
4814  Qualifiers OtherQuals = Other->getType().getQualifiers();
4815  QualType OtherRefType = Other->getType();
4816  if (const LValueReferenceType *OtherRef
4817                                = OtherRefType->getAs<LValueReferenceType>()) {
4818    OtherRefType = OtherRef->getPointeeType();
4819    OtherQuals = OtherRefType.getQualifiers();
4820  }
4821
4822  // Our location for everything implicitly-generated.
4823  SourceLocation Loc = CopyAssignOperator->getLocation();
4824
4825  // Construct a reference to the "other" object. We'll be using this
4826  // throughout the generated ASTs.
4827  Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, Loc).takeAs<Expr>();
4828  assert(OtherRef && "Reference to parameter cannot fail!");
4829
4830  // Construct the "this" pointer. We'll be using this throughout the generated
4831  // ASTs.
4832  Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
4833  assert(This && "Reference to this cannot fail!");
4834
4835  // Assign base classes.
4836  bool Invalid = false;
4837  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4838       E = ClassDecl->bases_end(); Base != E; ++Base) {
4839    // Form the assignment:
4840    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
4841    QualType BaseType = Base->getType().getUnqualifiedType();
4842    CXXRecordDecl *BaseClassDecl = 0;
4843    if (const RecordType *BaseRecordT = BaseType->getAs<RecordType>())
4844      BaseClassDecl = cast<CXXRecordDecl>(BaseRecordT->getDecl());
4845    else {
4846      Invalid = true;
4847      continue;
4848    }
4849
4850    // Construct the "from" expression, which is an implicit cast to the
4851    // appropriately-qualified base type.
4852    Expr *From = OtherRef->Retain();
4853    ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
4854                      CastExpr::CK_UncheckedDerivedToBase,
4855                      ImplicitCastExpr::LValue, CXXBaseSpecifierArray(Base));
4856
4857    // Dereference "this".
4858    OwningExprResult To = CreateBuiltinUnaryOp(Loc, UnaryOperator::Deref,
4859                                               Owned(This->Retain()));
4860
4861    // Implicitly cast "this" to the appropriately-qualified base type.
4862    Expr *ToE = To.takeAs<Expr>();
4863    ImpCastExprToType(ToE,
4864                      Context.getCVRQualifiedType(BaseType,
4865                                      CopyAssignOperator->getTypeQualifiers()),
4866                      CastExpr::CK_UncheckedDerivedToBase,
4867                      ImplicitCastExpr::LValue, CXXBaseSpecifierArray(Base));
4868    To = Owned(ToE);
4869
4870    // Build the copy.
4871    OwningStmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
4872                                                  move(To), Owned(From),
4873                                                /*CopyingBaseSubobject=*/true);
4874    if (Copy.isInvalid()) {
4875      Diag(CurrentLocation, diag::note_member_synthesized_at)
4876        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
4877      CopyAssignOperator->setInvalidDecl();
4878      return;
4879    }
4880
4881    // Success! Record the copy.
4882    Statements.push_back(Copy.takeAs<Expr>());
4883  }
4884
4885  // \brief Reference to the __builtin_memcpy function.
4886  Expr *BuiltinMemCpyRef = 0;
4887  // \brief Reference to the __builtin_objc_memmove_collectable function.
4888  Expr *CollectableMemCpyRef = 0;
4889
4890  // Assign non-static members.
4891  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4892                                  FieldEnd = ClassDecl->field_end();
4893       Field != FieldEnd; ++Field) {
4894    // Check for members of reference type; we can't copy those.
4895    if (Field->getType()->isReferenceType()) {
4896      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4897        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
4898      Diag(Field->getLocation(), diag::note_declared_at);
4899      Diag(CurrentLocation, diag::note_member_synthesized_at)
4900        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
4901      Invalid = true;
4902      continue;
4903    }
4904
4905    // Check for members of const-qualified, non-class type.
4906    QualType BaseType = Context.getBaseElementType(Field->getType());
4907    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
4908      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4909        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
4910      Diag(Field->getLocation(), diag::note_declared_at);
4911      Diag(CurrentLocation, diag::note_member_synthesized_at)
4912        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
4913      Invalid = true;
4914      continue;
4915    }
4916
4917    QualType FieldType = Field->getType().getNonReferenceType();
4918    if (FieldType->isIncompleteArrayType()) {
4919      assert(ClassDecl->hasFlexibleArrayMember() &&
4920             "Incomplete array type is not valid");
4921      continue;
4922    }
4923
4924    // Build references to the field in the object we're copying from and to.
4925    CXXScopeSpec SS; // Intentionally empty
4926    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
4927                              LookupMemberName);
4928    MemberLookup.addDecl(*Field);
4929    MemberLookup.resolveKind();
4930    OwningExprResult From = BuildMemberReferenceExpr(Owned(OtherRef->Retain()),
4931                                                     OtherRefType,
4932                                                     Loc, /*IsArrow=*/false,
4933                                                     SS, 0, MemberLookup, 0);
4934    OwningExprResult To = BuildMemberReferenceExpr(Owned(This->Retain()),
4935                                                   This->getType(),
4936                                                   Loc, /*IsArrow=*/true,
4937                                                   SS, 0, MemberLookup, 0);
4938    assert(!From.isInvalid() && "Implicit field reference cannot fail");
4939    assert(!To.isInvalid() && "Implicit field reference cannot fail");
4940
4941    // If the field should be copied with __builtin_memcpy rather than via
4942    // explicit assignments, do so. This optimization only applies for arrays
4943    // of scalars and arrays of class type with trivial copy-assignment
4944    // operators.
4945    if (FieldType->isArrayType() &&
4946        (!BaseType->isRecordType() ||
4947         cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
4948           ->hasTrivialCopyAssignment())) {
4949      // Compute the size of the memory buffer to be copied.
4950      QualType SizeType = Context.getSizeType();
4951      llvm::APInt Size(Context.getTypeSize(SizeType),
4952                       Context.getTypeSizeInChars(BaseType).getQuantity());
4953      for (const ConstantArrayType *Array
4954              = Context.getAsConstantArrayType(FieldType);
4955           Array;
4956           Array = Context.getAsConstantArrayType(Array->getElementType())) {
4957        llvm::APInt ArraySize = Array->getSize();
4958        ArraySize.zextOrTrunc(Size.getBitWidth());
4959        Size *= ArraySize;
4960      }
4961
4962      // Take the address of the field references for "from" and "to".
4963      From = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(From));
4964      To = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(To));
4965
4966      bool NeedsCollectableMemCpy =
4967          (BaseType->isRecordType() &&
4968           BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
4969
4970      if (NeedsCollectableMemCpy) {
4971        if (!CollectableMemCpyRef) {
4972          // Create a reference to the __builtin_objc_memmove_collectable function.
4973          LookupResult R(*this,
4974                         &Context.Idents.get("__builtin_objc_memmove_collectable"),
4975                         Loc, LookupOrdinaryName);
4976          LookupName(R, TUScope, true);
4977
4978          FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
4979          if (!CollectableMemCpy) {
4980            // Something went horribly wrong earlier, and we will have
4981            // complained about it.
4982            Invalid = true;
4983            continue;
4984          }
4985
4986          CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
4987                                                  CollectableMemCpy->getType(),
4988                                                  Loc, 0).takeAs<Expr>();
4989          assert(CollectableMemCpyRef && "Builtin reference cannot fail");
4990        }
4991      }
4992      // Create a reference to the __builtin_memcpy builtin function.
4993      else if (!BuiltinMemCpyRef) {
4994        LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
4995                       LookupOrdinaryName);
4996        LookupName(R, TUScope, true);
4997
4998        FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
4999        if (!BuiltinMemCpy) {
5000          // Something went horribly wrong earlier, and we will have complained
5001          // about it.
5002          Invalid = true;
5003          continue;
5004        }
5005
5006        BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5007                                            BuiltinMemCpy->getType(),
5008                                            Loc, 0).takeAs<Expr>();
5009        assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5010      }
5011
5012      ASTOwningVector<&ActionBase::DeleteExpr> CallArgs(*this);
5013      CallArgs.push_back(To.takeAs<Expr>());
5014      CallArgs.push_back(From.takeAs<Expr>());
5015      CallArgs.push_back(new (Context) IntegerLiteral(Size, SizeType, Loc));
5016      llvm::SmallVector<SourceLocation, 4> Commas; // FIXME: Silly
5017      Commas.push_back(Loc);
5018      Commas.push_back(Loc);
5019      OwningExprResult Call = ExprError();
5020      if (NeedsCollectableMemCpy)
5021        Call = ActOnCallExpr(/*Scope=*/0,
5022                             Owned(CollectableMemCpyRef->Retain()),
5023                             Loc, move_arg(CallArgs),
5024                             Commas.data(), Loc);
5025      else
5026        Call = ActOnCallExpr(/*Scope=*/0,
5027                             Owned(BuiltinMemCpyRef->Retain()),
5028                             Loc, move_arg(CallArgs),
5029                             Commas.data(), Loc);
5030
5031      assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5032      Statements.push_back(Call.takeAs<Expr>());
5033      continue;
5034    }
5035
5036    // Build the copy of this field.
5037    OwningStmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
5038                                                  move(To), move(From),
5039                                              /*CopyingBaseSubobject=*/false);
5040    if (Copy.isInvalid()) {
5041      Diag(CurrentLocation, diag::note_member_synthesized_at)
5042        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5043      CopyAssignOperator->setInvalidDecl();
5044      return;
5045    }
5046
5047    // Success! Record the copy.
5048    Statements.push_back(Copy.takeAs<Stmt>());
5049  }
5050
5051  if (!Invalid) {
5052    // Add a "return *this;"
5053    OwningExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UnaryOperator::Deref,
5054                                                    Owned(This->Retain()));
5055
5056    OwningStmtResult Return = ActOnReturnStmt(Loc, move(ThisObj));
5057    if (Return.isInvalid())
5058      Invalid = true;
5059    else {
5060      Statements.push_back(Return.takeAs<Stmt>());
5061
5062      if (Trap.hasErrorOccurred()) {
5063        Diag(CurrentLocation, diag::note_member_synthesized_at)
5064          << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5065        Invalid = true;
5066      }
5067    }
5068  }
5069
5070  if (Invalid) {
5071    CopyAssignOperator->setInvalidDecl();
5072    return;
5073  }
5074
5075  OwningStmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
5076                                            /*isStmtExpr=*/false);
5077  assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5078  CopyAssignOperator->setBody(Body.takeAs<Stmt>());
5079}
5080
5081CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5082                                                    CXXRecordDecl *ClassDecl) {
5083  // C++ [class.copy]p4:
5084  //   If the class definition does not explicitly declare a copy
5085  //   constructor, one is declared implicitly.
5086
5087  // C++ [class.copy]p5:
5088  //   The implicitly-declared copy constructor for a class X will
5089  //   have the form
5090  //
5091  //       X::X(const X&)
5092  //
5093  //   if
5094  bool HasConstCopyConstructor = true;
5095
5096  //     -- each direct or virtual base class B of X has a copy
5097  //        constructor whose first parameter is of type const B& or
5098  //        const volatile B&, and
5099  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5100                                       BaseEnd = ClassDecl->bases_end();
5101       HasConstCopyConstructor && Base != BaseEnd;
5102       ++Base) {
5103    // Virtual bases are handled below.
5104    if (Base->isVirtual())
5105      continue;
5106
5107    CXXRecordDecl *BaseClassDecl
5108      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
5109    if (!BaseClassDecl->hasDeclaredCopyConstructor())
5110      DeclareImplicitCopyConstructor(BaseClassDecl);
5111
5112    HasConstCopyConstructor
5113      = BaseClassDecl->hasConstCopyConstructor(Context);
5114  }
5115
5116  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5117                                       BaseEnd = ClassDecl->vbases_end();
5118       HasConstCopyConstructor && Base != BaseEnd;
5119       ++Base) {
5120    CXXRecordDecl *BaseClassDecl
5121      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
5122    if (!BaseClassDecl->hasDeclaredCopyConstructor())
5123      DeclareImplicitCopyConstructor(BaseClassDecl);
5124
5125    HasConstCopyConstructor
5126      = BaseClassDecl->hasConstCopyConstructor(Context);
5127  }
5128
5129  //     -- for all the nonstatic data members of X that are of a
5130  //        class type M (or array thereof), each such class type
5131  //        has a copy constructor whose first parameter is of type
5132  //        const M& or const volatile M&.
5133  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5134                                  FieldEnd = ClassDecl->field_end();
5135       HasConstCopyConstructor && Field != FieldEnd;
5136       ++Field) {
5137    QualType FieldType = Context.getBaseElementType((*Field)->getType());
5138    if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
5139      CXXRecordDecl *FieldClassDecl
5140        = cast<CXXRecordDecl>(FieldClassType->getDecl());
5141      if (!FieldClassDecl->hasDeclaredCopyConstructor())
5142        DeclareImplicitCopyConstructor(FieldClassDecl);
5143
5144      HasConstCopyConstructor
5145        = FieldClassDecl->hasConstCopyConstructor(Context);
5146    }
5147  }
5148
5149  //   Otherwise, the implicitly declared copy constructor will have
5150  //   the form
5151  //
5152  //       X::X(X&)
5153  QualType ClassType = Context.getTypeDeclType(ClassDecl);
5154  QualType ArgType = ClassType;
5155  if (HasConstCopyConstructor)
5156    ArgType = ArgType.withConst();
5157  ArgType = Context.getLValueReferenceType(ArgType);
5158
5159  // C++ [except.spec]p14:
5160  //   An implicitly declared special member function (Clause 12) shall have an
5161  //   exception-specification. [...]
5162  ImplicitExceptionSpecification ExceptSpec(Context);
5163  unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5164  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5165                                       BaseEnd = ClassDecl->bases_end();
5166       Base != BaseEnd;
5167       ++Base) {
5168    // Virtual bases are handled below.
5169    if (Base->isVirtual())
5170      continue;
5171
5172    CXXRecordDecl *BaseClassDecl
5173      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
5174    if (!BaseClassDecl->hasDeclaredCopyConstructor())
5175      DeclareImplicitCopyConstructor(BaseClassDecl);
5176
5177    if (CXXConstructorDecl *CopyConstructor
5178                          = BaseClassDecl->getCopyConstructor(Context, Quals))
5179      ExceptSpec.CalledDecl(CopyConstructor);
5180  }
5181  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5182                                       BaseEnd = ClassDecl->vbases_end();
5183       Base != BaseEnd;
5184       ++Base) {
5185    CXXRecordDecl *BaseClassDecl
5186      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
5187    if (!BaseClassDecl->hasDeclaredCopyConstructor())
5188      DeclareImplicitCopyConstructor(BaseClassDecl);
5189
5190    if (CXXConstructorDecl *CopyConstructor
5191                          = BaseClassDecl->getCopyConstructor(Context, Quals))
5192      ExceptSpec.CalledDecl(CopyConstructor);
5193  }
5194  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5195                                  FieldEnd = ClassDecl->field_end();
5196       Field != FieldEnd;
5197       ++Field) {
5198    QualType FieldType = Context.getBaseElementType((*Field)->getType());
5199    if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
5200      CXXRecordDecl *FieldClassDecl
5201        = cast<CXXRecordDecl>(FieldClassType->getDecl());
5202      if (!FieldClassDecl->hasDeclaredCopyConstructor())
5203        DeclareImplicitCopyConstructor(FieldClassDecl);
5204
5205      if (CXXConstructorDecl *CopyConstructor
5206                          = FieldClassDecl->getCopyConstructor(Context, Quals))
5207        ExceptSpec.CalledDecl(CopyConstructor);
5208    }
5209  }
5210
5211  //   An implicitly-declared copy constructor is an inline public
5212  //   member of its class.
5213  DeclarationName Name
5214    = Context.DeclarationNames.getCXXConstructorName(
5215                                           Context.getCanonicalType(ClassType));
5216  CXXConstructorDecl *CopyConstructor
5217    = CXXConstructorDecl::Create(Context, ClassDecl,
5218                                 ClassDecl->getLocation(), Name,
5219                                 Context.getFunctionType(Context.VoidTy,
5220                                                         &ArgType, 1,
5221                                                         false, 0,
5222                                         ExceptSpec.hasExceptionSpecification(),
5223                                      ExceptSpec.hasAnyExceptionSpecification(),
5224                                                         ExceptSpec.size(),
5225                                                         ExceptSpec.data(),
5226                                                       FunctionType::ExtInfo()),
5227                                 /*TInfo=*/0,
5228                                 /*isExplicit=*/false,
5229                                 /*isInline=*/true,
5230                                 /*isImplicitlyDeclared=*/true);
5231  CopyConstructor->setAccess(AS_public);
5232  CopyConstructor->setImplicit();
5233  CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5234
5235  // Note that we have declared this constructor.
5236  ClassDecl->setDeclaredCopyConstructor(true);
5237  ++ASTContext::NumImplicitCopyConstructorsDeclared;
5238
5239  // Add the parameter to the constructor.
5240  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
5241                                               ClassDecl->getLocation(),
5242                                               /*IdentifierInfo=*/0,
5243                                               ArgType, /*TInfo=*/0,
5244                                               VarDecl::None,
5245                                               VarDecl::None, 0);
5246  CopyConstructor->setParams(&FromParam, 1);
5247  if (Scope *S = getScopeForContext(ClassDecl))
5248    PushOnScopeChains(CopyConstructor, S, false);
5249  ClassDecl->addDecl(CopyConstructor);
5250
5251  return CopyConstructor;
5252}
5253
5254void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5255                                   CXXConstructorDecl *CopyConstructor,
5256                                   unsigned TypeQuals) {
5257  assert((CopyConstructor->isImplicit() &&
5258          CopyConstructor->isCopyConstructor(TypeQuals) &&
5259          !CopyConstructor->isUsed(false)) &&
5260         "DefineImplicitCopyConstructor - call it for implicit copy ctor");
5261
5262  CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
5263  assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
5264
5265  ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
5266  ErrorTrap Trap(*this);
5267
5268  if (SetBaseOrMemberInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
5269      Trap.hasErrorOccurred()) {
5270    Diag(CurrentLocation, diag::note_member_synthesized_at)
5271      << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
5272    CopyConstructor->setInvalidDecl();
5273  }  else {
5274    CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
5275                                               CopyConstructor->getLocation(),
5276                                               MultiStmtArg(*this, 0, 0),
5277                                               /*isStmtExpr=*/false)
5278                                                              .takeAs<Stmt>());
5279  }
5280
5281  CopyConstructor->setUsed();
5282}
5283
5284Sema::OwningExprResult
5285Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5286                            CXXConstructorDecl *Constructor,
5287                            MultiExprArg ExprArgs,
5288                            bool RequiresZeroInit,
5289                            CXXConstructExpr::ConstructionKind ConstructKind) {
5290  bool Elidable = false;
5291
5292  // C++0x [class.copy]p34:
5293  //   When certain criteria are met, an implementation is allowed to
5294  //   omit the copy/move construction of a class object, even if the
5295  //   copy/move constructor and/or destructor for the object have
5296  //   side effects. [...]
5297  //     - when a temporary class object that has not been bound to a
5298  //       reference (12.2) would be copied/moved to a class object
5299  //       with the same cv-unqualified type, the copy/move operation
5300  //       can be omitted by constructing the temporary object
5301  //       directly into the target of the omitted copy/move
5302  if (Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
5303    Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
5304    Elidable = SubExpr->isTemporaryObject() &&
5305      Context.hasSameUnqualifiedType(SubExpr->getType(),
5306                           Context.getTypeDeclType(Constructor->getParent()));
5307  }
5308
5309  return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
5310                               Elidable, move(ExprArgs), RequiresZeroInit,
5311                               ConstructKind);
5312}
5313
5314/// BuildCXXConstructExpr - Creates a complete call to a constructor,
5315/// including handling of its default argument expressions.
5316Sema::OwningExprResult
5317Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5318                            CXXConstructorDecl *Constructor, bool Elidable,
5319                            MultiExprArg ExprArgs,
5320                            bool RequiresZeroInit,
5321                            CXXConstructExpr::ConstructionKind ConstructKind) {
5322  unsigned NumExprs = ExprArgs.size();
5323  Expr **Exprs = (Expr **)ExprArgs.release();
5324
5325  MarkDeclarationReferenced(ConstructLoc, Constructor);
5326  return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
5327                                        Constructor, Elidable, Exprs, NumExprs,
5328                                        RequiresZeroInit, ConstructKind));
5329}
5330
5331bool Sema::InitializeVarWithConstructor(VarDecl *VD,
5332                                        CXXConstructorDecl *Constructor,
5333                                        MultiExprArg Exprs) {
5334  OwningExprResult TempResult =
5335    BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
5336                          move(Exprs));
5337  if (TempResult.isInvalid())
5338    return true;
5339
5340  Expr *Temp = TempResult.takeAs<Expr>();
5341  MarkDeclarationReferenced(VD->getLocation(), Constructor);
5342  Temp = MaybeCreateCXXExprWithTemporaries(Temp);
5343  VD->setInit(Temp);
5344
5345  return false;
5346}
5347
5348void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
5349  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
5350  if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
5351      !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
5352    CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
5353    MarkDeclarationReferenced(VD->getLocation(), Destructor);
5354    CheckDestructorAccess(VD->getLocation(), Destructor,
5355                          PDiag(diag::err_access_dtor_var)
5356                            << VD->getDeclName()
5357                            << VD->getType());
5358  }
5359}
5360
5361/// AddCXXDirectInitializerToDecl - This action is called immediately after
5362/// ActOnDeclarator, when a C++ direct initializer is present.
5363/// e.g: "int x(1);"
5364void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
5365                                         SourceLocation LParenLoc,
5366                                         MultiExprArg Exprs,
5367                                         SourceLocation *CommaLocs,
5368                                         SourceLocation RParenLoc) {
5369  assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
5370  Decl *RealDecl = Dcl.getAs<Decl>();
5371
5372  // If there is no declaration, there was an error parsing it.  Just ignore
5373  // the initializer.
5374  if (RealDecl == 0)
5375    return;
5376
5377  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5378  if (!VDecl) {
5379    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
5380    RealDecl->setInvalidDecl();
5381    return;
5382  }
5383
5384  // We will represent direct-initialization similarly to copy-initialization:
5385  //    int x(1);  -as-> int x = 1;
5386  //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
5387  //
5388  // Clients that want to distinguish between the two forms, can check for
5389  // direct initializer using VarDecl::hasCXXDirectInitializer().
5390  // A major benefit is that clients that don't particularly care about which
5391  // exactly form was it (like the CodeGen) can handle both cases without
5392  // special case code.
5393
5394  // C++ 8.5p11:
5395  // The form of initialization (using parentheses or '=') is generally
5396  // insignificant, but does matter when the entity being initialized has a
5397  // class type.
5398
5399  if (!VDecl->getType()->isDependentType() &&
5400      RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
5401                          diag::err_typecheck_decl_incomplete_type)) {
5402    VDecl->setInvalidDecl();
5403    return;
5404  }
5405
5406  // The variable can not have an abstract class type.
5407  if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5408                             diag::err_abstract_type_in_decl,
5409                             AbstractVariableType))
5410    VDecl->setInvalidDecl();
5411
5412  const VarDecl *Def;
5413  if ((Def = VDecl->getDefinition()) && Def != VDecl) {
5414    Diag(VDecl->getLocation(), diag::err_redefinition)
5415    << VDecl->getDeclName();
5416    Diag(Def->getLocation(), diag::note_previous_definition);
5417    VDecl->setInvalidDecl();
5418    return;
5419  }
5420
5421  // If either the declaration has a dependent type or if any of the
5422  // expressions is type-dependent, we represent the initialization
5423  // via a ParenListExpr for later use during template instantiation.
5424  if (VDecl->getType()->isDependentType() ||
5425      Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
5426    // Let clients know that initialization was done with a direct initializer.
5427    VDecl->setCXXDirectInitializer(true);
5428
5429    // Store the initialization expressions as a ParenListExpr.
5430    unsigned NumExprs = Exprs.size();
5431    VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
5432                                               (Expr **)Exprs.release(),
5433                                               NumExprs, RParenLoc));
5434    return;
5435  }
5436
5437  // Capture the variable that is being initialized and the style of
5438  // initialization.
5439  InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
5440
5441  // FIXME: Poor source location information.
5442  InitializationKind Kind
5443    = InitializationKind::CreateDirect(VDecl->getLocation(),
5444                                       LParenLoc, RParenLoc);
5445
5446  InitializationSequence InitSeq(*this, Entity, Kind,
5447                                 (Expr**)Exprs.get(), Exprs.size());
5448  OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
5449  if (Result.isInvalid()) {
5450    VDecl->setInvalidDecl();
5451    return;
5452  }
5453
5454  Result = MaybeCreateCXXExprWithTemporaries(move(Result));
5455  VDecl->setInit(Result.takeAs<Expr>());
5456  VDecl->setCXXDirectInitializer(true);
5457
5458  if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
5459    FinalizeVarWithDestructor(VDecl, Record);
5460}
5461
5462/// \brief Given a constructor and the set of arguments provided for the
5463/// constructor, convert the arguments and add any required default arguments
5464/// to form a proper call to this constructor.
5465///
5466/// \returns true if an error occurred, false otherwise.
5467bool
5468Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
5469                              MultiExprArg ArgsPtr,
5470                              SourceLocation Loc,
5471                     ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
5472  // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
5473  unsigned NumArgs = ArgsPtr.size();
5474  Expr **Args = (Expr **)ArgsPtr.get();
5475
5476  const FunctionProtoType *Proto
5477    = Constructor->getType()->getAs<FunctionProtoType>();
5478  assert(Proto && "Constructor without a prototype?");
5479  unsigned NumArgsInProto = Proto->getNumArgs();
5480
5481  // If too few arguments are available, we'll fill in the rest with defaults.
5482  if (NumArgs < NumArgsInProto)
5483    ConvertedArgs.reserve(NumArgsInProto);
5484  else
5485    ConvertedArgs.reserve(NumArgs);
5486
5487  VariadicCallType CallType =
5488    Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5489  llvm::SmallVector<Expr *, 8> AllArgs;
5490  bool Invalid = GatherArgumentsForCall(Loc, Constructor,
5491                                        Proto, 0, Args, NumArgs, AllArgs,
5492                                        CallType);
5493  for (unsigned i =0, size = AllArgs.size(); i < size; i++)
5494    ConvertedArgs.push_back(AllArgs[i]);
5495  return Invalid;
5496}
5497
5498static inline bool
5499CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
5500                                       const FunctionDecl *FnDecl) {
5501  const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
5502  if (isa<NamespaceDecl>(DC)) {
5503    return SemaRef.Diag(FnDecl->getLocation(),
5504                        diag::err_operator_new_delete_declared_in_namespace)
5505      << FnDecl->getDeclName();
5506  }
5507
5508  if (isa<TranslationUnitDecl>(DC) &&
5509      FnDecl->getStorageClass() == FunctionDecl::Static) {
5510    return SemaRef.Diag(FnDecl->getLocation(),
5511                        diag::err_operator_new_delete_declared_static)
5512      << FnDecl->getDeclName();
5513  }
5514
5515  return false;
5516}
5517
5518static inline bool
5519CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
5520                            CanQualType ExpectedResultType,
5521                            CanQualType ExpectedFirstParamType,
5522                            unsigned DependentParamTypeDiag,
5523                            unsigned InvalidParamTypeDiag) {
5524  QualType ResultType =
5525    FnDecl->getType()->getAs<FunctionType>()->getResultType();
5526
5527  // Check that the result type is not dependent.
5528  if (ResultType->isDependentType())
5529    return SemaRef.Diag(FnDecl->getLocation(),
5530                        diag::err_operator_new_delete_dependent_result_type)
5531    << FnDecl->getDeclName() << ExpectedResultType;
5532
5533  // Check that the result type is what we expect.
5534  if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
5535    return SemaRef.Diag(FnDecl->getLocation(),
5536                        diag::err_operator_new_delete_invalid_result_type)
5537    << FnDecl->getDeclName() << ExpectedResultType;
5538
5539  // A function template must have at least 2 parameters.
5540  if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
5541    return SemaRef.Diag(FnDecl->getLocation(),
5542                      diag::err_operator_new_delete_template_too_few_parameters)
5543        << FnDecl->getDeclName();
5544
5545  // The function decl must have at least 1 parameter.
5546  if (FnDecl->getNumParams() == 0)
5547    return SemaRef.Diag(FnDecl->getLocation(),
5548                        diag::err_operator_new_delete_too_few_parameters)
5549      << FnDecl->getDeclName();
5550
5551  // Check the the first parameter type is not dependent.
5552  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
5553  if (FirstParamType->isDependentType())
5554    return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
5555      << FnDecl->getDeclName() << ExpectedFirstParamType;
5556
5557  // Check that the first parameter type is what we expect.
5558  if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
5559      ExpectedFirstParamType)
5560    return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
5561    << FnDecl->getDeclName() << ExpectedFirstParamType;
5562
5563  return false;
5564}
5565
5566static bool
5567CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
5568  // C++ [basic.stc.dynamic.allocation]p1:
5569  //   A program is ill-formed if an allocation function is declared in a
5570  //   namespace scope other than global scope or declared static in global
5571  //   scope.
5572  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5573    return true;
5574
5575  CanQualType SizeTy =
5576    SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
5577
5578  // C++ [basic.stc.dynamic.allocation]p1:
5579  //  The return type shall be void*. The first parameter shall have type
5580  //  std::size_t.
5581  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
5582                                  SizeTy,
5583                                  diag::err_operator_new_dependent_param_type,
5584                                  diag::err_operator_new_param_type))
5585    return true;
5586
5587  // C++ [basic.stc.dynamic.allocation]p1:
5588  //  The first parameter shall not have an associated default argument.
5589  if (FnDecl->getParamDecl(0)->hasDefaultArg())
5590    return SemaRef.Diag(FnDecl->getLocation(),
5591                        diag::err_operator_new_default_arg)
5592      << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
5593
5594  return false;
5595}
5596
5597static bool
5598CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
5599  // C++ [basic.stc.dynamic.deallocation]p1:
5600  //   A program is ill-formed if deallocation functions are declared in a
5601  //   namespace scope other than global scope or declared static in global
5602  //   scope.
5603  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5604    return true;
5605
5606  // C++ [basic.stc.dynamic.deallocation]p2:
5607  //   Each deallocation function shall return void and its first parameter
5608  //   shall be void*.
5609  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
5610                                  SemaRef.Context.VoidPtrTy,
5611                                 diag::err_operator_delete_dependent_param_type,
5612                                 diag::err_operator_delete_param_type))
5613    return true;
5614
5615  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
5616  if (FirstParamType->isDependentType())
5617    return SemaRef.Diag(FnDecl->getLocation(),
5618                        diag::err_operator_delete_dependent_param_type)
5619    << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
5620
5621  if (SemaRef.Context.getCanonicalType(FirstParamType) !=
5622      SemaRef.Context.VoidPtrTy)
5623    return SemaRef.Diag(FnDecl->getLocation(),
5624                        diag::err_operator_delete_param_type)
5625      << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
5626
5627  return false;
5628}
5629
5630/// CheckOverloadedOperatorDeclaration - Check whether the declaration
5631/// of this overloaded operator is well-formed. If so, returns false;
5632/// otherwise, emits appropriate diagnostics and returns true.
5633bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
5634  assert(FnDecl && FnDecl->isOverloadedOperator() &&
5635         "Expected an overloaded operator declaration");
5636
5637  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
5638
5639  // C++ [over.oper]p5:
5640  //   The allocation and deallocation functions, operator new,
5641  //   operator new[], operator delete and operator delete[], are
5642  //   described completely in 3.7.3. The attributes and restrictions
5643  //   found in the rest of this subclause do not apply to them unless
5644  //   explicitly stated in 3.7.3.
5645  if (Op == OO_Delete || Op == OO_Array_Delete)
5646    return CheckOperatorDeleteDeclaration(*this, FnDecl);
5647
5648  if (Op == OO_New || Op == OO_Array_New)
5649    return CheckOperatorNewDeclaration(*this, FnDecl);
5650
5651  // C++ [over.oper]p6:
5652  //   An operator function shall either be a non-static member
5653  //   function or be a non-member function and have at least one
5654  //   parameter whose type is a class, a reference to a class, an
5655  //   enumeration, or a reference to an enumeration.
5656  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
5657    if (MethodDecl->isStatic())
5658      return Diag(FnDecl->getLocation(),
5659                  diag::err_operator_overload_static) << FnDecl->getDeclName();
5660  } else {
5661    bool ClassOrEnumParam = false;
5662    for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
5663                                   ParamEnd = FnDecl->param_end();
5664         Param != ParamEnd; ++Param) {
5665      QualType ParamType = (*Param)->getType().getNonReferenceType();
5666      if (ParamType->isDependentType() || ParamType->isRecordType() ||
5667          ParamType->isEnumeralType()) {
5668        ClassOrEnumParam = true;
5669        break;
5670      }
5671    }
5672
5673    if (!ClassOrEnumParam)
5674      return Diag(FnDecl->getLocation(),
5675                  diag::err_operator_overload_needs_class_or_enum)
5676        << FnDecl->getDeclName();
5677  }
5678
5679  // C++ [over.oper]p8:
5680  //   An operator function cannot have default arguments (8.3.6),
5681  //   except where explicitly stated below.
5682  //
5683  // Only the function-call operator allows default arguments
5684  // (C++ [over.call]p1).
5685  if (Op != OO_Call) {
5686    for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
5687         Param != FnDecl->param_end(); ++Param) {
5688      if ((*Param)->hasDefaultArg())
5689        return Diag((*Param)->getLocation(),
5690                    diag::err_operator_overload_default_arg)
5691          << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
5692    }
5693  }
5694
5695  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
5696    { false, false, false }
5697#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5698    , { Unary, Binary, MemberOnly }
5699#include "clang/Basic/OperatorKinds.def"
5700  };
5701
5702  bool CanBeUnaryOperator = OperatorUses[Op][0];
5703  bool CanBeBinaryOperator = OperatorUses[Op][1];
5704  bool MustBeMemberOperator = OperatorUses[Op][2];
5705
5706  // C++ [over.oper]p8:
5707  //   [...] Operator functions cannot have more or fewer parameters
5708  //   than the number required for the corresponding operator, as
5709  //   described in the rest of this subclause.
5710  unsigned NumParams = FnDecl->getNumParams()
5711                     + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
5712  if (Op != OO_Call &&
5713      ((NumParams == 1 && !CanBeUnaryOperator) ||
5714       (NumParams == 2 && !CanBeBinaryOperator) ||
5715       (NumParams < 1) || (NumParams > 2))) {
5716    // We have the wrong number of parameters.
5717    unsigned ErrorKind;
5718    if (CanBeUnaryOperator && CanBeBinaryOperator) {
5719      ErrorKind = 2;  // 2 -> unary or binary.
5720    } else if (CanBeUnaryOperator) {
5721      ErrorKind = 0;  // 0 -> unary
5722    } else {
5723      assert(CanBeBinaryOperator &&
5724             "All non-call overloaded operators are unary or binary!");
5725      ErrorKind = 1;  // 1 -> binary
5726    }
5727
5728    return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
5729      << FnDecl->getDeclName() << NumParams << ErrorKind;
5730  }
5731
5732  // Overloaded operators other than operator() cannot be variadic.
5733  if (Op != OO_Call &&
5734      FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
5735    return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
5736      << FnDecl->getDeclName();
5737  }
5738
5739  // Some operators must be non-static member functions.
5740  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5741    return Diag(FnDecl->getLocation(),
5742                diag::err_operator_overload_must_be_member)
5743      << FnDecl->getDeclName();
5744  }
5745
5746  // C++ [over.inc]p1:
5747  //   The user-defined function called operator++ implements the
5748  //   prefix and postfix ++ operator. If this function is a member
5749  //   function with no parameters, or a non-member function with one
5750  //   parameter of class or enumeration type, it defines the prefix
5751  //   increment operator ++ for objects of that type. If the function
5752  //   is a member function with one parameter (which shall be of type
5753  //   int) or a non-member function with two parameters (the second
5754  //   of which shall be of type int), it defines the postfix
5755  //   increment operator ++ for objects of that type.
5756  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5757    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5758    bool ParamIsInt = false;
5759    if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
5760      ParamIsInt = BT->getKind() == BuiltinType::Int;
5761
5762    if (!ParamIsInt)
5763      return Diag(LastParam->getLocation(),
5764                  diag::err_operator_overload_post_incdec_must_be_int)
5765        << LastParam->getType() << (Op == OO_MinusMinus);
5766  }
5767
5768  // Notify the class if it got an assignment operator.
5769  if (Op == OO_Equal) {
5770    // Would have returned earlier otherwise.
5771    assert(isa<CXXMethodDecl>(FnDecl) &&
5772      "Overloaded = not member, but not filtered.");
5773    CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5774    Method->getParent()->addedAssignmentOperator(Context, Method);
5775  }
5776
5777  return false;
5778}
5779
5780/// CheckLiteralOperatorDeclaration - Check whether the declaration
5781/// of this literal operator function is well-formed. If so, returns
5782/// false; otherwise, emits appropriate diagnostics and returns true.
5783bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5784  DeclContext *DC = FnDecl->getDeclContext();
5785  Decl::Kind Kind = DC->getDeclKind();
5786  if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5787      Kind != Decl::LinkageSpec) {
5788    Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5789      << FnDecl->getDeclName();
5790    return true;
5791  }
5792
5793  bool Valid = false;
5794
5795  // template <char...> type operator "" name() is the only valid template
5796  // signature, and the only valid signature with no parameters.
5797  if (FnDecl->param_size() == 0) {
5798    if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
5799      // Must have only one template parameter
5800      TemplateParameterList *Params = TpDecl->getTemplateParameters();
5801      if (Params->size() == 1) {
5802        NonTypeTemplateParmDecl *PmDecl =
5803          cast<NonTypeTemplateParmDecl>(Params->getParam(0));
5804
5805        // The template parameter must be a char parameter pack.
5806        // FIXME: This test will always fail because non-type parameter packs
5807        //   have not been implemented.
5808        if (PmDecl && PmDecl->isTemplateParameterPack() &&
5809            Context.hasSameType(PmDecl->getType(), Context.CharTy))
5810          Valid = true;
5811      }
5812    }
5813  } else {
5814    // Check the first parameter
5815    FunctionDecl::param_iterator Param = FnDecl->param_begin();
5816
5817    QualType T = (*Param)->getType();
5818
5819    // unsigned long long int, long double, and any character type are allowed
5820    // as the only parameters.
5821    if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5822        Context.hasSameType(T, Context.LongDoubleTy) ||
5823        Context.hasSameType(T, Context.CharTy) ||
5824        Context.hasSameType(T, Context.WCharTy) ||
5825        Context.hasSameType(T, Context.Char16Ty) ||
5826        Context.hasSameType(T, Context.Char32Ty)) {
5827      if (++Param == FnDecl->param_end())
5828        Valid = true;
5829      goto FinishedParams;
5830    }
5831
5832    // Otherwise it must be a pointer to const; let's strip those qualifiers.
5833    const PointerType *PT = T->getAs<PointerType>();
5834    if (!PT)
5835      goto FinishedParams;
5836    T = PT->getPointeeType();
5837    if (!T.isConstQualified())
5838      goto FinishedParams;
5839    T = T.getUnqualifiedType();
5840
5841    // Move on to the second parameter;
5842    ++Param;
5843
5844    // If there is no second parameter, the first must be a const char *
5845    if (Param == FnDecl->param_end()) {
5846      if (Context.hasSameType(T, Context.CharTy))
5847        Valid = true;
5848      goto FinishedParams;
5849    }
5850
5851    // const char *, const wchar_t*, const char16_t*, and const char32_t*
5852    // are allowed as the first parameter to a two-parameter function
5853    if (!(Context.hasSameType(T, Context.CharTy) ||
5854          Context.hasSameType(T, Context.WCharTy) ||
5855          Context.hasSameType(T, Context.Char16Ty) ||
5856          Context.hasSameType(T, Context.Char32Ty)))
5857      goto FinishedParams;
5858
5859    // The second and final parameter must be an std::size_t
5860    T = (*Param)->getType().getUnqualifiedType();
5861    if (Context.hasSameType(T, Context.getSizeType()) &&
5862        ++Param == FnDecl->param_end())
5863      Valid = true;
5864  }
5865
5866  // FIXME: This diagnostic is absolutely terrible.
5867FinishedParams:
5868  if (!Valid) {
5869    Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
5870      << FnDecl->getDeclName();
5871    return true;
5872  }
5873
5874  return false;
5875}
5876
5877/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5878/// linkage specification, including the language and (if present)
5879/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
5880/// the location of the language string literal, which is provided
5881/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
5882/// the '{' brace. Otherwise, this linkage specification does not
5883/// have any braces.
5884Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
5885                                                     SourceLocation ExternLoc,
5886                                                     SourceLocation LangLoc,
5887                                                     llvm::StringRef Lang,
5888                                                     SourceLocation LBraceLoc) {
5889  LinkageSpecDecl::LanguageIDs Language;
5890  if (Lang == "\"C\"")
5891    Language = LinkageSpecDecl::lang_c;
5892  else if (Lang == "\"C++\"")
5893    Language = LinkageSpecDecl::lang_cxx;
5894  else {
5895    Diag(LangLoc, diag::err_bad_language);
5896    return DeclPtrTy();
5897  }
5898
5899  // FIXME: Add all the various semantics of linkage specifications
5900
5901  LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
5902                                               LangLoc, Language,
5903                                               LBraceLoc.isValid());
5904  CurContext->addDecl(D);
5905  PushDeclContext(S, D);
5906  return DeclPtrTy::make(D);
5907}
5908
5909/// ActOnFinishLinkageSpecification - Completely the definition of
5910/// the C++ linkage specification LinkageSpec. If RBraceLoc is
5911/// valid, it's the position of the closing '}' brace in a linkage
5912/// specification that uses braces.
5913Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
5914                                                      DeclPtrTy LinkageSpec,
5915                                                      SourceLocation RBraceLoc) {
5916  if (LinkageSpec)
5917    PopDeclContext();
5918  return LinkageSpec;
5919}
5920
5921/// \brief Perform semantic analysis for the variable declaration that
5922/// occurs within a C++ catch clause, returning the newly-created
5923/// variable.
5924VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
5925                                         TypeSourceInfo *TInfo,
5926                                         IdentifierInfo *Name,
5927                                         SourceLocation Loc,
5928                                         SourceRange Range) {
5929  bool Invalid = false;
5930
5931  // Arrays and functions decay.
5932  if (ExDeclType->isArrayType())
5933    ExDeclType = Context.getArrayDecayedType(ExDeclType);
5934  else if (ExDeclType->isFunctionType())
5935    ExDeclType = Context.getPointerType(ExDeclType);
5936
5937  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
5938  // The exception-declaration shall not denote a pointer or reference to an
5939  // incomplete type, other than [cv] void*.
5940  // N2844 forbids rvalue references.
5941  if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
5942    Diag(Loc, diag::err_catch_rvalue_ref) << Range;
5943    Invalid = true;
5944  }
5945
5946  // GCC allows catching pointers and references to incomplete types
5947  // as an extension; so do we, but we warn by default.
5948
5949  QualType BaseType = ExDeclType;
5950  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
5951  unsigned DK = diag::err_catch_incomplete;
5952  bool IncompleteCatchIsInvalid = true;
5953  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
5954    BaseType = Ptr->getPointeeType();
5955    Mode = 1;
5956    DK = diag::ext_catch_incomplete_ptr;
5957    IncompleteCatchIsInvalid = false;
5958  } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
5959    // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
5960    BaseType = Ref->getPointeeType();
5961    Mode = 2;
5962    DK = diag::ext_catch_incomplete_ref;
5963    IncompleteCatchIsInvalid = false;
5964  }
5965  if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
5966      !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
5967      IncompleteCatchIsInvalid)
5968    Invalid = true;
5969
5970  if (!Invalid && !ExDeclType->isDependentType() &&
5971      RequireNonAbstractType(Loc, ExDeclType,
5972                             diag::err_abstract_type_in_decl,
5973                             AbstractVariableType))
5974    Invalid = true;
5975
5976  // Only the non-fragile NeXT runtime currently supports C++ catches
5977  // of ObjC types, and no runtime supports catching ObjC types by value.
5978  if (!Invalid && getLangOptions().ObjC1) {
5979    QualType T = ExDeclType;
5980    if (const ReferenceType *RT = T->getAs<ReferenceType>())
5981      T = RT->getPointeeType();
5982
5983    if (T->isObjCObjectType()) {
5984      Diag(Loc, diag::err_objc_object_catch);
5985      Invalid = true;
5986    } else if (T->isObjCObjectPointerType()) {
5987      if (!getLangOptions().NeXTRuntime) {
5988        Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu);
5989        Invalid = true;
5990      } else if (!getLangOptions().ObjCNonFragileABI) {
5991        Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
5992        Invalid = true;
5993      }
5994    }
5995  }
5996
5997  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
5998                                    Name, ExDeclType, TInfo, VarDecl::None,
5999                                    VarDecl::None);
6000  ExDecl->setExceptionVariable(true);
6001
6002  if (!Invalid) {
6003    if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
6004      // C++ [except.handle]p16:
6005      //   The object declared in an exception-declaration or, if the
6006      //   exception-declaration does not specify a name, a temporary (12.2) is
6007      //   copy-initialized (8.5) from the exception object. [...]
6008      //   The object is destroyed when the handler exits, after the destruction
6009      //   of any automatic objects initialized within the handler.
6010      //
6011      // We just pretend to initialize the object with itself, then make sure
6012      // it can be destroyed later.
6013      InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
6014      Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
6015                                            Loc, ExDeclType, 0);
6016      InitializationKind Kind = InitializationKind::CreateCopy(Loc,
6017                                                               SourceLocation());
6018      InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
6019      OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
6020                                    MultiExprArg(*this, (void**)&ExDeclRef, 1));
6021      if (Result.isInvalid())
6022        Invalid = true;
6023      else
6024        FinalizeVarWithDestructor(ExDecl, RecordTy);
6025    }
6026  }
6027
6028  if (Invalid)
6029    ExDecl->setInvalidDecl();
6030
6031  return ExDecl;
6032}
6033
6034/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6035/// handler.
6036Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
6037  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6038  QualType ExDeclType = TInfo->getType();
6039
6040  bool Invalid = D.isInvalidType();
6041  IdentifierInfo *II = D.getIdentifier();
6042  if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
6043                                             LookupOrdinaryName,
6044                                             ForRedeclaration)) {
6045    // The scope should be freshly made just for us. There is just no way
6046    // it contains any previous declaration.
6047    assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
6048    if (PrevDecl->isTemplateParameter()) {
6049      // Maybe we will complain about the shadowed template parameter.
6050      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
6051    }
6052  }
6053
6054  if (D.getCXXScopeSpec().isSet() && !Invalid) {
6055    Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6056      << D.getCXXScopeSpec().getRange();
6057    Invalid = true;
6058  }
6059
6060  VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
6061                                              D.getIdentifier(),
6062                                              D.getIdentifierLoc(),
6063                                            D.getDeclSpec().getSourceRange());
6064
6065  if (Invalid)
6066    ExDecl->setInvalidDecl();
6067
6068  // Add the exception declaration into this scope.
6069  if (II)
6070    PushOnScopeChains(ExDecl, S);
6071  else
6072    CurContext->addDecl(ExDecl);
6073
6074  ProcessDeclAttributes(S, ExDecl, D);
6075  return DeclPtrTy::make(ExDecl);
6076}
6077
6078Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
6079                                                   ExprArg assertexpr,
6080                                                   ExprArg assertmessageexpr) {
6081  Expr *AssertExpr = (Expr *)assertexpr.get();
6082  StringLiteral *AssertMessage =
6083    cast<StringLiteral>((Expr *)assertmessageexpr.get());
6084
6085  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6086    llvm::APSInt Value(32);
6087    if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
6088      Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
6089        AssertExpr->getSourceRange();
6090      return DeclPtrTy();
6091    }
6092
6093    if (Value == 0) {
6094      Diag(AssertLoc, diag::err_static_assert_failed)
6095        << AssertMessage->getString() << AssertExpr->getSourceRange();
6096    }
6097  }
6098
6099  assertexpr.release();
6100  assertmessageexpr.release();
6101  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
6102                                        AssertExpr, AssertMessage);
6103
6104  CurContext->addDecl(Decl);
6105  return DeclPtrTy::make(Decl);
6106}
6107
6108/// \brief Perform semantic analysis of the given friend type declaration.
6109///
6110/// \returns A friend declaration that.
6111FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6112                                      TypeSourceInfo *TSInfo) {
6113  assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6114
6115  QualType T = TSInfo->getType();
6116  SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
6117
6118  if (!getLangOptions().CPlusPlus0x) {
6119    // C++03 [class.friend]p2:
6120    //   An elaborated-type-specifier shall be used in a friend declaration
6121    //   for a class.*
6122    //
6123    //   * The class-key of the elaborated-type-specifier is required.
6124    if (!ActiveTemplateInstantiations.empty()) {
6125      // Do not complain about the form of friend template types during
6126      // template instantiation; we will already have complained when the
6127      // template was declared.
6128    } else if (!T->isElaboratedTypeSpecifier()) {
6129      // If we evaluated the type to a record type, suggest putting
6130      // a tag in front.
6131      if (const RecordType *RT = T->getAs<RecordType>()) {
6132        RecordDecl *RD = RT->getDecl();
6133
6134        std::string InsertionText = std::string(" ") + RD->getKindName();
6135
6136        Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6137          << (unsigned) RD->getTagKind()
6138          << T
6139          << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6140                                        InsertionText);
6141      } else {
6142        Diag(FriendLoc, diag::ext_nonclass_type_friend)
6143          << T
6144          << SourceRange(FriendLoc, TypeRange.getEnd());
6145      }
6146    } else if (T->getAs<EnumType>()) {
6147      Diag(FriendLoc, diag::ext_enum_friend)
6148        << T
6149        << SourceRange(FriendLoc, TypeRange.getEnd());
6150    }
6151  }
6152
6153  // C++0x [class.friend]p3:
6154  //   If the type specifier in a friend declaration designates a (possibly
6155  //   cv-qualified) class type, that class is declared as a friend; otherwise,
6156  //   the friend declaration is ignored.
6157
6158  // FIXME: C++0x has some syntactic restrictions on friend type declarations
6159  // in [class.friend]p3 that we do not implement.
6160
6161  return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6162}
6163
6164/// Handle a friend type declaration.  This works in tandem with
6165/// ActOnTag.
6166///
6167/// Notes on friend class templates:
6168///
6169/// We generally treat friend class declarations as if they were
6170/// declaring a class.  So, for example, the elaborated type specifier
6171/// in a friend declaration is required to obey the restrictions of a
6172/// class-head (i.e. no typedefs in the scope chain), template
6173/// parameters are required to match up with simple template-ids, &c.
6174/// However, unlike when declaring a template specialization, it's
6175/// okay to refer to a template specialization without an empty
6176/// template parameter declaration, e.g.
6177///   friend class A<T>::B<unsigned>;
6178/// We permit this as a special case; if there are any template
6179/// parameters present at all, require proper matching, i.e.
6180///   template <> template <class T> friend class A<int>::B;
6181Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
6182                                          MultiTemplateParamsArg TempParams) {
6183  SourceLocation Loc = DS.getSourceRange().getBegin();
6184
6185  assert(DS.isFriendSpecified());
6186  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6187
6188  // Try to convert the decl specifier to a type.  This works for
6189  // friend templates because ActOnTag never produces a ClassTemplateDecl
6190  // for a TUK_Friend.
6191  Declarator TheDeclarator(DS, Declarator::MemberContext);
6192  TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
6193  QualType T = TSI->getType();
6194  if (TheDeclarator.isInvalidType())
6195    return DeclPtrTy();
6196
6197  // This is definitely an error in C++98.  It's probably meant to
6198  // be forbidden in C++0x, too, but the specification is just
6199  // poorly written.
6200  //
6201  // The problem is with declarations like the following:
6202  //   template <T> friend A<T>::foo;
6203  // where deciding whether a class C is a friend or not now hinges
6204  // on whether there exists an instantiation of A that causes
6205  // 'foo' to equal C.  There are restrictions on class-heads
6206  // (which we declare (by fiat) elaborated friend declarations to
6207  // be) that makes this tractable.
6208  //
6209  // FIXME: handle "template <> friend class A<T>;", which
6210  // is possibly well-formed?  Who even knows?
6211  if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
6212    Diag(Loc, diag::err_tagless_friend_type_template)
6213      << DS.getSourceRange();
6214    return DeclPtrTy();
6215  }
6216
6217  // C++98 [class.friend]p1: A friend of a class is a function
6218  //   or class that is not a member of the class . . .
6219  // This is fixed in DR77, which just barely didn't make the C++03
6220  // deadline.  It's also a very silly restriction that seriously
6221  // affects inner classes and which nobody else seems to implement;
6222  // thus we never diagnose it, not even in -pedantic.
6223  //
6224  // But note that we could warn about it: it's always useless to
6225  // friend one of your own members (it's not, however, worthless to
6226  // friend a member of an arbitrary specialization of your template).
6227
6228  Decl *D;
6229  if (unsigned NumTempParamLists = TempParams.size())
6230    D = FriendTemplateDecl::Create(Context, CurContext, Loc,
6231                                   NumTempParamLists,
6232                                 (TemplateParameterList**) TempParams.release(),
6233                                   TSI,
6234                                   DS.getFriendSpecLoc());
6235  else
6236    D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
6237
6238  if (!D)
6239    return DeclPtrTy();
6240
6241  D->setAccess(AS_public);
6242  CurContext->addDecl(D);
6243
6244  return DeclPtrTy::make(D);
6245}
6246
6247Sema::DeclPtrTy
6248Sema::ActOnFriendFunctionDecl(Scope *S,
6249                              Declarator &D,
6250                              bool IsDefinition,
6251                              MultiTemplateParamsArg TemplateParams) {
6252  const DeclSpec &DS = D.getDeclSpec();
6253
6254  assert(DS.isFriendSpecified());
6255  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6256
6257  SourceLocation Loc = D.getIdentifierLoc();
6258  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6259  QualType T = TInfo->getType();
6260
6261  // C++ [class.friend]p1
6262  //   A friend of a class is a function or class....
6263  // Note that this sees through typedefs, which is intended.
6264  // It *doesn't* see through dependent types, which is correct
6265  // according to [temp.arg.type]p3:
6266  //   If a declaration acquires a function type through a
6267  //   type dependent on a template-parameter and this causes
6268  //   a declaration that does not use the syntactic form of a
6269  //   function declarator to have a function type, the program
6270  //   is ill-formed.
6271  if (!T->isFunctionType()) {
6272    Diag(Loc, diag::err_unexpected_friend);
6273
6274    // It might be worthwhile to try to recover by creating an
6275    // appropriate declaration.
6276    return DeclPtrTy();
6277  }
6278
6279  // C++ [namespace.memdef]p3
6280  //  - If a friend declaration in a non-local class first declares a
6281  //    class or function, the friend class or function is a member
6282  //    of the innermost enclosing namespace.
6283  //  - The name of the friend is not found by simple name lookup
6284  //    until a matching declaration is provided in that namespace
6285  //    scope (either before or after the class declaration granting
6286  //    friendship).
6287  //  - If a friend function is called, its name may be found by the
6288  //    name lookup that considers functions from namespaces and
6289  //    classes associated with the types of the function arguments.
6290  //  - When looking for a prior declaration of a class or a function
6291  //    declared as a friend, scopes outside the innermost enclosing
6292  //    namespace scope are not considered.
6293
6294  CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
6295  DeclarationName Name = GetNameForDeclarator(D);
6296  assert(Name);
6297
6298  // The context we found the declaration in, or in which we should
6299  // create the declaration.
6300  DeclContext *DC;
6301
6302  // FIXME: handle local classes
6303
6304  // Recover from invalid scope qualifiers as if they just weren't there.
6305  LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
6306                        ForRedeclaration);
6307  if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
6308    DC = computeDeclContext(ScopeQual);
6309
6310    // FIXME: handle dependent contexts
6311    if (!DC) return DeclPtrTy();
6312    if (RequireCompleteDeclContext(ScopeQual, DC)) return DeclPtrTy();
6313
6314    LookupQualifiedName(Previous, DC);
6315
6316    // Ignore things found implicitly in the wrong scope.
6317    // TODO: better diagnostics for this case.  Suggesting the right
6318    // qualified scope would be nice...
6319    LookupResult::Filter F = Previous.makeFilter();
6320    while (F.hasNext()) {
6321      NamedDecl *D = F.next();
6322      if (!D->getDeclContext()->getLookupContext()->Equals(DC))
6323        F.erase();
6324    }
6325    F.done();
6326
6327    if (Previous.empty()) {
6328      D.setInvalidType();
6329      Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
6330      return DeclPtrTy();
6331    }
6332
6333    // C++ [class.friend]p1: A friend of a class is a function or
6334    //   class that is not a member of the class . . .
6335    if (DC->Equals(CurContext))
6336      Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6337
6338  // Otherwise walk out to the nearest namespace scope looking for matches.
6339  } else {
6340    // TODO: handle local class contexts.
6341
6342    DC = CurContext;
6343    while (true) {
6344      // Skip class contexts.  If someone can cite chapter and verse
6345      // for this behavior, that would be nice --- it's what GCC and
6346      // EDG do, and it seems like a reasonable intent, but the spec
6347      // really only says that checks for unqualified existing
6348      // declarations should stop at the nearest enclosing namespace,
6349      // not that they should only consider the nearest enclosing
6350      // namespace.
6351      while (DC->isRecord())
6352        DC = DC->getParent();
6353
6354      LookupQualifiedName(Previous, DC);
6355
6356      // TODO: decide what we think about using declarations.
6357      if (!Previous.empty())
6358        break;
6359
6360      if (DC->isFileContext()) break;
6361      DC = DC->getParent();
6362    }
6363
6364    // C++ [class.friend]p1: A friend of a class is a function or
6365    //   class that is not a member of the class . . .
6366    // C++0x changes this for both friend types and functions.
6367    // Most C++ 98 compilers do seem to give an error here, so
6368    // we do, too.
6369    if (!Previous.empty() && DC->Equals(CurContext)
6370        && !getLangOptions().CPlusPlus0x)
6371      Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6372  }
6373
6374  if (DC->isFileContext()) {
6375    // This implies that it has to be an operator or function.
6376    if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
6377        D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
6378        D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
6379      Diag(Loc, diag::err_introducing_special_friend) <<
6380        (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
6381         D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
6382      return DeclPtrTy();
6383    }
6384  }
6385
6386  bool Redeclaration = false;
6387  NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
6388                                          move(TemplateParams),
6389                                          IsDefinition,
6390                                          Redeclaration);
6391  if (!ND) return DeclPtrTy();
6392
6393  assert(ND->getDeclContext() == DC);
6394  assert(ND->getLexicalDeclContext() == CurContext);
6395
6396  // Add the function declaration to the appropriate lookup tables,
6397  // adjusting the redeclarations list as necessary.  We don't
6398  // want to do this yet if the friending class is dependent.
6399  //
6400  // Also update the scope-based lookup if the target context's
6401  // lookup context is in lexical scope.
6402  if (!CurContext->isDependentContext()) {
6403    DC = DC->getLookupContext();
6404    DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
6405    if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
6406      PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
6407  }
6408
6409  FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
6410                                       D.getIdentifierLoc(), ND,
6411                                       DS.getFriendSpecLoc());
6412  FrD->setAccess(AS_public);
6413  CurContext->addDecl(FrD);
6414
6415  return DeclPtrTy::make(ND);
6416}
6417
6418void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
6419  AdjustDeclIfTemplate(dcl);
6420
6421  Decl *Dcl = dcl.getAs<Decl>();
6422  FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
6423  if (!Fn) {
6424    Diag(DelLoc, diag::err_deleted_non_function);
6425    return;
6426  }
6427  if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
6428    Diag(DelLoc, diag::err_deleted_decl_not_first);
6429    Diag(Prev->getLocation(), diag::note_previous_declaration);
6430    // If the declaration wasn't the first, we delete the function anyway for
6431    // recovery.
6432  }
6433  Fn->setDeleted();
6434}
6435
6436static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
6437  for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
6438       ++CI) {
6439    Stmt *SubStmt = *CI;
6440    if (!SubStmt)
6441      continue;
6442    if (isa<ReturnStmt>(SubStmt))
6443      Self.Diag(SubStmt->getSourceRange().getBegin(),
6444           diag::err_return_in_constructor_handler);
6445    if (!isa<Expr>(SubStmt))
6446      SearchForReturnInStmt(Self, SubStmt);
6447  }
6448}
6449
6450void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
6451  for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
6452    CXXCatchStmt *Handler = TryBlock->getHandler(I);
6453    SearchForReturnInStmt(*this, Handler);
6454  }
6455}
6456
6457bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
6458                                             const CXXMethodDecl *Old) {
6459  QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
6460  QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
6461
6462  if (Context.hasSameType(NewTy, OldTy) ||
6463      NewTy->isDependentType() || OldTy->isDependentType())
6464    return false;
6465
6466  // Check if the return types are covariant
6467  QualType NewClassTy, OldClassTy;
6468
6469  /// Both types must be pointers or references to classes.
6470  if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
6471    if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
6472      NewClassTy = NewPT->getPointeeType();
6473      OldClassTy = OldPT->getPointeeType();
6474    }
6475  } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
6476    if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
6477      if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
6478        NewClassTy = NewRT->getPointeeType();
6479        OldClassTy = OldRT->getPointeeType();
6480      }
6481    }
6482  }
6483
6484  // The return types aren't either both pointers or references to a class type.
6485  if (NewClassTy.isNull()) {
6486    Diag(New->getLocation(),
6487         diag::err_different_return_type_for_overriding_virtual_function)
6488      << New->getDeclName() << NewTy << OldTy;
6489    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6490
6491    return true;
6492  }
6493
6494  // C++ [class.virtual]p6:
6495  //   If the return type of D::f differs from the return type of B::f, the
6496  //   class type in the return type of D::f shall be complete at the point of
6497  //   declaration of D::f or shall be the class type D.
6498  if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
6499    if (!RT->isBeingDefined() &&
6500        RequireCompleteType(New->getLocation(), NewClassTy,
6501                            PDiag(diag::err_covariant_return_incomplete)
6502                              << New->getDeclName()))
6503    return true;
6504  }
6505
6506  if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
6507    // Check if the new class derives from the old class.
6508    if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
6509      Diag(New->getLocation(),
6510           diag::err_covariant_return_not_derived)
6511      << New->getDeclName() << NewTy << OldTy;
6512      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6513      return true;
6514    }
6515
6516    // Check if we the conversion from derived to base is valid.
6517    if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
6518                    diag::err_covariant_return_inaccessible_base,
6519                    diag::err_covariant_return_ambiguous_derived_to_base_conv,
6520                    // FIXME: Should this point to the return type?
6521                    New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
6522      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6523      return true;
6524    }
6525  }
6526
6527  // The qualifiers of the return types must be the same.
6528  if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
6529    Diag(New->getLocation(),
6530         diag::err_covariant_return_type_different_qualifications)
6531    << New->getDeclName() << NewTy << OldTy;
6532    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6533    return true;
6534  };
6535
6536
6537  // The new class type must have the same or less qualifiers as the old type.
6538  if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
6539    Diag(New->getLocation(),
6540         diag::err_covariant_return_type_class_type_more_qualified)
6541    << New->getDeclName() << NewTy << OldTy;
6542    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6543    return true;
6544  };
6545
6546  return false;
6547}
6548
6549bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
6550                                             const CXXMethodDecl *Old)
6551{
6552  if (Old->hasAttr<FinalAttr>()) {
6553    Diag(New->getLocation(), diag::err_final_function_overridden)
6554      << New->getDeclName();
6555    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6556    return true;
6557  }
6558
6559  return false;
6560}
6561
6562/// \brief Mark the given method pure.
6563///
6564/// \param Method the method to be marked pure.
6565///
6566/// \param InitRange the source range that covers the "0" initializer.
6567bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
6568  if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
6569    Method->setPure();
6570
6571    // A class is abstract if at least one function is pure virtual.
6572    Method->getParent()->setAbstract(true);
6573    return false;
6574  }
6575
6576  if (!Method->isInvalidDecl())
6577    Diag(Method->getLocation(), diag::err_non_virtual_pure)
6578      << Method->getDeclName() << InitRange;
6579  return true;
6580}
6581
6582/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
6583/// an initializer for the out-of-line declaration 'Dcl'.  The scope
6584/// is a fresh scope pushed for just this purpose.
6585///
6586/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6587/// static data member of class X, names should be looked up in the scope of
6588/// class X.
6589void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
6590  // If there is no declaration, there was an error parsing it.
6591  Decl *D = Dcl.getAs<Decl>();
6592  if (D == 0) return;
6593
6594  // We should only get called for declarations with scope specifiers, like:
6595  //   int foo::bar;
6596  assert(D->isOutOfLine());
6597  EnterDeclaratorContext(S, D->getDeclContext());
6598}
6599
6600/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
6601/// initializer for the out-of-line declaration 'Dcl'.
6602void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
6603  // If there is no declaration, there was an error parsing it.
6604  Decl *D = Dcl.getAs<Decl>();
6605  if (D == 0) return;
6606
6607  assert(D->isOutOfLine());
6608  ExitDeclaratorContext(S);
6609}
6610
6611/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6612/// C++ if/switch/while/for statement.
6613/// e.g: "if (int x = f()) {...}"
6614Action::DeclResult
6615Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
6616  // C++ 6.4p2:
6617  // The declarator shall not specify a function or an array.
6618  // The type-specifier-seq shall not contain typedef and shall not declare a
6619  // new class or enumeration.
6620  assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6621         "Parser allowed 'typedef' as storage class of condition decl.");
6622
6623  TagDecl *OwnedTag = 0;
6624  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
6625  QualType Ty = TInfo->getType();
6626
6627  if (Ty->isFunctionType()) { // The declarator shall not specify a function...
6628                              // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
6629                              // would be created and CXXConditionDeclExpr wants a VarDecl.
6630    Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
6631      << D.getSourceRange();
6632    return DeclResult();
6633  } else if (OwnedTag && OwnedTag->isDefinition()) {
6634    // The type-specifier-seq shall not declare a new class or enumeration.
6635    Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
6636  }
6637
6638  DeclPtrTy Dcl = ActOnDeclarator(S, D);
6639  if (!Dcl)
6640    return DeclResult();
6641
6642  VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
6643  VD->setDeclaredInCondition(true);
6644  return Dcl;
6645}
6646
6647void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
6648                          bool DefinitionRequired) {
6649  // Ignore any vtable uses in unevaluated operands or for classes that do
6650  // not have a vtable.
6651  if (!Class->isDynamicClass() || Class->isDependentContext() ||
6652      CurContext->isDependentContext() ||
6653      ExprEvalContexts.back().Context == Unevaluated)
6654    return;
6655
6656  // Try to insert this class into the map.
6657  Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6658  std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
6659    Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
6660  if (!Pos.second) {
6661    // If we already had an entry, check to see if we are promoting this vtable
6662    // to required a definition. If so, we need to reappend to the VTableUses
6663    // list, since we may have already processed the first entry.
6664    if (DefinitionRequired && !Pos.first->second) {
6665      Pos.first->second = true;
6666    } else {
6667      // Otherwise, we can early exit.
6668      return;
6669    }
6670  }
6671
6672  // Local classes need to have their virtual members marked
6673  // immediately. For all other classes, we mark their virtual members
6674  // at the end of the translation unit.
6675  if (Class->isLocalClass())
6676    MarkVirtualMembersReferenced(Loc, Class);
6677  else
6678    VTableUses.push_back(std::make_pair(Class, Loc));
6679}
6680
6681bool Sema::DefineUsedVTables() {
6682  // If any dynamic classes have their key function defined within
6683  // this translation unit, then those vtables are considered "used" and must
6684  // be emitted.
6685  for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
6686    if (const CXXMethodDecl *KeyFunction
6687                             = Context.getKeyFunction(DynamicClasses[I])) {
6688      const FunctionDecl *Definition = 0;
6689      if (KeyFunction->hasBody(Definition))
6690        MarkVTableUsed(Definition->getLocation(), DynamicClasses[I], true);
6691    }
6692  }
6693
6694  if (VTableUses.empty())
6695    return false;
6696
6697  // Note: The VTableUses vector could grow as a result of marking
6698  // the members of a class as "used", so we check the size each
6699  // time through the loop and prefer indices (with are stable) to
6700  // iterators (which are not).
6701  for (unsigned I = 0; I != VTableUses.size(); ++I) {
6702    CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
6703    if (!Class)
6704      continue;
6705
6706    SourceLocation Loc = VTableUses[I].second;
6707
6708    // If this class has a key function, but that key function is
6709    // defined in another translation unit, we don't need to emit the
6710    // vtable even though we're using it.
6711    const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
6712    if (KeyFunction && !KeyFunction->hasBody()) {
6713      switch (KeyFunction->getTemplateSpecializationKind()) {
6714      case TSK_Undeclared:
6715      case TSK_ExplicitSpecialization:
6716      case TSK_ExplicitInstantiationDeclaration:
6717        // The key function is in another translation unit.
6718        continue;
6719
6720      case TSK_ExplicitInstantiationDefinition:
6721      case TSK_ImplicitInstantiation:
6722        // We will be instantiating the key function.
6723        break;
6724      }
6725    } else if (!KeyFunction) {
6726      // If we have a class with no key function that is the subject
6727      // of an explicit instantiation declaration, suppress the
6728      // vtable; it will live with the explicit instantiation
6729      // definition.
6730      bool IsExplicitInstantiationDeclaration
6731        = Class->getTemplateSpecializationKind()
6732                                      == TSK_ExplicitInstantiationDeclaration;
6733      for (TagDecl::redecl_iterator R = Class->redecls_begin(),
6734                                 REnd = Class->redecls_end();
6735           R != REnd; ++R) {
6736        TemplateSpecializationKind TSK
6737          = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
6738        if (TSK == TSK_ExplicitInstantiationDeclaration)
6739          IsExplicitInstantiationDeclaration = true;
6740        else if (TSK == TSK_ExplicitInstantiationDefinition) {
6741          IsExplicitInstantiationDeclaration = false;
6742          break;
6743        }
6744      }
6745
6746      if (IsExplicitInstantiationDeclaration)
6747        continue;
6748    }
6749
6750    // Mark all of the virtual members of this class as referenced, so
6751    // that we can build a vtable. Then, tell the AST consumer that a
6752    // vtable for this class is required.
6753    MarkVirtualMembersReferenced(Loc, Class);
6754    CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6755    Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
6756
6757    // Optionally warn if we're emitting a weak vtable.
6758    if (Class->getLinkage() == ExternalLinkage &&
6759        Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
6760      if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
6761        Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
6762    }
6763  }
6764  VTableUses.clear();
6765
6766  return true;
6767}
6768
6769void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
6770                                        const CXXRecordDecl *RD) {
6771  for (CXXRecordDecl::method_iterator i = RD->method_begin(),
6772       e = RD->method_end(); i != e; ++i) {
6773    CXXMethodDecl *MD = *i;
6774
6775    // C++ [basic.def.odr]p2:
6776    //   [...] A virtual member function is used if it is not pure. [...]
6777    if (MD->isVirtual() && !MD->isPure())
6778      MarkDeclarationReferenced(Loc, MD);
6779  }
6780
6781  // Only classes that have virtual bases need a VTT.
6782  if (RD->getNumVBases() == 0)
6783    return;
6784
6785  for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
6786           e = RD->bases_end(); i != e; ++i) {
6787    const CXXRecordDecl *Base =
6788        cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
6789    if (i->isVirtual())
6790      continue;
6791    if (Base->getNumVBases() == 0)
6792      continue;
6793    MarkVirtualMembersReferenced(Loc, Base);
6794  }
6795}
6796
6797/// SetIvarInitializers - This routine builds initialization ASTs for the
6798/// Objective-C implementation whose ivars need be initialized.
6799void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
6800  if (!getLangOptions().CPlusPlus)
6801    return;
6802  if (const ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
6803    llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
6804    CollectIvarsToConstructOrDestruct(OID, ivars);
6805    if (ivars.empty())
6806      return;
6807    llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
6808    for (unsigned i = 0; i < ivars.size(); i++) {
6809      FieldDecl *Field = ivars[i];
6810      if (Field->isInvalidDecl())
6811        continue;
6812
6813      CXXBaseOrMemberInitializer *Member;
6814      InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
6815      InitializationKind InitKind =
6816        InitializationKind::CreateDefault(ObjCImplementation->getLocation());
6817
6818      InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
6819      Sema::OwningExprResult MemberInit =
6820        InitSeq.Perform(*this, InitEntity, InitKind,
6821                        Sema::MultiExprArg(*this, 0, 0));
6822      MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
6823      // Note, MemberInit could actually come back empty if no initialization
6824      // is required (e.g., because it would call a trivial default constructor)
6825      if (!MemberInit.get() || MemberInit.isInvalid())
6826        continue;
6827
6828      Member =
6829        new (Context) CXXBaseOrMemberInitializer(Context,
6830                                                 Field, SourceLocation(),
6831                                                 SourceLocation(),
6832                                                 MemberInit.takeAs<Expr>(),
6833                                                 SourceLocation());
6834      AllToInit.push_back(Member);
6835
6836      // Be sure that the destructor is accessible and is marked as referenced.
6837      if (const RecordType *RecordTy
6838                  = Context.getBaseElementType(Field->getType())
6839                                                        ->getAs<RecordType>()) {
6840                    CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
6841        if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
6842          MarkDeclarationReferenced(Field->getLocation(), Destructor);
6843          CheckDestructorAccess(Field->getLocation(), Destructor,
6844                            PDiag(diag::err_access_dtor_ivar)
6845                              << Context.getBaseElementType(Field->getType()));
6846        }
6847      }
6848    }
6849    ObjCImplementation->setIvarInitializers(Context,
6850                                            AllToInit.data(), AllToInit.size());
6851  }
6852}
6853