SemaDeclCXX.cpp revision eb0b821426061a6fa5806bf31236d1ba4aaca69c
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/RecordLayout.h"
20#include "clang/AST/CXXInheritance.h"
21#include "clang/AST/DeclVisitor.h"
22#include "clang/AST/TypeLoc.h"
23#include "clang/AST/TypeOrdering.h"
24#include "clang/AST/StmtVisitor.h"
25#include "clang/Parse/DeclSpec.h"
26#include "clang/Parse/Template.h"
27#include "clang/Basic/PartialDiagnostic.h"
28#include "clang/Lex/Preprocessor.h"
29#include "llvm/ADT/STLExtras.h"
30#include <map>
31#include <set>
32
33using namespace clang;
34
35//===----------------------------------------------------------------------===//
36// CheckDefaultArgumentVisitor
37//===----------------------------------------------------------------------===//
38
39namespace {
40  /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
41  /// the default argument of a parameter to determine whether it
42  /// contains any ill-formed subexpressions. For example, this will
43  /// diagnose the use of local variables or parameters within the
44  /// default argument expression.
45  class CheckDefaultArgumentVisitor
46    : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
47    Expr *DefaultArg;
48    Sema *S;
49
50  public:
51    CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
52      : DefaultArg(defarg), S(s) {}
53
54    bool VisitExpr(Expr *Node);
55    bool VisitDeclRefExpr(DeclRefExpr *DRE);
56    bool VisitCXXThisExpr(CXXThisExpr *ThisE);
57  };
58
59  /// VisitExpr - Visit all of the children of this expression.
60  bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
61    bool IsInvalid = false;
62    for (Stmt::child_iterator I = Node->child_begin(),
63         E = Node->child_end(); I != E; ++I)
64      IsInvalid |= Visit(*I);
65    return IsInvalid;
66  }
67
68  /// VisitDeclRefExpr - Visit a reference to a declaration, to
69  /// determine whether this declaration can be used in the default
70  /// argument expression.
71  bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
72    NamedDecl *Decl = DRE->getDecl();
73    if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
74      // C++ [dcl.fct.default]p9
75      //   Default arguments are evaluated each time the function is
76      //   called. The order of evaluation of function arguments is
77      //   unspecified. Consequently, parameters of a function shall not
78      //   be used in default argument expressions, even if they are not
79      //   evaluated. Parameters of a function declared before a default
80      //   argument expression are in scope and can hide namespace and
81      //   class member names.
82      return S->Diag(DRE->getSourceRange().getBegin(),
83                     diag::err_param_default_argument_references_param)
84         << Param->getDeclName() << DefaultArg->getSourceRange();
85    } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
86      // C++ [dcl.fct.default]p7
87      //   Local variables shall not be used in default argument
88      //   expressions.
89      if (VDecl->isBlockVarDecl())
90        return S->Diag(DRE->getSourceRange().getBegin(),
91                       diag::err_param_default_argument_references_local)
92          << VDecl->getDeclName() << DefaultArg->getSourceRange();
93    }
94
95    return false;
96  }
97
98  /// VisitCXXThisExpr - Visit a C++ "this" expression.
99  bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
100    // C++ [dcl.fct.default]p8:
101    //   The keyword this shall not be used in a default argument of a
102    //   member function.
103    return S->Diag(ThisE->getSourceRange().getBegin(),
104                   diag::err_param_default_argument_references_this)
105               << ThisE->getSourceRange();
106  }
107}
108
109bool
110Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
111                              SourceLocation EqualLoc) {
112  if (RequireCompleteType(Param->getLocation(), Param->getType(),
113                          diag::err_typecheck_decl_incomplete_type)) {
114    Param->setInvalidDecl();
115    return true;
116  }
117
118  Expr *Arg = (Expr *)DefaultArg.get();
119
120  // C++ [dcl.fct.default]p5
121  //   A default argument expression is implicitly converted (clause
122  //   4) to the parameter type. The default argument expression has
123  //   the same semantic constraints as the initializer expression in
124  //   a declaration of a variable of the parameter type, using the
125  //   copy-initialization semantics (8.5).
126  InitializedEntity Entity = InitializedEntity::InitializeParameter(Param);
127  InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
128                                                           EqualLoc);
129  InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
130  OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
131                                          MultiExprArg(*this, (void**)&Arg, 1));
132  if (Result.isInvalid())
133    return true;
134  Arg = Result.takeAs<Expr>();
135
136  Arg = MaybeCreateCXXExprWithTemporaries(Arg);
137
138  // Okay: add the default argument to the parameter
139  Param->setDefaultArg(Arg);
140
141  DefaultArg.release();
142
143  return false;
144}
145
146/// ActOnParamDefaultArgument - Check whether the default argument
147/// provided for a function parameter is well-formed. If so, attach it
148/// to the parameter declaration.
149void
150Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
151                                ExprArg defarg) {
152  if (!param || !defarg.get())
153    return;
154
155  ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
156  UnparsedDefaultArgLocs.erase(Param);
157
158  ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
159
160  // Default arguments are only permitted in C++
161  if (!getLangOptions().CPlusPlus) {
162    Diag(EqualLoc, diag::err_param_default_argument)
163      << DefaultArg->getSourceRange();
164    Param->setInvalidDecl();
165    return;
166  }
167
168  // Check that the default argument is well-formed
169  CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
170  if (DefaultArgChecker.Visit(DefaultArg.get())) {
171    Param->setInvalidDecl();
172    return;
173  }
174
175  SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
176}
177
178/// ActOnParamUnparsedDefaultArgument - We've seen a default
179/// argument for a function parameter, but we can't parse it yet
180/// because we're inside a class definition. Note that this default
181/// argument will be parsed later.
182void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
183                                             SourceLocation EqualLoc,
184                                             SourceLocation ArgLoc) {
185  if (!param)
186    return;
187
188  ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
189  if (Param)
190    Param->setUnparsedDefaultArg();
191
192  UnparsedDefaultArgLocs[Param] = ArgLoc;
193}
194
195/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
196/// the default argument for the parameter param failed.
197void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
198  if (!param)
199    return;
200
201  ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
202
203  Param->setInvalidDecl();
204
205  UnparsedDefaultArgLocs.erase(Param);
206}
207
208/// CheckExtraCXXDefaultArguments - Check for any extra default
209/// arguments in the declarator, which is not a function declaration
210/// or definition and therefore is not permitted to have default
211/// arguments. This routine should be invoked for every declarator
212/// that is not a function declaration or definition.
213void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
214  // C++ [dcl.fct.default]p3
215  //   A default argument expression shall be specified only in the
216  //   parameter-declaration-clause of a function declaration or in a
217  //   template-parameter (14.1). It shall not be specified for a
218  //   parameter pack. If it is specified in a
219  //   parameter-declaration-clause, it shall not occur within a
220  //   declarator or abstract-declarator of a parameter-declaration.
221  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
222    DeclaratorChunk &chunk = D.getTypeObject(i);
223    if (chunk.Kind == DeclaratorChunk::Function) {
224      for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
225        ParmVarDecl *Param =
226          cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
227        if (Param->hasUnparsedDefaultArg()) {
228          CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
229          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
230            << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
231          delete Toks;
232          chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
233        } else if (Param->getDefaultArg()) {
234          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
235            << Param->getDefaultArg()->getSourceRange();
236          Param->setDefaultArg(0);
237        }
238      }
239    }
240  }
241}
242
243// MergeCXXFunctionDecl - Merge two declarations of the same C++
244// function, once we already know that they have the same
245// type. Subroutine of MergeFunctionDecl. Returns true if there was an
246// error, false otherwise.
247bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
248  bool Invalid = false;
249
250  // C++ [dcl.fct.default]p4:
251  //   For non-template functions, default arguments can be added in
252  //   later declarations of a function in the same
253  //   scope. Declarations in different scopes have completely
254  //   distinct sets of default arguments. That is, declarations in
255  //   inner scopes do not acquire default arguments from
256  //   declarations in outer scopes, and vice versa. In a given
257  //   function declaration, all parameters subsequent to a
258  //   parameter with a default argument shall have default
259  //   arguments supplied in this or previous declarations. A
260  //   default argument shall not be redefined by a later
261  //   declaration (not even to the same value).
262  //
263  // C++ [dcl.fct.default]p6:
264  //   Except for member functions of class templates, the default arguments
265  //   in a member function definition that appears outside of the class
266  //   definition are added to the set of default arguments provided by the
267  //   member function declaration in the class definition.
268  for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
269    ParmVarDecl *OldParam = Old->getParamDecl(p);
270    ParmVarDecl *NewParam = New->getParamDecl(p);
271
272    if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
273      // FIXME: If we knew where the '=' was, we could easily provide a fix-it
274      // hint here. Alternatively, we could walk the type-source information
275      // for NewParam to find the last source location in the type... but it
276      // isn't worth the effort right now. This is the kind of test case that
277      // is hard to get right:
278
279      //   int f(int);
280      //   void g(int (*fp)(int) = f);
281      //   void g(int (*fp)(int) = &f);
282      Diag(NewParam->getLocation(),
283           diag::err_param_default_argument_redefinition)
284        << NewParam->getDefaultArgRange();
285
286      // Look for the function declaration where the default argument was
287      // actually written, which may be a declaration prior to Old.
288      for (FunctionDecl *Older = Old->getPreviousDeclaration();
289           Older; Older = Older->getPreviousDeclaration()) {
290        if (!Older->getParamDecl(p)->hasDefaultArg())
291          break;
292
293        OldParam = Older->getParamDecl(p);
294      }
295
296      Diag(OldParam->getLocation(), diag::note_previous_definition)
297        << OldParam->getDefaultArgRange();
298      Invalid = true;
299    } else if (OldParam->hasDefaultArg()) {
300      // Merge the old default argument into the new parameter
301      if (OldParam->hasUninstantiatedDefaultArg())
302        NewParam->setUninstantiatedDefaultArg(
303                                      OldParam->getUninstantiatedDefaultArg());
304      else
305        NewParam->setDefaultArg(OldParam->getDefaultArg());
306    } else if (NewParam->hasDefaultArg()) {
307      if (New->getDescribedFunctionTemplate()) {
308        // Paragraph 4, quoted above, only applies to non-template functions.
309        Diag(NewParam->getLocation(),
310             diag::err_param_default_argument_template_redecl)
311          << NewParam->getDefaultArgRange();
312        Diag(Old->getLocation(), diag::note_template_prev_declaration)
313          << false;
314      } else if (New->getTemplateSpecializationKind()
315                   != TSK_ImplicitInstantiation &&
316                 New->getTemplateSpecializationKind() != TSK_Undeclared) {
317        // C++ [temp.expr.spec]p21:
318        //   Default function arguments shall not be specified in a declaration
319        //   or a definition for one of the following explicit specializations:
320        //     - the explicit specialization of a function template;
321        //     - the explicit specialization of a member function template;
322        //     - the explicit specialization of a member function of a class
323        //       template where the class template specialization to which the
324        //       member function specialization belongs is implicitly
325        //       instantiated.
326        Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
327          << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
328          << New->getDeclName()
329          << NewParam->getDefaultArgRange();
330      } else if (New->getDeclContext()->isDependentContext()) {
331        // C++ [dcl.fct.default]p6 (DR217):
332        //   Default arguments for a member function of a class template shall
333        //   be specified on the initial declaration of the member function
334        //   within the class template.
335        //
336        // Reading the tea leaves a bit in DR217 and its reference to DR205
337        // leads me to the conclusion that one cannot add default function
338        // arguments for an out-of-line definition of a member function of a
339        // dependent type.
340        int WhichKind = 2;
341        if (CXXRecordDecl *Record
342              = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
343          if (Record->getDescribedClassTemplate())
344            WhichKind = 0;
345          else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
346            WhichKind = 1;
347          else
348            WhichKind = 2;
349        }
350
351        Diag(NewParam->getLocation(),
352             diag::err_param_default_argument_member_template_redecl)
353          << WhichKind
354          << NewParam->getDefaultArgRange();
355      }
356    }
357  }
358
359  if (CheckEquivalentExceptionSpec(
360          Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
361          New->getType()->getAs<FunctionProtoType>(), New->getLocation()))
362    Invalid = true;
363
364  return Invalid;
365}
366
367/// CheckCXXDefaultArguments - Verify that the default arguments for a
368/// function declaration are well-formed according to C++
369/// [dcl.fct.default].
370void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
371  unsigned NumParams = FD->getNumParams();
372  unsigned p;
373
374  // Find first parameter with a default argument
375  for (p = 0; p < NumParams; ++p) {
376    ParmVarDecl *Param = FD->getParamDecl(p);
377    if (Param->hasDefaultArg())
378      break;
379  }
380
381  // C++ [dcl.fct.default]p4:
382  //   In a given function declaration, all parameters
383  //   subsequent to a parameter with a default argument shall
384  //   have default arguments supplied in this or previous
385  //   declarations. A default argument shall not be redefined
386  //   by a later declaration (not even to the same value).
387  unsigned LastMissingDefaultArg = 0;
388  for (; p < NumParams; ++p) {
389    ParmVarDecl *Param = FD->getParamDecl(p);
390    if (!Param->hasDefaultArg()) {
391      if (Param->isInvalidDecl())
392        /* We already complained about this parameter. */;
393      else if (Param->getIdentifier())
394        Diag(Param->getLocation(),
395             diag::err_param_default_argument_missing_name)
396          << Param->getIdentifier();
397      else
398        Diag(Param->getLocation(),
399             diag::err_param_default_argument_missing);
400
401      LastMissingDefaultArg = p;
402    }
403  }
404
405  if (LastMissingDefaultArg > 0) {
406    // Some default arguments were missing. Clear out all of the
407    // default arguments up to (and including) the last missing
408    // default argument, so that we leave the function parameters
409    // in a semantically valid state.
410    for (p = 0; p <= LastMissingDefaultArg; ++p) {
411      ParmVarDecl *Param = FD->getParamDecl(p);
412      if (Param->hasDefaultArg()) {
413        if (!Param->hasUnparsedDefaultArg())
414          Param->getDefaultArg()->Destroy(Context);
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)
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() == RecordDecl::TK_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(Context);
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  // FIXME: Allocate via ASTContext?
506  return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
507                              Class->getTagKind() == RecordDecl::TK_class,
508                              Access, BaseType);
509}
510
511void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class,
512                                          const CXXRecordDecl *BaseClass,
513                                          bool BaseIsVirtual) {
514  // A class with a non-empty base class is not empty.
515  // FIXME: Standard ref?
516  if (!BaseClass->isEmpty())
517    Class->setEmpty(false);
518
519  // C++ [class.virtual]p1:
520  //   A class that [...] inherits a virtual function is called a polymorphic
521  //   class.
522  if (BaseClass->isPolymorphic())
523    Class->setPolymorphic(true);
524
525  // C++ [dcl.init.aggr]p1:
526  //   An aggregate is [...] a class with [...] no base classes [...].
527  Class->setAggregate(false);
528
529  // C++ [class]p4:
530  //   A POD-struct is an aggregate class...
531  Class->setPOD(false);
532
533  if (BaseIsVirtual) {
534    // C++ [class.ctor]p5:
535    //   A constructor is trivial if its class has no virtual base classes.
536    Class->setHasTrivialConstructor(false);
537
538    // C++ [class.copy]p6:
539    //   A copy constructor is trivial if its class has no virtual base classes.
540    Class->setHasTrivialCopyConstructor(false);
541
542    // C++ [class.copy]p11:
543    //   A copy assignment operator is trivial if its class has no virtual
544    //   base classes.
545    Class->setHasTrivialCopyAssignment(false);
546
547    // C++0x [meta.unary.prop] is_empty:
548    //    T is a class type, but not a union type, with ... no virtual base
549    //    classes
550    Class->setEmpty(false);
551  } else {
552    // C++ [class.ctor]p5:
553    //   A constructor is trivial if all the direct base classes of its
554    //   class have trivial constructors.
555    if (!BaseClass->hasTrivialConstructor())
556      Class->setHasTrivialConstructor(false);
557
558    // C++ [class.copy]p6:
559    //   A copy constructor is trivial if all the direct base classes of its
560    //   class have trivial copy constructors.
561    if (!BaseClass->hasTrivialCopyConstructor())
562      Class->setHasTrivialCopyConstructor(false);
563
564    // C++ [class.copy]p11:
565    //   A copy assignment operator is trivial if all the direct base classes
566    //   of its class have trivial copy assignment operators.
567    if (!BaseClass->hasTrivialCopyAssignment())
568      Class->setHasTrivialCopyAssignment(false);
569  }
570
571  // C++ [class.ctor]p3:
572  //   A destructor is trivial if all the direct base classes of its class
573  //   have trivial destructors.
574  if (!BaseClass->hasTrivialDestructor())
575    Class->setHasTrivialDestructor(false);
576}
577
578/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
579/// one entry in the base class list of a class specifier, for
580/// example:
581///    class foo : public bar, virtual private baz {
582/// 'public bar' and 'virtual private baz' are each base-specifiers.
583Sema::BaseResult
584Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
585                         bool Virtual, AccessSpecifier Access,
586                         TypeTy *basetype, SourceLocation BaseLoc) {
587  if (!classdecl)
588    return true;
589
590  AdjustDeclIfTemplate(classdecl);
591  CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
592  QualType BaseType = GetTypeFromParser(basetype);
593  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
594                                                      Virtual, Access,
595                                                      BaseType, BaseLoc))
596    return BaseSpec;
597
598  return true;
599}
600
601/// \brief Performs the actual work of attaching the given base class
602/// specifiers to a C++ class.
603bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
604                                unsigned NumBases) {
605 if (NumBases == 0)
606    return false;
607
608  // Used to keep track of which base types we have already seen, so
609  // that we can properly diagnose redundant direct base types. Note
610  // that the key is always the unqualified canonical type of the base
611  // class.
612  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
613
614  // Copy non-redundant base specifiers into permanent storage.
615  unsigned NumGoodBases = 0;
616  bool Invalid = false;
617  for (unsigned idx = 0; idx < NumBases; ++idx) {
618    QualType NewBaseType
619      = Context.getCanonicalType(Bases[idx]->getType());
620    NewBaseType = NewBaseType.getLocalUnqualifiedType();
621
622    if (KnownBaseTypes[NewBaseType]) {
623      // C++ [class.mi]p3:
624      //   A class shall not be specified as a direct base class of a
625      //   derived class more than once.
626      Diag(Bases[idx]->getSourceRange().getBegin(),
627           diag::err_duplicate_base_class)
628        << KnownBaseTypes[NewBaseType]->getType()
629        << Bases[idx]->getSourceRange();
630
631      // Delete the duplicate base class specifier; we're going to
632      // overwrite its pointer later.
633      Context.Deallocate(Bases[idx]);
634
635      Invalid = true;
636    } else {
637      // Okay, add this new base class.
638      KnownBaseTypes[NewBaseType] = Bases[idx];
639      Bases[NumGoodBases++] = Bases[idx];
640    }
641  }
642
643  // Attach the remaining base class specifiers to the derived class.
644  Class->setBases(Context, Bases, NumGoodBases);
645
646  // Delete the remaining (good) base class specifiers, since their
647  // data has been copied into the CXXRecordDecl.
648  for (unsigned idx = 0; idx < NumGoodBases; ++idx)
649    Context.Deallocate(Bases[idx]);
650
651  return Invalid;
652}
653
654/// ActOnBaseSpecifiers - Attach the given base specifiers to the
655/// class, after checking whether there are any duplicate base
656/// classes.
657void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
658                               unsigned NumBases) {
659  if (!ClassDecl || !Bases || !NumBases)
660    return;
661
662  AdjustDeclIfTemplate(ClassDecl);
663  AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
664                       (CXXBaseSpecifier**)(Bases), NumBases);
665}
666
667/// \brief Determine whether the type \p Derived is a C++ class that is
668/// derived from the type \p Base.
669bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
670  if (!getLangOptions().CPlusPlus)
671    return false;
672
673  const RecordType *DerivedRT = Derived->getAs<RecordType>();
674  if (!DerivedRT)
675    return false;
676
677  const RecordType *BaseRT = Base->getAs<RecordType>();
678  if (!BaseRT)
679    return false;
680
681  CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
682  CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
683  return DerivedRD->isDerivedFrom(BaseRD);
684}
685
686/// \brief Determine whether the type \p Derived is a C++ class that is
687/// derived from the type \p Base.
688bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
689  if (!getLangOptions().CPlusPlus)
690    return false;
691
692  const RecordType *DerivedRT = Derived->getAs<RecordType>();
693  if (!DerivedRT)
694    return false;
695
696  const RecordType *BaseRT = Base->getAs<RecordType>();
697  if (!BaseRT)
698    return false;
699
700  CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
701  CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
702  return DerivedRD->isDerivedFrom(BaseRD, Paths);
703}
704
705/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
706/// conversion (where Derived and Base are class types) is
707/// well-formed, meaning that the conversion is unambiguous (and
708/// that all of the base classes are accessible). Returns true
709/// and emits a diagnostic if the code is ill-formed, returns false
710/// otherwise. Loc is the location where this routine should point to
711/// if there is an error, and Range is the source range to highlight
712/// if there is an error.
713bool
714Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
715                                   unsigned InaccessibleBaseID,
716                                   unsigned AmbigiousBaseConvID,
717                                   SourceLocation Loc, SourceRange Range,
718                                   DeclarationName Name) {
719  // First, determine whether the path from Derived to Base is
720  // ambiguous. This is slightly more expensive than checking whether
721  // the Derived to Base conversion exists, because here we need to
722  // explore multiple paths to determine if there is an ambiguity.
723  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
724                     /*DetectVirtual=*/false);
725  bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
726  assert(DerivationOkay &&
727         "Can only be used with a derived-to-base conversion");
728  (void)DerivationOkay;
729
730  if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
731    if (InaccessibleBaseID == 0)
732      return false;
733    // Check that the base class can be accessed.
734    return CheckBaseClassAccess(Derived, Base, InaccessibleBaseID, Paths, Loc,
735                                Name);
736  }
737
738  // We know that the derived-to-base conversion is ambiguous, and
739  // we're going to produce a diagnostic. Perform the derived-to-base
740  // search just one more time to compute all of the possible paths so
741  // that we can print them out. This is more expensive than any of
742  // the previous derived-to-base checks we've done, but at this point
743  // performance isn't as much of an issue.
744  Paths.clear();
745  Paths.setRecordingPaths(true);
746  bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
747  assert(StillOkay && "Can only be used with a derived-to-base conversion");
748  (void)StillOkay;
749
750  // Build up a textual representation of the ambiguous paths, e.g.,
751  // D -> B -> A, that will be used to illustrate the ambiguous
752  // conversions in the diagnostic. We only print one of the paths
753  // to each base class subobject.
754  std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
755
756  Diag(Loc, AmbigiousBaseConvID)
757  << Derived << Base << PathDisplayStr << Range << Name;
758  return true;
759}
760
761bool
762Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
763                                   SourceLocation Loc, SourceRange Range,
764                                   bool IgnoreAccess) {
765  return CheckDerivedToBaseConversion(Derived, Base,
766                                      IgnoreAccess ? 0 :
767                                        diag::err_conv_to_inaccessible_base,
768                                      diag::err_ambiguous_derived_to_base_conv,
769                                      Loc, Range, DeclarationName());
770}
771
772
773/// @brief Builds a string representing ambiguous paths from a
774/// specific derived class to different subobjects of the same base
775/// class.
776///
777/// This function builds a string that can be used in error messages
778/// to show the different paths that one can take through the
779/// inheritance hierarchy to go from the derived class to different
780/// subobjects of a base class. The result looks something like this:
781/// @code
782/// struct D -> struct B -> struct A
783/// struct D -> struct C -> struct A
784/// @endcode
785std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
786  std::string PathDisplayStr;
787  std::set<unsigned> DisplayedPaths;
788  for (CXXBasePaths::paths_iterator Path = Paths.begin();
789       Path != Paths.end(); ++Path) {
790    if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
791      // We haven't displayed a path to this particular base
792      // class subobject yet.
793      PathDisplayStr += "\n    ";
794      PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
795      for (CXXBasePath::const_iterator Element = Path->begin();
796           Element != Path->end(); ++Element)
797        PathDisplayStr += " -> " + Element->Base->getType().getAsString();
798    }
799  }
800
801  return PathDisplayStr;
802}
803
804//===----------------------------------------------------------------------===//
805// C++ class member Handling
806//===----------------------------------------------------------------------===//
807
808/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
809/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
810/// bitfield width if there is one and 'InitExpr' specifies the initializer if
811/// any.
812Sema::DeclPtrTy
813Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
814                               MultiTemplateParamsArg TemplateParameterLists,
815                               ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
816                               bool Deleted) {
817  const DeclSpec &DS = D.getDeclSpec();
818  DeclarationName Name = GetNameForDeclarator(D);
819  Expr *BitWidth = static_cast<Expr*>(BW);
820  Expr *Init = static_cast<Expr*>(InitExpr);
821  SourceLocation Loc = D.getIdentifierLoc();
822
823  bool isFunc = D.isFunctionDeclarator();
824
825  assert(!DS.isFriendSpecified());
826
827  // C++ 9.2p6: A member shall not be declared to have automatic storage
828  // duration (auto, register) or with the extern storage-class-specifier.
829  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
830  // data members and cannot be applied to names declared const or static,
831  // and cannot be applied to reference members.
832  switch (DS.getStorageClassSpec()) {
833    case DeclSpec::SCS_unspecified:
834    case DeclSpec::SCS_typedef:
835    case DeclSpec::SCS_static:
836      // FALL THROUGH.
837      break;
838    case DeclSpec::SCS_mutable:
839      if (isFunc) {
840        if (DS.getStorageClassSpecLoc().isValid())
841          Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
842        else
843          Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
844
845        // FIXME: It would be nicer if the keyword was ignored only for this
846        // declarator. Otherwise we could get follow-up errors.
847        D.getMutableDeclSpec().ClearStorageClassSpecs();
848      } else {
849        QualType T = GetTypeForDeclarator(D, S);
850        diag::kind err = static_cast<diag::kind>(0);
851        if (T->isReferenceType())
852          err = diag::err_mutable_reference;
853        else if (T.isConstQualified())
854          err = diag::err_mutable_const;
855        if (err != 0) {
856          if (DS.getStorageClassSpecLoc().isValid())
857            Diag(DS.getStorageClassSpecLoc(), err);
858          else
859            Diag(DS.getThreadSpecLoc(), err);
860          // FIXME: It would be nicer if the keyword was ignored only for this
861          // declarator. Otherwise we could get follow-up errors.
862          D.getMutableDeclSpec().ClearStorageClassSpecs();
863        }
864      }
865      break;
866    default:
867      if (DS.getStorageClassSpecLoc().isValid())
868        Diag(DS.getStorageClassSpecLoc(),
869             diag::err_storageclass_invalid_for_member);
870      else
871        Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
872      D.getMutableDeclSpec().ClearStorageClassSpecs();
873  }
874
875  if (!isFunc &&
876      D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
877      D.getNumTypeObjects() == 0) {
878    // Check also for this case:
879    //
880    // typedef int f();
881    // f a;
882    //
883    QualType TDType = GetTypeFromParser(DS.getTypeRep());
884    isFunc = TDType->isFunctionType();
885  }
886
887  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
888                       DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
889                      !isFunc);
890
891  Decl *Member;
892  if (isInstField) {
893    // FIXME: Check for template parameters!
894    Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
895                         AS);
896    assert(Member && "HandleField never returns null");
897  } else {
898    Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
899               .getAs<Decl>();
900    if (!Member) {
901      if (BitWidth) DeleteExpr(BitWidth);
902      return DeclPtrTy();
903    }
904
905    // Non-instance-fields can't have a bitfield.
906    if (BitWidth) {
907      if (Member->isInvalidDecl()) {
908        // don't emit another diagnostic.
909      } else if (isa<VarDecl>(Member)) {
910        // C++ 9.6p3: A bit-field shall not be a static member.
911        // "static member 'A' cannot be a bit-field"
912        Diag(Loc, diag::err_static_not_bitfield)
913          << Name << BitWidth->getSourceRange();
914      } else if (isa<TypedefDecl>(Member)) {
915        // "typedef member 'x' cannot be a bit-field"
916        Diag(Loc, diag::err_typedef_not_bitfield)
917          << Name << BitWidth->getSourceRange();
918      } else {
919        // A function typedef ("typedef int f(); f a;").
920        // C++ 9.6p3: A bit-field shall have integral or enumeration type.
921        Diag(Loc, diag::err_not_integral_type_bitfield)
922          << Name << cast<ValueDecl>(Member)->getType()
923          << BitWidth->getSourceRange();
924      }
925
926      DeleteExpr(BitWidth);
927      BitWidth = 0;
928      Member->setInvalidDecl();
929    }
930
931    Member->setAccess(AS);
932
933    // If we have declared a member function template, set the access of the
934    // templated declaration as well.
935    if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
936      FunTmpl->getTemplatedDecl()->setAccess(AS);
937  }
938
939  assert((Name || isInstField) && "No identifier for non-field ?");
940
941  if (Init)
942    AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
943  if (Deleted) // FIXME: Source location is not very good.
944    SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
945
946  if (isInstField) {
947    FieldCollector->Add(cast<FieldDecl>(Member));
948    return DeclPtrTy();
949  }
950  return DeclPtrTy::make(Member);
951}
952
953/// \brief Find the direct and/or virtual base specifiers that
954/// correspond to the given base type, for use in base initialization
955/// within a constructor.
956static bool FindBaseInitializer(Sema &SemaRef,
957                                CXXRecordDecl *ClassDecl,
958                                QualType BaseType,
959                                const CXXBaseSpecifier *&DirectBaseSpec,
960                                const CXXBaseSpecifier *&VirtualBaseSpec) {
961  // First, check for a direct base class.
962  DirectBaseSpec = 0;
963  for (CXXRecordDecl::base_class_const_iterator Base
964         = ClassDecl->bases_begin();
965       Base != ClassDecl->bases_end(); ++Base) {
966    if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
967      // We found a direct base of this type. That's what we're
968      // initializing.
969      DirectBaseSpec = &*Base;
970      break;
971    }
972  }
973
974  // Check for a virtual base class.
975  // FIXME: We might be able to short-circuit this if we know in advance that
976  // there are no virtual bases.
977  VirtualBaseSpec = 0;
978  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
979    // We haven't found a base yet; search the class hierarchy for a
980    // virtual base class.
981    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
982                       /*DetectVirtual=*/false);
983    if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
984                              BaseType, Paths)) {
985      for (CXXBasePaths::paths_iterator Path = Paths.begin();
986           Path != Paths.end(); ++Path) {
987        if (Path->back().Base->isVirtual()) {
988          VirtualBaseSpec = Path->back().Base;
989          break;
990        }
991      }
992    }
993  }
994
995  return DirectBaseSpec || VirtualBaseSpec;
996}
997
998/// ActOnMemInitializer - Handle a C++ member initializer.
999Sema::MemInitResult
1000Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
1001                          Scope *S,
1002                          const CXXScopeSpec &SS,
1003                          IdentifierInfo *MemberOrBase,
1004                          TypeTy *TemplateTypeTy,
1005                          SourceLocation IdLoc,
1006                          SourceLocation LParenLoc,
1007                          ExprTy **Args, unsigned NumArgs,
1008                          SourceLocation *CommaLocs,
1009                          SourceLocation RParenLoc) {
1010  if (!ConstructorD)
1011    return true;
1012
1013  AdjustDeclIfTemplate(ConstructorD);
1014
1015  CXXConstructorDecl *Constructor
1016    = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
1017  if (!Constructor) {
1018    // The user wrote a constructor initializer on a function that is
1019    // not a C++ constructor. Ignore the error for now, because we may
1020    // have more member initializers coming; we'll diagnose it just
1021    // once in ActOnMemInitializers.
1022    return true;
1023  }
1024
1025  CXXRecordDecl *ClassDecl = Constructor->getParent();
1026
1027  // C++ [class.base.init]p2:
1028  //   Names in a mem-initializer-id are looked up in the scope of the
1029  //   constructor’s class and, if not found in that scope, are looked
1030  //   up in the scope containing the constructor’s
1031  //   definition. [Note: if the constructor’s class contains a member
1032  //   with the same name as a direct or virtual base class of the
1033  //   class, a mem-initializer-id naming the member or base class and
1034  //   composed of a single identifier refers to the class member. A
1035  //   mem-initializer-id for the hidden base class may be specified
1036  //   using a qualified name. ]
1037  if (!SS.getScopeRep() && !TemplateTypeTy) {
1038    // Look for a member, first.
1039    FieldDecl *Member = 0;
1040    DeclContext::lookup_result Result
1041      = ClassDecl->lookup(MemberOrBase);
1042    if (Result.first != Result.second)
1043      Member = dyn_cast<FieldDecl>(*Result.first);
1044
1045    // FIXME: Handle members of an anonymous union.
1046
1047    if (Member)
1048      return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1049                                    LParenLoc, RParenLoc);
1050  }
1051  // It didn't name a member, so see if it names a class.
1052  QualType BaseType;
1053  TypeSourceInfo *TInfo = 0;
1054
1055  if (TemplateTypeTy) {
1056    BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
1057  } else {
1058    LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1059    LookupParsedName(R, S, &SS);
1060
1061    TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1062    if (!TyD) {
1063      if (R.isAmbiguous()) return true;
1064
1065      if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1066        bool NotUnknownSpecialization = false;
1067        DeclContext *DC = computeDeclContext(SS, false);
1068        if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1069          NotUnknownSpecialization = !Record->hasAnyDependentBases();
1070
1071        if (!NotUnknownSpecialization) {
1072          // When the scope specifier can refer to a member of an unknown
1073          // specialization, we take it as a type name.
1074          BaseType = CheckTypenameType((NestedNameSpecifier *)SS.getScopeRep(),
1075                                       *MemberOrBase, SS.getRange());
1076          R.clear();
1077        }
1078      }
1079
1080      // If no results were found, try to correct typos.
1081      if (R.empty() && BaseType.isNull() &&
1082          CorrectTypo(R, S, &SS, ClassDecl) && R.isSingleResult()) {
1083        if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
1084          if (Member->getDeclContext()->getLookupContext()->Equals(ClassDecl)) {
1085            // We have found a non-static data member with a similar
1086            // name to what was typed; complain and initialize that
1087            // member.
1088            Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1089              << MemberOrBase << true << R.getLookupName()
1090              << CodeModificationHint::CreateReplacement(R.getNameLoc(),
1091                                               R.getLookupName().getAsString());
1092            Diag(Member->getLocation(), diag::note_previous_decl)
1093              << Member->getDeclName();
1094
1095            return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1096                                          LParenLoc, RParenLoc);
1097          }
1098        } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1099          const CXXBaseSpecifier *DirectBaseSpec;
1100          const CXXBaseSpecifier *VirtualBaseSpec;
1101          if (FindBaseInitializer(*this, ClassDecl,
1102                                  Context.getTypeDeclType(Type),
1103                                  DirectBaseSpec, VirtualBaseSpec)) {
1104            // We have found a direct or virtual base class with a
1105            // similar name to what was typed; complain and initialize
1106            // that base class.
1107            Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1108              << MemberOrBase << false << R.getLookupName()
1109              << CodeModificationHint::CreateReplacement(R.getNameLoc(),
1110                                               R.getLookupName().getAsString());
1111
1112            const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1113                                                             : VirtualBaseSpec;
1114            Diag(BaseSpec->getSourceRange().getBegin(),
1115                 diag::note_base_class_specified_here)
1116              << BaseSpec->getType()
1117              << BaseSpec->getSourceRange();
1118
1119            TyD = Type;
1120          }
1121        }
1122      }
1123
1124      if (!TyD && BaseType.isNull()) {
1125        Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1126          << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1127        return true;
1128      }
1129    }
1130
1131    if (BaseType.isNull()) {
1132      BaseType = Context.getTypeDeclType(TyD);
1133      if (SS.isSet()) {
1134        NestedNameSpecifier *Qualifier =
1135          static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1136
1137        // FIXME: preserve source range information
1138        BaseType = Context.getQualifiedNameType(Qualifier, BaseType);
1139      }
1140    }
1141  }
1142
1143  if (!TInfo)
1144    TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
1145
1146  return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
1147                              LParenLoc, RParenLoc, ClassDecl);
1148}
1149
1150/// Checks an initializer expression for use of uninitialized fields, such as
1151/// containing the field that is being initialized. Returns true if there is an
1152/// uninitialized field was used an updates the SourceLocation parameter; false
1153/// otherwise.
1154static bool InitExprContainsUninitializedFields(const Stmt* S,
1155                                                const FieldDecl* LhsField,
1156                                                SourceLocation* L) {
1157  const MemberExpr* ME = dyn_cast<MemberExpr>(S);
1158  if (ME) {
1159    const NamedDecl* RhsField = ME->getMemberDecl();
1160    if (RhsField == LhsField) {
1161      // Initializing a field with itself. Throw a warning.
1162      // But wait; there are exceptions!
1163      // Exception #1:  The field may not belong to this record.
1164      // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1165      const Expr* base = ME->getBase();
1166      if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1167        // Even though the field matches, it does not belong to this record.
1168        return false;
1169      }
1170      // None of the exceptions triggered; return true to indicate an
1171      // uninitialized field was used.
1172      *L = ME->getMemberLoc();
1173      return true;
1174    }
1175  }
1176  bool found = false;
1177  for (Stmt::const_child_iterator it = S->child_begin();
1178       it != S->child_end() && found == false;
1179       ++it) {
1180    if (isa<CallExpr>(S)) {
1181      // Do not descend into function calls or constructors, as the use
1182      // of an uninitialized field may be valid. One would have to inspect
1183      // the contents of the function/ctor to determine if it is safe or not.
1184      // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1185      // may be safe, depending on what the function/ctor does.
1186      continue;
1187    }
1188    found = InitExprContainsUninitializedFields(*it, LhsField, L);
1189  }
1190  return found;
1191}
1192
1193Sema::MemInitResult
1194Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1195                             unsigned NumArgs, SourceLocation IdLoc,
1196                             SourceLocation LParenLoc,
1197                             SourceLocation RParenLoc) {
1198  // Diagnose value-uses of fields to initialize themselves, e.g.
1199  //   foo(foo)
1200  // where foo is not also a parameter to the constructor.
1201  // TODO: implement -Wuninitialized and fold this into that framework.
1202  for (unsigned i = 0; i < NumArgs; ++i) {
1203    SourceLocation L;
1204    if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1205      // FIXME: Return true in the case when other fields are used before being
1206      // uninitialized. For example, let this field be the i'th field. When
1207      // initializing the i'th field, throw a warning if any of the >= i'th
1208      // fields are used, as they are not yet initialized.
1209      // Right now we are only handling the case where the i'th field uses
1210      // itself in its initializer.
1211      Diag(L, diag::warn_field_is_uninit);
1212    }
1213  }
1214
1215  bool HasDependentArg = false;
1216  for (unsigned i = 0; i < NumArgs; i++)
1217    HasDependentArg |= Args[i]->isTypeDependent();
1218
1219  QualType FieldType = Member->getType();
1220  if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1221    FieldType = Array->getElementType();
1222  ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1223  if (FieldType->isDependentType() || HasDependentArg) {
1224    // Can't check initialization for a member of dependent type or when
1225    // any of the arguments are type-dependent expressions.
1226    OwningExprResult Init
1227      = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1228                                          RParenLoc));
1229
1230    // Erase any temporaries within this evaluation context; we're not
1231    // going to track them in the AST, since we'll be rebuilding the
1232    // ASTs during template instantiation.
1233    ExprTemporaries.erase(
1234              ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1235                          ExprTemporaries.end());
1236
1237    return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1238                                                    LParenLoc,
1239                                                    Init.takeAs<Expr>(),
1240                                                    RParenLoc);
1241
1242  }
1243
1244  if (Member->isInvalidDecl())
1245    return true;
1246
1247  // Initialize the member.
1248  InitializedEntity MemberEntity =
1249    InitializedEntity::InitializeMember(Member, 0);
1250  InitializationKind Kind =
1251    InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1252
1253  InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1254
1255  OwningExprResult MemberInit =
1256    InitSeq.Perform(*this, MemberEntity, Kind,
1257                    MultiExprArg(*this, (void**)Args, NumArgs), 0);
1258  if (MemberInit.isInvalid())
1259    return true;
1260
1261  // C++0x [class.base.init]p7:
1262  //   The initialization of each base and member constitutes a
1263  //   full-expression.
1264  MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1265  if (MemberInit.isInvalid())
1266    return true;
1267
1268  // If we are in a dependent context, template instantiation will
1269  // perform this type-checking again. Just save the arguments that we
1270  // received in a ParenListExpr.
1271  // FIXME: This isn't quite ideal, since our ASTs don't capture all
1272  // of the information that we have about the member
1273  // initializer. However, deconstructing the ASTs is a dicey process,
1274  // and this approach is far more likely to get the corner cases right.
1275  if (CurContext->isDependentContext()) {
1276    // Bump the reference count of all of the arguments.
1277    for (unsigned I = 0; I != NumArgs; ++I)
1278      Args[I]->Retain();
1279
1280    OwningExprResult Init
1281      = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1282                                          RParenLoc));
1283    return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1284                                                    LParenLoc,
1285                                                    Init.takeAs<Expr>(),
1286                                                    RParenLoc);
1287  }
1288
1289  return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1290                                                  LParenLoc,
1291                                                  MemberInit.takeAs<Expr>(),
1292                                                  RParenLoc);
1293}
1294
1295Sema::MemInitResult
1296Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
1297                           Expr **Args, unsigned NumArgs,
1298                           SourceLocation LParenLoc, SourceLocation RParenLoc,
1299                           CXXRecordDecl *ClassDecl) {
1300  bool HasDependentArg = false;
1301  for (unsigned i = 0; i < NumArgs; i++)
1302    HasDependentArg |= Args[i]->isTypeDependent();
1303
1304  SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getSourceRange().getBegin();
1305  if (BaseType->isDependentType() || HasDependentArg) {
1306    // Can't check initialization for a base of dependent type or when
1307    // any of the arguments are type-dependent expressions.
1308    OwningExprResult BaseInit
1309      = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1310                                          RParenLoc));
1311
1312    // Erase any temporaries within this evaluation context; we're not
1313    // going to track them in the AST, since we'll be rebuilding the
1314    // ASTs during template instantiation.
1315    ExprTemporaries.erase(
1316              ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1317                          ExprTemporaries.end());
1318
1319    return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1320                                                    LParenLoc,
1321                                                    BaseInit.takeAs<Expr>(),
1322                                                    RParenLoc);
1323  }
1324
1325  if (!BaseType->isRecordType())
1326    return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1327             << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1328
1329  // C++ [class.base.init]p2:
1330  //   [...] Unless the mem-initializer-id names a nonstatic data
1331  //   member of the constructor’s class or a direct or virtual base
1332  //   of that class, the mem-initializer is ill-formed. A
1333  //   mem-initializer-list can initialize a base class using any
1334  //   name that denotes that base class type.
1335
1336  // Check for direct and virtual base classes.
1337  const CXXBaseSpecifier *DirectBaseSpec = 0;
1338  const CXXBaseSpecifier *VirtualBaseSpec = 0;
1339  FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1340                      VirtualBaseSpec);
1341
1342  // C++ [base.class.init]p2:
1343  //   If a mem-initializer-id is ambiguous because it designates both
1344  //   a direct non-virtual base class and an inherited virtual base
1345  //   class, the mem-initializer is ill-formed.
1346  if (DirectBaseSpec && VirtualBaseSpec)
1347    return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
1348      << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1349  // C++ [base.class.init]p2:
1350  // Unless the mem-initializer-id names a nonstatic data membeer of the
1351  // constructor's class ot a direst or virtual base of that class, the
1352  // mem-initializer is ill-formed.
1353  if (!DirectBaseSpec && !VirtualBaseSpec)
1354    return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1355      << BaseType << ClassDecl->getNameAsCString()
1356      << BaseTInfo->getTypeLoc().getSourceRange();
1357
1358  CXXBaseSpecifier *BaseSpec
1359    = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1360  if (!BaseSpec)
1361    BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1362
1363  // Initialize the base.
1364  InitializedEntity BaseEntity =
1365    InitializedEntity::InitializeBase(Context, BaseSpec);
1366  InitializationKind Kind =
1367    InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1368
1369  InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1370
1371  OwningExprResult BaseInit =
1372    InitSeq.Perform(*this, BaseEntity, Kind,
1373                    MultiExprArg(*this, (void**)Args, NumArgs), 0);
1374  if (BaseInit.isInvalid())
1375    return true;
1376
1377  // C++0x [class.base.init]p7:
1378  //   The initialization of each base and member constitutes a
1379  //   full-expression.
1380  BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1381  if (BaseInit.isInvalid())
1382    return true;
1383
1384  // If we are in a dependent context, template instantiation will
1385  // perform this type-checking again. Just save the arguments that we
1386  // received in a ParenListExpr.
1387  // FIXME: This isn't quite ideal, since our ASTs don't capture all
1388  // of the information that we have about the base
1389  // initializer. However, deconstructing the ASTs is a dicey process,
1390  // and this approach is far more likely to get the corner cases right.
1391  if (CurContext->isDependentContext()) {
1392    // Bump the reference count of all of the arguments.
1393    for (unsigned I = 0; I != NumArgs; ++I)
1394      Args[I]->Retain();
1395
1396    OwningExprResult Init
1397      = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1398                                          RParenLoc));
1399    return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1400                                                    LParenLoc,
1401                                                    Init.takeAs<Expr>(),
1402                                                    RParenLoc);
1403  }
1404
1405  return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1406                                                  LParenLoc,
1407                                                  BaseInit.takeAs<Expr>(),
1408                                                  RParenLoc);
1409}
1410
1411bool
1412Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
1413                                  CXXBaseOrMemberInitializer **Initializers,
1414                                  unsigned NumInitializers,
1415                                  bool IsImplicitConstructor,
1416                                  bool AnyErrors) {
1417  // We need to build the initializer AST according to order of construction
1418  // and not what user specified in the Initializers list.
1419  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1420  llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1421  llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1422  bool HasDependentBaseInit = false;
1423  bool HadError = false;
1424
1425  for (unsigned i = 0; i < NumInitializers; i++) {
1426    CXXBaseOrMemberInitializer *Member = Initializers[i];
1427    if (Member->isBaseInitializer()) {
1428      if (Member->getBaseClass()->isDependentType())
1429        HasDependentBaseInit = true;
1430      AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1431    } else {
1432      AllBaseFields[Member->getMember()] = Member;
1433    }
1434  }
1435
1436  if (HasDependentBaseInit) {
1437    // FIXME. This does not preserve the ordering of the initializers.
1438    // Try (with -Wreorder)
1439    // template<class X> struct A {};
1440    // template<class X> struct B : A<X> {
1441    //   B() : x1(10), A<X>() {}
1442    //   int x1;
1443    // };
1444    // B<int> x;
1445    // On seeing one dependent type, we should essentially exit this routine
1446    // while preserving user-declared initializer list. When this routine is
1447    // called during instantiatiation process, this routine will rebuild the
1448    // ordered initializer list correctly.
1449
1450    // If we have a dependent base initialization, we can't determine the
1451    // association between initializers and bases; just dump the known
1452    // initializers into the list, and don't try to deal with other bases.
1453    for (unsigned i = 0; i < NumInitializers; i++) {
1454      CXXBaseOrMemberInitializer *Member = Initializers[i];
1455      if (Member->isBaseInitializer())
1456        AllToInit.push_back(Member);
1457    }
1458  } else {
1459    llvm::SmallVector<CXXBaseSpecifier *, 4> BasesToDefaultInit;
1460
1461    // Push virtual bases before others.
1462    for (CXXRecordDecl::base_class_iterator VBase =
1463         ClassDecl->vbases_begin(),
1464         E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1465      if (VBase->getType()->isDependentType())
1466        continue;
1467      if (CXXBaseOrMemberInitializer *Value
1468            = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1469        AllToInit.push_back(Value);
1470      } else if (!AnyErrors) {
1471        InitializedEntity InitEntity
1472          = InitializedEntity::InitializeBase(Context, VBase);
1473        InitializationKind InitKind
1474          = InitializationKind::CreateDefault(Constructor->getLocation());
1475        InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1476        OwningExprResult BaseInit = InitSeq.Perform(*this, InitEntity, InitKind,
1477                                                    MultiExprArg(*this, 0, 0));
1478        BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1479        if (BaseInit.isInvalid()) {
1480          HadError = true;
1481          continue;
1482        }
1483
1484        // Don't attach synthesized base initializers in a dependent
1485        // context; they'll be checked again at template instantiation
1486        // time.
1487        if (CurContext->isDependentContext())
1488          continue;
1489
1490        CXXBaseOrMemberInitializer *CXXBaseInit =
1491          new (Context) CXXBaseOrMemberInitializer(Context,
1492                             Context.getTrivialTypeSourceInfo(VBase->getType(),
1493                                                              SourceLocation()),
1494                                                   SourceLocation(),
1495                                                   BaseInit.takeAs<Expr>(),
1496                                                   SourceLocation());
1497        AllToInit.push_back(CXXBaseInit);
1498      }
1499    }
1500
1501    for (CXXRecordDecl::base_class_iterator Base =
1502         ClassDecl->bases_begin(),
1503         E = ClassDecl->bases_end(); Base != E; ++Base) {
1504      // Virtuals are in the virtual base list and already constructed.
1505      if (Base->isVirtual())
1506        continue;
1507      // Skip dependent types.
1508      if (Base->getType()->isDependentType())
1509        continue;
1510      if (CXXBaseOrMemberInitializer *Value
1511            = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1512        AllToInit.push_back(Value);
1513      }
1514      else if (!AnyErrors) {
1515        InitializedEntity InitEntity
1516          = InitializedEntity::InitializeBase(Context, Base);
1517        InitializationKind InitKind
1518          = InitializationKind::CreateDefault(Constructor->getLocation());
1519        InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1520        OwningExprResult BaseInit = InitSeq.Perform(*this, InitEntity, InitKind,
1521                                                    MultiExprArg(*this, 0, 0));
1522        BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1523        if (BaseInit.isInvalid()) {
1524          HadError = true;
1525          continue;
1526        }
1527
1528        // Don't attach synthesized base initializers in a dependent
1529        // context; they'll be regenerated at template instantiation
1530        // time.
1531        if (CurContext->isDependentContext())
1532          continue;
1533
1534        CXXBaseOrMemberInitializer *CXXBaseInit =
1535          new (Context) CXXBaseOrMemberInitializer(Context,
1536                             Context.getTrivialTypeSourceInfo(Base->getType(),
1537                                                              SourceLocation()),
1538                                                   SourceLocation(),
1539                                                   BaseInit.takeAs<Expr>(),
1540                                                   SourceLocation());
1541        AllToInit.push_back(CXXBaseInit);
1542      }
1543    }
1544  }
1545
1546  // non-static data members.
1547  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1548       E = ClassDecl->field_end(); Field != E; ++Field) {
1549    if ((*Field)->isAnonymousStructOrUnion()) {
1550      if (const RecordType *FieldClassType =
1551          Field->getType()->getAs<RecordType>()) {
1552        CXXRecordDecl *FieldClassDecl
1553          = cast<CXXRecordDecl>(FieldClassType->getDecl());
1554        for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1555            EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1556          if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1557            // 'Member' is the anonymous union field and 'AnonUnionMember' is
1558            // set to the anonymous union data member used in the initializer
1559            // list.
1560            Value->setMember(*Field);
1561            Value->setAnonUnionMember(*FA);
1562            AllToInit.push_back(Value);
1563            break;
1564          }
1565        }
1566      }
1567      continue;
1568    }
1569    if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1570      AllToInit.push_back(Value);
1571      continue;
1572    }
1573
1574    if ((*Field)->getType()->isDependentType() || AnyErrors)
1575      continue;
1576
1577    QualType FT = Context.getBaseElementType((*Field)->getType());
1578    if (FT->getAs<RecordType>()) {
1579      InitializedEntity InitEntity
1580        = InitializedEntity::InitializeMember(*Field);
1581      InitializationKind InitKind
1582        = InitializationKind::CreateDefault(Constructor->getLocation());
1583
1584      InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1585      OwningExprResult MemberInit = InitSeq.Perform(*this, InitEntity, InitKind,
1586                                                    MultiExprArg(*this, 0, 0));
1587      MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1588      if (MemberInit.isInvalid()) {
1589        HadError = true;
1590        continue;
1591      }
1592
1593      // Don't attach synthesized member initializers in a dependent
1594      // context; they'll be regenerated a template instantiation
1595      // time.
1596      if (CurContext->isDependentContext())
1597        continue;
1598
1599      CXXBaseOrMemberInitializer *Member =
1600        new (Context) CXXBaseOrMemberInitializer(Context,
1601                                                 *Field, SourceLocation(),
1602                                                 SourceLocation(),
1603                                                 MemberInit.takeAs<Expr>(),
1604                                                 SourceLocation());
1605
1606      AllToInit.push_back(Member);
1607    }
1608    else if (FT->isReferenceType()) {
1609      Diag(Constructor->getLocation(), diag::err_uninitialized_member_in_ctor)
1610        << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1611        << 0 << (*Field)->getDeclName();
1612      Diag((*Field)->getLocation(), diag::note_declared_at);
1613      HadError = true;
1614    }
1615    else if (FT.isConstQualified()) {
1616      Diag(Constructor->getLocation(), diag::err_uninitialized_member_in_ctor)
1617        << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1618        << 1 << (*Field)->getDeclName();
1619      Diag((*Field)->getLocation(), diag::note_declared_at);
1620      HadError = true;
1621    }
1622  }
1623
1624  NumInitializers = AllToInit.size();
1625  if (NumInitializers > 0) {
1626    Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1627    CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1628      new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1629
1630    Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1631    for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1632      baseOrMemberInitializers[Idx] = AllToInit[Idx];
1633  }
1634
1635  return HadError;
1636}
1637
1638static void *GetKeyForTopLevelField(FieldDecl *Field) {
1639  // For anonymous unions, use the class declaration as the key.
1640  if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
1641    if (RT->getDecl()->isAnonymousStructOrUnion())
1642      return static_cast<void *>(RT->getDecl());
1643  }
1644  return static_cast<void *>(Field);
1645}
1646
1647static void *GetKeyForBase(QualType BaseType) {
1648  if (const RecordType *RT = BaseType->getAs<RecordType>())
1649    return (void *)RT;
1650
1651  assert(0 && "Unexpected base type!");
1652  return 0;
1653}
1654
1655static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
1656                             bool MemberMaybeAnon = false) {
1657  // For fields injected into the class via declaration of an anonymous union,
1658  // use its anonymous union class declaration as the unique key.
1659  if (Member->isMemberInitializer()) {
1660    FieldDecl *Field = Member->getMember();
1661
1662    // After SetBaseOrMemberInitializers call, Field is the anonymous union
1663    // data member of the class. Data member used in the initializer list is
1664    // in AnonUnionMember field.
1665    if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1666      Field = Member->getAnonUnionMember();
1667    if (Field->getDeclContext()->isRecord()) {
1668      RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1669      if (RD->isAnonymousStructOrUnion())
1670        return static_cast<void *>(RD);
1671    }
1672    return static_cast<void *>(Field);
1673  }
1674
1675  return GetKeyForBase(QualType(Member->getBaseClass(), 0));
1676}
1677
1678/// ActOnMemInitializers - Handle the member initializers for a constructor.
1679void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
1680                                SourceLocation ColonLoc,
1681                                MemInitTy **MemInits, unsigned NumMemInits,
1682                                bool AnyErrors) {
1683  if (!ConstructorDecl)
1684    return;
1685
1686  AdjustDeclIfTemplate(ConstructorDecl);
1687
1688  CXXConstructorDecl *Constructor
1689    = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
1690
1691  if (!Constructor) {
1692    Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1693    return;
1694  }
1695
1696  if (!Constructor->isDependentContext()) {
1697    llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1698    bool err = false;
1699    for (unsigned i = 0; i < NumMemInits; i++) {
1700      CXXBaseOrMemberInitializer *Member =
1701        static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1702      void *KeyToMember = GetKeyForMember(Member);
1703      CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1704      if (!PrevMember) {
1705        PrevMember = Member;
1706        continue;
1707      }
1708      if (FieldDecl *Field = Member->getMember())
1709        Diag(Member->getSourceLocation(),
1710             diag::error_multiple_mem_initialization)
1711          << Field->getNameAsString()
1712          << Member->getSourceRange();
1713      else {
1714        Type *BaseClass = Member->getBaseClass();
1715        assert(BaseClass && "ActOnMemInitializers - neither field or base");
1716        Diag(Member->getSourceLocation(),
1717             diag::error_multiple_base_initialization)
1718          << QualType(BaseClass, 0)
1719          << Member->getSourceRange();
1720      }
1721      Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1722        << 0;
1723      err = true;
1724    }
1725
1726    if (err)
1727      return;
1728  }
1729
1730  SetBaseOrMemberInitializers(Constructor,
1731                      reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
1732                      NumMemInits, false, AnyErrors);
1733
1734  if (Constructor->isDependentContext())
1735    return;
1736
1737  if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
1738      Diagnostic::Ignored &&
1739      Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
1740      Diagnostic::Ignored)
1741    return;
1742
1743  // Also issue warning if order of ctor-initializer list does not match order
1744  // of 1) base class declarations and 2) order of non-static data members.
1745  llvm::SmallVector<const void*, 32> AllBaseOrMembers;
1746
1747  CXXRecordDecl *ClassDecl
1748    = cast<CXXRecordDecl>(Constructor->getDeclContext());
1749  // Push virtual bases before others.
1750  for (CXXRecordDecl::base_class_iterator VBase =
1751       ClassDecl->vbases_begin(),
1752       E = ClassDecl->vbases_end(); VBase != E; ++VBase)
1753    AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
1754
1755  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1756       E = ClassDecl->bases_end(); Base != E; ++Base) {
1757    // Virtuals are alread in the virtual base list and are constructed
1758    // first.
1759    if (Base->isVirtual())
1760      continue;
1761    AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
1762  }
1763
1764  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1765       E = ClassDecl->field_end(); Field != E; ++Field)
1766    AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
1767
1768  int Last = AllBaseOrMembers.size();
1769  int curIndex = 0;
1770  CXXBaseOrMemberInitializer *PrevMember = 0;
1771  for (unsigned i = 0; i < NumMemInits; i++) {
1772    CXXBaseOrMemberInitializer *Member =
1773      static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1774    void *MemberInCtorList = GetKeyForMember(Member, true);
1775
1776    for (; curIndex < Last; curIndex++)
1777      if (MemberInCtorList == AllBaseOrMembers[curIndex])
1778        break;
1779    if (curIndex == Last) {
1780      assert(PrevMember && "Member not in member list?!");
1781      // Initializer as specified in ctor-initializer list is out of order.
1782      // Issue a warning diagnostic.
1783      if (PrevMember->isBaseInitializer()) {
1784        // Diagnostics is for an initialized base class.
1785        Type *BaseClass = PrevMember->getBaseClass();
1786        Diag(PrevMember->getSourceLocation(),
1787             diag::warn_base_initialized)
1788          << QualType(BaseClass, 0);
1789      } else {
1790        FieldDecl *Field = PrevMember->getMember();
1791        Diag(PrevMember->getSourceLocation(),
1792             diag::warn_field_initialized)
1793          << Field->getNameAsString();
1794      }
1795      // Also the note!
1796      if (FieldDecl *Field = Member->getMember())
1797        Diag(Member->getSourceLocation(),
1798             diag::note_fieldorbase_initialized_here) << 0
1799          << Field->getNameAsString();
1800      else {
1801        Type *BaseClass = Member->getBaseClass();
1802        Diag(Member->getSourceLocation(),
1803             diag::note_fieldorbase_initialized_here) << 1
1804          << QualType(BaseClass, 0);
1805      }
1806      for (curIndex = 0; curIndex < Last; curIndex++)
1807        if (MemberInCtorList == AllBaseOrMembers[curIndex])
1808          break;
1809    }
1810    PrevMember = Member;
1811  }
1812}
1813
1814void
1815Sema::MarkBaseAndMemberDestructorsReferenced(CXXDestructorDecl *Destructor) {
1816  // Ignore dependent destructors.
1817  if (Destructor->isDependentContext())
1818    return;
1819
1820  CXXRecordDecl *ClassDecl = Destructor->getParent();
1821
1822  // Non-static data members.
1823  for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1824       E = ClassDecl->field_end(); I != E; ++I) {
1825    FieldDecl *Field = *I;
1826
1827    QualType FieldType = Context.getBaseElementType(Field->getType());
1828
1829    const RecordType* RT = FieldType->getAs<RecordType>();
1830    if (!RT)
1831      continue;
1832
1833    CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1834    if (FieldClassDecl->hasTrivialDestructor())
1835      continue;
1836
1837    const CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
1838    MarkDeclarationReferenced(Destructor->getLocation(),
1839                              const_cast<CXXDestructorDecl*>(Dtor));
1840  }
1841
1842  // Bases.
1843  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1844       E = ClassDecl->bases_end(); Base != E; ++Base) {
1845    // Ignore virtual bases.
1846    if (Base->isVirtual())
1847      continue;
1848
1849    // Ignore trivial destructors.
1850    CXXRecordDecl *BaseClassDecl
1851      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1852    if (BaseClassDecl->hasTrivialDestructor())
1853      continue;
1854
1855    const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1856    MarkDeclarationReferenced(Destructor->getLocation(),
1857                              const_cast<CXXDestructorDecl*>(Dtor));
1858  }
1859
1860  // Virtual bases.
1861  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1862       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1863    // Ignore trivial destructors.
1864    CXXRecordDecl *BaseClassDecl
1865      = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1866    if (BaseClassDecl->hasTrivialDestructor())
1867      continue;
1868
1869    const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1870    MarkDeclarationReferenced(Destructor->getLocation(),
1871                              const_cast<CXXDestructorDecl*>(Dtor));
1872  }
1873}
1874
1875void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
1876  if (!CDtorDecl)
1877    return;
1878
1879  AdjustDeclIfTemplate(CDtorDecl);
1880
1881  if (CXXConstructorDecl *Constructor
1882      = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
1883    SetBaseOrMemberInitializers(Constructor, 0, 0, false, false);
1884}
1885
1886namespace {
1887  /// PureVirtualMethodCollector - traverses a class and its superclasses
1888  /// and determines if it has any pure virtual methods.
1889  class PureVirtualMethodCollector {
1890    ASTContext &Context;
1891
1892  public:
1893    typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
1894
1895  private:
1896    MethodList Methods;
1897
1898    void Collect(const CXXRecordDecl* RD, MethodList& Methods);
1899
1900  public:
1901    PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
1902      : Context(Ctx) {
1903
1904      MethodList List;
1905      Collect(RD, List);
1906
1907      // Copy the temporary list to methods, and make sure to ignore any
1908      // null entries.
1909      for (size_t i = 0, e = List.size(); i != e; ++i) {
1910        if (List[i])
1911          Methods.push_back(List[i]);
1912      }
1913    }
1914
1915    bool empty() const { return Methods.empty(); }
1916
1917    MethodList::const_iterator methods_begin() { return Methods.begin(); }
1918    MethodList::const_iterator methods_end() { return Methods.end(); }
1919  };
1920
1921  void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
1922                                           MethodList& Methods) {
1923    // First, collect the pure virtual methods for the base classes.
1924    for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1925         BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
1926      if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
1927        const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
1928        if (BaseDecl && BaseDecl->isAbstract())
1929          Collect(BaseDecl, Methods);
1930      }
1931    }
1932
1933    // Next, zero out any pure virtual methods that this class overrides.
1934    typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
1935
1936    MethodSetTy OverriddenMethods;
1937    size_t MethodsSize = Methods.size();
1938
1939    for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
1940         i != e; ++i) {
1941      // Traverse the record, looking for methods.
1942      if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
1943        // If the method is pure virtual, add it to the methods vector.
1944        if (MD->isPure())
1945          Methods.push_back(MD);
1946
1947        // Record all the overridden methods in our set.
1948        for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1949             E = MD->end_overridden_methods(); I != E; ++I) {
1950          // Keep track of the overridden methods.
1951          OverriddenMethods.insert(*I);
1952        }
1953      }
1954    }
1955
1956    // Now go through the methods and zero out all the ones we know are
1957    // overridden.
1958    for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1959      if (OverriddenMethods.count(Methods[i]))
1960        Methods[i] = 0;
1961    }
1962
1963  }
1964}
1965
1966
1967bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1968                                  unsigned DiagID, AbstractDiagSelID SelID,
1969                                  const CXXRecordDecl *CurrentRD) {
1970  if (SelID == -1)
1971    return RequireNonAbstractType(Loc, T,
1972                                  PDiag(DiagID), CurrentRD);
1973  else
1974    return RequireNonAbstractType(Loc, T,
1975                                  PDiag(DiagID) << SelID, CurrentRD);
1976}
1977
1978bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1979                                  const PartialDiagnostic &PD,
1980                                  const CXXRecordDecl *CurrentRD) {
1981  if (!getLangOptions().CPlusPlus)
1982    return false;
1983
1984  if (const ArrayType *AT = Context.getAsArrayType(T))
1985    return RequireNonAbstractType(Loc, AT->getElementType(), PD,
1986                                  CurrentRD);
1987
1988  if (const PointerType *PT = T->getAs<PointerType>()) {
1989    // Find the innermost pointer type.
1990    while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
1991      PT = T;
1992
1993    if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
1994      return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
1995  }
1996
1997  const RecordType *RT = T->getAs<RecordType>();
1998  if (!RT)
1999    return false;
2000
2001  const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2002  if (!RD)
2003    return false;
2004
2005  if (CurrentRD && CurrentRD != RD)
2006    return false;
2007
2008  if (!RD->isAbstract())
2009    return false;
2010
2011  Diag(Loc, PD) << RD->getDeclName();
2012
2013  // Check if we've already emitted the list of pure virtual functions for this
2014  // class.
2015  if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
2016    return true;
2017
2018  PureVirtualMethodCollector Collector(Context, RD);
2019
2020  for (PureVirtualMethodCollector::MethodList::const_iterator I =
2021       Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
2022    const CXXMethodDecl *MD = *I;
2023
2024    Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
2025      MD->getDeclName();
2026  }
2027
2028  if (!PureVirtualClassDiagSet)
2029    PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2030  PureVirtualClassDiagSet->insert(RD);
2031
2032  return true;
2033}
2034
2035namespace {
2036  class AbstractClassUsageDiagnoser
2037    : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
2038    Sema &SemaRef;
2039    CXXRecordDecl *AbstractClass;
2040
2041    bool VisitDeclContext(const DeclContext *DC) {
2042      bool Invalid = false;
2043
2044      for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
2045           E = DC->decls_end(); I != E; ++I)
2046        Invalid |= Visit(*I);
2047
2048      return Invalid;
2049    }
2050
2051  public:
2052    AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
2053      : SemaRef(SemaRef), AbstractClass(ac) {
2054        Visit(SemaRef.Context.getTranslationUnitDecl());
2055    }
2056
2057    bool VisitFunctionDecl(const FunctionDecl *FD) {
2058      if (FD->isThisDeclarationADefinition()) {
2059        // No need to do the check if we're in a definition, because it requires
2060        // that the return/param types are complete.
2061        // because that requires
2062        return VisitDeclContext(FD);
2063      }
2064
2065      // Check the return type.
2066      QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
2067      bool Invalid =
2068        SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
2069                                       diag::err_abstract_type_in_decl,
2070                                       Sema::AbstractReturnType,
2071                                       AbstractClass);
2072
2073      for (FunctionDecl::param_const_iterator I = FD->param_begin(),
2074           E = FD->param_end(); I != E; ++I) {
2075        const ParmVarDecl *VD = *I;
2076        Invalid |=
2077          SemaRef.RequireNonAbstractType(VD->getLocation(),
2078                                         VD->getOriginalType(),
2079                                         diag::err_abstract_type_in_decl,
2080                                         Sema::AbstractParamType,
2081                                         AbstractClass);
2082      }
2083
2084      return Invalid;
2085    }
2086
2087    bool VisitDecl(const Decl* D) {
2088      if (const DeclContext *DC = dyn_cast<DeclContext>(D))
2089        return VisitDeclContext(DC);
2090
2091      return false;
2092    }
2093  };
2094}
2095
2096/// \brief Perform semantic checks on a class definition that has been
2097/// completing, introducing implicitly-declared members, checking for
2098/// abstract types, etc.
2099void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
2100  if (!Record || Record->isInvalidDecl())
2101    return;
2102
2103  if (!Record->isDependentType())
2104    AddImplicitlyDeclaredMembersToClass(Record);
2105
2106  if (Record->isInvalidDecl())
2107    return;
2108
2109  // Set access bits correctly on the directly-declared conversions.
2110  UnresolvedSetImpl *Convs = Record->getConversionFunctions();
2111  for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I)
2112    Convs->setAccess(I, (*I)->getAccess());
2113
2114  if (!Record->isAbstract()) {
2115    // Collect all the pure virtual methods and see if this is an abstract
2116    // class after all.
2117    PureVirtualMethodCollector Collector(Context, Record);
2118    if (!Collector.empty())
2119      Record->setAbstract(true);
2120  }
2121
2122  if (Record->isAbstract())
2123    (void)AbstractClassUsageDiagnoser(*this, Record);
2124}
2125
2126void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
2127                                             DeclPtrTy TagDecl,
2128                                             SourceLocation LBrac,
2129                                             SourceLocation RBrac) {
2130  if (!TagDecl)
2131    return;
2132
2133  AdjustDeclIfTemplate(TagDecl);
2134
2135  ActOnFields(S, RLoc, TagDecl,
2136              (DeclPtrTy*)FieldCollector->getCurFields(),
2137              FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
2138
2139  CheckCompletedCXXClass(
2140                      dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
2141}
2142
2143/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2144/// special functions, such as the default constructor, copy
2145/// constructor, or destructor, to the given C++ class (C++
2146/// [special]p1).  This routine can only be executed just before the
2147/// definition of the class is complete.
2148void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
2149  CanQualType ClassType
2150    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
2151
2152  // FIXME: Implicit declarations have exception specifications, which are
2153  // the union of the specifications of the implicitly called functions.
2154
2155  if (!ClassDecl->hasUserDeclaredConstructor()) {
2156    // C++ [class.ctor]p5:
2157    //   A default constructor for a class X is a constructor of class X
2158    //   that can be called without an argument. If there is no
2159    //   user-declared constructor for class X, a default constructor is
2160    //   implicitly declared. An implicitly-declared default constructor
2161    //   is an inline public member of its class.
2162    DeclarationName Name
2163      = Context.DeclarationNames.getCXXConstructorName(ClassType);
2164    CXXConstructorDecl *DefaultCon =
2165      CXXConstructorDecl::Create(Context, ClassDecl,
2166                                 ClassDecl->getLocation(), Name,
2167                                 Context.getFunctionType(Context.VoidTy,
2168                                                         0, 0, false, 0),
2169                                 /*TInfo=*/0,
2170                                 /*isExplicit=*/false,
2171                                 /*isInline=*/true,
2172                                 /*isImplicitlyDeclared=*/true);
2173    DefaultCon->setAccess(AS_public);
2174    DefaultCon->setImplicit();
2175    DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
2176    ClassDecl->addDecl(DefaultCon);
2177  }
2178
2179  if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
2180    // C++ [class.copy]p4:
2181    //   If the class definition does not explicitly declare a copy
2182    //   constructor, one is declared implicitly.
2183
2184    // C++ [class.copy]p5:
2185    //   The implicitly-declared copy constructor for a class X will
2186    //   have the form
2187    //
2188    //       X::X(const X&)
2189    //
2190    //   if
2191    bool HasConstCopyConstructor = true;
2192
2193    //     -- each direct or virtual base class B of X has a copy
2194    //        constructor whose first parameter is of type const B& or
2195    //        const volatile B&, and
2196    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2197         HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2198      const CXXRecordDecl *BaseClassDecl
2199        = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2200      HasConstCopyConstructor
2201        = BaseClassDecl->hasConstCopyConstructor(Context);
2202    }
2203
2204    //     -- for all the nonstatic data members of X that are of a
2205    //        class type M (or array thereof), each such class type
2206    //        has a copy constructor whose first parameter is of type
2207    //        const M& or const volatile M&.
2208    for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2209         HasConstCopyConstructor && Field != ClassDecl->field_end();
2210         ++Field) {
2211      QualType FieldType = (*Field)->getType();
2212      if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2213        FieldType = Array->getElementType();
2214      if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
2215        const CXXRecordDecl *FieldClassDecl
2216          = cast<CXXRecordDecl>(FieldClassType->getDecl());
2217        HasConstCopyConstructor
2218          = FieldClassDecl->hasConstCopyConstructor(Context);
2219      }
2220    }
2221
2222    //   Otherwise, the implicitly declared copy constructor will have
2223    //   the form
2224    //
2225    //       X::X(X&)
2226    QualType ArgType = ClassType;
2227    if (HasConstCopyConstructor)
2228      ArgType = ArgType.withConst();
2229    ArgType = Context.getLValueReferenceType(ArgType);
2230
2231    //   An implicitly-declared copy constructor is an inline public
2232    //   member of its class.
2233    DeclarationName Name
2234      = Context.DeclarationNames.getCXXConstructorName(ClassType);
2235    CXXConstructorDecl *CopyConstructor
2236      = CXXConstructorDecl::Create(Context, ClassDecl,
2237                                   ClassDecl->getLocation(), Name,
2238                                   Context.getFunctionType(Context.VoidTy,
2239                                                           &ArgType, 1,
2240                                                           false, 0),
2241                                   /*TInfo=*/0,
2242                                   /*isExplicit=*/false,
2243                                   /*isInline=*/true,
2244                                   /*isImplicitlyDeclared=*/true);
2245    CopyConstructor->setAccess(AS_public);
2246    CopyConstructor->setImplicit();
2247    CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
2248
2249    // Add the parameter to the constructor.
2250    ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2251                                                 ClassDecl->getLocation(),
2252                                                 /*IdentifierInfo=*/0,
2253                                                 ArgType, /*TInfo=*/0,
2254                                                 VarDecl::None, 0);
2255    CopyConstructor->setParams(Context, &FromParam, 1);
2256    ClassDecl->addDecl(CopyConstructor);
2257  }
2258
2259  if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2260    // Note: The following rules are largely analoguous to the copy
2261    // constructor rules. Note that virtual bases are not taken into account
2262    // for determining the argument type of the operator. Note also that
2263    // operators taking an object instead of a reference are allowed.
2264    //
2265    // C++ [class.copy]p10:
2266    //   If the class definition does not explicitly declare a copy
2267    //   assignment operator, one is declared implicitly.
2268    //   The implicitly-defined copy assignment operator for a class X
2269    //   will have the form
2270    //
2271    //       X& X::operator=(const X&)
2272    //
2273    //   if
2274    bool HasConstCopyAssignment = true;
2275
2276    //       -- each direct base class B of X has a copy assignment operator
2277    //          whose parameter is of type const B&, const volatile B& or B,
2278    //          and
2279    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2280         HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
2281      assert(!Base->getType()->isDependentType() &&
2282            "Cannot generate implicit members for class with dependent bases.");
2283      const CXXRecordDecl *BaseClassDecl
2284        = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2285      const CXXMethodDecl *MD = 0;
2286      HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
2287                                                                     MD);
2288    }
2289
2290    //       -- for all the nonstatic data members of X that are of a class
2291    //          type M (or array thereof), each such class type has a copy
2292    //          assignment operator whose parameter is of type const M&,
2293    //          const volatile M& or M.
2294    for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2295         HasConstCopyAssignment && Field != ClassDecl->field_end();
2296         ++Field) {
2297      QualType FieldType = (*Field)->getType();
2298      if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2299        FieldType = Array->getElementType();
2300      if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
2301        const CXXRecordDecl *FieldClassDecl
2302          = cast<CXXRecordDecl>(FieldClassType->getDecl());
2303        const CXXMethodDecl *MD = 0;
2304        HasConstCopyAssignment
2305          = FieldClassDecl->hasConstCopyAssignment(Context, MD);
2306      }
2307    }
2308
2309    //   Otherwise, the implicitly declared copy assignment operator will
2310    //   have the form
2311    //
2312    //       X& X::operator=(X&)
2313    QualType ArgType = ClassType;
2314    QualType RetType = Context.getLValueReferenceType(ArgType);
2315    if (HasConstCopyAssignment)
2316      ArgType = ArgType.withConst();
2317    ArgType = Context.getLValueReferenceType(ArgType);
2318
2319    //   An implicitly-declared copy assignment operator is an inline public
2320    //   member of its class.
2321    DeclarationName Name =
2322      Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2323    CXXMethodDecl *CopyAssignment =
2324      CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2325                            Context.getFunctionType(RetType, &ArgType, 1,
2326                                                    false, 0),
2327                            /*TInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
2328    CopyAssignment->setAccess(AS_public);
2329    CopyAssignment->setImplicit();
2330    CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
2331    CopyAssignment->setCopyAssignment(true);
2332
2333    // Add the parameter to the operator.
2334    ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2335                                                 ClassDecl->getLocation(),
2336                                                 /*IdentifierInfo=*/0,
2337                                                 ArgType, /*TInfo=*/0,
2338                                                 VarDecl::None, 0);
2339    CopyAssignment->setParams(Context, &FromParam, 1);
2340
2341    // Don't call addedAssignmentOperator. There is no way to distinguish an
2342    // implicit from an explicit assignment operator.
2343    ClassDecl->addDecl(CopyAssignment);
2344    AddOverriddenMethods(ClassDecl, CopyAssignment);
2345  }
2346
2347  if (!ClassDecl->hasUserDeclaredDestructor()) {
2348    // C++ [class.dtor]p2:
2349    //   If a class has no user-declared destructor, a destructor is
2350    //   declared implicitly. An implicitly-declared destructor is an
2351    //   inline public member of its class.
2352    DeclarationName Name
2353      = Context.DeclarationNames.getCXXDestructorName(ClassType);
2354    CXXDestructorDecl *Destructor
2355      = CXXDestructorDecl::Create(Context, ClassDecl,
2356                                  ClassDecl->getLocation(), Name,
2357                                  Context.getFunctionType(Context.VoidTy,
2358                                                          0, 0, false, 0),
2359                                  /*isInline=*/true,
2360                                  /*isImplicitlyDeclared=*/true);
2361    Destructor->setAccess(AS_public);
2362    Destructor->setImplicit();
2363    Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
2364    ClassDecl->addDecl(Destructor);
2365
2366    AddOverriddenMethods(ClassDecl, Destructor);
2367  }
2368}
2369
2370void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
2371  Decl *D = TemplateD.getAs<Decl>();
2372  if (!D)
2373    return;
2374
2375  TemplateParameterList *Params = 0;
2376  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2377    Params = Template->getTemplateParameters();
2378  else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2379           = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2380    Params = PartialSpec->getTemplateParameters();
2381  else
2382    return;
2383
2384  for (TemplateParameterList::iterator Param = Params->begin(),
2385                                    ParamEnd = Params->end();
2386       Param != ParamEnd; ++Param) {
2387    NamedDecl *Named = cast<NamedDecl>(*Param);
2388    if (Named->getDeclName()) {
2389      S->AddDecl(DeclPtrTy::make(Named));
2390      IdResolver.AddDecl(Named);
2391    }
2392  }
2393}
2394
2395void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2396  if (!RecordD) return;
2397  AdjustDeclIfTemplate(RecordD);
2398  CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>());
2399  PushDeclContext(S, Record);
2400}
2401
2402void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2403  if (!RecordD) return;
2404  PopDeclContext();
2405}
2406
2407/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2408/// parsing a top-level (non-nested) C++ class, and we are now
2409/// parsing those parts of the given Method declaration that could
2410/// not be parsed earlier (C++ [class.mem]p2), such as default
2411/// arguments. This action should enter the scope of the given
2412/// Method declaration as if we had just parsed the qualified method
2413/// name. However, it should not bring the parameters into scope;
2414/// that will be performed by ActOnDelayedCXXMethodParameter.
2415void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
2416}
2417
2418/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2419/// C++ method declaration. We're (re-)introducing the given
2420/// function parameter into scope for use in parsing later parts of
2421/// the method declaration. For example, we could see an
2422/// ActOnParamDefaultArgument event for this parameter.
2423void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
2424  if (!ParamD)
2425    return;
2426
2427  ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
2428
2429  // If this parameter has an unparsed default argument, clear it out
2430  // to make way for the parsed default argument.
2431  if (Param->hasUnparsedDefaultArg())
2432    Param->setDefaultArg(0);
2433
2434  S->AddDecl(DeclPtrTy::make(Param));
2435  if (Param->getDeclName())
2436    IdResolver.AddDecl(Param);
2437}
2438
2439/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2440/// processing the delayed method declaration for Method. The method
2441/// declaration is now considered finished. There may be a separate
2442/// ActOnStartOfFunctionDef action later (not necessarily
2443/// immediately!) for this method, if it was also defined inside the
2444/// class body.
2445void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
2446  if (!MethodD)
2447    return;
2448
2449  AdjustDeclIfTemplate(MethodD);
2450
2451  FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
2452
2453  // Now that we have our default arguments, check the constructor
2454  // again. It could produce additional diagnostics or affect whether
2455  // the class has implicitly-declared destructors, among other
2456  // things.
2457  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2458    CheckConstructor(Constructor);
2459
2460  // Check the default arguments, which we may have added.
2461  if (!Method->isInvalidDecl())
2462    CheckCXXDefaultArguments(Method);
2463}
2464
2465/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
2466/// the well-formedness of the constructor declarator @p D with type @p
2467/// R. If there are any errors in the declarator, this routine will
2468/// emit diagnostics and set the invalid bit to true.  In any case, the type
2469/// will be updated to reflect a well-formed type for the constructor and
2470/// returned.
2471QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2472                                          FunctionDecl::StorageClass &SC) {
2473  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
2474
2475  // C++ [class.ctor]p3:
2476  //   A constructor shall not be virtual (10.3) or static (9.4). A
2477  //   constructor can be invoked for a const, volatile or const
2478  //   volatile object. A constructor shall not be declared const,
2479  //   volatile, or const volatile (9.3.2).
2480  if (isVirtual) {
2481    if (!D.isInvalidType())
2482      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2483        << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2484        << SourceRange(D.getIdentifierLoc());
2485    D.setInvalidType();
2486  }
2487  if (SC == FunctionDecl::Static) {
2488    if (!D.isInvalidType())
2489      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2490        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2491        << SourceRange(D.getIdentifierLoc());
2492    D.setInvalidType();
2493    SC = FunctionDecl::None;
2494  }
2495
2496  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2497  if (FTI.TypeQuals != 0) {
2498    if (FTI.TypeQuals & Qualifiers::Const)
2499      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2500        << "const" << SourceRange(D.getIdentifierLoc());
2501    if (FTI.TypeQuals & Qualifiers::Volatile)
2502      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2503        << "volatile" << SourceRange(D.getIdentifierLoc());
2504    if (FTI.TypeQuals & Qualifiers::Restrict)
2505      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2506        << "restrict" << SourceRange(D.getIdentifierLoc());
2507  }
2508
2509  // Rebuild the function type "R" without any type qualifiers (in
2510  // case any of the errors above fired) and with "void" as the
2511  // return type, since constructors don't have return types. We
2512  // *always* have to do this, because GetTypeForDeclarator will
2513  // put in a result type of "int" when none was specified.
2514  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
2515  return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2516                                 Proto->getNumArgs(),
2517                                 Proto->isVariadic(), 0);
2518}
2519
2520/// CheckConstructor - Checks a fully-formed constructor for
2521/// well-formedness, issuing any diagnostics required. Returns true if
2522/// the constructor declarator is invalid.
2523void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
2524  CXXRecordDecl *ClassDecl
2525    = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2526  if (!ClassDecl)
2527    return Constructor->setInvalidDecl();
2528
2529  // C++ [class.copy]p3:
2530  //   A declaration of a constructor for a class X is ill-formed if
2531  //   its first parameter is of type (optionally cv-qualified) X and
2532  //   either there are no other parameters or else all other
2533  //   parameters have default arguments.
2534  if (!Constructor->isInvalidDecl() &&
2535      ((Constructor->getNumParams() == 1) ||
2536       (Constructor->getNumParams() > 1 &&
2537        Constructor->getParamDecl(1)->hasDefaultArg())) &&
2538      Constructor->getTemplateSpecializationKind()
2539                                              != TSK_ImplicitInstantiation) {
2540    QualType ParamType = Constructor->getParamDecl(0)->getType();
2541    QualType ClassTy = Context.getTagDeclType(ClassDecl);
2542    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
2543      SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2544      Diag(ParamLoc, diag::err_constructor_byvalue_arg)
2545        << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
2546
2547      // FIXME: Rather that making the constructor invalid, we should endeavor
2548      // to fix the type.
2549      Constructor->setInvalidDecl();
2550    }
2551  }
2552
2553  // Notify the class that we've added a constructor.
2554  ClassDecl->addedConstructor(Context, Constructor);
2555}
2556
2557/// CheckDestructor - Checks a fully-formed destructor for well-formedness,
2558/// issuing any diagnostics required. Returns true on error.
2559bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
2560  CXXRecordDecl *RD = Destructor->getParent();
2561
2562  if (Destructor->isVirtual()) {
2563    SourceLocation Loc;
2564
2565    if (!Destructor->isImplicit())
2566      Loc = Destructor->getLocation();
2567    else
2568      Loc = RD->getLocation();
2569
2570    // If we have a virtual destructor, look up the deallocation function
2571    FunctionDecl *OperatorDelete = 0;
2572    DeclarationName Name =
2573    Context.DeclarationNames.getCXXOperatorName(OO_Delete);
2574    if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2575      return true;
2576
2577    Destructor->setOperatorDelete(OperatorDelete);
2578  }
2579
2580  return false;
2581}
2582
2583static inline bool
2584FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2585  return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2586          FTI.ArgInfo[0].Param &&
2587          FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2588}
2589
2590/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2591/// the well-formednes of the destructor declarator @p D with type @p
2592/// R. If there are any errors in the declarator, this routine will
2593/// emit diagnostics and set the declarator to invalid.  Even if this happens,
2594/// will be updated to reflect a well-formed type for the destructor and
2595/// returned.
2596QualType Sema::CheckDestructorDeclarator(Declarator &D,
2597                                         FunctionDecl::StorageClass& SC) {
2598  // C++ [class.dtor]p1:
2599  //   [...] A typedef-name that names a class is a class-name
2600  //   (7.1.3); however, a typedef-name that names a class shall not
2601  //   be used as the identifier in the declarator for a destructor
2602  //   declaration.
2603  QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
2604  if (isa<TypedefType>(DeclaratorType)) {
2605    Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
2606      << DeclaratorType;
2607    D.setInvalidType();
2608  }
2609
2610  // C++ [class.dtor]p2:
2611  //   A destructor is used to destroy objects of its class type. A
2612  //   destructor takes no parameters, and no return type can be
2613  //   specified for it (not even void). The address of a destructor
2614  //   shall not be taken. A destructor shall not be static. A
2615  //   destructor can be invoked for a const, volatile or const
2616  //   volatile object. A destructor shall not be declared const,
2617  //   volatile or const volatile (9.3.2).
2618  if (SC == FunctionDecl::Static) {
2619    if (!D.isInvalidType())
2620      Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2621        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2622        << SourceRange(D.getIdentifierLoc());
2623    SC = FunctionDecl::None;
2624    D.setInvalidType();
2625  }
2626  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
2627    // Destructors don't have return types, but the parser will
2628    // happily parse something like:
2629    //
2630    //   class X {
2631    //     float ~X();
2632    //   };
2633    //
2634    // The return type will be eliminated later.
2635    Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2636      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2637      << SourceRange(D.getIdentifierLoc());
2638  }
2639
2640  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2641  if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
2642    if (FTI.TypeQuals & Qualifiers::Const)
2643      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2644        << "const" << SourceRange(D.getIdentifierLoc());
2645    if (FTI.TypeQuals & Qualifiers::Volatile)
2646      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2647        << "volatile" << SourceRange(D.getIdentifierLoc());
2648    if (FTI.TypeQuals & Qualifiers::Restrict)
2649      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2650        << "restrict" << SourceRange(D.getIdentifierLoc());
2651    D.setInvalidType();
2652  }
2653
2654  // Make sure we don't have any parameters.
2655  if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
2656    Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2657
2658    // Delete the parameters.
2659    FTI.freeArgs();
2660    D.setInvalidType();
2661  }
2662
2663  // Make sure the destructor isn't variadic.
2664  if (FTI.isVariadic) {
2665    Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
2666    D.setInvalidType();
2667  }
2668
2669  // Rebuild the function type "R" without any type qualifiers or
2670  // parameters (in case any of the errors above fired) and with
2671  // "void" as the return type, since destructors don't have return
2672  // types. We *always* have to do this, because GetTypeForDeclarator
2673  // will put in a result type of "int" when none was specified.
2674  return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
2675}
2676
2677/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2678/// well-formednes of the conversion function declarator @p D with
2679/// type @p R. If there are any errors in the declarator, this routine
2680/// will emit diagnostics and return true. Otherwise, it will return
2681/// false. Either way, the type @p R will be updated to reflect a
2682/// well-formed type for the conversion operator.
2683void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
2684                                     FunctionDecl::StorageClass& SC) {
2685  // C++ [class.conv.fct]p1:
2686  //   Neither parameter types nor return type can be specified. The
2687  //   type of a conversion function (8.3.5) is "function taking no
2688  //   parameter returning conversion-type-id."
2689  if (SC == FunctionDecl::Static) {
2690    if (!D.isInvalidType())
2691      Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2692        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2693        << SourceRange(D.getIdentifierLoc());
2694    D.setInvalidType();
2695    SC = FunctionDecl::None;
2696  }
2697  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
2698    // Conversion functions don't have return types, but the parser will
2699    // happily parse something like:
2700    //
2701    //   class X {
2702    //     float operator bool();
2703    //   };
2704    //
2705    // The return type will be changed later anyway.
2706    Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2707      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2708      << SourceRange(D.getIdentifierLoc());
2709  }
2710
2711  // Make sure we don't have any parameters.
2712  if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
2713    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2714
2715    // Delete the parameters.
2716    D.getTypeObject(0).Fun.freeArgs();
2717    D.setInvalidType();
2718  }
2719
2720  // Make sure the conversion function isn't variadic.
2721  if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
2722    Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
2723    D.setInvalidType();
2724  }
2725
2726  // C++ [class.conv.fct]p4:
2727  //   The conversion-type-id shall not represent a function type nor
2728  //   an array type.
2729  QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
2730  if (ConvType->isArrayType()) {
2731    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2732    ConvType = Context.getPointerType(ConvType);
2733    D.setInvalidType();
2734  } else if (ConvType->isFunctionType()) {
2735    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2736    ConvType = Context.getPointerType(ConvType);
2737    D.setInvalidType();
2738  }
2739
2740  // Rebuild the function type "R" without any parameters (in case any
2741  // of the errors above fired) and with the conversion type as the
2742  // return type.
2743  R = Context.getFunctionType(ConvType, 0, 0, false,
2744                              R->getAs<FunctionProtoType>()->getTypeQuals());
2745
2746  // C++0x explicit conversion operators.
2747  if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
2748    Diag(D.getDeclSpec().getExplicitSpecLoc(),
2749         diag::warn_explicit_conversion_functions)
2750      << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
2751}
2752
2753/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2754/// the declaration of the given C++ conversion function. This routine
2755/// is responsible for recording the conversion function in the C++
2756/// class, if possible.
2757Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
2758  assert(Conversion && "Expected to receive a conversion function declaration");
2759
2760  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
2761
2762  // Make sure we aren't redeclaring the conversion function.
2763  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
2764
2765  // C++ [class.conv.fct]p1:
2766  //   [...] A conversion function is never used to convert a
2767  //   (possibly cv-qualified) object to the (possibly cv-qualified)
2768  //   same object type (or a reference to it), to a (possibly
2769  //   cv-qualified) base class of that type (or a reference to it),
2770  //   or to (possibly cv-qualified) void.
2771  // FIXME: Suppress this warning if the conversion function ends up being a
2772  // virtual function that overrides a virtual function in a base class.
2773  QualType ClassType
2774    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
2775  if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
2776    ConvType = ConvTypeRef->getPointeeType();
2777  if (ConvType->isRecordType()) {
2778    ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2779    if (ConvType == ClassType)
2780      Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
2781        << ClassType;
2782    else if (IsDerivedFrom(ClassType, ConvType))
2783      Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
2784        <<  ClassType << ConvType;
2785  } else if (ConvType->isVoidType()) {
2786    Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
2787      << ClassType << ConvType;
2788  }
2789
2790  if (Conversion->getPrimaryTemplate()) {
2791    // ignore specializations
2792  } else if (Conversion->getPreviousDeclaration()) {
2793    if (FunctionTemplateDecl *ConversionTemplate
2794                                  = Conversion->getDescribedFunctionTemplate()) {
2795      if (ClassDecl->replaceConversion(
2796                                   ConversionTemplate->getPreviousDeclaration(),
2797                                       ConversionTemplate))
2798        return DeclPtrTy::make(ConversionTemplate);
2799    } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(),
2800                                            Conversion))
2801      return DeclPtrTy::make(Conversion);
2802    assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
2803  } else if (FunctionTemplateDecl *ConversionTemplate
2804               = Conversion->getDescribedFunctionTemplate())
2805    ClassDecl->addConversionFunction(ConversionTemplate);
2806  else
2807    ClassDecl->addConversionFunction(Conversion);
2808
2809  return DeclPtrTy::make(Conversion);
2810}
2811
2812//===----------------------------------------------------------------------===//
2813// Namespace Handling
2814//===----------------------------------------------------------------------===//
2815
2816/// ActOnStartNamespaceDef - This is called at the start of a namespace
2817/// definition.
2818Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2819                                             SourceLocation IdentLoc,
2820                                             IdentifierInfo *II,
2821                                             SourceLocation LBrace) {
2822  NamespaceDecl *Namespc =
2823      NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2824  Namespc->setLBracLoc(LBrace);
2825
2826  Scope *DeclRegionScope = NamespcScope->getParent();
2827
2828  if (II) {
2829    // C++ [namespace.def]p2:
2830    // The identifier in an original-namespace-definition shall not have been
2831    // previously defined in the declarative region in which the
2832    // original-namespace-definition appears. The identifier in an
2833    // original-namespace-definition is the name of the namespace. Subsequently
2834    // in that declarative region, it is treated as an original-namespace-name.
2835
2836    NamedDecl *PrevDecl
2837      = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName,
2838                         ForRedeclaration);
2839
2840    if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2841      // This is an extended namespace definition.
2842      // Attach this namespace decl to the chain of extended namespace
2843      // definitions.
2844      OrigNS->setNextNamespace(Namespc);
2845      Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
2846
2847      // Remove the previous declaration from the scope.
2848      if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
2849        IdResolver.RemoveDecl(OrigNS);
2850        DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
2851      }
2852    } else if (PrevDecl) {
2853      // This is an invalid name redefinition.
2854      Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2855       << Namespc->getDeclName();
2856      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2857      Namespc->setInvalidDecl();
2858      // Continue on to push Namespc as current DeclContext and return it.
2859    } else if (II->isStr("std") &&
2860               CurContext->getLookupContext()->isTranslationUnit()) {
2861      // This is the first "real" definition of the namespace "std", so update
2862      // our cache of the "std" namespace to point at this definition.
2863      if (StdNamespace) {
2864        // We had already defined a dummy namespace "std". Link this new
2865        // namespace definition to the dummy namespace "std".
2866        StdNamespace->setNextNamespace(Namespc);
2867        StdNamespace->setLocation(IdentLoc);
2868        Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2869      }
2870
2871      // Make our StdNamespace cache point at the first real definition of the
2872      // "std" namespace.
2873      StdNamespace = Namespc;
2874    }
2875
2876    PushOnScopeChains(Namespc, DeclRegionScope);
2877  } else {
2878    // Anonymous namespaces.
2879    assert(Namespc->isAnonymousNamespace());
2880    CurContext->addDecl(Namespc);
2881
2882    // Link the anonymous namespace into its parent.
2883    NamespaceDecl *PrevDecl;
2884    DeclContext *Parent = CurContext->getLookupContext();
2885    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
2886      PrevDecl = TU->getAnonymousNamespace();
2887      TU->setAnonymousNamespace(Namespc);
2888    } else {
2889      NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
2890      PrevDecl = ND->getAnonymousNamespace();
2891      ND->setAnonymousNamespace(Namespc);
2892    }
2893
2894    // Link the anonymous namespace with its previous declaration.
2895    if (PrevDecl) {
2896      assert(PrevDecl->isAnonymousNamespace());
2897      assert(!PrevDecl->getNextNamespace());
2898      Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
2899      PrevDecl->setNextNamespace(Namespc);
2900    }
2901
2902    // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
2903    //   behaves as if it were replaced by
2904    //     namespace unique { /* empty body */ }
2905    //     using namespace unique;
2906    //     namespace unique { namespace-body }
2907    //   where all occurrences of 'unique' in a translation unit are
2908    //   replaced by the same identifier and this identifier differs
2909    //   from all other identifiers in the entire program.
2910
2911    // We just create the namespace with an empty name and then add an
2912    // implicit using declaration, just like the standard suggests.
2913    //
2914    // CodeGen enforces the "universally unique" aspect by giving all
2915    // declarations semantically contained within an anonymous
2916    // namespace internal linkage.
2917
2918    if (!PrevDecl) {
2919      UsingDirectiveDecl* UD
2920        = UsingDirectiveDecl::Create(Context, CurContext,
2921                                     /* 'using' */ LBrace,
2922                                     /* 'namespace' */ SourceLocation(),
2923                                     /* qualifier */ SourceRange(),
2924                                     /* NNS */ NULL,
2925                                     /* identifier */ SourceLocation(),
2926                                     Namespc,
2927                                     /* Ancestor */ CurContext);
2928      UD->setImplicit();
2929      CurContext->addDecl(UD);
2930    }
2931  }
2932
2933  // Although we could have an invalid decl (i.e. the namespace name is a
2934  // redefinition), push it as current DeclContext and try to continue parsing.
2935  // FIXME: We should be able to push Namespc here, so that the each DeclContext
2936  // for the namespace has the declarations that showed up in that particular
2937  // namespace definition.
2938  PushDeclContext(NamespcScope, Namespc);
2939  return DeclPtrTy::make(Namespc);
2940}
2941
2942/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2943/// is a namespace alias, returns the namespace it points to.
2944static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2945  if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2946    return AD->getNamespace();
2947  return dyn_cast_or_null<NamespaceDecl>(D);
2948}
2949
2950/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2951/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
2952void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2953  Decl *Dcl = D.getAs<Decl>();
2954  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2955  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2956  Namespc->setRBracLoc(RBrace);
2957  PopDeclContext();
2958}
2959
2960Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2961                                          SourceLocation UsingLoc,
2962                                          SourceLocation NamespcLoc,
2963                                          const CXXScopeSpec &SS,
2964                                          SourceLocation IdentLoc,
2965                                          IdentifierInfo *NamespcName,
2966                                          AttributeList *AttrList) {
2967  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2968  assert(NamespcName && "Invalid NamespcName.");
2969  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
2970  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
2971
2972  UsingDirectiveDecl *UDir = 0;
2973
2974  // Lookup namespace name.
2975  LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
2976  LookupParsedName(R, S, &SS);
2977  if (R.isAmbiguous())
2978    return DeclPtrTy();
2979
2980  if (!R.empty()) {
2981    NamedDecl *Named = R.getFoundDecl();
2982    assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
2983        && "expected namespace decl");
2984    // C++ [namespace.udir]p1:
2985    //   A using-directive specifies that the names in the nominated
2986    //   namespace can be used in the scope in which the
2987    //   using-directive appears after the using-directive. During
2988    //   unqualified name lookup (3.4.1), the names appear as if they
2989    //   were declared in the nearest enclosing namespace which
2990    //   contains both the using-directive and the nominated
2991    //   namespace. [Note: in this context, "contains" means "contains
2992    //   directly or indirectly". ]
2993
2994    // Find enclosing context containing both using-directive and
2995    // nominated namespace.
2996    NamespaceDecl *NS = getNamespaceDecl(Named);
2997    DeclContext *CommonAncestor = cast<DeclContext>(NS);
2998    while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2999      CommonAncestor = CommonAncestor->getParent();
3000
3001    UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
3002                                      SS.getRange(),
3003                                      (NestedNameSpecifier *)SS.getScopeRep(),
3004                                      IdentLoc, Named, CommonAncestor);
3005    PushUsingDirective(S, UDir);
3006  } else {
3007    Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
3008  }
3009
3010  // FIXME: We ignore attributes for now.
3011  delete AttrList;
3012  return DeclPtrTy::make(UDir);
3013}
3014
3015void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3016  // If scope has associated entity, then using directive is at namespace
3017  // or translation unit scope. We add UsingDirectiveDecls, into
3018  // it's lookup structure.
3019  if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
3020    Ctx->addDecl(UDir);
3021  else
3022    // Otherwise it is block-sope. using-directives will affect lookup
3023    // only to the end of scope.
3024    S->PushUsingDirective(DeclPtrTy::make(UDir));
3025}
3026
3027
3028Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
3029                                            AccessSpecifier AS,
3030                                            bool HasUsingKeyword,
3031                                            SourceLocation UsingLoc,
3032                                            const CXXScopeSpec &SS,
3033                                            UnqualifiedId &Name,
3034                                            AttributeList *AttrList,
3035                                            bool IsTypeName,
3036                                            SourceLocation TypenameLoc) {
3037  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
3038
3039  switch (Name.getKind()) {
3040  case UnqualifiedId::IK_Identifier:
3041  case UnqualifiedId::IK_OperatorFunctionId:
3042  case UnqualifiedId::IK_LiteralOperatorId:
3043  case UnqualifiedId::IK_ConversionFunctionId:
3044    break;
3045
3046  case UnqualifiedId::IK_ConstructorName:
3047  case UnqualifiedId::IK_ConstructorTemplateId:
3048    // C++0x inherited constructors.
3049    if (getLangOptions().CPlusPlus0x) break;
3050
3051    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3052      << SS.getRange();
3053    return DeclPtrTy();
3054
3055  case UnqualifiedId::IK_DestructorName:
3056    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3057      << SS.getRange();
3058    return DeclPtrTy();
3059
3060  case UnqualifiedId::IK_TemplateId:
3061    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3062      << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
3063    return DeclPtrTy();
3064  }
3065
3066  DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
3067  if (!TargetName)
3068    return DeclPtrTy();
3069
3070  // Warn about using declarations.
3071  // TODO: store that the declaration was written without 'using' and
3072  // talk about access decls instead of using decls in the
3073  // diagnostics.
3074  if (!HasUsingKeyword) {
3075    UsingLoc = Name.getSourceRange().getBegin();
3076
3077    Diag(UsingLoc, diag::warn_access_decl_deprecated)
3078      << CodeModificationHint::CreateInsertion(SS.getRange().getBegin(),
3079                                               "using ");
3080  }
3081
3082  NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
3083                                        Name.getSourceRange().getBegin(),
3084                                        TargetName, AttrList,
3085                                        /* IsInstantiation */ false,
3086                                        IsTypeName, TypenameLoc);
3087  if (UD)
3088    PushOnScopeChains(UD, S, /*AddToContext*/ false);
3089
3090  return DeclPtrTy::make(UD);
3091}
3092
3093/// Determines whether to create a using shadow decl for a particular
3094/// decl, given the set of decls existing prior to this using lookup.
3095bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3096                                const LookupResult &Previous) {
3097  // Diagnose finding a decl which is not from a base class of the
3098  // current class.  We do this now because there are cases where this
3099  // function will silently decide not to build a shadow decl, which
3100  // will pre-empt further diagnostics.
3101  //
3102  // We don't need to do this in C++0x because we do the check once on
3103  // the qualifier.
3104  //
3105  // FIXME: diagnose the following if we care enough:
3106  //   struct A { int foo; };
3107  //   struct B : A { using A::foo; };
3108  //   template <class T> struct C : A {};
3109  //   template <class T> struct D : C<T> { using B::foo; } // <---
3110  // This is invalid (during instantiation) in C++03 because B::foo
3111  // resolves to the using decl in B, which is not a base class of D<T>.
3112  // We can't diagnose it immediately because C<T> is an unknown
3113  // specialization.  The UsingShadowDecl in D<T> then points directly
3114  // to A::foo, which will look well-formed when we instantiate.
3115  // The right solution is to not collapse the shadow-decl chain.
3116  if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3117    DeclContext *OrigDC = Orig->getDeclContext();
3118
3119    // Handle enums and anonymous structs.
3120    if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3121    CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3122    while (OrigRec->isAnonymousStructOrUnion())
3123      OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3124
3125    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3126      if (OrigDC == CurContext) {
3127        Diag(Using->getLocation(),
3128             diag::err_using_decl_nested_name_specifier_is_current_class)
3129          << Using->getNestedNameRange();
3130        Diag(Orig->getLocation(), diag::note_using_decl_target);
3131        return true;
3132      }
3133
3134      Diag(Using->getNestedNameRange().getBegin(),
3135           diag::err_using_decl_nested_name_specifier_is_not_base_class)
3136        << Using->getTargetNestedNameDecl()
3137        << cast<CXXRecordDecl>(CurContext)
3138        << Using->getNestedNameRange();
3139      Diag(Orig->getLocation(), diag::note_using_decl_target);
3140      return true;
3141    }
3142  }
3143
3144  if (Previous.empty()) return false;
3145
3146  NamedDecl *Target = Orig;
3147  if (isa<UsingShadowDecl>(Target))
3148    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3149
3150  // If the target happens to be one of the previous declarations, we
3151  // don't have a conflict.
3152  //
3153  // FIXME: but we might be increasing its access, in which case we
3154  // should redeclare it.
3155  NamedDecl *NonTag = 0, *Tag = 0;
3156  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3157         I != E; ++I) {
3158    NamedDecl *D = (*I)->getUnderlyingDecl();
3159    if (D->getCanonicalDecl() == Target->getCanonicalDecl())
3160      return false;
3161
3162    (isa<TagDecl>(D) ? Tag : NonTag) = D;
3163  }
3164
3165  if (Target->isFunctionOrFunctionTemplate()) {
3166    FunctionDecl *FD;
3167    if (isa<FunctionTemplateDecl>(Target))
3168      FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3169    else
3170      FD = cast<FunctionDecl>(Target);
3171
3172    NamedDecl *OldDecl = 0;
3173    switch (CheckOverload(FD, Previous, OldDecl)) {
3174    case Ovl_Overload:
3175      return false;
3176
3177    case Ovl_NonFunction:
3178      Diag(Using->getLocation(), diag::err_using_decl_conflict);
3179      break;
3180
3181    // We found a decl with the exact signature.
3182    case Ovl_Match:
3183      if (isa<UsingShadowDecl>(OldDecl)) {
3184        // Silently ignore the possible conflict.
3185        return false;
3186      }
3187
3188      // If we're in a record, we want to hide the target, so we
3189      // return true (without a diagnostic) to tell the caller not to
3190      // build a shadow decl.
3191      if (CurContext->isRecord())
3192        return true;
3193
3194      // If we're not in a record, this is an error.
3195      Diag(Using->getLocation(), diag::err_using_decl_conflict);
3196      break;
3197    }
3198
3199    Diag(Target->getLocation(), diag::note_using_decl_target);
3200    Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3201    return true;
3202  }
3203
3204  // Target is not a function.
3205
3206  if (isa<TagDecl>(Target)) {
3207    // No conflict between a tag and a non-tag.
3208    if (!Tag) return false;
3209
3210    Diag(Using->getLocation(), diag::err_using_decl_conflict);
3211    Diag(Target->getLocation(), diag::note_using_decl_target);
3212    Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3213    return true;
3214  }
3215
3216  // No conflict between a tag and a non-tag.
3217  if (!NonTag) return false;
3218
3219  Diag(Using->getLocation(), diag::err_using_decl_conflict);
3220  Diag(Target->getLocation(), diag::note_using_decl_target);
3221  Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3222  return true;
3223}
3224
3225/// Builds a shadow declaration corresponding to a 'using' declaration.
3226UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
3227                                            UsingDecl *UD,
3228                                            NamedDecl *Orig) {
3229
3230  // If we resolved to another shadow declaration, just coalesce them.
3231  NamedDecl *Target = Orig;
3232  if (isa<UsingShadowDecl>(Target)) {
3233    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3234    assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
3235  }
3236
3237  UsingShadowDecl *Shadow
3238    = UsingShadowDecl::Create(Context, CurContext,
3239                              UD->getLocation(), UD, Target);
3240  UD->addShadowDecl(Shadow);
3241
3242  if (S)
3243    PushOnScopeChains(Shadow, S);
3244  else
3245    CurContext->addDecl(Shadow);
3246  Shadow->setAccess(UD->getAccess());
3247
3248  if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3249    Shadow->setInvalidDecl();
3250
3251  return Shadow;
3252}
3253
3254/// Hides a using shadow declaration.  This is required by the current
3255/// using-decl implementation when a resolvable using declaration in a
3256/// class is followed by a declaration which would hide or override
3257/// one or more of the using decl's targets; for example:
3258///
3259///   struct Base { void foo(int); };
3260///   struct Derived : Base {
3261///     using Base::foo;
3262///     void foo(int);
3263///   };
3264///
3265/// The governing language is C++03 [namespace.udecl]p12:
3266///
3267///   When a using-declaration brings names from a base class into a
3268///   derived class scope, member functions in the derived class
3269///   override and/or hide member functions with the same name and
3270///   parameter types in a base class (rather than conflicting).
3271///
3272/// There are two ways to implement this:
3273///   (1) optimistically create shadow decls when they're not hidden
3274///       by existing declarations, or
3275///   (2) don't create any shadow decls (or at least don't make them
3276///       visible) until we've fully parsed/instantiated the class.
3277/// The problem with (1) is that we might have to retroactively remove
3278/// a shadow decl, which requires several O(n) operations because the
3279/// decl structures are (very reasonably) not designed for removal.
3280/// (2) avoids this but is very fiddly and phase-dependent.
3281void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
3282  // Remove it from the DeclContext...
3283  Shadow->getDeclContext()->removeDecl(Shadow);
3284
3285  // ...and the scope, if applicable...
3286  if (S) {
3287    S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow)));
3288    IdResolver.RemoveDecl(Shadow);
3289  }
3290
3291  // ...and the using decl.
3292  Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3293
3294  // TODO: complain somehow if Shadow was used.  It shouldn't
3295  // be possible for this to happen, because
3296}
3297
3298/// Builds a using declaration.
3299///
3300/// \param IsInstantiation - Whether this call arises from an
3301///   instantiation of an unresolved using declaration.  We treat
3302///   the lookup differently for these declarations.
3303NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3304                                       SourceLocation UsingLoc,
3305                                       const CXXScopeSpec &SS,
3306                                       SourceLocation IdentLoc,
3307                                       DeclarationName Name,
3308                                       AttributeList *AttrList,
3309                                       bool IsInstantiation,
3310                                       bool IsTypeName,
3311                                       SourceLocation TypenameLoc) {
3312  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3313  assert(IdentLoc.isValid() && "Invalid TargetName location.");
3314
3315  // FIXME: We ignore attributes for now.
3316  delete AttrList;
3317
3318  if (SS.isEmpty()) {
3319    Diag(IdentLoc, diag::err_using_requires_qualname);
3320    return 0;
3321  }
3322
3323  // Do the redeclaration lookup in the current scope.
3324  LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName,
3325                        ForRedeclaration);
3326  Previous.setHideTags(false);
3327  if (S) {
3328    LookupName(Previous, S);
3329
3330    // It is really dumb that we have to do this.
3331    LookupResult::Filter F = Previous.makeFilter();
3332    while (F.hasNext()) {
3333      NamedDecl *D = F.next();
3334      if (!isDeclInScope(D, CurContext, S))
3335        F.erase();
3336    }
3337    F.done();
3338  } else {
3339    assert(IsInstantiation && "no scope in non-instantiation");
3340    assert(CurContext->isRecord() && "scope not record in instantiation");
3341    LookupQualifiedName(Previous, CurContext);
3342  }
3343
3344  NestedNameSpecifier *NNS =
3345    static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3346
3347  // Check for invalid redeclarations.
3348  if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3349    return 0;
3350
3351  // Check for bad qualifiers.
3352  if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3353    return 0;
3354
3355  DeclContext *LookupContext = computeDeclContext(SS);
3356  NamedDecl *D;
3357  if (!LookupContext) {
3358    if (IsTypeName) {
3359      // FIXME: not all declaration name kinds are legal here
3360      D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3361                                              UsingLoc, TypenameLoc,
3362                                              SS.getRange(), NNS,
3363                                              IdentLoc, Name);
3364    } else {
3365      D = UnresolvedUsingValueDecl::Create(Context, CurContext,
3366                                           UsingLoc, SS.getRange(), NNS,
3367                                           IdentLoc, Name);
3368    }
3369  } else {
3370    D = UsingDecl::Create(Context, CurContext, IdentLoc,
3371                          SS.getRange(), UsingLoc, NNS, Name,
3372                          IsTypeName);
3373  }
3374  D->setAccess(AS);
3375  CurContext->addDecl(D);
3376
3377  if (!LookupContext) return D;
3378  UsingDecl *UD = cast<UsingDecl>(D);
3379
3380  if (RequireCompleteDeclContext(SS)) {
3381    UD->setInvalidDecl();
3382    return UD;
3383  }
3384
3385  // Look up the target name.
3386
3387  LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
3388
3389  // Unlike most lookups, we don't always want to hide tag
3390  // declarations: tag names are visible through the using declaration
3391  // even if hidden by ordinary names, *except* in a dependent context
3392  // where it's important for the sanity of two-phase lookup.
3393  if (!IsInstantiation)
3394    R.setHideTags(false);
3395
3396  LookupQualifiedName(R, LookupContext);
3397
3398  if (R.empty()) {
3399    Diag(IdentLoc, diag::err_no_member)
3400      << Name << LookupContext << SS.getRange();
3401    UD->setInvalidDecl();
3402    return UD;
3403  }
3404
3405  if (R.isAmbiguous()) {
3406    UD->setInvalidDecl();
3407    return UD;
3408  }
3409
3410  if (IsTypeName) {
3411    // If we asked for a typename and got a non-type decl, error out.
3412    if (!R.getAsSingle<TypeDecl>()) {
3413      Diag(IdentLoc, diag::err_using_typename_non_type);
3414      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3415        Diag((*I)->getUnderlyingDecl()->getLocation(),
3416             diag::note_using_decl_target);
3417      UD->setInvalidDecl();
3418      return UD;
3419    }
3420  } else {
3421    // If we asked for a non-typename and we got a type, error out,
3422    // but only if this is an instantiation of an unresolved using
3423    // decl.  Otherwise just silently find the type name.
3424    if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
3425      Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3426      Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
3427      UD->setInvalidDecl();
3428      return UD;
3429    }
3430  }
3431
3432  // C++0x N2914 [namespace.udecl]p6:
3433  // A using-declaration shall not name a namespace.
3434  if (R.getAsSingle<NamespaceDecl>()) {
3435    Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3436      << SS.getRange();
3437    UD->setInvalidDecl();
3438    return UD;
3439  }
3440
3441  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3442    if (!CheckUsingShadowDecl(UD, *I, Previous))
3443      BuildUsingShadowDecl(S, UD, *I);
3444  }
3445
3446  return UD;
3447}
3448
3449/// Checks that the given using declaration is not an invalid
3450/// redeclaration.  Note that this is checking only for the using decl
3451/// itself, not for any ill-formedness among the UsingShadowDecls.
3452bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3453                                       bool isTypeName,
3454                                       const CXXScopeSpec &SS,
3455                                       SourceLocation NameLoc,
3456                                       const LookupResult &Prev) {
3457  // C++03 [namespace.udecl]p8:
3458  // C++0x [namespace.udecl]p10:
3459  //   A using-declaration is a declaration and can therefore be used
3460  //   repeatedly where (and only where) multiple declarations are
3461  //   allowed.
3462  // That's only in file contexts.
3463  if (CurContext->getLookupContext()->isFileContext())
3464    return false;
3465
3466  NestedNameSpecifier *Qual
3467    = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3468
3469  for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3470    NamedDecl *D = *I;
3471
3472    bool DTypename;
3473    NestedNameSpecifier *DQual;
3474    if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3475      DTypename = UD->isTypeName();
3476      DQual = UD->getTargetNestedNameDecl();
3477    } else if (UnresolvedUsingValueDecl *UD
3478                 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3479      DTypename = false;
3480      DQual = UD->getTargetNestedNameSpecifier();
3481    } else if (UnresolvedUsingTypenameDecl *UD
3482                 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3483      DTypename = true;
3484      DQual = UD->getTargetNestedNameSpecifier();
3485    } else continue;
3486
3487    // using decls differ if one says 'typename' and the other doesn't.
3488    // FIXME: non-dependent using decls?
3489    if (isTypeName != DTypename) continue;
3490
3491    // using decls differ if they name different scopes (but note that
3492    // template instantiation can cause this check to trigger when it
3493    // didn't before instantiation).
3494    if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3495        Context.getCanonicalNestedNameSpecifier(DQual))
3496      continue;
3497
3498    Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
3499    Diag(D->getLocation(), diag::note_using_decl) << 1;
3500    return true;
3501  }
3502
3503  return false;
3504}
3505
3506
3507/// Checks that the given nested-name qualifier used in a using decl
3508/// in the current context is appropriately related to the current
3509/// scope.  If an error is found, diagnoses it and returns true.
3510bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3511                                   const CXXScopeSpec &SS,
3512                                   SourceLocation NameLoc) {
3513  DeclContext *NamedContext = computeDeclContext(SS);
3514
3515  if (!CurContext->isRecord()) {
3516    // C++03 [namespace.udecl]p3:
3517    // C++0x [namespace.udecl]p8:
3518    //   A using-declaration for a class member shall be a member-declaration.
3519
3520    // If we weren't able to compute a valid scope, it must be a
3521    // dependent class scope.
3522    if (!NamedContext || NamedContext->isRecord()) {
3523      Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
3524        << SS.getRange();
3525      return true;
3526    }
3527
3528    // Otherwise, everything is known to be fine.
3529    return false;
3530  }
3531
3532  // The current scope is a record.
3533
3534  // If the named context is dependent, we can't decide much.
3535  if (!NamedContext) {
3536    // FIXME: in C++0x, we can diagnose if we can prove that the
3537    // nested-name-specifier does not refer to a base class, which is
3538    // still possible in some cases.
3539
3540    // Otherwise we have to conservatively report that things might be
3541    // okay.
3542    return false;
3543  }
3544
3545  if (!NamedContext->isRecord()) {
3546    // Ideally this would point at the last name in the specifier,
3547    // but we don't have that level of source info.
3548    Diag(SS.getRange().getBegin(),
3549         diag::err_using_decl_nested_name_specifier_is_not_class)
3550      << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
3551    return true;
3552  }
3553
3554  if (getLangOptions().CPlusPlus0x) {
3555    // C++0x [namespace.udecl]p3:
3556    //   In a using-declaration used as a member-declaration, the
3557    //   nested-name-specifier shall name a base class of the class
3558    //   being defined.
3559
3560    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
3561                                 cast<CXXRecordDecl>(NamedContext))) {
3562      if (CurContext == NamedContext) {
3563        Diag(NameLoc,
3564             diag::err_using_decl_nested_name_specifier_is_current_class)
3565          << SS.getRange();
3566        return true;
3567      }
3568
3569      Diag(SS.getRange().getBegin(),
3570           diag::err_using_decl_nested_name_specifier_is_not_base_class)
3571        << (NestedNameSpecifier*) SS.getScopeRep()
3572        << cast<CXXRecordDecl>(CurContext)
3573        << SS.getRange();
3574      return true;
3575    }
3576
3577    return false;
3578  }
3579
3580  // C++03 [namespace.udecl]p4:
3581  //   A using-declaration used as a member-declaration shall refer
3582  //   to a member of a base class of the class being defined [etc.].
3583
3584  // Salient point: SS doesn't have to name a base class as long as
3585  // lookup only finds members from base classes.  Therefore we can
3586  // diagnose here only if we can prove that that can't happen,
3587  // i.e. if the class hierarchies provably don't intersect.
3588
3589  // TODO: it would be nice if "definitely valid" results were cached
3590  // in the UsingDecl and UsingShadowDecl so that these checks didn't
3591  // need to be repeated.
3592
3593  struct UserData {
3594    llvm::DenseSet<const CXXRecordDecl*> Bases;
3595
3596    static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
3597      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3598      Data->Bases.insert(Base);
3599      return true;
3600    }
3601
3602    bool hasDependentBases(const CXXRecordDecl *Class) {
3603      return !Class->forallBases(collect, this);
3604    }
3605
3606    /// Returns true if the base is dependent or is one of the
3607    /// accumulated base classes.
3608    static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
3609      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3610      return !Data->Bases.count(Base);
3611    }
3612
3613    bool mightShareBases(const CXXRecordDecl *Class) {
3614      return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
3615    }
3616  };
3617
3618  UserData Data;
3619
3620  // Returns false if we find a dependent base.
3621  if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
3622    return false;
3623
3624  // Returns false if the class has a dependent base or if it or one
3625  // of its bases is present in the base set of the current context.
3626  if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
3627    return false;
3628
3629  Diag(SS.getRange().getBegin(),
3630       diag::err_using_decl_nested_name_specifier_is_not_base_class)
3631    << (NestedNameSpecifier*) SS.getScopeRep()
3632    << cast<CXXRecordDecl>(CurContext)
3633    << SS.getRange();
3634
3635  return true;
3636}
3637
3638Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
3639                                             SourceLocation NamespaceLoc,
3640                                             SourceLocation AliasLoc,
3641                                             IdentifierInfo *Alias,
3642                                             const CXXScopeSpec &SS,
3643                                             SourceLocation IdentLoc,
3644                                             IdentifierInfo *Ident) {
3645
3646  // Lookup the namespace name.
3647  LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
3648  LookupParsedName(R, S, &SS);
3649
3650  // Check if we have a previous declaration with the same name.
3651  if (NamedDecl *PrevDecl
3652        = LookupSingleName(S, Alias, LookupOrdinaryName, ForRedeclaration)) {
3653    if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
3654      // We already have an alias with the same name that points to the same
3655      // namespace, so don't create a new one.
3656      if (!R.isAmbiguous() && !R.empty() &&
3657          AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
3658        return DeclPtrTy();
3659    }
3660
3661    unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
3662      diag::err_redefinition_different_kind;
3663    Diag(AliasLoc, DiagID) << Alias;
3664    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3665    return DeclPtrTy();
3666  }
3667
3668  if (R.isAmbiguous())
3669    return DeclPtrTy();
3670
3671  if (R.empty()) {
3672    Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
3673    return DeclPtrTy();
3674  }
3675
3676  NamespaceAliasDecl *AliasDecl =
3677    NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
3678                               Alias, SS.getRange(),
3679                               (NestedNameSpecifier *)SS.getScopeRep(),
3680                               IdentLoc, R.getFoundDecl());
3681
3682  CurContext->addDecl(AliasDecl);
3683  return DeclPtrTy::make(AliasDecl);
3684}
3685
3686void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3687                                            CXXConstructorDecl *Constructor) {
3688  assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3689          !Constructor->isUsed()) &&
3690    "DefineImplicitDefaultConstructor - call it for implicit default ctor");
3691
3692  CXXRecordDecl *ClassDecl
3693    = cast<CXXRecordDecl>(Constructor->getDeclContext());
3694  assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
3695
3696  DeclContext *PreviousContext = CurContext;
3697  CurContext = Constructor;
3698  if (SetBaseOrMemberInitializers(Constructor, 0, 0, true, false)) {
3699    Diag(CurrentLocation, diag::note_member_synthesized_at)
3700      << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
3701    Constructor->setInvalidDecl();
3702  } else {
3703    Constructor->setUsed();
3704  }
3705  CurContext = PreviousContext;
3706}
3707
3708void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
3709                                    CXXDestructorDecl *Destructor) {
3710  assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
3711         "DefineImplicitDestructor - call it for implicit default dtor");
3712  CXXRecordDecl *ClassDecl = Destructor->getParent();
3713  assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
3714
3715  DeclContext *PreviousContext = CurContext;
3716  CurContext = Destructor;
3717
3718  // C++ [class.dtor] p5
3719  // Before the implicitly-declared default destructor for a class is
3720  // implicitly defined, all the implicitly-declared default destructors
3721  // for its base class and its non-static data members shall have been
3722  // implicitly defined.
3723  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3724       E = ClassDecl->bases_end(); Base != E; ++Base) {
3725    CXXRecordDecl *BaseClassDecl
3726      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3727    if (!BaseClassDecl->hasTrivialDestructor()) {
3728      if (CXXDestructorDecl *BaseDtor =
3729          const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3730        MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3731      else
3732        assert(false &&
3733               "DefineImplicitDestructor - missing dtor in a base class");
3734    }
3735  }
3736
3737  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3738       E = ClassDecl->field_end(); Field != E; ++Field) {
3739    QualType FieldType = Context.getCanonicalType((*Field)->getType());
3740    if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3741      FieldType = Array->getElementType();
3742    if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
3743      CXXRecordDecl *FieldClassDecl
3744        = cast<CXXRecordDecl>(FieldClassType->getDecl());
3745      if (!FieldClassDecl->hasTrivialDestructor()) {
3746        if (CXXDestructorDecl *FieldDtor =
3747            const_cast<CXXDestructorDecl*>(
3748                                        FieldClassDecl->getDestructor(Context)))
3749          MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3750        else
3751          assert(false &&
3752          "DefineImplicitDestructor - missing dtor in class of a data member");
3753      }
3754    }
3755  }
3756
3757  // FIXME: If CheckDestructor fails, we should emit a note about where the
3758  // implicit destructor was needed.
3759  if (CheckDestructor(Destructor)) {
3760    Diag(CurrentLocation, diag::note_member_synthesized_at)
3761      << CXXDestructor << Context.getTagDeclType(ClassDecl);
3762
3763    Destructor->setInvalidDecl();
3764    CurContext = PreviousContext;
3765
3766    return;
3767  }
3768  CurContext = PreviousContext;
3769
3770  Destructor->setUsed();
3771}
3772
3773void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3774                                          CXXMethodDecl *MethodDecl) {
3775  assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3776          MethodDecl->getOverloadedOperator() == OO_Equal &&
3777          !MethodDecl->isUsed()) &&
3778         "DefineImplicitOverloadedAssign - call it for implicit assignment op");
3779
3780  CXXRecordDecl *ClassDecl
3781    = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
3782
3783  DeclContext *PreviousContext = CurContext;
3784  CurContext = MethodDecl;
3785
3786  // C++[class.copy] p12
3787  // Before the implicitly-declared copy assignment operator for a class is
3788  // implicitly defined, all implicitly-declared copy assignment operators
3789  // for its direct base classes and its nonstatic data members shall have
3790  // been implicitly defined.
3791  bool err = false;
3792  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3793       E = ClassDecl->bases_end(); Base != E; ++Base) {
3794    CXXRecordDecl *BaseClassDecl
3795      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3796    if (CXXMethodDecl *BaseAssignOpMethod =
3797          getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3798                                  BaseClassDecl))
3799      MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3800  }
3801  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3802       E = ClassDecl->field_end(); Field != E; ++Field) {
3803    QualType FieldType = Context.getCanonicalType((*Field)->getType());
3804    if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3805      FieldType = Array->getElementType();
3806    if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
3807      CXXRecordDecl *FieldClassDecl
3808        = cast<CXXRecordDecl>(FieldClassType->getDecl());
3809      if (CXXMethodDecl *FieldAssignOpMethod =
3810          getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3811                                  FieldClassDecl))
3812        MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
3813    } else if (FieldType->isReferenceType()) {
3814      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
3815      << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3816      Diag(Field->getLocation(), diag::note_declared_at);
3817      Diag(CurrentLocation, diag::note_first_required_here);
3818      err = true;
3819    } else if (FieldType.isConstQualified()) {
3820      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
3821      << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3822      Diag(Field->getLocation(), diag::note_declared_at);
3823      Diag(CurrentLocation, diag::note_first_required_here);
3824      err = true;
3825    }
3826  }
3827  if (!err)
3828    MethodDecl->setUsed();
3829
3830  CurContext = PreviousContext;
3831}
3832
3833CXXMethodDecl *
3834Sema::getAssignOperatorMethod(SourceLocation CurrentLocation,
3835                              ParmVarDecl *ParmDecl,
3836                              CXXRecordDecl *ClassDecl) {
3837  QualType LHSType = Context.getTypeDeclType(ClassDecl);
3838  QualType RHSType(LHSType);
3839  // If class's assignment operator argument is const/volatile qualified,
3840  // look for operator = (const/volatile B&). Otherwise, look for
3841  // operator = (B&).
3842  RHSType = Context.getCVRQualifiedType(RHSType,
3843                                     ParmDecl->getType().getCVRQualifiers());
3844  ExprOwningPtr<Expr> LHS(this,  new (Context) DeclRefExpr(ParmDecl,
3845                                                           LHSType,
3846                                                           SourceLocation()));
3847  ExprOwningPtr<Expr> RHS(this,  new (Context) DeclRefExpr(ParmDecl,
3848                                                           RHSType,
3849                                                           CurrentLocation));
3850  Expr *Args[2] = { &*LHS, &*RHS };
3851  OverloadCandidateSet CandidateSet;
3852  AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
3853                              CandidateSet);
3854  OverloadCandidateSet::iterator Best;
3855  if (BestViableFunction(CandidateSet, CurrentLocation, Best) == OR_Success)
3856    return cast<CXXMethodDecl>(Best->Function);
3857  assert(false &&
3858         "getAssignOperatorMethod - copy assignment operator method not found");
3859  return 0;
3860}
3861
3862void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3863                                   CXXConstructorDecl *CopyConstructor,
3864                                   unsigned TypeQuals) {
3865  assert((CopyConstructor->isImplicit() &&
3866          CopyConstructor->isCopyConstructor(TypeQuals) &&
3867          !CopyConstructor->isUsed()) &&
3868         "DefineImplicitCopyConstructor - call it for implicit copy ctor");
3869
3870  CXXRecordDecl *ClassDecl
3871    = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3872  assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
3873
3874  DeclContext *PreviousContext = CurContext;
3875  CurContext = CopyConstructor;
3876
3877  // C++ [class.copy] p209
3878  // Before the implicitly-declared copy constructor for a class is
3879  // implicitly defined, all the implicitly-declared copy constructors
3880  // for its base class and its non-static data members shall have been
3881  // implicitly defined.
3882  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3883       Base != ClassDecl->bases_end(); ++Base) {
3884    CXXRecordDecl *BaseClassDecl
3885      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3886    if (CXXConstructorDecl *BaseCopyCtor =
3887        BaseClassDecl->getCopyConstructor(Context, TypeQuals))
3888      MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
3889  }
3890  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3891                                  FieldEnd = ClassDecl->field_end();
3892       Field != FieldEnd; ++Field) {
3893    QualType FieldType = Context.getCanonicalType((*Field)->getType());
3894    if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3895      FieldType = Array->getElementType();
3896    if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
3897      CXXRecordDecl *FieldClassDecl
3898        = cast<CXXRecordDecl>(FieldClassType->getDecl());
3899      if (CXXConstructorDecl *FieldCopyCtor =
3900          FieldClassDecl->getCopyConstructor(Context, TypeQuals))
3901        MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
3902    }
3903  }
3904  CopyConstructor->setUsed();
3905
3906  CurContext = PreviousContext;
3907}
3908
3909Sema::OwningExprResult
3910Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3911                            CXXConstructorDecl *Constructor,
3912                            MultiExprArg ExprArgs,
3913                            bool RequiresZeroInit,
3914                            bool BaseInitialization) {
3915  bool Elidable = false;
3916
3917  // C++ [class.copy]p15:
3918  //   Whenever a temporary class object is copied using a copy constructor, and
3919  //   this object and the copy have the same cv-unqualified type, an
3920  //   implementation is permitted to treat the original and the copy as two
3921  //   different ways of referring to the same object and not perform a copy at
3922  //   all, even if the class copy constructor or destructor have side effects.
3923
3924  // FIXME: Is this enough?
3925  if (Constructor->isCopyConstructor()) {
3926    Expr *E = ((Expr **)ExprArgs.get())[0];
3927    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3928      if (ICE->getCastKind() == CastExpr::CK_NoOp)
3929        E = ICE->getSubExpr();
3930    if (CXXFunctionalCastExpr *FCE = dyn_cast<CXXFunctionalCastExpr>(E))
3931      E = FCE->getSubExpr();
3932    while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3933      E = BE->getSubExpr();
3934    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3935      if (ICE->getCastKind() == CastExpr::CK_NoOp)
3936        E = ICE->getSubExpr();
3937
3938    if (CallExpr *CE = dyn_cast<CallExpr>(E))
3939      Elidable = !CE->getCallReturnType()->isReferenceType();
3940    else if (isa<CXXTemporaryObjectExpr>(E))
3941      Elidable = true;
3942    else if (isa<CXXConstructExpr>(E))
3943      Elidable = true;
3944  }
3945
3946  return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
3947                               Elidable, move(ExprArgs), RequiresZeroInit,
3948                               BaseInitialization);
3949}
3950
3951/// BuildCXXConstructExpr - Creates a complete call to a constructor,
3952/// including handling of its default argument expressions.
3953Sema::OwningExprResult
3954Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3955                            CXXConstructorDecl *Constructor, bool Elidable,
3956                            MultiExprArg ExprArgs,
3957                            bool RequiresZeroInit,
3958                            bool BaseInitialization) {
3959  unsigned NumExprs = ExprArgs.size();
3960  Expr **Exprs = (Expr **)ExprArgs.release();
3961
3962  MarkDeclarationReferenced(ConstructLoc, Constructor);
3963  return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
3964                                        Constructor, Elidable, Exprs, NumExprs,
3965                                        RequiresZeroInit, BaseInitialization));
3966}
3967
3968bool Sema::InitializeVarWithConstructor(VarDecl *VD,
3969                                        CXXConstructorDecl *Constructor,
3970                                        MultiExprArg Exprs) {
3971  OwningExprResult TempResult =
3972    BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
3973                          move(Exprs));
3974  if (TempResult.isInvalid())
3975    return true;
3976
3977  Expr *Temp = TempResult.takeAs<Expr>();
3978  MarkDeclarationReferenced(VD->getLocation(), Constructor);
3979  Temp = MaybeCreateCXXExprWithTemporaries(Temp);
3980  VD->setInit(Context, Temp);
3981
3982  return false;
3983}
3984
3985void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
3986  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
3987  if (!ClassDecl->hasTrivialDestructor()) {
3988    CXXDestructorDecl *Destructor = ClassDecl->getDestructor(Context);
3989    MarkDeclarationReferenced(VD->getLocation(), Destructor);
3990    CheckDestructorAccess(VD->getLocation(), Record);
3991  }
3992}
3993
3994/// AddCXXDirectInitializerToDecl - This action is called immediately after
3995/// ActOnDeclarator, when a C++ direct initializer is present.
3996/// e.g: "int x(1);"
3997void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
3998                                         SourceLocation LParenLoc,
3999                                         MultiExprArg Exprs,
4000                                         SourceLocation *CommaLocs,
4001                                         SourceLocation RParenLoc) {
4002  assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
4003  Decl *RealDecl = Dcl.getAs<Decl>();
4004
4005  // If there is no declaration, there was an error parsing it.  Just ignore
4006  // the initializer.
4007  if (RealDecl == 0)
4008    return;
4009
4010  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
4011  if (!VDecl) {
4012    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
4013    RealDecl->setInvalidDecl();
4014    return;
4015  }
4016
4017  // We will represent direct-initialization similarly to copy-initialization:
4018  //    int x(1);  -as-> int x = 1;
4019  //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
4020  //
4021  // Clients that want to distinguish between the two forms, can check for
4022  // direct initializer using VarDecl::hasCXXDirectInitializer().
4023  // A major benefit is that clients that don't particularly care about which
4024  // exactly form was it (like the CodeGen) can handle both cases without
4025  // special case code.
4026
4027  // If either the declaration has a dependent type or if any of the expressions
4028  // is type-dependent, we represent the initialization via a ParenListExpr for
4029  // later use during template instantiation.
4030  if (VDecl->getType()->isDependentType() ||
4031      Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
4032    // Let clients know that initialization was done with a direct initializer.
4033    VDecl->setCXXDirectInitializer(true);
4034
4035    // Store the initialization expressions as a ParenListExpr.
4036    unsigned NumExprs = Exprs.size();
4037    VDecl->setInit(Context,
4038                   new (Context) ParenListExpr(Context, LParenLoc,
4039                                               (Expr **)Exprs.release(),
4040                                               NumExprs, RParenLoc));
4041    return;
4042  }
4043
4044
4045  // C++ 8.5p11:
4046  // The form of initialization (using parentheses or '=') is generally
4047  // insignificant, but does matter when the entity being initialized has a
4048  // class type.
4049  QualType DeclInitType = VDecl->getType();
4050  if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
4051    DeclInitType = Context.getBaseElementType(Array);
4052
4053  if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
4054                          diag::err_typecheck_decl_incomplete_type)) {
4055    VDecl->setInvalidDecl();
4056    return;
4057  }
4058
4059  // The variable can not have an abstract class type.
4060  if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
4061                             diag::err_abstract_type_in_decl,
4062                             AbstractVariableType))
4063    VDecl->setInvalidDecl();
4064
4065  const VarDecl *Def;
4066  if ((Def = VDecl->getDefinition()) && Def != VDecl) {
4067    Diag(VDecl->getLocation(), diag::err_redefinition)
4068    << VDecl->getDeclName();
4069    Diag(Def->getLocation(), diag::note_previous_definition);
4070    VDecl->setInvalidDecl();
4071    return;
4072  }
4073
4074  // Capture the variable that is being initialized and the style of
4075  // initialization.
4076  InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
4077
4078  // FIXME: Poor source location information.
4079  InitializationKind Kind
4080    = InitializationKind::CreateDirect(VDecl->getLocation(),
4081                                       LParenLoc, RParenLoc);
4082
4083  InitializationSequence InitSeq(*this, Entity, Kind,
4084                                 (Expr**)Exprs.get(), Exprs.size());
4085  OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
4086  if (Result.isInvalid()) {
4087    VDecl->setInvalidDecl();
4088    return;
4089  }
4090
4091  Result = MaybeCreateCXXExprWithTemporaries(move(Result));
4092  VDecl->setInit(Context, Result.takeAs<Expr>());
4093  VDecl->setCXXDirectInitializer(true);
4094
4095  if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
4096    FinalizeVarWithDestructor(VDecl, Record);
4097}
4098
4099/// \brief Add the applicable constructor candidates for an initialization
4100/// by constructor.
4101static void AddConstructorInitializationCandidates(Sema &SemaRef,
4102                                                   QualType ClassType,
4103                                                   Expr **Args,
4104                                                   unsigned NumArgs,
4105                                                   InitializationKind Kind,
4106                                           OverloadCandidateSet &CandidateSet) {
4107  // C++ [dcl.init]p14:
4108  //   If the initialization is direct-initialization, or if it is
4109  //   copy-initialization where the cv-unqualified version of the
4110  //   source type is the same class as, or a derived class of, the
4111  //   class of the destination, constructors are considered. The
4112  //   applicable constructors are enumerated (13.3.1.3), and the
4113  //   best one is chosen through overload resolution (13.3). The
4114  //   constructor so selected is called to initialize the object,
4115  //   with the initializer expression(s) as its argument(s). If no
4116  //   constructor applies, or the overload resolution is ambiguous,
4117  //   the initialization is ill-formed.
4118  const RecordType *ClassRec = ClassType->getAs<RecordType>();
4119  assert(ClassRec && "Can only initialize a class type here");
4120
4121  // FIXME: When we decide not to synthesize the implicitly-declared
4122  // constructors, we'll need to make them appear here.
4123
4124  const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
4125  DeclarationName ConstructorName
4126    = SemaRef.Context.DeclarationNames.getCXXConstructorName(
4127              SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType());
4128  DeclContext::lookup_const_iterator Con, ConEnd;
4129  for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
4130       Con != ConEnd; ++Con) {
4131    // Find the constructor (which may be a template).
4132    CXXConstructorDecl *Constructor = 0;
4133    FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
4134    if (ConstructorTmpl)
4135      Constructor
4136      = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
4137    else
4138      Constructor = cast<CXXConstructorDecl>(*Con);
4139
4140    if ((Kind.getKind() == InitializationKind::IK_Direct) ||
4141        (Kind.getKind() == InitializationKind::IK_Value) ||
4142        (Kind.getKind() == InitializationKind::IK_Copy &&
4143         Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
4144        ((Kind.getKind() == InitializationKind::IK_Default) &&
4145         Constructor->isDefaultConstructor())) {
4146      if (ConstructorTmpl)
4147        SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl,
4148                                             ConstructorTmpl->getAccess(),
4149                                             /*ExplicitArgs*/ 0,
4150                                             Args, NumArgs, CandidateSet);
4151      else
4152        SemaRef.AddOverloadCandidate(Constructor, Constructor->getAccess(),
4153                                     Args, NumArgs, CandidateSet);
4154    }
4155  }
4156}
4157
4158/// \brief Attempt to perform initialization by constructor
4159/// (C++ [dcl.init]p14), which may occur as part of direct-initialization or
4160/// copy-initialization.
4161///
4162/// This routine determines whether initialization by constructor is possible,
4163/// but it does not emit any diagnostics in the case where the initialization
4164/// is ill-formed.
4165///
4166/// \param ClassType the type of the object being initialized, which must have
4167/// class type.
4168///
4169/// \param Args the arguments provided to initialize the object
4170///
4171/// \param NumArgs the number of arguments provided to initialize the object
4172///
4173/// \param Kind the type of initialization being performed
4174///
4175/// \returns the constructor used to initialize the object, if successful.
4176/// Otherwise, emits a diagnostic and returns NULL.
4177CXXConstructorDecl *
4178Sema::TryInitializationByConstructor(QualType ClassType,
4179                                     Expr **Args, unsigned NumArgs,
4180                                     SourceLocation Loc,
4181                                     InitializationKind Kind) {
4182  // Build the overload candidate set
4183  OverloadCandidateSet CandidateSet;
4184  AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
4185                                         CandidateSet);
4186
4187  // Determine whether we found a constructor we can use.
4188  OverloadCandidateSet::iterator Best;
4189  switch (BestViableFunction(CandidateSet, Loc, Best)) {
4190    case OR_Success:
4191    case OR_Deleted:
4192      // We found a constructor. Return it.
4193      return cast<CXXConstructorDecl>(Best->Function);
4194
4195    case OR_No_Viable_Function:
4196    case OR_Ambiguous:
4197      // Overload resolution failed. Return nothing.
4198      return 0;
4199  }
4200
4201  // Silence GCC warning
4202  return 0;
4203}
4204
4205/// \brief Given a constructor and the set of arguments provided for the
4206/// constructor, convert the arguments and add any required default arguments
4207/// to form a proper call to this constructor.
4208///
4209/// \returns true if an error occurred, false otherwise.
4210bool
4211Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
4212                              MultiExprArg ArgsPtr,
4213                              SourceLocation Loc,
4214                     ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
4215  // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
4216  unsigned NumArgs = ArgsPtr.size();
4217  Expr **Args = (Expr **)ArgsPtr.get();
4218
4219  const FunctionProtoType *Proto
4220    = Constructor->getType()->getAs<FunctionProtoType>();
4221  assert(Proto && "Constructor without a prototype?");
4222  unsigned NumArgsInProto = Proto->getNumArgs();
4223
4224  // If too few arguments are available, we'll fill in the rest with defaults.
4225  if (NumArgs < NumArgsInProto)
4226    ConvertedArgs.reserve(NumArgsInProto);
4227  else
4228    ConvertedArgs.reserve(NumArgs);
4229
4230  VariadicCallType CallType =
4231    Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4232  llvm::SmallVector<Expr *, 8> AllArgs;
4233  bool Invalid = GatherArgumentsForCall(Loc, Constructor,
4234                                        Proto, 0, Args, NumArgs, AllArgs,
4235                                        CallType);
4236  for (unsigned i =0, size = AllArgs.size(); i < size; i++)
4237    ConvertedArgs.push_back(AllArgs[i]);
4238  return Invalid;
4239}
4240
4241/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4242/// determine whether they are reference-related,
4243/// reference-compatible, reference-compatible with added
4244/// qualification, or incompatible, for use in C++ initialization by
4245/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4246/// type, and the first type (T1) is the pointee type of the reference
4247/// type being initialized.
4248Sema::ReferenceCompareResult
4249Sema::CompareReferenceRelationship(SourceLocation Loc,
4250                                   QualType OrigT1, QualType OrigT2,
4251                                   bool& DerivedToBase) {
4252  assert(!OrigT1->isReferenceType() &&
4253    "T1 must be the pointee type of the reference type");
4254  assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4255
4256  QualType T1 = Context.getCanonicalType(OrigT1);
4257  QualType T2 = Context.getCanonicalType(OrigT2);
4258  Qualifiers T1Quals, T2Quals;
4259  QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4260  QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4261
4262  // C++ [dcl.init.ref]p4:
4263  //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4264  //   reference-related to "cv2 T2" if T1 is the same type as T2, or
4265  //   T1 is a base class of T2.
4266  if (UnqualT1 == UnqualT2)
4267    DerivedToBase = false;
4268  else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
4269           !RequireCompleteType(Loc, OrigT2, PDiag()) &&
4270           IsDerivedFrom(UnqualT2, UnqualT1))
4271    DerivedToBase = true;
4272  else
4273    return Ref_Incompatible;
4274
4275  // At this point, we know that T1 and T2 are reference-related (at
4276  // least).
4277
4278  // If the type is an array type, promote the element qualifiers to the type
4279  // for comparison.
4280  if (isa<ArrayType>(T1) && T1Quals)
4281    T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4282  if (isa<ArrayType>(T2) && T2Quals)
4283    T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4284
4285  // C++ [dcl.init.ref]p4:
4286  //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4287  //   reference-related to T2 and cv1 is the same cv-qualification
4288  //   as, or greater cv-qualification than, cv2. For purposes of
4289  //   overload resolution, cases for which cv1 is greater
4290  //   cv-qualification than cv2 are identified as
4291  //   reference-compatible with added qualification (see 13.3.3.2).
4292  if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
4293    return Ref_Compatible;
4294  else if (T1.isMoreQualifiedThan(T2))
4295    return Ref_Compatible_With_Added_Qualification;
4296  else
4297    return Ref_Related;
4298}
4299
4300/// CheckReferenceInit - Check the initialization of a reference
4301/// variable with the given initializer (C++ [dcl.init.ref]). Init is
4302/// the initializer (either a simple initializer or an initializer
4303/// list), and DeclType is the type of the declaration. When ICS is
4304/// non-null, this routine will compute the implicit conversion
4305/// sequence according to C++ [over.ics.ref] and will not produce any
4306/// diagnostics; when ICS is null, it will emit diagnostics when any
4307/// errors are found. Either way, a return value of true indicates
4308/// that there was a failure, a return value of false indicates that
4309/// the reference initialization succeeded.
4310///
4311/// When @p SuppressUserConversions, user-defined conversions are
4312/// suppressed.
4313/// When @p AllowExplicit, we also permit explicit user-defined
4314/// conversion functions.
4315/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
4316/// When @p IgnoreBaseAccess, we don't do access control on to-base conversion.
4317/// This is used when this is called from a C-style cast.
4318bool
4319Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
4320                         SourceLocation DeclLoc,
4321                         bool SuppressUserConversions,
4322                         bool AllowExplicit, bool ForceRValue,
4323                         ImplicitConversionSequence *ICS,
4324                         bool IgnoreBaseAccess) {
4325  assert(DeclType->isReferenceType() && "Reference init needs a reference");
4326
4327  QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4328  QualType T2 = Init->getType();
4329
4330  // If the initializer is the address of an overloaded function, try
4331  // to resolve the overloaded function. If all goes well, T2 is the
4332  // type of the resulting function.
4333  if (Context.getCanonicalType(T2) == Context.OverloadTy) {
4334    FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
4335                                                          ICS != 0);
4336    if (Fn) {
4337      // Since we're performing this reference-initialization for
4338      // real, update the initializer with the resulting function.
4339      if (!ICS) {
4340        if (DiagnoseUseOfDecl(Fn, DeclLoc))
4341          return true;
4342
4343        Init = FixOverloadedFunctionReference(Init, Fn);
4344      }
4345
4346      T2 = Fn->getType();
4347    }
4348  }
4349
4350  // Compute some basic properties of the types and the initializer.
4351  bool isRValRef = DeclType->isRValueReferenceType();
4352  bool DerivedToBase = false;
4353  Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
4354                                                  Init->isLvalue(Context);
4355  ReferenceCompareResult RefRelationship
4356    = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
4357
4358  // Most paths end in a failed conversion.
4359  if (ICS) {
4360    ICS->setBad();
4361    ICS->Bad.init(BadConversionSequence::no_conversion, Init, DeclType);
4362  }
4363
4364  // C++ [dcl.init.ref]p5:
4365  //   A reference to type "cv1 T1" is initialized by an expression
4366  //   of type "cv2 T2" as follows:
4367
4368  //     -- If the initializer expression
4369
4370  // Rvalue references cannot bind to lvalues (N2812).
4371  // There is absolutely no situation where they can. In particular, note that
4372  // this is ill-formed, even if B has a user-defined conversion to A&&:
4373  //   B b;
4374  //   A&& r = b;
4375  if (isRValRef && InitLvalue == Expr::LV_Valid) {
4376    if (!ICS)
4377      Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4378        << Init->getSourceRange();
4379    return true;
4380  }
4381
4382  bool BindsDirectly = false;
4383  //       -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4384  //          reference-compatible with "cv2 T2," or
4385  //
4386  // Note that the bit-field check is skipped if we are just computing
4387  // the implicit conversion sequence (C++ [over.best.ics]p2).
4388  if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
4389      RefRelationship >= Ref_Compatible_With_Added_Qualification) {
4390    BindsDirectly = true;
4391
4392    if (ICS) {
4393      // C++ [over.ics.ref]p1:
4394      //   When a parameter of reference type binds directly (8.5.3)
4395      //   to an argument expression, the implicit conversion sequence
4396      //   is the identity conversion, unless the argument expression
4397      //   has a type that is a derived class of the parameter type,
4398      //   in which case the implicit conversion sequence is a
4399      //   derived-to-base Conversion (13.3.3.1).
4400      ICS->setStandard();
4401      ICS->Standard.First = ICK_Identity;
4402      ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4403      ICS->Standard.Third = ICK_Identity;
4404      ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
4405      ICS->Standard.setToType(0, T2);
4406      ICS->Standard.setToType(1, T1);
4407      ICS->Standard.setToType(2, T1);
4408      ICS->Standard.ReferenceBinding = true;
4409      ICS->Standard.DirectBinding = true;
4410      ICS->Standard.RRefBinding = false;
4411      ICS->Standard.CopyConstructor = 0;
4412
4413      // Nothing more to do: the inaccessibility/ambiguity check for
4414      // derived-to-base conversions is suppressed when we're
4415      // computing the implicit conversion sequence (C++
4416      // [over.best.ics]p2).
4417      return false;
4418    } else {
4419      // Perform the conversion.
4420      CastExpr::CastKind CK = CastExpr::CK_NoOp;
4421      if (DerivedToBase)
4422        CK = CastExpr::CK_DerivedToBase;
4423      else if(CheckExceptionSpecCompatibility(Init, T1))
4424        return true;
4425      ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
4426    }
4427  }
4428
4429  //       -- has a class type (i.e., T2 is a class type) and can be
4430  //          implicitly converted to an lvalue of type "cv3 T3,"
4431  //          where "cv1 T1" is reference-compatible with "cv3 T3"
4432  //          92) (this conversion is selected by enumerating the
4433  //          applicable conversion functions (13.3.1.6) and choosing
4434  //          the best one through overload resolution (13.3)),
4435  if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
4436      !RequireCompleteType(DeclLoc, T2, 0)) {
4437    CXXRecordDecl *T2RecordDecl
4438      = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4439
4440    OverloadCandidateSet CandidateSet;
4441    const UnresolvedSetImpl *Conversions
4442      = T2RecordDecl->getVisibleConversionFunctions();
4443    for (UnresolvedSetImpl::iterator I = Conversions->begin(),
4444           E = Conversions->end(); I != E; ++I) {
4445      NamedDecl *D = *I;
4446      CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4447      if (isa<UsingShadowDecl>(D))
4448        D = cast<UsingShadowDecl>(D)->getTargetDecl();
4449
4450      FunctionTemplateDecl *ConvTemplate
4451        = dyn_cast<FunctionTemplateDecl>(D);
4452      CXXConversionDecl *Conv;
4453      if (ConvTemplate)
4454        Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4455      else
4456        Conv = cast<CXXConversionDecl>(D);
4457
4458      // If the conversion function doesn't return a reference type,
4459      // it can't be considered for this conversion.
4460      if (Conv->getConversionType()->isLValueReferenceType() &&
4461          (AllowExplicit || !Conv->isExplicit())) {
4462        if (ConvTemplate)
4463          AddTemplateConversionCandidate(ConvTemplate, I.getAccess(), ActingDC,
4464                                         Init, DeclType, CandidateSet);
4465        else
4466          AddConversionCandidate(Conv, I.getAccess(), ActingDC, Init,
4467                                 DeclType, CandidateSet);
4468      }
4469    }
4470
4471    OverloadCandidateSet::iterator Best;
4472    switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
4473    case OR_Success:
4474      // This is a direct binding.
4475      BindsDirectly = true;
4476
4477      if (ICS) {
4478        // C++ [over.ics.ref]p1:
4479        //
4480        //   [...] If the parameter binds directly to the result of
4481        //   applying a conversion function to the argument
4482        //   expression, the implicit conversion sequence is a
4483        //   user-defined conversion sequence (13.3.3.1.2), with the
4484        //   second standard conversion sequence either an identity
4485        //   conversion or, if the conversion function returns an
4486        //   entity of a type that is a derived class of the parameter
4487        //   type, a derived-to-base Conversion.
4488        ICS->setUserDefined();
4489        ICS->UserDefined.Before = Best->Conversions[0].Standard;
4490        ICS->UserDefined.After = Best->FinalConversion;
4491        ICS->UserDefined.ConversionFunction = Best->Function;
4492        ICS->UserDefined.EllipsisConversion = false;
4493        assert(ICS->UserDefined.After.ReferenceBinding &&
4494               ICS->UserDefined.After.DirectBinding &&
4495               "Expected a direct reference binding!");
4496        return false;
4497      } else {
4498        OwningExprResult InitConversion =
4499          BuildCXXCastArgument(DeclLoc, QualType(),
4500                               CastExpr::CK_UserDefinedConversion,
4501                               cast<CXXMethodDecl>(Best->Function),
4502                               Owned(Init));
4503        Init = InitConversion.takeAs<Expr>();
4504
4505        if (CheckExceptionSpecCompatibility(Init, T1))
4506          return true;
4507        ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
4508                          /*isLvalue=*/true);
4509      }
4510      break;
4511
4512    case OR_Ambiguous:
4513      if (ICS) {
4514        ICS->setAmbiguous();
4515        for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4516             Cand != CandidateSet.end(); ++Cand)
4517          if (Cand->Viable)
4518            ICS->Ambiguous.addConversion(Cand->Function);
4519        break;
4520      }
4521      Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
4522            << Init->getSourceRange();
4523      PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Init, 1);
4524      return true;
4525
4526    case OR_No_Viable_Function:
4527    case OR_Deleted:
4528      // There was no suitable conversion, or we found a deleted
4529      // conversion; continue with other checks.
4530      break;
4531    }
4532  }
4533
4534  if (BindsDirectly) {
4535    // C++ [dcl.init.ref]p4:
4536    //   [...] In all cases where the reference-related or
4537    //   reference-compatible relationship of two types is used to
4538    //   establish the validity of a reference binding, and T1 is a
4539    //   base class of T2, a program that necessitates such a binding
4540    //   is ill-formed if T1 is an inaccessible (clause 11) or
4541    //   ambiguous (10.2) base class of T2.
4542    //
4543    // Note that we only check this condition when we're allowed to
4544    // complain about errors, because we should not be checking for
4545    // ambiguity (or inaccessibility) unless the reference binding
4546    // actually happens.
4547    if (DerivedToBase)
4548      return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
4549                                          Init->getSourceRange(),
4550                                          IgnoreBaseAccess);
4551    else
4552      return false;
4553  }
4554
4555  //     -- Otherwise, the reference shall be to a non-volatile const
4556  //        type (i.e., cv1 shall be const), or the reference shall be an
4557  //        rvalue reference and the initializer expression shall be an rvalue.
4558  if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
4559    if (!ICS)
4560      Diag(DeclLoc, diag::err_not_reference_to_const_init)
4561        << T1.isVolatileQualified()
4562        << T1 << int(InitLvalue != Expr::LV_Valid)
4563        << T2 << Init->getSourceRange();
4564    return true;
4565  }
4566
4567  //       -- If the initializer expression is an rvalue, with T2 a
4568  //          class type, and "cv1 T1" is reference-compatible with
4569  //          "cv2 T2," the reference is bound in one of the
4570  //          following ways (the choice is implementation-defined):
4571  //
4572  //          -- The reference is bound to the object represented by
4573  //             the rvalue (see 3.10) or to a sub-object within that
4574  //             object.
4575  //
4576  //          -- A temporary of type "cv1 T2" [sic] is created, and
4577  //             a constructor is called to copy the entire rvalue
4578  //             object into the temporary. The reference is bound to
4579  //             the temporary or to a sub-object within the
4580  //             temporary.
4581  //
4582  //          The constructor that would be used to make the copy
4583  //          shall be callable whether or not the copy is actually
4584  //          done.
4585  //
4586  // Note that C++0x [dcl.init.ref]p5 takes away this implementation
4587  // freedom, so we will always take the first option and never build
4588  // a temporary in this case. FIXME: We will, however, have to check
4589  // for the presence of a copy constructor in C++98/03 mode.
4590  if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
4591      RefRelationship >= Ref_Compatible_With_Added_Qualification) {
4592    if (ICS) {
4593      ICS->setStandard();
4594      ICS->Standard.First = ICK_Identity;
4595      ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4596      ICS->Standard.Third = ICK_Identity;
4597      ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
4598      ICS->Standard.setToType(0, T2);
4599      ICS->Standard.setToType(1, T1);
4600      ICS->Standard.setToType(2, T1);
4601      ICS->Standard.ReferenceBinding = true;
4602      ICS->Standard.DirectBinding = false;
4603      ICS->Standard.RRefBinding = isRValRef;
4604      ICS->Standard.CopyConstructor = 0;
4605    } else {
4606      CastExpr::CastKind CK = CastExpr::CK_NoOp;
4607      if (DerivedToBase)
4608        CK = CastExpr::CK_DerivedToBase;
4609      else if(CheckExceptionSpecCompatibility(Init, T1))
4610        return true;
4611      ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
4612    }
4613    return false;
4614  }
4615
4616  //       -- Otherwise, a temporary of type "cv1 T1" is created and
4617  //          initialized from the initializer expression using the
4618  //          rules for a non-reference copy initialization (8.5). The
4619  //          reference is then bound to the temporary. If T1 is
4620  //          reference-related to T2, cv1 must be the same
4621  //          cv-qualification as, or greater cv-qualification than,
4622  //          cv2; otherwise, the program is ill-formed.
4623  if (RefRelationship == Ref_Related) {
4624    // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4625    // we would be reference-compatible or reference-compatible with
4626    // added qualification. But that wasn't the case, so the reference
4627    // initialization fails.
4628    if (!ICS)
4629      Diag(DeclLoc, diag::err_reference_init_drops_quals)
4630        << T1 << int(InitLvalue != Expr::LV_Valid)
4631        << T2 << Init->getSourceRange();
4632    return true;
4633  }
4634
4635  // If at least one of the types is a class type, the types are not
4636  // related, and we aren't allowed any user conversions, the
4637  // reference binding fails. This case is important for breaking
4638  // recursion, since TryImplicitConversion below will attempt to
4639  // create a temporary through the use of a copy constructor.
4640  if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
4641      (T1->isRecordType() || T2->isRecordType())) {
4642    if (!ICS)
4643      Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
4644        << DeclType << Init->getType() << AA_Initializing << Init->getSourceRange();
4645    return true;
4646  }
4647
4648  // Actually try to convert the initializer to T1.
4649  if (ICS) {
4650    // C++ [over.ics.ref]p2:
4651    //
4652    //   When a parameter of reference type is not bound directly to
4653    //   an argument expression, the conversion sequence is the one
4654    //   required to convert the argument expression to the
4655    //   underlying type of the reference according to
4656    //   13.3.3.1. Conceptually, this conversion sequence corresponds
4657    //   to copy-initializing a temporary of the underlying type with
4658    //   the argument expression. Any difference in top-level
4659    //   cv-qualification is subsumed by the initialization itself
4660    //   and does not constitute a conversion.
4661    *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
4662                                 /*AllowExplicit=*/false,
4663                                 /*ForceRValue=*/false,
4664                                 /*InOverloadResolution=*/false);
4665
4666    // Of course, that's still a reference binding.
4667    if (ICS->isStandard()) {
4668      ICS->Standard.ReferenceBinding = true;
4669      ICS->Standard.RRefBinding = isRValRef;
4670    } else if (ICS->isUserDefined()) {
4671      ICS->UserDefined.After.ReferenceBinding = true;
4672      ICS->UserDefined.After.RRefBinding = isRValRef;
4673    }
4674    return ICS->isBad();
4675  } else {
4676    ImplicitConversionSequence Conversions;
4677    bool badConversion = PerformImplicitConversion(Init, T1, AA_Initializing,
4678                                                   false, false,
4679                                                   Conversions);
4680    if (badConversion) {
4681      if (Conversions.isAmbiguous()) {
4682        Diag(DeclLoc,
4683             diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
4684        for (int j = Conversions.Ambiguous.conversions().size()-1;
4685             j >= 0; j--) {
4686          FunctionDecl *Func = Conversions.Ambiguous.conversions()[j];
4687          NoteOverloadCandidate(Func);
4688        }
4689      }
4690      else {
4691        if (isRValRef)
4692          Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4693            << Init->getSourceRange();
4694        else
4695          Diag(DeclLoc, diag::err_invalid_initialization)
4696            << DeclType << Init->getType() << Init->getSourceRange();
4697      }
4698    }
4699    return badConversion;
4700  }
4701}
4702
4703static inline bool
4704CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
4705                                       const FunctionDecl *FnDecl) {
4706  const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
4707  if (isa<NamespaceDecl>(DC)) {
4708    return SemaRef.Diag(FnDecl->getLocation(),
4709                        diag::err_operator_new_delete_declared_in_namespace)
4710      << FnDecl->getDeclName();
4711  }
4712
4713  if (isa<TranslationUnitDecl>(DC) &&
4714      FnDecl->getStorageClass() == FunctionDecl::Static) {
4715    return SemaRef.Diag(FnDecl->getLocation(),
4716                        diag::err_operator_new_delete_declared_static)
4717      << FnDecl->getDeclName();
4718  }
4719
4720  return false;
4721}
4722
4723static inline bool
4724CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
4725                            CanQualType ExpectedResultType,
4726                            CanQualType ExpectedFirstParamType,
4727                            unsigned DependentParamTypeDiag,
4728                            unsigned InvalidParamTypeDiag) {
4729  QualType ResultType =
4730    FnDecl->getType()->getAs<FunctionType>()->getResultType();
4731
4732  // Check that the result type is not dependent.
4733  if (ResultType->isDependentType())
4734    return SemaRef.Diag(FnDecl->getLocation(),
4735                        diag::err_operator_new_delete_dependent_result_type)
4736    << FnDecl->getDeclName() << ExpectedResultType;
4737
4738  // Check that the result type is what we expect.
4739  if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
4740    return SemaRef.Diag(FnDecl->getLocation(),
4741                        diag::err_operator_new_delete_invalid_result_type)
4742    << FnDecl->getDeclName() << ExpectedResultType;
4743
4744  // A function template must have at least 2 parameters.
4745  if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
4746    return SemaRef.Diag(FnDecl->getLocation(),
4747                      diag::err_operator_new_delete_template_too_few_parameters)
4748        << FnDecl->getDeclName();
4749
4750  // The function decl must have at least 1 parameter.
4751  if (FnDecl->getNumParams() == 0)
4752    return SemaRef.Diag(FnDecl->getLocation(),
4753                        diag::err_operator_new_delete_too_few_parameters)
4754      << FnDecl->getDeclName();
4755
4756  // Check the the first parameter type is not dependent.
4757  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4758  if (FirstParamType->isDependentType())
4759    return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
4760      << FnDecl->getDeclName() << ExpectedFirstParamType;
4761
4762  // Check that the first parameter type is what we expect.
4763  if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
4764      ExpectedFirstParamType)
4765    return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
4766    << FnDecl->getDeclName() << ExpectedFirstParamType;
4767
4768  return false;
4769}
4770
4771static bool
4772CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
4773  // C++ [basic.stc.dynamic.allocation]p1:
4774  //   A program is ill-formed if an allocation function is declared in a
4775  //   namespace scope other than global scope or declared static in global
4776  //   scope.
4777  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4778    return true;
4779
4780  CanQualType SizeTy =
4781    SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
4782
4783  // C++ [basic.stc.dynamic.allocation]p1:
4784  //  The return type shall be void*. The first parameter shall have type
4785  //  std::size_t.
4786  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
4787                                  SizeTy,
4788                                  diag::err_operator_new_dependent_param_type,
4789                                  diag::err_operator_new_param_type))
4790    return true;
4791
4792  // C++ [basic.stc.dynamic.allocation]p1:
4793  //  The first parameter shall not have an associated default argument.
4794  if (FnDecl->getParamDecl(0)->hasDefaultArg())
4795    return SemaRef.Diag(FnDecl->getLocation(),
4796                        diag::err_operator_new_default_arg)
4797      << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
4798
4799  return false;
4800}
4801
4802static bool
4803CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
4804  // C++ [basic.stc.dynamic.deallocation]p1:
4805  //   A program is ill-formed if deallocation functions are declared in a
4806  //   namespace scope other than global scope or declared static in global
4807  //   scope.
4808  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4809    return true;
4810
4811  // C++ [basic.stc.dynamic.deallocation]p2:
4812  //   Each deallocation function shall return void and its first parameter
4813  //   shall be void*.
4814  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
4815                                  SemaRef.Context.VoidPtrTy,
4816                                 diag::err_operator_delete_dependent_param_type,
4817                                 diag::err_operator_delete_param_type))
4818    return true;
4819
4820  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4821  if (FirstParamType->isDependentType())
4822    return SemaRef.Diag(FnDecl->getLocation(),
4823                        diag::err_operator_delete_dependent_param_type)
4824    << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
4825
4826  if (SemaRef.Context.getCanonicalType(FirstParamType) !=
4827      SemaRef.Context.VoidPtrTy)
4828    return SemaRef.Diag(FnDecl->getLocation(),
4829                        diag::err_operator_delete_param_type)
4830      << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
4831
4832  return false;
4833}
4834
4835/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4836/// of this overloaded operator is well-formed. If so, returns false;
4837/// otherwise, emits appropriate diagnostics and returns true.
4838bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
4839  assert(FnDecl && FnDecl->isOverloadedOperator() &&
4840         "Expected an overloaded operator declaration");
4841
4842  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4843
4844  // C++ [over.oper]p5:
4845  //   The allocation and deallocation functions, operator new,
4846  //   operator new[], operator delete and operator delete[], are
4847  //   described completely in 3.7.3. The attributes and restrictions
4848  //   found in the rest of this subclause do not apply to them unless
4849  //   explicitly stated in 3.7.3.
4850  if (Op == OO_Delete || Op == OO_Array_Delete)
4851    return CheckOperatorDeleteDeclaration(*this, FnDecl);
4852
4853  if (Op == OO_New || Op == OO_Array_New)
4854    return CheckOperatorNewDeclaration(*this, FnDecl);
4855
4856  // C++ [over.oper]p6:
4857  //   An operator function shall either be a non-static member
4858  //   function or be a non-member function and have at least one
4859  //   parameter whose type is a class, a reference to a class, an
4860  //   enumeration, or a reference to an enumeration.
4861  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4862    if (MethodDecl->isStatic())
4863      return Diag(FnDecl->getLocation(),
4864                  diag::err_operator_overload_static) << FnDecl->getDeclName();
4865  } else {
4866    bool ClassOrEnumParam = false;
4867    for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4868                                   ParamEnd = FnDecl->param_end();
4869         Param != ParamEnd; ++Param) {
4870      QualType ParamType = (*Param)->getType().getNonReferenceType();
4871      if (ParamType->isDependentType() || ParamType->isRecordType() ||
4872          ParamType->isEnumeralType()) {
4873        ClassOrEnumParam = true;
4874        break;
4875      }
4876    }
4877
4878    if (!ClassOrEnumParam)
4879      return Diag(FnDecl->getLocation(),
4880                  diag::err_operator_overload_needs_class_or_enum)
4881        << FnDecl->getDeclName();
4882  }
4883
4884  // C++ [over.oper]p8:
4885  //   An operator function cannot have default arguments (8.3.6),
4886  //   except where explicitly stated below.
4887  //
4888  // Only the function-call operator allows default arguments
4889  // (C++ [over.call]p1).
4890  if (Op != OO_Call) {
4891    for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4892         Param != FnDecl->param_end(); ++Param) {
4893      if ((*Param)->hasDefaultArg())
4894        return Diag((*Param)->getLocation(),
4895                    diag::err_operator_overload_default_arg)
4896          << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
4897    }
4898  }
4899
4900  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4901    { false, false, false }
4902#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4903    , { Unary, Binary, MemberOnly }
4904#include "clang/Basic/OperatorKinds.def"
4905  };
4906
4907  bool CanBeUnaryOperator = OperatorUses[Op][0];
4908  bool CanBeBinaryOperator = OperatorUses[Op][1];
4909  bool MustBeMemberOperator = OperatorUses[Op][2];
4910
4911  // C++ [over.oper]p8:
4912  //   [...] Operator functions cannot have more or fewer parameters
4913  //   than the number required for the corresponding operator, as
4914  //   described in the rest of this subclause.
4915  unsigned NumParams = FnDecl->getNumParams()
4916                     + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
4917  if (Op != OO_Call &&
4918      ((NumParams == 1 && !CanBeUnaryOperator) ||
4919       (NumParams == 2 && !CanBeBinaryOperator) ||
4920       (NumParams < 1) || (NumParams > 2))) {
4921    // We have the wrong number of parameters.
4922    unsigned ErrorKind;
4923    if (CanBeUnaryOperator && CanBeBinaryOperator) {
4924      ErrorKind = 2;  // 2 -> unary or binary.
4925    } else if (CanBeUnaryOperator) {
4926      ErrorKind = 0;  // 0 -> unary
4927    } else {
4928      assert(CanBeBinaryOperator &&
4929             "All non-call overloaded operators are unary or binary!");
4930      ErrorKind = 1;  // 1 -> binary
4931    }
4932
4933    return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
4934      << FnDecl->getDeclName() << NumParams << ErrorKind;
4935  }
4936
4937  // Overloaded operators other than operator() cannot be variadic.
4938  if (Op != OO_Call &&
4939      FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
4940    return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
4941      << FnDecl->getDeclName();
4942  }
4943
4944  // Some operators must be non-static member functions.
4945  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4946    return Diag(FnDecl->getLocation(),
4947                diag::err_operator_overload_must_be_member)
4948      << FnDecl->getDeclName();
4949  }
4950
4951  // C++ [over.inc]p1:
4952  //   The user-defined function called operator++ implements the
4953  //   prefix and postfix ++ operator. If this function is a member
4954  //   function with no parameters, or a non-member function with one
4955  //   parameter of class or enumeration type, it defines the prefix
4956  //   increment operator ++ for objects of that type. If the function
4957  //   is a member function with one parameter (which shall be of type
4958  //   int) or a non-member function with two parameters (the second
4959  //   of which shall be of type int), it defines the postfix
4960  //   increment operator ++ for objects of that type.
4961  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
4962    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
4963    bool ParamIsInt = false;
4964    if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
4965      ParamIsInt = BT->getKind() == BuiltinType::Int;
4966
4967    if (!ParamIsInt)
4968      return Diag(LastParam->getLocation(),
4969                  diag::err_operator_overload_post_incdec_must_be_int)
4970        << LastParam->getType() << (Op == OO_MinusMinus);
4971  }
4972
4973  // Notify the class if it got an assignment operator.
4974  if (Op == OO_Equal) {
4975    // Would have returned earlier otherwise.
4976    assert(isa<CXXMethodDecl>(FnDecl) &&
4977      "Overloaded = not member, but not filtered.");
4978    CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
4979    Method->getParent()->addedAssignmentOperator(Context, Method);
4980  }
4981
4982  return false;
4983}
4984
4985/// CheckLiteralOperatorDeclaration - Check whether the declaration
4986/// of this literal operator function is well-formed. If so, returns
4987/// false; otherwise, emits appropriate diagnostics and returns true.
4988bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
4989  DeclContext *DC = FnDecl->getDeclContext();
4990  Decl::Kind Kind = DC->getDeclKind();
4991  if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
4992      Kind != Decl::LinkageSpec) {
4993    Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
4994      << FnDecl->getDeclName();
4995    return true;
4996  }
4997
4998  bool Valid = false;
4999
5000  // FIXME: Check for the one valid template signature
5001  // template <char...> type operator "" name();
5002
5003  if (FunctionDecl::param_iterator Param = FnDecl->param_begin()) {
5004    // Check the first parameter
5005    QualType T = (*Param)->getType();
5006
5007    // unsigned long long int and long double are allowed, but only
5008    // alone.
5009    // We also allow any character type; their omission seems to be a bug
5010    // in n3000
5011    if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5012        Context.hasSameType(T, Context.LongDoubleTy) ||
5013        Context.hasSameType(T, Context.CharTy) ||
5014        Context.hasSameType(T, Context.WCharTy) ||
5015        Context.hasSameType(T, Context.Char16Ty) ||
5016        Context.hasSameType(T, Context.Char32Ty)) {
5017      if (++Param == FnDecl->param_end())
5018        Valid = true;
5019      goto FinishedParams;
5020    }
5021
5022    // Otherwise it must be a pointer to const; let's strip those.
5023    const PointerType *PT = T->getAs<PointerType>();
5024    if (!PT)
5025      goto FinishedParams;
5026    T = PT->getPointeeType();
5027    if (!T.isConstQualified())
5028      goto FinishedParams;
5029    T = T.getUnqualifiedType();
5030
5031    // Move on to the second parameter;
5032    ++Param;
5033
5034    // If there is no second parameter, the first must be a const char *
5035    if (Param == FnDecl->param_end()) {
5036      if (Context.hasSameType(T, Context.CharTy))
5037        Valid = true;
5038      goto FinishedParams;
5039    }
5040
5041    // const char *, const wchar_t*, const char16_t*, and const char32_t*
5042    // are allowed as the first parameter to a two-parameter function
5043    if (!(Context.hasSameType(T, Context.CharTy) ||
5044          Context.hasSameType(T, Context.WCharTy) ||
5045          Context.hasSameType(T, Context.Char16Ty) ||
5046          Context.hasSameType(T, Context.Char32Ty)))
5047      goto FinishedParams;
5048
5049    // The second and final parameter must be an std::size_t
5050    T = (*Param)->getType().getUnqualifiedType();
5051    if (Context.hasSameType(T, Context.getSizeType()) &&
5052        ++Param == FnDecl->param_end())
5053      Valid = true;
5054  }
5055
5056  // FIXME: This diagnostic is absolutely terrible.
5057FinishedParams:
5058  if (!Valid) {
5059    Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
5060      << FnDecl->getDeclName();
5061    return true;
5062  }
5063
5064  return false;
5065}
5066
5067/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5068/// linkage specification, including the language and (if present)
5069/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
5070/// the location of the language string literal, which is provided
5071/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
5072/// the '{' brace. Otherwise, this linkage specification does not
5073/// have any braces.
5074Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
5075                                                     SourceLocation ExternLoc,
5076                                                     SourceLocation LangLoc,
5077                                                     const char *Lang,
5078                                                     unsigned StrSize,
5079                                                     SourceLocation LBraceLoc) {
5080  LinkageSpecDecl::LanguageIDs Language;
5081  if (strncmp(Lang, "\"C\"", StrSize) == 0)
5082    Language = LinkageSpecDecl::lang_c;
5083  else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
5084    Language = LinkageSpecDecl::lang_cxx;
5085  else {
5086    Diag(LangLoc, diag::err_bad_language);
5087    return DeclPtrTy();
5088  }
5089
5090  // FIXME: Add all the various semantics of linkage specifications
5091
5092  LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
5093                                               LangLoc, Language,
5094                                               LBraceLoc.isValid());
5095  CurContext->addDecl(D);
5096  PushDeclContext(S, D);
5097  return DeclPtrTy::make(D);
5098}
5099
5100/// ActOnFinishLinkageSpecification - Completely the definition of
5101/// the C++ linkage specification LinkageSpec. If RBraceLoc is
5102/// valid, it's the position of the closing '}' brace in a linkage
5103/// specification that uses braces.
5104Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
5105                                                      DeclPtrTy LinkageSpec,
5106                                                      SourceLocation RBraceLoc) {
5107  if (LinkageSpec)
5108    PopDeclContext();
5109  return LinkageSpec;
5110}
5111
5112/// \brief Perform semantic analysis for the variable declaration that
5113/// occurs within a C++ catch clause, returning the newly-created
5114/// variable.
5115VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
5116                                         TypeSourceInfo *TInfo,
5117                                         IdentifierInfo *Name,
5118                                         SourceLocation Loc,
5119                                         SourceRange Range) {
5120  bool Invalid = false;
5121
5122  // Arrays and functions decay.
5123  if (ExDeclType->isArrayType())
5124    ExDeclType = Context.getArrayDecayedType(ExDeclType);
5125  else if (ExDeclType->isFunctionType())
5126    ExDeclType = Context.getPointerType(ExDeclType);
5127
5128  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
5129  // The exception-declaration shall not denote a pointer or reference to an
5130  // incomplete type, other than [cv] void*.
5131  // N2844 forbids rvalue references.
5132  if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
5133    Diag(Loc, diag::err_catch_rvalue_ref) << Range;
5134    Invalid = true;
5135  }
5136
5137  QualType BaseType = ExDeclType;
5138  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
5139  unsigned DK = diag::err_catch_incomplete;
5140  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
5141    BaseType = Ptr->getPointeeType();
5142    Mode = 1;
5143    DK = diag::err_catch_incomplete_ptr;
5144  } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
5145    // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
5146    BaseType = Ref->getPointeeType();
5147    Mode = 2;
5148    DK = diag::err_catch_incomplete_ref;
5149  }
5150  if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
5151      !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
5152    Invalid = true;
5153
5154  if (!Invalid && !ExDeclType->isDependentType() &&
5155      RequireNonAbstractType(Loc, ExDeclType,
5156                             diag::err_abstract_type_in_decl,
5157                             AbstractVariableType))
5158    Invalid = true;
5159
5160  // FIXME: Need to test for ability to copy-construct and destroy the
5161  // exception variable.
5162
5163  // FIXME: Need to check for abstract classes.
5164
5165  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
5166                                    Name, ExDeclType, TInfo, VarDecl::None);
5167
5168  if (Invalid)
5169    ExDecl->setInvalidDecl();
5170
5171  return ExDecl;
5172}
5173
5174/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
5175/// handler.
5176Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
5177  TypeSourceInfo *TInfo = 0;
5178  QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo);
5179
5180  bool Invalid = D.isInvalidType();
5181  IdentifierInfo *II = D.getIdentifier();
5182  if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
5183    // The scope should be freshly made just for us. There is just no way
5184    // it contains any previous declaration.
5185    assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
5186    if (PrevDecl->isTemplateParameter()) {
5187      // Maybe we will complain about the shadowed template parameter.
5188      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
5189    }
5190  }
5191
5192  if (D.getCXXScopeSpec().isSet() && !Invalid) {
5193    Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
5194      << D.getCXXScopeSpec().getRange();
5195    Invalid = true;
5196  }
5197
5198  VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
5199                                              D.getIdentifier(),
5200                                              D.getIdentifierLoc(),
5201                                            D.getDeclSpec().getSourceRange());
5202
5203  if (Invalid)
5204    ExDecl->setInvalidDecl();
5205
5206  // Add the exception declaration into this scope.
5207  if (II)
5208    PushOnScopeChains(ExDecl, S);
5209  else
5210    CurContext->addDecl(ExDecl);
5211
5212  ProcessDeclAttributes(S, ExDecl, D);
5213  return DeclPtrTy::make(ExDecl);
5214}
5215
5216Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
5217                                                   ExprArg assertexpr,
5218                                                   ExprArg assertmessageexpr) {
5219  Expr *AssertExpr = (Expr *)assertexpr.get();
5220  StringLiteral *AssertMessage =
5221    cast<StringLiteral>((Expr *)assertmessageexpr.get());
5222
5223  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
5224    llvm::APSInt Value(32);
5225    if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
5226      Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
5227        AssertExpr->getSourceRange();
5228      return DeclPtrTy();
5229    }
5230
5231    if (Value == 0) {
5232      Diag(AssertLoc, diag::err_static_assert_failed)
5233        << AssertMessage->getString() << AssertExpr->getSourceRange();
5234    }
5235  }
5236
5237  assertexpr.release();
5238  assertmessageexpr.release();
5239  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
5240                                        AssertExpr, AssertMessage);
5241
5242  CurContext->addDecl(Decl);
5243  return DeclPtrTy::make(Decl);
5244}
5245
5246/// Handle a friend type declaration.  This works in tandem with
5247/// ActOnTag.
5248///
5249/// Notes on friend class templates:
5250///
5251/// We generally treat friend class declarations as if they were
5252/// declaring a class.  So, for example, the elaborated type specifier
5253/// in a friend declaration is required to obey the restrictions of a
5254/// class-head (i.e. no typedefs in the scope chain), template
5255/// parameters are required to match up with simple template-ids, &c.
5256/// However, unlike when declaring a template specialization, it's
5257/// okay to refer to a template specialization without an empty
5258/// template parameter declaration, e.g.
5259///   friend class A<T>::B<unsigned>;
5260/// We permit this as a special case; if there are any template
5261/// parameters present at all, require proper matching, i.e.
5262///   template <> template <class T> friend class A<int>::B;
5263Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
5264                                          MultiTemplateParamsArg TempParams) {
5265  SourceLocation Loc = DS.getSourceRange().getBegin();
5266
5267  assert(DS.isFriendSpecified());
5268  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5269
5270  // Try to convert the decl specifier to a type.  This works for
5271  // friend templates because ActOnTag never produces a ClassTemplateDecl
5272  // for a TUK_Friend.
5273  Declarator TheDeclarator(DS, Declarator::MemberContext);
5274  QualType T = GetTypeForDeclarator(TheDeclarator, S);
5275  if (TheDeclarator.isInvalidType())
5276    return DeclPtrTy();
5277
5278  // This is definitely an error in C++98.  It's probably meant to
5279  // be forbidden in C++0x, too, but the specification is just
5280  // poorly written.
5281  //
5282  // The problem is with declarations like the following:
5283  //   template <T> friend A<T>::foo;
5284  // where deciding whether a class C is a friend or not now hinges
5285  // on whether there exists an instantiation of A that causes
5286  // 'foo' to equal C.  There are restrictions on class-heads
5287  // (which we declare (by fiat) elaborated friend declarations to
5288  // be) that makes this tractable.
5289  //
5290  // FIXME: handle "template <> friend class A<T>;", which
5291  // is possibly well-formed?  Who even knows?
5292  if (TempParams.size() && !isa<ElaboratedType>(T)) {
5293    Diag(Loc, diag::err_tagless_friend_type_template)
5294      << DS.getSourceRange();
5295    return DeclPtrTy();
5296  }
5297
5298  // C++ [class.friend]p2:
5299  //   An elaborated-type-specifier shall be used in a friend declaration
5300  //   for a class.*
5301  //   * The class-key of the elaborated-type-specifier is required.
5302  // This is one of the rare places in Clang where it's legitimate to
5303  // ask about the "spelling" of the type.
5304  if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
5305    // If we evaluated the type to a record type, suggest putting
5306    // a tag in front.
5307    if (const RecordType *RT = T->getAs<RecordType>()) {
5308      RecordDecl *RD = RT->getDecl();
5309
5310      std::string InsertionText = std::string(" ") + RD->getKindName();
5311
5312      Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
5313        << (unsigned) RD->getTagKind()
5314        << T
5315        << SourceRange(DS.getFriendSpecLoc())
5316        << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
5317                                                 InsertionText);
5318      return DeclPtrTy();
5319    }else {
5320      Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
5321          << DS.getSourceRange();
5322      return DeclPtrTy();
5323    }
5324  }
5325
5326  // Enum types cannot be friends.
5327  if (T->getAs<EnumType>()) {
5328    Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
5329      << SourceRange(DS.getFriendSpecLoc());
5330    return DeclPtrTy();
5331  }
5332
5333  // C++98 [class.friend]p1: A friend of a class is a function
5334  //   or class that is not a member of the class . . .
5335  // This is fixed in DR77, which just barely didn't make the C++03
5336  // deadline.  It's also a very silly restriction that seriously
5337  // affects inner classes and which nobody else seems to implement;
5338  // thus we never diagnose it, not even in -pedantic.
5339
5340  Decl *D;
5341  if (TempParams.size())
5342    D = FriendTemplateDecl::Create(Context, CurContext, Loc,
5343                                   TempParams.size(),
5344                                 (TemplateParameterList**) TempParams.release(),
5345                                   T.getTypePtr(),
5346                                   DS.getFriendSpecLoc());
5347  else
5348    D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
5349                           DS.getFriendSpecLoc());
5350  D->setAccess(AS_public);
5351  CurContext->addDecl(D);
5352
5353  return DeclPtrTy::make(D);
5354}
5355
5356Sema::DeclPtrTy
5357Sema::ActOnFriendFunctionDecl(Scope *S,
5358                              Declarator &D,
5359                              bool IsDefinition,
5360                              MultiTemplateParamsArg TemplateParams) {
5361  const DeclSpec &DS = D.getDeclSpec();
5362
5363  assert(DS.isFriendSpecified());
5364  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5365
5366  SourceLocation Loc = D.getIdentifierLoc();
5367  TypeSourceInfo *TInfo = 0;
5368  QualType T = GetTypeForDeclarator(D, S, &TInfo);
5369
5370  // C++ [class.friend]p1
5371  //   A friend of a class is a function or class....
5372  // Note that this sees through typedefs, which is intended.
5373  // It *doesn't* see through dependent types, which is correct
5374  // according to [temp.arg.type]p3:
5375  //   If a declaration acquires a function type through a
5376  //   type dependent on a template-parameter and this causes
5377  //   a declaration that does not use the syntactic form of a
5378  //   function declarator to have a function type, the program
5379  //   is ill-formed.
5380  if (!T->isFunctionType()) {
5381    Diag(Loc, diag::err_unexpected_friend);
5382
5383    // It might be worthwhile to try to recover by creating an
5384    // appropriate declaration.
5385    return DeclPtrTy();
5386  }
5387
5388  // C++ [namespace.memdef]p3
5389  //  - If a friend declaration in a non-local class first declares a
5390  //    class or function, the friend class or function is a member
5391  //    of the innermost enclosing namespace.
5392  //  - The name of the friend is not found by simple name lookup
5393  //    until a matching declaration is provided in that namespace
5394  //    scope (either before or after the class declaration granting
5395  //    friendship).
5396  //  - If a friend function is called, its name may be found by the
5397  //    name lookup that considers functions from namespaces and
5398  //    classes associated with the types of the function arguments.
5399  //  - When looking for a prior declaration of a class or a function
5400  //    declared as a friend, scopes outside the innermost enclosing
5401  //    namespace scope are not considered.
5402
5403  CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
5404  DeclarationName Name = GetNameForDeclarator(D);
5405  assert(Name);
5406
5407  // The context we found the declaration in, or in which we should
5408  // create the declaration.
5409  DeclContext *DC;
5410
5411  // FIXME: handle local classes
5412
5413  // Recover from invalid scope qualifiers as if they just weren't there.
5414  LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
5415                        ForRedeclaration);
5416  if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
5417    // FIXME: RequireCompleteDeclContext
5418    DC = computeDeclContext(ScopeQual);
5419
5420    // FIXME: handle dependent contexts
5421    if (!DC) return DeclPtrTy();
5422
5423    LookupQualifiedName(Previous, DC);
5424
5425    // If searching in that context implicitly found a declaration in
5426    // a different context, treat it like it wasn't found at all.
5427    // TODO: better diagnostics for this case.  Suggesting the right
5428    // qualified scope would be nice...
5429    // FIXME: getRepresentativeDecl() is not right here at all
5430    if (Previous.empty() ||
5431        !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
5432      D.setInvalidType();
5433      Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
5434      return DeclPtrTy();
5435    }
5436
5437    // C++ [class.friend]p1: A friend of a class is a function or
5438    //   class that is not a member of the class . . .
5439    if (DC->Equals(CurContext))
5440      Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5441
5442  // Otherwise walk out to the nearest namespace scope looking for matches.
5443  } else {
5444    // TODO: handle local class contexts.
5445
5446    DC = CurContext;
5447    while (true) {
5448      // Skip class contexts.  If someone can cite chapter and verse
5449      // for this behavior, that would be nice --- it's what GCC and
5450      // EDG do, and it seems like a reasonable intent, but the spec
5451      // really only says that checks for unqualified existing
5452      // declarations should stop at the nearest enclosing namespace,
5453      // not that they should only consider the nearest enclosing
5454      // namespace.
5455      while (DC->isRecord())
5456        DC = DC->getParent();
5457
5458      LookupQualifiedName(Previous, DC);
5459
5460      // TODO: decide what we think about using declarations.
5461      if (!Previous.empty())
5462        break;
5463
5464      if (DC->isFileContext()) break;
5465      DC = DC->getParent();
5466    }
5467
5468    // C++ [class.friend]p1: A friend of a class is a function or
5469    //   class that is not a member of the class . . .
5470    // C++0x changes this for both friend types and functions.
5471    // Most C++ 98 compilers do seem to give an error here, so
5472    // we do, too.
5473    if (!Previous.empty() && DC->Equals(CurContext)
5474        && !getLangOptions().CPlusPlus0x)
5475      Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5476  }
5477
5478  if (DC->isFileContext()) {
5479    // This implies that it has to be an operator or function.
5480    if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
5481        D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
5482        D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
5483      Diag(Loc, diag::err_introducing_special_friend) <<
5484        (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
5485         D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
5486      return DeclPtrTy();
5487    }
5488  }
5489
5490  bool Redeclaration = false;
5491  NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
5492                                          move(TemplateParams),
5493                                          IsDefinition,
5494                                          Redeclaration);
5495  if (!ND) return DeclPtrTy();
5496
5497  assert(ND->getDeclContext() == DC);
5498  assert(ND->getLexicalDeclContext() == CurContext);
5499
5500  // Add the function declaration to the appropriate lookup tables,
5501  // adjusting the redeclarations list as necessary.  We don't
5502  // want to do this yet if the friending class is dependent.
5503  //
5504  // Also update the scope-based lookup if the target context's
5505  // lookup context is in lexical scope.
5506  if (!CurContext->isDependentContext()) {
5507    DC = DC->getLookupContext();
5508    DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
5509    if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
5510      PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
5511  }
5512
5513  FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
5514                                       D.getIdentifierLoc(), ND,
5515                                       DS.getFriendSpecLoc());
5516  FrD->setAccess(AS_public);
5517  CurContext->addDecl(FrD);
5518
5519  if (D.getName().getKind() == UnqualifiedId::IK_TemplateId)
5520    FrD->setSpecialization(true);
5521
5522  return DeclPtrTy::make(ND);
5523}
5524
5525void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
5526  AdjustDeclIfTemplate(dcl);
5527
5528  Decl *Dcl = dcl.getAs<Decl>();
5529  FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
5530  if (!Fn) {
5531    Diag(DelLoc, diag::err_deleted_non_function);
5532    return;
5533  }
5534  if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
5535    Diag(DelLoc, diag::err_deleted_decl_not_first);
5536    Diag(Prev->getLocation(), diag::note_previous_declaration);
5537    // If the declaration wasn't the first, we delete the function anyway for
5538    // recovery.
5539  }
5540  Fn->setDeleted();
5541}
5542
5543static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
5544  for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
5545       ++CI) {
5546    Stmt *SubStmt = *CI;
5547    if (!SubStmt)
5548      continue;
5549    if (isa<ReturnStmt>(SubStmt))
5550      Self.Diag(SubStmt->getSourceRange().getBegin(),
5551           diag::err_return_in_constructor_handler);
5552    if (!isa<Expr>(SubStmt))
5553      SearchForReturnInStmt(Self, SubStmt);
5554  }
5555}
5556
5557void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
5558  for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
5559    CXXCatchStmt *Handler = TryBlock->getHandler(I);
5560    SearchForReturnInStmt(*this, Handler);
5561  }
5562}
5563
5564bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
5565                                             const CXXMethodDecl *Old) {
5566  QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
5567  QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
5568
5569  if (Context.hasSameType(NewTy, OldTy))
5570    return false;
5571
5572  // Check if the return types are covariant
5573  QualType NewClassTy, OldClassTy;
5574
5575  /// Both types must be pointers or references to classes.
5576  if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
5577    if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
5578      NewClassTy = NewPT->getPointeeType();
5579      OldClassTy = OldPT->getPointeeType();
5580    }
5581  } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
5582    if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
5583      if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
5584        NewClassTy = NewRT->getPointeeType();
5585        OldClassTy = OldRT->getPointeeType();
5586      }
5587    }
5588  }
5589
5590  // The return types aren't either both pointers or references to a class type.
5591  if (NewClassTy.isNull()) {
5592    Diag(New->getLocation(),
5593         diag::err_different_return_type_for_overriding_virtual_function)
5594      << New->getDeclName() << NewTy << OldTy;
5595    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5596
5597    return true;
5598  }
5599
5600  // C++ [class.virtual]p6:
5601  //   If the return type of D::f differs from the return type of B::f, the
5602  //   class type in the return type of D::f shall be complete at the point of
5603  //   declaration of D::f or shall be the class type D.
5604  if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
5605    if (!RT->isBeingDefined() &&
5606        RequireCompleteType(New->getLocation(), NewClassTy,
5607                            PDiag(diag::err_covariant_return_incomplete)
5608                              << New->getDeclName()))
5609    return true;
5610  }
5611
5612  if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
5613    // Check if the new class derives from the old class.
5614    if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
5615      Diag(New->getLocation(),
5616           diag::err_covariant_return_not_derived)
5617      << New->getDeclName() << NewTy << OldTy;
5618      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5619      return true;
5620    }
5621
5622    // Check if we the conversion from derived to base is valid.
5623    if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
5624                      diag::err_covariant_return_inaccessible_base,
5625                      diag::err_covariant_return_ambiguous_derived_to_base_conv,
5626                      // FIXME: Should this point to the return type?
5627                      New->getLocation(), SourceRange(), New->getDeclName())) {
5628      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5629      return true;
5630    }
5631  }
5632
5633  // The qualifiers of the return types must be the same.
5634  if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
5635    Diag(New->getLocation(),
5636         diag::err_covariant_return_type_different_qualifications)
5637    << New->getDeclName() << NewTy << OldTy;
5638    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5639    return true;
5640  };
5641
5642
5643  // The new class type must have the same or less qualifiers as the old type.
5644  if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
5645    Diag(New->getLocation(),
5646         diag::err_covariant_return_type_class_type_more_qualified)
5647    << New->getDeclName() << NewTy << OldTy;
5648    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5649    return true;
5650  };
5651
5652  return false;
5653}
5654
5655bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5656                                             const CXXMethodDecl *Old)
5657{
5658  if (Old->hasAttr<FinalAttr>()) {
5659    Diag(New->getLocation(), diag::err_final_function_overridden)
5660      << New->getDeclName();
5661    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5662    return true;
5663  }
5664
5665  return false;
5666}
5667
5668/// \brief Mark the given method pure.
5669///
5670/// \param Method the method to be marked pure.
5671///
5672/// \param InitRange the source range that covers the "0" initializer.
5673bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
5674  if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
5675    Method->setPure();
5676
5677    // A class is abstract if at least one function is pure virtual.
5678    Method->getParent()->setAbstract(true);
5679    return false;
5680  }
5681
5682  if (!Method->isInvalidDecl())
5683    Diag(Method->getLocation(), diag::err_non_virtual_pure)
5684      << Method->getDeclName() << InitRange;
5685  return true;
5686}
5687
5688/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
5689/// an initializer for the out-of-line declaration 'Dcl'.  The scope
5690/// is a fresh scope pushed for just this purpose.
5691///
5692/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5693/// static data member of class X, names should be looked up in the scope of
5694/// class X.
5695void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
5696  // If there is no declaration, there was an error parsing it.
5697  Decl *D = Dcl.getAs<Decl>();
5698  if (D == 0) return;
5699
5700  // We should only get called for declarations with scope specifiers, like:
5701  //   int foo::bar;
5702  assert(D->isOutOfLine());
5703  EnterDeclaratorContext(S, D->getDeclContext());
5704}
5705
5706/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5707/// initializer for the out-of-line declaration 'Dcl'.
5708void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
5709  // If there is no declaration, there was an error parsing it.
5710  Decl *D = Dcl.getAs<Decl>();
5711  if (D == 0) return;
5712
5713  assert(D->isOutOfLine());
5714  ExitDeclaratorContext(S);
5715}
5716
5717/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
5718/// C++ if/switch/while/for statement.
5719/// e.g: "if (int x = f()) {...}"
5720Action::DeclResult
5721Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
5722  // C++ 6.4p2:
5723  // The declarator shall not specify a function or an array.
5724  // The type-specifier-seq shall not contain typedef and shall not declare a
5725  // new class or enumeration.
5726  assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5727         "Parser allowed 'typedef' as storage class of condition decl.");
5728
5729  TypeSourceInfo *TInfo = 0;
5730  TagDecl *OwnedTag = 0;
5731  QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
5732
5733  if (Ty->isFunctionType()) { // The declarator shall not specify a function...
5734                              // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
5735                              // would be created and CXXConditionDeclExpr wants a VarDecl.
5736    Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
5737      << D.getSourceRange();
5738    return DeclResult();
5739  } else if (OwnedTag && OwnedTag->isDefinition()) {
5740    // The type-specifier-seq shall not declare a new class or enumeration.
5741    Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
5742  }
5743
5744  DeclPtrTy Dcl = ActOnDeclarator(S, D);
5745  if (!Dcl)
5746    return DeclResult();
5747
5748  VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
5749  VD->setDeclaredInCondition(true);
5750  return Dcl;
5751}
5752
5753void Sema::MaybeMarkVirtualMembersReferenced(SourceLocation Loc,
5754                                             CXXMethodDecl *MD) {
5755  // Ignore dependent types.
5756  if (MD->isDependentContext())
5757    return;
5758
5759  CXXRecordDecl *RD = MD->getParent();
5760
5761  // Ignore classes without a vtable.
5762  if (!RD->isDynamicClass())
5763    return;
5764
5765  // Ignore declarations that are not definitions.
5766  if (!MD->isThisDeclarationADefinition())
5767    return;
5768
5769  if (isa<CXXConstructorDecl>(MD)) {
5770    switch (MD->getParent()->getTemplateSpecializationKind()) {
5771    case TSK_Undeclared:
5772    case TSK_ExplicitSpecialization:
5773      // Classes that aren't instantiations of templates don't need their
5774      // virtual methods marked until we see the definition of the key
5775      // function.
5776      return;
5777
5778    case TSK_ImplicitInstantiation:
5779    case TSK_ExplicitInstantiationDeclaration:
5780    case TSK_ExplicitInstantiationDefinition:
5781      // This is a constructor of a class template; mark all of the virtual
5782      // members as referenced to ensure that they get instantiatied.
5783      break;
5784    }
5785  } else if (!MD->isOutOfLine()) {
5786    // Consider only out-of-line definitions of member functions. When we see
5787    // an inline definition, it's too early to compute the key function.
5788    return;
5789  } else if (const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD)) {
5790    // If this is not the key function, we don't need to mark virtual members.
5791    if (KeyFunction->getCanonicalDecl() != MD->getCanonicalDecl())
5792      return;
5793  } else {
5794    // The class has no key function, so we've already noted that we need to
5795    // mark the virtual members of this class.
5796    return;
5797  }
5798
5799  // We will need to mark all of the virtual members as referenced to build the
5800  // vtable.
5801  ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(RD, Loc));
5802}
5803
5804bool Sema::ProcessPendingClassesWithUnmarkedVirtualMembers() {
5805  if (ClassesWithUnmarkedVirtualMembers.empty())
5806    return false;
5807
5808  while (!ClassesWithUnmarkedVirtualMembers.empty()) {
5809    CXXRecordDecl *RD = ClassesWithUnmarkedVirtualMembers.back().first;
5810    SourceLocation Loc = ClassesWithUnmarkedVirtualMembers.back().second;
5811    ClassesWithUnmarkedVirtualMembers.pop_back();
5812    MarkVirtualMembersReferenced(Loc, RD);
5813  }
5814
5815  return true;
5816}
5817
5818void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, CXXRecordDecl *RD) {
5819  for (CXXRecordDecl::method_iterator i = RD->method_begin(),
5820       e = RD->method_end(); i != e; ++i) {
5821    CXXMethodDecl *MD = *i;
5822
5823    // C++ [basic.def.odr]p2:
5824    //   [...] A virtual member function is used if it is not pure. [...]
5825    if (MD->isVirtual() && !MD->isPure())
5826      MarkDeclarationReferenced(Loc, MD);
5827  }
5828}
5829
5830