SemaDeclCXX.cpp revision 4f9506a27cb6b865bf38beea48eadfa9dc93f510
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, QualType DeclInitType) {
3986  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
3987                                  DeclInitType->getAs<RecordType>()->getDecl());
3988  if (!ClassDecl->hasTrivialDestructor()) {
3989    CXXDestructorDecl *Destructor = ClassDecl->getDestructor(Context);
3990    MarkDeclarationReferenced(VD->getLocation(), Destructor);
3991    CheckDestructorAccess(VD->getLocation(), VD->getType());
3992  }
3993}
3994
3995/// AddCXXDirectInitializerToDecl - This action is called immediately after
3996/// ActOnDeclarator, when a C++ direct initializer is present.
3997/// e.g: "int x(1);"
3998void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
3999                                         SourceLocation LParenLoc,
4000                                         MultiExprArg Exprs,
4001                                         SourceLocation *CommaLocs,
4002                                         SourceLocation RParenLoc) {
4003  assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
4004  Decl *RealDecl = Dcl.getAs<Decl>();
4005
4006  // If there is no declaration, there was an error parsing it.  Just ignore
4007  // the initializer.
4008  if (RealDecl == 0)
4009    return;
4010
4011  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
4012  if (!VDecl) {
4013    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
4014    RealDecl->setInvalidDecl();
4015    return;
4016  }
4017
4018  // We will represent direct-initialization similarly to copy-initialization:
4019  //    int x(1);  -as-> int x = 1;
4020  //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
4021  //
4022  // Clients that want to distinguish between the two forms, can check for
4023  // direct initializer using VarDecl::hasCXXDirectInitializer().
4024  // A major benefit is that clients that don't particularly care about which
4025  // exactly form was it (like the CodeGen) can handle both cases without
4026  // special case code.
4027
4028  // If either the declaration has a dependent type or if any of the expressions
4029  // is type-dependent, we represent the initialization via a ParenListExpr for
4030  // later use during template instantiation.
4031  if (VDecl->getType()->isDependentType() ||
4032      Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
4033    // Let clients know that initialization was done with a direct initializer.
4034    VDecl->setCXXDirectInitializer(true);
4035
4036    // Store the initialization expressions as a ParenListExpr.
4037    unsigned NumExprs = Exprs.size();
4038    VDecl->setInit(Context,
4039                   new (Context) ParenListExpr(Context, LParenLoc,
4040                                               (Expr **)Exprs.release(),
4041                                               NumExprs, RParenLoc));
4042    return;
4043  }
4044
4045
4046  // C++ 8.5p11:
4047  // The form of initialization (using parentheses or '=') is generally
4048  // insignificant, but does matter when the entity being initialized has a
4049  // class type.
4050  QualType DeclInitType = VDecl->getType();
4051  if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
4052    DeclInitType = Context.getBaseElementType(Array);
4053
4054  if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
4055                          diag::err_typecheck_decl_incomplete_type)) {
4056    VDecl->setInvalidDecl();
4057    return;
4058  }
4059
4060  // The variable can not have an abstract class type.
4061  if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
4062                             diag::err_abstract_type_in_decl,
4063                             AbstractVariableType))
4064    VDecl->setInvalidDecl();
4065
4066  const VarDecl *Def;
4067  if ((Def = VDecl->getDefinition()) && Def != VDecl) {
4068    Diag(VDecl->getLocation(), diag::err_redefinition)
4069    << VDecl->getDeclName();
4070    Diag(Def->getLocation(), diag::note_previous_definition);
4071    VDecl->setInvalidDecl();
4072    return;
4073  }
4074
4075  // Capture the variable that is being initialized and the style of
4076  // initialization.
4077  InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
4078
4079  // FIXME: Poor source location information.
4080  InitializationKind Kind
4081    = InitializationKind::CreateDirect(VDecl->getLocation(),
4082                                       LParenLoc, RParenLoc);
4083
4084  InitializationSequence InitSeq(*this, Entity, Kind,
4085                                 (Expr**)Exprs.get(), Exprs.size());
4086  OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
4087  if (Result.isInvalid()) {
4088    VDecl->setInvalidDecl();
4089    return;
4090  }
4091
4092  Result = MaybeCreateCXXExprWithTemporaries(move(Result));
4093  VDecl->setInit(Context, Result.takeAs<Expr>());
4094  VDecl->setCXXDirectInitializer(true);
4095
4096  if (VDecl->getType()->getAs<RecordType>())
4097    FinalizeVarWithDestructor(VDecl, DeclInitType);
4098}
4099
4100/// \brief Add the applicable constructor candidates for an initialization
4101/// by constructor.
4102static void AddConstructorInitializationCandidates(Sema &SemaRef,
4103                                                   QualType ClassType,
4104                                                   Expr **Args,
4105                                                   unsigned NumArgs,
4106                                                   InitializationKind Kind,
4107                                           OverloadCandidateSet &CandidateSet) {
4108  // C++ [dcl.init]p14:
4109  //   If the initialization is direct-initialization, or if it is
4110  //   copy-initialization where the cv-unqualified version of the
4111  //   source type is the same class as, or a derived class of, the
4112  //   class of the destination, constructors are considered. The
4113  //   applicable constructors are enumerated (13.3.1.3), and the
4114  //   best one is chosen through overload resolution (13.3). The
4115  //   constructor so selected is called to initialize the object,
4116  //   with the initializer expression(s) as its argument(s). If no
4117  //   constructor applies, or the overload resolution is ambiguous,
4118  //   the initialization is ill-formed.
4119  const RecordType *ClassRec = ClassType->getAs<RecordType>();
4120  assert(ClassRec && "Can only initialize a class type here");
4121
4122  // FIXME: When we decide not to synthesize the implicitly-declared
4123  // constructors, we'll need to make them appear here.
4124
4125  const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
4126  DeclarationName ConstructorName
4127    = SemaRef.Context.DeclarationNames.getCXXConstructorName(
4128              SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType());
4129  DeclContext::lookup_const_iterator Con, ConEnd;
4130  for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
4131       Con != ConEnd; ++Con) {
4132    // Find the constructor (which may be a template).
4133    CXXConstructorDecl *Constructor = 0;
4134    FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
4135    if (ConstructorTmpl)
4136      Constructor
4137      = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
4138    else
4139      Constructor = cast<CXXConstructorDecl>(*Con);
4140
4141    if ((Kind.getKind() == InitializationKind::IK_Direct) ||
4142        (Kind.getKind() == InitializationKind::IK_Value) ||
4143        (Kind.getKind() == InitializationKind::IK_Copy &&
4144         Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
4145        ((Kind.getKind() == InitializationKind::IK_Default) &&
4146         Constructor->isDefaultConstructor())) {
4147      if (ConstructorTmpl)
4148        SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl,
4149                                             ConstructorTmpl->getAccess(),
4150                                             /*ExplicitArgs*/ 0,
4151                                             Args, NumArgs, CandidateSet);
4152      else
4153        SemaRef.AddOverloadCandidate(Constructor, Constructor->getAccess(),
4154                                     Args, NumArgs, CandidateSet);
4155    }
4156  }
4157}
4158
4159/// \brief Attempt to perform initialization by constructor
4160/// (C++ [dcl.init]p14), which may occur as part of direct-initialization or
4161/// copy-initialization.
4162///
4163/// This routine determines whether initialization by constructor is possible,
4164/// but it does not emit any diagnostics in the case where the initialization
4165/// is ill-formed.
4166///
4167/// \param ClassType the type of the object being initialized, which must have
4168/// class type.
4169///
4170/// \param Args the arguments provided to initialize the object
4171///
4172/// \param NumArgs the number of arguments provided to initialize the object
4173///
4174/// \param Kind the type of initialization being performed
4175///
4176/// \returns the constructor used to initialize the object, if successful.
4177/// Otherwise, emits a diagnostic and returns NULL.
4178CXXConstructorDecl *
4179Sema::TryInitializationByConstructor(QualType ClassType,
4180                                     Expr **Args, unsigned NumArgs,
4181                                     SourceLocation Loc,
4182                                     InitializationKind Kind) {
4183  // Build the overload candidate set
4184  OverloadCandidateSet CandidateSet;
4185  AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
4186                                         CandidateSet);
4187
4188  // Determine whether we found a constructor we can use.
4189  OverloadCandidateSet::iterator Best;
4190  switch (BestViableFunction(CandidateSet, Loc, Best)) {
4191    case OR_Success:
4192    case OR_Deleted:
4193      // We found a constructor. Return it.
4194      return cast<CXXConstructorDecl>(Best->Function);
4195
4196    case OR_No_Viable_Function:
4197    case OR_Ambiguous:
4198      // Overload resolution failed. Return nothing.
4199      return 0;
4200  }
4201
4202  // Silence GCC warning
4203  return 0;
4204}
4205
4206/// \brief Given a constructor and the set of arguments provided for the
4207/// constructor, convert the arguments and add any required default arguments
4208/// to form a proper call to this constructor.
4209///
4210/// \returns true if an error occurred, false otherwise.
4211bool
4212Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
4213                              MultiExprArg ArgsPtr,
4214                              SourceLocation Loc,
4215                     ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
4216  // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
4217  unsigned NumArgs = ArgsPtr.size();
4218  Expr **Args = (Expr **)ArgsPtr.get();
4219
4220  const FunctionProtoType *Proto
4221    = Constructor->getType()->getAs<FunctionProtoType>();
4222  assert(Proto && "Constructor without a prototype?");
4223  unsigned NumArgsInProto = Proto->getNumArgs();
4224
4225  // If too few arguments are available, we'll fill in the rest with defaults.
4226  if (NumArgs < NumArgsInProto)
4227    ConvertedArgs.reserve(NumArgsInProto);
4228  else
4229    ConvertedArgs.reserve(NumArgs);
4230
4231  VariadicCallType CallType =
4232    Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4233  llvm::SmallVector<Expr *, 8> AllArgs;
4234  bool Invalid = GatherArgumentsForCall(Loc, Constructor,
4235                                        Proto, 0, Args, NumArgs, AllArgs,
4236                                        CallType);
4237  for (unsigned i =0, size = AllArgs.size(); i < size; i++)
4238    ConvertedArgs.push_back(AllArgs[i]);
4239  return Invalid;
4240}
4241
4242/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4243/// determine whether they are reference-related,
4244/// reference-compatible, reference-compatible with added
4245/// qualification, or incompatible, for use in C++ initialization by
4246/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4247/// type, and the first type (T1) is the pointee type of the reference
4248/// type being initialized.
4249Sema::ReferenceCompareResult
4250Sema::CompareReferenceRelationship(SourceLocation Loc,
4251                                   QualType OrigT1, QualType OrigT2,
4252                                   bool& DerivedToBase) {
4253  assert(!OrigT1->isReferenceType() &&
4254    "T1 must be the pointee type of the reference type");
4255  assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4256
4257  QualType T1 = Context.getCanonicalType(OrigT1);
4258  QualType T2 = Context.getCanonicalType(OrigT2);
4259  Qualifiers T1Quals, T2Quals;
4260  QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4261  QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4262
4263  // C++ [dcl.init.ref]p4:
4264  //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4265  //   reference-related to "cv2 T2" if T1 is the same type as T2, or
4266  //   T1 is a base class of T2.
4267  if (UnqualT1 == UnqualT2)
4268    DerivedToBase = false;
4269  else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
4270           !RequireCompleteType(Loc, OrigT2, PDiag()) &&
4271           IsDerivedFrom(UnqualT2, UnqualT1))
4272    DerivedToBase = true;
4273  else
4274    return Ref_Incompatible;
4275
4276  // At this point, we know that T1 and T2 are reference-related (at
4277  // least).
4278
4279  // If the type is an array type, promote the element qualifiers to the type
4280  // for comparison.
4281  if (isa<ArrayType>(T1) && T1Quals)
4282    T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4283  if (isa<ArrayType>(T2) && T2Quals)
4284    T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4285
4286  // C++ [dcl.init.ref]p4:
4287  //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4288  //   reference-related to T2 and cv1 is the same cv-qualification
4289  //   as, or greater cv-qualification than, cv2. For purposes of
4290  //   overload resolution, cases for which cv1 is greater
4291  //   cv-qualification than cv2 are identified as
4292  //   reference-compatible with added qualification (see 13.3.3.2).
4293  if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
4294    return Ref_Compatible;
4295  else if (T1.isMoreQualifiedThan(T2))
4296    return Ref_Compatible_With_Added_Qualification;
4297  else
4298    return Ref_Related;
4299}
4300
4301/// CheckReferenceInit - Check the initialization of a reference
4302/// variable with the given initializer (C++ [dcl.init.ref]). Init is
4303/// the initializer (either a simple initializer or an initializer
4304/// list), and DeclType is the type of the declaration. When ICS is
4305/// non-null, this routine will compute the implicit conversion
4306/// sequence according to C++ [over.ics.ref] and will not produce any
4307/// diagnostics; when ICS is null, it will emit diagnostics when any
4308/// errors are found. Either way, a return value of true indicates
4309/// that there was a failure, a return value of false indicates that
4310/// the reference initialization succeeded.
4311///
4312/// When @p SuppressUserConversions, user-defined conversions are
4313/// suppressed.
4314/// When @p AllowExplicit, we also permit explicit user-defined
4315/// conversion functions.
4316/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
4317/// When @p IgnoreBaseAccess, we don't do access control on to-base conversion.
4318/// This is used when this is called from a C-style cast.
4319bool
4320Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
4321                         SourceLocation DeclLoc,
4322                         bool SuppressUserConversions,
4323                         bool AllowExplicit, bool ForceRValue,
4324                         ImplicitConversionSequence *ICS,
4325                         bool IgnoreBaseAccess) {
4326  assert(DeclType->isReferenceType() && "Reference init needs a reference");
4327
4328  QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4329  QualType T2 = Init->getType();
4330
4331  // If the initializer is the address of an overloaded function, try
4332  // to resolve the overloaded function. If all goes well, T2 is the
4333  // type of the resulting function.
4334  if (Context.getCanonicalType(T2) == Context.OverloadTy) {
4335    FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
4336                                                          ICS != 0);
4337    if (Fn) {
4338      // Since we're performing this reference-initialization for
4339      // real, update the initializer with the resulting function.
4340      if (!ICS) {
4341        if (DiagnoseUseOfDecl(Fn, DeclLoc))
4342          return true;
4343
4344        Init = FixOverloadedFunctionReference(Init, Fn);
4345      }
4346
4347      T2 = Fn->getType();
4348    }
4349  }
4350
4351  // Compute some basic properties of the types and the initializer.
4352  bool isRValRef = DeclType->isRValueReferenceType();
4353  bool DerivedToBase = false;
4354  Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
4355                                                  Init->isLvalue(Context);
4356  ReferenceCompareResult RefRelationship
4357    = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
4358
4359  // Most paths end in a failed conversion.
4360  if (ICS) {
4361    ICS->setBad();
4362    ICS->Bad.init(BadConversionSequence::no_conversion, Init, DeclType);
4363  }
4364
4365  // C++ [dcl.init.ref]p5:
4366  //   A reference to type "cv1 T1" is initialized by an expression
4367  //   of type "cv2 T2" as follows:
4368
4369  //     -- If the initializer expression
4370
4371  // Rvalue references cannot bind to lvalues (N2812).
4372  // There is absolutely no situation where they can. In particular, note that
4373  // this is ill-formed, even if B has a user-defined conversion to A&&:
4374  //   B b;
4375  //   A&& r = b;
4376  if (isRValRef && InitLvalue == Expr::LV_Valid) {
4377    if (!ICS)
4378      Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4379        << Init->getSourceRange();
4380    return true;
4381  }
4382
4383  bool BindsDirectly = false;
4384  //       -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4385  //          reference-compatible with "cv2 T2," or
4386  //
4387  // Note that the bit-field check is skipped if we are just computing
4388  // the implicit conversion sequence (C++ [over.best.ics]p2).
4389  if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
4390      RefRelationship >= Ref_Compatible_With_Added_Qualification) {
4391    BindsDirectly = true;
4392
4393    if (ICS) {
4394      // C++ [over.ics.ref]p1:
4395      //   When a parameter of reference type binds directly (8.5.3)
4396      //   to an argument expression, the implicit conversion sequence
4397      //   is the identity conversion, unless the argument expression
4398      //   has a type that is a derived class of the parameter type,
4399      //   in which case the implicit conversion sequence is a
4400      //   derived-to-base Conversion (13.3.3.1).
4401      ICS->setStandard();
4402      ICS->Standard.First = ICK_Identity;
4403      ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4404      ICS->Standard.Third = ICK_Identity;
4405      ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
4406      ICS->Standard.setToType(0, T2);
4407      ICS->Standard.setToType(1, T1);
4408      ICS->Standard.setToType(2, T1);
4409      ICS->Standard.ReferenceBinding = true;
4410      ICS->Standard.DirectBinding = true;
4411      ICS->Standard.RRefBinding = false;
4412      ICS->Standard.CopyConstructor = 0;
4413
4414      // Nothing more to do: the inaccessibility/ambiguity check for
4415      // derived-to-base conversions is suppressed when we're
4416      // computing the implicit conversion sequence (C++
4417      // [over.best.ics]p2).
4418      return false;
4419    } else {
4420      // Perform the conversion.
4421      CastExpr::CastKind CK = CastExpr::CK_NoOp;
4422      if (DerivedToBase)
4423        CK = CastExpr::CK_DerivedToBase;
4424      else if(CheckExceptionSpecCompatibility(Init, T1))
4425        return true;
4426      ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
4427    }
4428  }
4429
4430  //       -- has a class type (i.e., T2 is a class type) and can be
4431  //          implicitly converted to an lvalue of type "cv3 T3,"
4432  //          where "cv1 T1" is reference-compatible with "cv3 T3"
4433  //          92) (this conversion is selected by enumerating the
4434  //          applicable conversion functions (13.3.1.6) and choosing
4435  //          the best one through overload resolution (13.3)),
4436  if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
4437      !RequireCompleteType(DeclLoc, T2, 0)) {
4438    CXXRecordDecl *T2RecordDecl
4439      = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4440
4441    OverloadCandidateSet CandidateSet;
4442    const UnresolvedSetImpl *Conversions
4443      = T2RecordDecl->getVisibleConversionFunctions();
4444    for (UnresolvedSetImpl::iterator I = Conversions->begin(),
4445           E = Conversions->end(); I != E; ++I) {
4446      NamedDecl *D = *I;
4447      CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4448      if (isa<UsingShadowDecl>(D))
4449        D = cast<UsingShadowDecl>(D)->getTargetDecl();
4450
4451      FunctionTemplateDecl *ConvTemplate
4452        = dyn_cast<FunctionTemplateDecl>(D);
4453      CXXConversionDecl *Conv;
4454      if (ConvTemplate)
4455        Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4456      else
4457        Conv = cast<CXXConversionDecl>(D);
4458
4459      // If the conversion function doesn't return a reference type,
4460      // it can't be considered for this conversion.
4461      if (Conv->getConversionType()->isLValueReferenceType() &&
4462          (AllowExplicit || !Conv->isExplicit())) {
4463        if (ConvTemplate)
4464          AddTemplateConversionCandidate(ConvTemplate, I.getAccess(), ActingDC,
4465                                         Init, DeclType, CandidateSet);
4466        else
4467          AddConversionCandidate(Conv, I.getAccess(), ActingDC, Init,
4468                                 DeclType, CandidateSet);
4469      }
4470    }
4471
4472    OverloadCandidateSet::iterator Best;
4473    switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
4474    case OR_Success:
4475      // This is a direct binding.
4476      BindsDirectly = true;
4477
4478      if (ICS) {
4479        // C++ [over.ics.ref]p1:
4480        //
4481        //   [...] If the parameter binds directly to the result of
4482        //   applying a conversion function to the argument
4483        //   expression, the implicit conversion sequence is a
4484        //   user-defined conversion sequence (13.3.3.1.2), with the
4485        //   second standard conversion sequence either an identity
4486        //   conversion or, if the conversion function returns an
4487        //   entity of a type that is a derived class of the parameter
4488        //   type, a derived-to-base Conversion.
4489        ICS->setUserDefined();
4490        ICS->UserDefined.Before = Best->Conversions[0].Standard;
4491        ICS->UserDefined.After = Best->FinalConversion;
4492        ICS->UserDefined.ConversionFunction = Best->Function;
4493        ICS->UserDefined.EllipsisConversion = false;
4494        assert(ICS->UserDefined.After.ReferenceBinding &&
4495               ICS->UserDefined.After.DirectBinding &&
4496               "Expected a direct reference binding!");
4497        return false;
4498      } else {
4499        OwningExprResult InitConversion =
4500          BuildCXXCastArgument(DeclLoc, QualType(),
4501                               CastExpr::CK_UserDefinedConversion,
4502                               cast<CXXMethodDecl>(Best->Function),
4503                               Owned(Init));
4504        Init = InitConversion.takeAs<Expr>();
4505
4506        if (CheckExceptionSpecCompatibility(Init, T1))
4507          return true;
4508        ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
4509                          /*isLvalue=*/true);
4510      }
4511      break;
4512
4513    case OR_Ambiguous:
4514      if (ICS) {
4515        ICS->setAmbiguous();
4516        for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4517             Cand != CandidateSet.end(); ++Cand)
4518          if (Cand->Viable)
4519            ICS->Ambiguous.addConversion(Cand->Function);
4520        break;
4521      }
4522      Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
4523            << Init->getSourceRange();
4524      PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Init, 1);
4525      return true;
4526
4527    case OR_No_Viable_Function:
4528    case OR_Deleted:
4529      // There was no suitable conversion, or we found a deleted
4530      // conversion; continue with other checks.
4531      break;
4532    }
4533  }
4534
4535  if (BindsDirectly) {
4536    // C++ [dcl.init.ref]p4:
4537    //   [...] In all cases where the reference-related or
4538    //   reference-compatible relationship of two types is used to
4539    //   establish the validity of a reference binding, and T1 is a
4540    //   base class of T2, a program that necessitates such a binding
4541    //   is ill-formed if T1 is an inaccessible (clause 11) or
4542    //   ambiguous (10.2) base class of T2.
4543    //
4544    // Note that we only check this condition when we're allowed to
4545    // complain about errors, because we should not be checking for
4546    // ambiguity (or inaccessibility) unless the reference binding
4547    // actually happens.
4548    if (DerivedToBase)
4549      return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
4550                                          Init->getSourceRange(),
4551                                          IgnoreBaseAccess);
4552    else
4553      return false;
4554  }
4555
4556  //     -- Otherwise, the reference shall be to a non-volatile const
4557  //        type (i.e., cv1 shall be const), or the reference shall be an
4558  //        rvalue reference and the initializer expression shall be an rvalue.
4559  if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
4560    if (!ICS)
4561      Diag(DeclLoc, diag::err_not_reference_to_const_init)
4562        << T1.isVolatileQualified()
4563        << T1 << int(InitLvalue != Expr::LV_Valid)
4564        << T2 << Init->getSourceRange();
4565    return true;
4566  }
4567
4568  //       -- If the initializer expression is an rvalue, with T2 a
4569  //          class type, and "cv1 T1" is reference-compatible with
4570  //          "cv2 T2," the reference is bound in one of the
4571  //          following ways (the choice is implementation-defined):
4572  //
4573  //          -- The reference is bound to the object represented by
4574  //             the rvalue (see 3.10) or to a sub-object within that
4575  //             object.
4576  //
4577  //          -- A temporary of type "cv1 T2" [sic] is created, and
4578  //             a constructor is called to copy the entire rvalue
4579  //             object into the temporary. The reference is bound to
4580  //             the temporary or to a sub-object within the
4581  //             temporary.
4582  //
4583  //          The constructor that would be used to make the copy
4584  //          shall be callable whether or not the copy is actually
4585  //          done.
4586  //
4587  // Note that C++0x [dcl.init.ref]p5 takes away this implementation
4588  // freedom, so we will always take the first option and never build
4589  // a temporary in this case. FIXME: We will, however, have to check
4590  // for the presence of a copy constructor in C++98/03 mode.
4591  if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
4592      RefRelationship >= Ref_Compatible_With_Added_Qualification) {
4593    if (ICS) {
4594      ICS->setStandard();
4595      ICS->Standard.First = ICK_Identity;
4596      ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4597      ICS->Standard.Third = ICK_Identity;
4598      ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
4599      ICS->Standard.setToType(0, T2);
4600      ICS->Standard.setToType(1, T1);
4601      ICS->Standard.setToType(2, T1);
4602      ICS->Standard.ReferenceBinding = true;
4603      ICS->Standard.DirectBinding = false;
4604      ICS->Standard.RRefBinding = isRValRef;
4605      ICS->Standard.CopyConstructor = 0;
4606    } else {
4607      CastExpr::CastKind CK = CastExpr::CK_NoOp;
4608      if (DerivedToBase)
4609        CK = CastExpr::CK_DerivedToBase;
4610      else if(CheckExceptionSpecCompatibility(Init, T1))
4611        return true;
4612      ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
4613    }
4614    return false;
4615  }
4616
4617  //       -- Otherwise, a temporary of type "cv1 T1" is created and
4618  //          initialized from the initializer expression using the
4619  //          rules for a non-reference copy initialization (8.5). The
4620  //          reference is then bound to the temporary. If T1 is
4621  //          reference-related to T2, cv1 must be the same
4622  //          cv-qualification as, or greater cv-qualification than,
4623  //          cv2; otherwise, the program is ill-formed.
4624  if (RefRelationship == Ref_Related) {
4625    // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4626    // we would be reference-compatible or reference-compatible with
4627    // added qualification. But that wasn't the case, so the reference
4628    // initialization fails.
4629    if (!ICS)
4630      Diag(DeclLoc, diag::err_reference_init_drops_quals)
4631        << T1 << int(InitLvalue != Expr::LV_Valid)
4632        << T2 << Init->getSourceRange();
4633    return true;
4634  }
4635
4636  // If at least one of the types is a class type, the types are not
4637  // related, and we aren't allowed any user conversions, the
4638  // reference binding fails. This case is important for breaking
4639  // recursion, since TryImplicitConversion below will attempt to
4640  // create a temporary through the use of a copy constructor.
4641  if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
4642      (T1->isRecordType() || T2->isRecordType())) {
4643    if (!ICS)
4644      Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
4645        << DeclType << Init->getType() << AA_Initializing << Init->getSourceRange();
4646    return true;
4647  }
4648
4649  // Actually try to convert the initializer to T1.
4650  if (ICS) {
4651    // C++ [over.ics.ref]p2:
4652    //
4653    //   When a parameter of reference type is not bound directly to
4654    //   an argument expression, the conversion sequence is the one
4655    //   required to convert the argument expression to the
4656    //   underlying type of the reference according to
4657    //   13.3.3.1. Conceptually, this conversion sequence corresponds
4658    //   to copy-initializing a temporary of the underlying type with
4659    //   the argument expression. Any difference in top-level
4660    //   cv-qualification is subsumed by the initialization itself
4661    //   and does not constitute a conversion.
4662    *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
4663                                 /*AllowExplicit=*/false,
4664                                 /*ForceRValue=*/false,
4665                                 /*InOverloadResolution=*/false);
4666
4667    // Of course, that's still a reference binding.
4668    if (ICS->isStandard()) {
4669      ICS->Standard.ReferenceBinding = true;
4670      ICS->Standard.RRefBinding = isRValRef;
4671    } else if (ICS->isUserDefined()) {
4672      ICS->UserDefined.After.ReferenceBinding = true;
4673      ICS->UserDefined.After.RRefBinding = isRValRef;
4674    }
4675    return ICS->isBad();
4676  } else {
4677    ImplicitConversionSequence Conversions;
4678    bool badConversion = PerformImplicitConversion(Init, T1, AA_Initializing,
4679                                                   false, false,
4680                                                   Conversions);
4681    if (badConversion) {
4682      if (Conversions.isAmbiguous()) {
4683        Diag(DeclLoc,
4684             diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
4685        for (int j = Conversions.Ambiguous.conversions().size()-1;
4686             j >= 0; j--) {
4687          FunctionDecl *Func = Conversions.Ambiguous.conversions()[j];
4688          NoteOverloadCandidate(Func);
4689        }
4690      }
4691      else {
4692        if (isRValRef)
4693          Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4694            << Init->getSourceRange();
4695        else
4696          Diag(DeclLoc, diag::err_invalid_initialization)
4697            << DeclType << Init->getType() << Init->getSourceRange();
4698      }
4699    }
4700    return badConversion;
4701  }
4702}
4703
4704static inline bool
4705CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
4706                                       const FunctionDecl *FnDecl) {
4707  const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
4708  if (isa<NamespaceDecl>(DC)) {
4709    return SemaRef.Diag(FnDecl->getLocation(),
4710                        diag::err_operator_new_delete_declared_in_namespace)
4711      << FnDecl->getDeclName();
4712  }
4713
4714  if (isa<TranslationUnitDecl>(DC) &&
4715      FnDecl->getStorageClass() == FunctionDecl::Static) {
4716    return SemaRef.Diag(FnDecl->getLocation(),
4717                        diag::err_operator_new_delete_declared_static)
4718      << FnDecl->getDeclName();
4719  }
4720
4721  return false;
4722}
4723
4724static inline bool
4725CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
4726                            CanQualType ExpectedResultType,
4727                            CanQualType ExpectedFirstParamType,
4728                            unsigned DependentParamTypeDiag,
4729                            unsigned InvalidParamTypeDiag) {
4730  QualType ResultType =
4731    FnDecl->getType()->getAs<FunctionType>()->getResultType();
4732
4733  // Check that the result type is not dependent.
4734  if (ResultType->isDependentType())
4735    return SemaRef.Diag(FnDecl->getLocation(),
4736                        diag::err_operator_new_delete_dependent_result_type)
4737    << FnDecl->getDeclName() << ExpectedResultType;
4738
4739  // Check that the result type is what we expect.
4740  if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
4741    return SemaRef.Diag(FnDecl->getLocation(),
4742                        diag::err_operator_new_delete_invalid_result_type)
4743    << FnDecl->getDeclName() << ExpectedResultType;
4744
4745  // A function template must have at least 2 parameters.
4746  if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
4747    return SemaRef.Diag(FnDecl->getLocation(),
4748                      diag::err_operator_new_delete_template_too_few_parameters)
4749        << FnDecl->getDeclName();
4750
4751  // The function decl must have at least 1 parameter.
4752  if (FnDecl->getNumParams() == 0)
4753    return SemaRef.Diag(FnDecl->getLocation(),
4754                        diag::err_operator_new_delete_too_few_parameters)
4755      << FnDecl->getDeclName();
4756
4757  // Check the the first parameter type is not dependent.
4758  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4759  if (FirstParamType->isDependentType())
4760    return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
4761      << FnDecl->getDeclName() << ExpectedFirstParamType;
4762
4763  // Check that the first parameter type is what we expect.
4764  if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
4765      ExpectedFirstParamType)
4766    return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
4767    << FnDecl->getDeclName() << ExpectedFirstParamType;
4768
4769  return false;
4770}
4771
4772static bool
4773CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
4774  // C++ [basic.stc.dynamic.allocation]p1:
4775  //   A program is ill-formed if an allocation function is declared in a
4776  //   namespace scope other than global scope or declared static in global
4777  //   scope.
4778  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4779    return true;
4780
4781  CanQualType SizeTy =
4782    SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
4783
4784  // C++ [basic.stc.dynamic.allocation]p1:
4785  //  The return type shall be void*. The first parameter shall have type
4786  //  std::size_t.
4787  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
4788                                  SizeTy,
4789                                  diag::err_operator_new_dependent_param_type,
4790                                  diag::err_operator_new_param_type))
4791    return true;
4792
4793  // C++ [basic.stc.dynamic.allocation]p1:
4794  //  The first parameter shall not have an associated default argument.
4795  if (FnDecl->getParamDecl(0)->hasDefaultArg())
4796    return SemaRef.Diag(FnDecl->getLocation(),
4797                        diag::err_operator_new_default_arg)
4798      << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
4799
4800  return false;
4801}
4802
4803static bool
4804CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
4805  // C++ [basic.stc.dynamic.deallocation]p1:
4806  //   A program is ill-formed if deallocation functions are declared in a
4807  //   namespace scope other than global scope or declared static in global
4808  //   scope.
4809  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4810    return true;
4811
4812  // C++ [basic.stc.dynamic.deallocation]p2:
4813  //   Each deallocation function shall return void and its first parameter
4814  //   shall be void*.
4815  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
4816                                  SemaRef.Context.VoidPtrTy,
4817                                 diag::err_operator_delete_dependent_param_type,
4818                                 diag::err_operator_delete_param_type))
4819    return true;
4820
4821  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4822  if (FirstParamType->isDependentType())
4823    return SemaRef.Diag(FnDecl->getLocation(),
4824                        diag::err_operator_delete_dependent_param_type)
4825    << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
4826
4827  if (SemaRef.Context.getCanonicalType(FirstParamType) !=
4828      SemaRef.Context.VoidPtrTy)
4829    return SemaRef.Diag(FnDecl->getLocation(),
4830                        diag::err_operator_delete_param_type)
4831      << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
4832
4833  return false;
4834}
4835
4836/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4837/// of this overloaded operator is well-formed. If so, returns false;
4838/// otherwise, emits appropriate diagnostics and returns true.
4839bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
4840  assert(FnDecl && FnDecl->isOverloadedOperator() &&
4841         "Expected an overloaded operator declaration");
4842
4843  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4844
4845  // C++ [over.oper]p5:
4846  //   The allocation and deallocation functions, operator new,
4847  //   operator new[], operator delete and operator delete[], are
4848  //   described completely in 3.7.3. The attributes and restrictions
4849  //   found in the rest of this subclause do not apply to them unless
4850  //   explicitly stated in 3.7.3.
4851  if (Op == OO_Delete || Op == OO_Array_Delete)
4852    return CheckOperatorDeleteDeclaration(*this, FnDecl);
4853
4854  if (Op == OO_New || Op == OO_Array_New)
4855    return CheckOperatorNewDeclaration(*this, FnDecl);
4856
4857  // C++ [over.oper]p6:
4858  //   An operator function shall either be a non-static member
4859  //   function or be a non-member function and have at least one
4860  //   parameter whose type is a class, a reference to a class, an
4861  //   enumeration, or a reference to an enumeration.
4862  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4863    if (MethodDecl->isStatic())
4864      return Diag(FnDecl->getLocation(),
4865                  diag::err_operator_overload_static) << FnDecl->getDeclName();
4866  } else {
4867    bool ClassOrEnumParam = false;
4868    for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4869                                   ParamEnd = FnDecl->param_end();
4870         Param != ParamEnd; ++Param) {
4871      QualType ParamType = (*Param)->getType().getNonReferenceType();
4872      if (ParamType->isDependentType() || ParamType->isRecordType() ||
4873          ParamType->isEnumeralType()) {
4874        ClassOrEnumParam = true;
4875        break;
4876      }
4877    }
4878
4879    if (!ClassOrEnumParam)
4880      return Diag(FnDecl->getLocation(),
4881                  diag::err_operator_overload_needs_class_or_enum)
4882        << FnDecl->getDeclName();
4883  }
4884
4885  // C++ [over.oper]p8:
4886  //   An operator function cannot have default arguments (8.3.6),
4887  //   except where explicitly stated below.
4888  //
4889  // Only the function-call operator allows default arguments
4890  // (C++ [over.call]p1).
4891  if (Op != OO_Call) {
4892    for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4893         Param != FnDecl->param_end(); ++Param) {
4894      if ((*Param)->hasDefaultArg())
4895        return Diag((*Param)->getLocation(),
4896                    diag::err_operator_overload_default_arg)
4897          << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
4898    }
4899  }
4900
4901  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4902    { false, false, false }
4903#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4904    , { Unary, Binary, MemberOnly }
4905#include "clang/Basic/OperatorKinds.def"
4906  };
4907
4908  bool CanBeUnaryOperator = OperatorUses[Op][0];
4909  bool CanBeBinaryOperator = OperatorUses[Op][1];
4910  bool MustBeMemberOperator = OperatorUses[Op][2];
4911
4912  // C++ [over.oper]p8:
4913  //   [...] Operator functions cannot have more or fewer parameters
4914  //   than the number required for the corresponding operator, as
4915  //   described in the rest of this subclause.
4916  unsigned NumParams = FnDecl->getNumParams()
4917                     + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
4918  if (Op != OO_Call &&
4919      ((NumParams == 1 && !CanBeUnaryOperator) ||
4920       (NumParams == 2 && !CanBeBinaryOperator) ||
4921       (NumParams < 1) || (NumParams > 2))) {
4922    // We have the wrong number of parameters.
4923    unsigned ErrorKind;
4924    if (CanBeUnaryOperator && CanBeBinaryOperator) {
4925      ErrorKind = 2;  // 2 -> unary or binary.
4926    } else if (CanBeUnaryOperator) {
4927      ErrorKind = 0;  // 0 -> unary
4928    } else {
4929      assert(CanBeBinaryOperator &&
4930             "All non-call overloaded operators are unary or binary!");
4931      ErrorKind = 1;  // 1 -> binary
4932    }
4933
4934    return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
4935      << FnDecl->getDeclName() << NumParams << ErrorKind;
4936  }
4937
4938  // Overloaded operators other than operator() cannot be variadic.
4939  if (Op != OO_Call &&
4940      FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
4941    return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
4942      << FnDecl->getDeclName();
4943  }
4944
4945  // Some operators must be non-static member functions.
4946  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4947    return Diag(FnDecl->getLocation(),
4948                diag::err_operator_overload_must_be_member)
4949      << FnDecl->getDeclName();
4950  }
4951
4952  // C++ [over.inc]p1:
4953  //   The user-defined function called operator++ implements the
4954  //   prefix and postfix ++ operator. If this function is a member
4955  //   function with no parameters, or a non-member function with one
4956  //   parameter of class or enumeration type, it defines the prefix
4957  //   increment operator ++ for objects of that type. If the function
4958  //   is a member function with one parameter (which shall be of type
4959  //   int) or a non-member function with two parameters (the second
4960  //   of which shall be of type int), it defines the postfix
4961  //   increment operator ++ for objects of that type.
4962  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
4963    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
4964    bool ParamIsInt = false;
4965    if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
4966      ParamIsInt = BT->getKind() == BuiltinType::Int;
4967
4968    if (!ParamIsInt)
4969      return Diag(LastParam->getLocation(),
4970                  diag::err_operator_overload_post_incdec_must_be_int)
4971        << LastParam->getType() << (Op == OO_MinusMinus);
4972  }
4973
4974  // Notify the class if it got an assignment operator.
4975  if (Op == OO_Equal) {
4976    // Would have returned earlier otherwise.
4977    assert(isa<CXXMethodDecl>(FnDecl) &&
4978      "Overloaded = not member, but not filtered.");
4979    CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
4980    Method->getParent()->addedAssignmentOperator(Context, Method);
4981  }
4982
4983  return false;
4984}
4985
4986/// CheckLiteralOperatorDeclaration - Check whether the declaration
4987/// of this literal operator function is well-formed. If so, returns
4988/// false; otherwise, emits appropriate diagnostics and returns true.
4989bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
4990  DeclContext *DC = FnDecl->getDeclContext();
4991  Decl::Kind Kind = DC->getDeclKind();
4992  if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
4993      Kind != Decl::LinkageSpec) {
4994    Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
4995      << FnDecl->getDeclName();
4996    return true;
4997  }
4998
4999  bool Valid = false;
5000
5001  // FIXME: Check for the one valid template signature
5002  // template <char...> type operator "" name();
5003
5004  if (FunctionDecl::param_iterator Param = FnDecl->param_begin()) {
5005    // Check the first parameter
5006    QualType T = (*Param)->getType();
5007
5008    // unsigned long long int and long double are allowed, but only
5009    // alone.
5010    // We also allow any character type; their omission seems to be a bug
5011    // in n3000
5012    if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5013        Context.hasSameType(T, Context.LongDoubleTy) ||
5014        Context.hasSameType(T, Context.CharTy) ||
5015        Context.hasSameType(T, Context.WCharTy) ||
5016        Context.hasSameType(T, Context.Char16Ty) ||
5017        Context.hasSameType(T, Context.Char32Ty)) {
5018      if (++Param == FnDecl->param_end())
5019        Valid = true;
5020      goto FinishedParams;
5021    }
5022
5023    // Otherwise it must be a pointer to const; let's strip those.
5024    const PointerType *PT = T->getAs<PointerType>();
5025    if (!PT)
5026      goto FinishedParams;
5027    T = PT->getPointeeType();
5028    if (!T.isConstQualified())
5029      goto FinishedParams;
5030    T = T.getUnqualifiedType();
5031
5032    // Move on to the second parameter;
5033    ++Param;
5034
5035    // If there is no second parameter, the first must be a const char *
5036    if (Param == FnDecl->param_end()) {
5037      if (Context.hasSameType(T, Context.CharTy))
5038        Valid = true;
5039      goto FinishedParams;
5040    }
5041
5042    // const char *, const wchar_t*, const char16_t*, and const char32_t*
5043    // are allowed as the first parameter to a two-parameter function
5044    if (!(Context.hasSameType(T, Context.CharTy) ||
5045          Context.hasSameType(T, Context.WCharTy) ||
5046          Context.hasSameType(T, Context.Char16Ty) ||
5047          Context.hasSameType(T, Context.Char32Ty)))
5048      goto FinishedParams;
5049
5050    // The second and final parameter must be an std::size_t
5051    T = (*Param)->getType().getUnqualifiedType();
5052    if (Context.hasSameType(T, Context.getSizeType()) &&
5053        ++Param == FnDecl->param_end())
5054      Valid = true;
5055  }
5056
5057  // FIXME: This diagnostic is absolutely terrible.
5058FinishedParams:
5059  if (!Valid) {
5060    Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
5061      << FnDecl->getDeclName();
5062    return true;
5063  }
5064
5065  return false;
5066}
5067
5068/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5069/// linkage specification, including the language and (if present)
5070/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
5071/// the location of the language string literal, which is provided
5072/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
5073/// the '{' brace. Otherwise, this linkage specification does not
5074/// have any braces.
5075Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
5076                                                     SourceLocation ExternLoc,
5077                                                     SourceLocation LangLoc,
5078                                                     const char *Lang,
5079                                                     unsigned StrSize,
5080                                                     SourceLocation LBraceLoc) {
5081  LinkageSpecDecl::LanguageIDs Language;
5082  if (strncmp(Lang, "\"C\"", StrSize) == 0)
5083    Language = LinkageSpecDecl::lang_c;
5084  else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
5085    Language = LinkageSpecDecl::lang_cxx;
5086  else {
5087    Diag(LangLoc, diag::err_bad_language);
5088    return DeclPtrTy();
5089  }
5090
5091  // FIXME: Add all the various semantics of linkage specifications
5092
5093  LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
5094                                               LangLoc, Language,
5095                                               LBraceLoc.isValid());
5096  CurContext->addDecl(D);
5097  PushDeclContext(S, D);
5098  return DeclPtrTy::make(D);
5099}
5100
5101/// ActOnFinishLinkageSpecification - Completely the definition of
5102/// the C++ linkage specification LinkageSpec. If RBraceLoc is
5103/// valid, it's the position of the closing '}' brace in a linkage
5104/// specification that uses braces.
5105Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
5106                                                      DeclPtrTy LinkageSpec,
5107                                                      SourceLocation RBraceLoc) {
5108  if (LinkageSpec)
5109    PopDeclContext();
5110  return LinkageSpec;
5111}
5112
5113/// \brief Perform semantic analysis for the variable declaration that
5114/// occurs within a C++ catch clause, returning the newly-created
5115/// variable.
5116VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
5117                                         TypeSourceInfo *TInfo,
5118                                         IdentifierInfo *Name,
5119                                         SourceLocation Loc,
5120                                         SourceRange Range) {
5121  bool Invalid = false;
5122
5123  // Arrays and functions decay.
5124  if (ExDeclType->isArrayType())
5125    ExDeclType = Context.getArrayDecayedType(ExDeclType);
5126  else if (ExDeclType->isFunctionType())
5127    ExDeclType = Context.getPointerType(ExDeclType);
5128
5129  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
5130  // The exception-declaration shall not denote a pointer or reference to an
5131  // incomplete type, other than [cv] void*.
5132  // N2844 forbids rvalue references.
5133  if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
5134    Diag(Loc, diag::err_catch_rvalue_ref) << Range;
5135    Invalid = true;
5136  }
5137
5138  QualType BaseType = ExDeclType;
5139  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
5140  unsigned DK = diag::err_catch_incomplete;
5141  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
5142    BaseType = Ptr->getPointeeType();
5143    Mode = 1;
5144    DK = diag::err_catch_incomplete_ptr;
5145  } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
5146    // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
5147    BaseType = Ref->getPointeeType();
5148    Mode = 2;
5149    DK = diag::err_catch_incomplete_ref;
5150  }
5151  if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
5152      !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
5153    Invalid = true;
5154
5155  if (!Invalid && !ExDeclType->isDependentType() &&
5156      RequireNonAbstractType(Loc, ExDeclType,
5157                             diag::err_abstract_type_in_decl,
5158                             AbstractVariableType))
5159    Invalid = true;
5160
5161  // FIXME: Need to test for ability to copy-construct and destroy the
5162  // exception variable.
5163
5164  // FIXME: Need to check for abstract classes.
5165
5166  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
5167                                    Name, ExDeclType, TInfo, VarDecl::None);
5168
5169  if (Invalid)
5170    ExDecl->setInvalidDecl();
5171
5172  return ExDecl;
5173}
5174
5175/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
5176/// handler.
5177Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
5178  TypeSourceInfo *TInfo = 0;
5179  QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo);
5180
5181  bool Invalid = D.isInvalidType();
5182  IdentifierInfo *II = D.getIdentifier();
5183  if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
5184    // The scope should be freshly made just for us. There is just no way
5185    // it contains any previous declaration.
5186    assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
5187    if (PrevDecl->isTemplateParameter()) {
5188      // Maybe we will complain about the shadowed template parameter.
5189      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
5190    }
5191  }
5192
5193  if (D.getCXXScopeSpec().isSet() && !Invalid) {
5194    Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
5195      << D.getCXXScopeSpec().getRange();
5196    Invalid = true;
5197  }
5198
5199  VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
5200                                              D.getIdentifier(),
5201                                              D.getIdentifierLoc(),
5202                                            D.getDeclSpec().getSourceRange());
5203
5204  if (Invalid)
5205    ExDecl->setInvalidDecl();
5206
5207  // Add the exception declaration into this scope.
5208  if (II)
5209    PushOnScopeChains(ExDecl, S);
5210  else
5211    CurContext->addDecl(ExDecl);
5212
5213  ProcessDeclAttributes(S, ExDecl, D);
5214  return DeclPtrTy::make(ExDecl);
5215}
5216
5217Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
5218                                                   ExprArg assertexpr,
5219                                                   ExprArg assertmessageexpr) {
5220  Expr *AssertExpr = (Expr *)assertexpr.get();
5221  StringLiteral *AssertMessage =
5222    cast<StringLiteral>((Expr *)assertmessageexpr.get());
5223
5224  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
5225    llvm::APSInt Value(32);
5226    if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
5227      Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
5228        AssertExpr->getSourceRange();
5229      return DeclPtrTy();
5230    }
5231
5232    if (Value == 0) {
5233      Diag(AssertLoc, diag::err_static_assert_failed)
5234        << AssertMessage->getString() << AssertExpr->getSourceRange();
5235    }
5236  }
5237
5238  assertexpr.release();
5239  assertmessageexpr.release();
5240  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
5241                                        AssertExpr, AssertMessage);
5242
5243  CurContext->addDecl(Decl);
5244  return DeclPtrTy::make(Decl);
5245}
5246
5247/// Handle a friend type declaration.  This works in tandem with
5248/// ActOnTag.
5249///
5250/// Notes on friend class templates:
5251///
5252/// We generally treat friend class declarations as if they were
5253/// declaring a class.  So, for example, the elaborated type specifier
5254/// in a friend declaration is required to obey the restrictions of a
5255/// class-head (i.e. no typedefs in the scope chain), template
5256/// parameters are required to match up with simple template-ids, &c.
5257/// However, unlike when declaring a template specialization, it's
5258/// okay to refer to a template specialization without an empty
5259/// template parameter declaration, e.g.
5260///   friend class A<T>::B<unsigned>;
5261/// We permit this as a special case; if there are any template
5262/// parameters present at all, require proper matching, i.e.
5263///   template <> template <class T> friend class A<int>::B;
5264Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
5265                                          MultiTemplateParamsArg TempParams) {
5266  SourceLocation Loc = DS.getSourceRange().getBegin();
5267
5268  assert(DS.isFriendSpecified());
5269  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5270
5271  // Try to convert the decl specifier to a type.  This works for
5272  // friend templates because ActOnTag never produces a ClassTemplateDecl
5273  // for a TUK_Friend.
5274  Declarator TheDeclarator(DS, Declarator::MemberContext);
5275  QualType T = GetTypeForDeclarator(TheDeclarator, S);
5276  if (TheDeclarator.isInvalidType())
5277    return DeclPtrTy();
5278
5279  // This is definitely an error in C++98.  It's probably meant to
5280  // be forbidden in C++0x, too, but the specification is just
5281  // poorly written.
5282  //
5283  // The problem is with declarations like the following:
5284  //   template <T> friend A<T>::foo;
5285  // where deciding whether a class C is a friend or not now hinges
5286  // on whether there exists an instantiation of A that causes
5287  // 'foo' to equal C.  There are restrictions on class-heads
5288  // (which we declare (by fiat) elaborated friend declarations to
5289  // be) that makes this tractable.
5290  //
5291  // FIXME: handle "template <> friend class A<T>;", which
5292  // is possibly well-formed?  Who even knows?
5293  if (TempParams.size() && !isa<ElaboratedType>(T)) {
5294    Diag(Loc, diag::err_tagless_friend_type_template)
5295      << DS.getSourceRange();
5296    return DeclPtrTy();
5297  }
5298
5299  // C++ [class.friend]p2:
5300  //   An elaborated-type-specifier shall be used in a friend declaration
5301  //   for a class.*
5302  //   * The class-key of the elaborated-type-specifier is required.
5303  // This is one of the rare places in Clang where it's legitimate to
5304  // ask about the "spelling" of the type.
5305  if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
5306    // If we evaluated the type to a record type, suggest putting
5307    // a tag in front.
5308    if (const RecordType *RT = T->getAs<RecordType>()) {
5309      RecordDecl *RD = RT->getDecl();
5310
5311      std::string InsertionText = std::string(" ") + RD->getKindName();
5312
5313      Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
5314        << (unsigned) RD->getTagKind()
5315        << T
5316        << SourceRange(DS.getFriendSpecLoc())
5317        << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
5318                                                 InsertionText);
5319      return DeclPtrTy();
5320    }else {
5321      Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
5322          << DS.getSourceRange();
5323      return DeclPtrTy();
5324    }
5325  }
5326
5327  // Enum types cannot be friends.
5328  if (T->getAs<EnumType>()) {
5329    Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
5330      << SourceRange(DS.getFriendSpecLoc());
5331    return DeclPtrTy();
5332  }
5333
5334  // C++98 [class.friend]p1: A friend of a class is a function
5335  //   or class that is not a member of the class . . .
5336  // This is fixed in DR77, which just barely didn't make the C++03
5337  // deadline.  It's also a very silly restriction that seriously
5338  // affects inner classes and which nobody else seems to implement;
5339  // thus we never diagnose it, not even in -pedantic.
5340
5341  Decl *D;
5342  if (TempParams.size())
5343    D = FriendTemplateDecl::Create(Context, CurContext, Loc,
5344                                   TempParams.size(),
5345                                 (TemplateParameterList**) TempParams.release(),
5346                                   T.getTypePtr(),
5347                                   DS.getFriendSpecLoc());
5348  else
5349    D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
5350                           DS.getFriendSpecLoc());
5351  D->setAccess(AS_public);
5352  CurContext->addDecl(D);
5353
5354  return DeclPtrTy::make(D);
5355}
5356
5357Sema::DeclPtrTy
5358Sema::ActOnFriendFunctionDecl(Scope *S,
5359                              Declarator &D,
5360                              bool IsDefinition,
5361                              MultiTemplateParamsArg TemplateParams) {
5362  const DeclSpec &DS = D.getDeclSpec();
5363
5364  assert(DS.isFriendSpecified());
5365  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5366
5367  SourceLocation Loc = D.getIdentifierLoc();
5368  TypeSourceInfo *TInfo = 0;
5369  QualType T = GetTypeForDeclarator(D, S, &TInfo);
5370
5371  // C++ [class.friend]p1
5372  //   A friend of a class is a function or class....
5373  // Note that this sees through typedefs, which is intended.
5374  // It *doesn't* see through dependent types, which is correct
5375  // according to [temp.arg.type]p3:
5376  //   If a declaration acquires a function type through a
5377  //   type dependent on a template-parameter and this causes
5378  //   a declaration that does not use the syntactic form of a
5379  //   function declarator to have a function type, the program
5380  //   is ill-formed.
5381  if (!T->isFunctionType()) {
5382    Diag(Loc, diag::err_unexpected_friend);
5383
5384    // It might be worthwhile to try to recover by creating an
5385    // appropriate declaration.
5386    return DeclPtrTy();
5387  }
5388
5389  // C++ [namespace.memdef]p3
5390  //  - If a friend declaration in a non-local class first declares a
5391  //    class or function, the friend class or function is a member
5392  //    of the innermost enclosing namespace.
5393  //  - The name of the friend is not found by simple name lookup
5394  //    until a matching declaration is provided in that namespace
5395  //    scope (either before or after the class declaration granting
5396  //    friendship).
5397  //  - If a friend function is called, its name may be found by the
5398  //    name lookup that considers functions from namespaces and
5399  //    classes associated with the types of the function arguments.
5400  //  - When looking for a prior declaration of a class or a function
5401  //    declared as a friend, scopes outside the innermost enclosing
5402  //    namespace scope are not considered.
5403
5404  CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
5405  DeclarationName Name = GetNameForDeclarator(D);
5406  assert(Name);
5407
5408  // The context we found the declaration in, or in which we should
5409  // create the declaration.
5410  DeclContext *DC;
5411
5412  // FIXME: handle local classes
5413
5414  // Recover from invalid scope qualifiers as if they just weren't there.
5415  LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
5416                        ForRedeclaration);
5417  if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
5418    // FIXME: RequireCompleteDeclContext
5419    DC = computeDeclContext(ScopeQual);
5420
5421    // FIXME: handle dependent contexts
5422    if (!DC) return DeclPtrTy();
5423
5424    LookupQualifiedName(Previous, DC);
5425
5426    // If searching in that context implicitly found a declaration in
5427    // a different context, treat it like it wasn't found at all.
5428    // TODO: better diagnostics for this case.  Suggesting the right
5429    // qualified scope would be nice...
5430    // FIXME: getRepresentativeDecl() is not right here at all
5431    if (Previous.empty() ||
5432        !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
5433      D.setInvalidType();
5434      Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
5435      return DeclPtrTy();
5436    }
5437
5438    // C++ [class.friend]p1: A friend of a class is a function or
5439    //   class that is not a member of the class . . .
5440    if (DC->Equals(CurContext))
5441      Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5442
5443  // Otherwise walk out to the nearest namespace scope looking for matches.
5444  } else {
5445    // TODO: handle local class contexts.
5446
5447    DC = CurContext;
5448    while (true) {
5449      // Skip class contexts.  If someone can cite chapter and verse
5450      // for this behavior, that would be nice --- it's what GCC and
5451      // EDG do, and it seems like a reasonable intent, but the spec
5452      // really only says that checks for unqualified existing
5453      // declarations should stop at the nearest enclosing namespace,
5454      // not that they should only consider the nearest enclosing
5455      // namespace.
5456      while (DC->isRecord())
5457        DC = DC->getParent();
5458
5459      LookupQualifiedName(Previous, DC);
5460
5461      // TODO: decide what we think about using declarations.
5462      if (!Previous.empty())
5463        break;
5464
5465      if (DC->isFileContext()) break;
5466      DC = DC->getParent();
5467    }
5468
5469    // C++ [class.friend]p1: A friend of a class is a function or
5470    //   class that is not a member of the class . . .
5471    // C++0x changes this for both friend types and functions.
5472    // Most C++ 98 compilers do seem to give an error here, so
5473    // we do, too.
5474    if (!Previous.empty() && DC->Equals(CurContext)
5475        && !getLangOptions().CPlusPlus0x)
5476      Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5477  }
5478
5479  if (DC->isFileContext()) {
5480    // This implies that it has to be an operator or function.
5481    if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
5482        D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
5483        D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
5484      Diag(Loc, diag::err_introducing_special_friend) <<
5485        (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
5486         D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
5487      return DeclPtrTy();
5488    }
5489  }
5490
5491  bool Redeclaration = false;
5492  NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
5493                                          move(TemplateParams),
5494                                          IsDefinition,
5495                                          Redeclaration);
5496  if (!ND) return DeclPtrTy();
5497
5498  assert(ND->getDeclContext() == DC);
5499  assert(ND->getLexicalDeclContext() == CurContext);
5500
5501  // Add the function declaration to the appropriate lookup tables,
5502  // adjusting the redeclarations list as necessary.  We don't
5503  // want to do this yet if the friending class is dependent.
5504  //
5505  // Also update the scope-based lookup if the target context's
5506  // lookup context is in lexical scope.
5507  if (!CurContext->isDependentContext()) {
5508    DC = DC->getLookupContext();
5509    DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
5510    if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
5511      PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
5512  }
5513
5514  FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
5515                                       D.getIdentifierLoc(), ND,
5516                                       DS.getFriendSpecLoc());
5517  FrD->setAccess(AS_public);
5518  CurContext->addDecl(FrD);
5519
5520  if (D.getName().getKind() == UnqualifiedId::IK_TemplateId)
5521    FrD->setSpecialization(true);
5522
5523  return DeclPtrTy::make(ND);
5524}
5525
5526void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
5527  AdjustDeclIfTemplate(dcl);
5528
5529  Decl *Dcl = dcl.getAs<Decl>();
5530  FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
5531  if (!Fn) {
5532    Diag(DelLoc, diag::err_deleted_non_function);
5533    return;
5534  }
5535  if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
5536    Diag(DelLoc, diag::err_deleted_decl_not_first);
5537    Diag(Prev->getLocation(), diag::note_previous_declaration);
5538    // If the declaration wasn't the first, we delete the function anyway for
5539    // recovery.
5540  }
5541  Fn->setDeleted();
5542}
5543
5544static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
5545  for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
5546       ++CI) {
5547    Stmt *SubStmt = *CI;
5548    if (!SubStmt)
5549      continue;
5550    if (isa<ReturnStmt>(SubStmt))
5551      Self.Diag(SubStmt->getSourceRange().getBegin(),
5552           diag::err_return_in_constructor_handler);
5553    if (!isa<Expr>(SubStmt))
5554      SearchForReturnInStmt(Self, SubStmt);
5555  }
5556}
5557
5558void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
5559  for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
5560    CXXCatchStmt *Handler = TryBlock->getHandler(I);
5561    SearchForReturnInStmt(*this, Handler);
5562  }
5563}
5564
5565bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
5566                                             const CXXMethodDecl *Old) {
5567  QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
5568  QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
5569
5570  if (Context.hasSameType(NewTy, OldTy))
5571    return false;
5572
5573  // Check if the return types are covariant
5574  QualType NewClassTy, OldClassTy;
5575
5576  /// Both types must be pointers or references to classes.
5577  if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
5578    if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
5579      NewClassTy = NewPT->getPointeeType();
5580      OldClassTy = OldPT->getPointeeType();
5581    }
5582  } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
5583    if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
5584      if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
5585        NewClassTy = NewRT->getPointeeType();
5586        OldClassTy = OldRT->getPointeeType();
5587      }
5588    }
5589  }
5590
5591  // The return types aren't either both pointers or references to a class type.
5592  if (NewClassTy.isNull()) {
5593    Diag(New->getLocation(),
5594         diag::err_different_return_type_for_overriding_virtual_function)
5595      << New->getDeclName() << NewTy << OldTy;
5596    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5597
5598    return true;
5599  }
5600
5601  // C++ [class.virtual]p6:
5602  //   If the return type of D::f differs from the return type of B::f, the
5603  //   class type in the return type of D::f shall be complete at the point of
5604  //   declaration of D::f or shall be the class type D.
5605  if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
5606    if (!RT->isBeingDefined() &&
5607        RequireCompleteType(New->getLocation(), NewClassTy,
5608                            PDiag(diag::err_covariant_return_incomplete)
5609                              << New->getDeclName()))
5610    return true;
5611  }
5612
5613  if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
5614    // Check if the new class derives from the old class.
5615    if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
5616      Diag(New->getLocation(),
5617           diag::err_covariant_return_not_derived)
5618      << New->getDeclName() << NewTy << OldTy;
5619      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5620      return true;
5621    }
5622
5623    // Check if we the conversion from derived to base is valid.
5624    if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
5625                      diag::err_covariant_return_inaccessible_base,
5626                      diag::err_covariant_return_ambiguous_derived_to_base_conv,
5627                      // FIXME: Should this point to the return type?
5628                      New->getLocation(), SourceRange(), New->getDeclName())) {
5629      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5630      return true;
5631    }
5632  }
5633
5634  // The qualifiers of the return types must be the same.
5635  if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
5636    Diag(New->getLocation(),
5637         diag::err_covariant_return_type_different_qualifications)
5638    << New->getDeclName() << NewTy << OldTy;
5639    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5640    return true;
5641  };
5642
5643
5644  // The new class type must have the same or less qualifiers as the old type.
5645  if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
5646    Diag(New->getLocation(),
5647         diag::err_covariant_return_type_class_type_more_qualified)
5648    << New->getDeclName() << NewTy << OldTy;
5649    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5650    return true;
5651  };
5652
5653  return false;
5654}
5655
5656bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5657                                             const CXXMethodDecl *Old)
5658{
5659  if (Old->hasAttr<FinalAttr>()) {
5660    Diag(New->getLocation(), diag::err_final_function_overridden)
5661      << New->getDeclName();
5662    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5663    return true;
5664  }
5665
5666  return false;
5667}
5668
5669/// \brief Mark the given method pure.
5670///
5671/// \param Method the method to be marked pure.
5672///
5673/// \param InitRange the source range that covers the "0" initializer.
5674bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
5675  if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
5676    Method->setPure();
5677
5678    // A class is abstract if at least one function is pure virtual.
5679    Method->getParent()->setAbstract(true);
5680    return false;
5681  }
5682
5683  if (!Method->isInvalidDecl())
5684    Diag(Method->getLocation(), diag::err_non_virtual_pure)
5685      << Method->getDeclName() << InitRange;
5686  return true;
5687}
5688
5689/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
5690/// an initializer for the out-of-line declaration 'Dcl'.  The scope
5691/// is a fresh scope pushed for just this purpose.
5692///
5693/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5694/// static data member of class X, names should be looked up in the scope of
5695/// class X.
5696void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
5697  // If there is no declaration, there was an error parsing it.
5698  Decl *D = Dcl.getAs<Decl>();
5699  if (D == 0) return;
5700
5701  // We should only get called for declarations with scope specifiers, like:
5702  //   int foo::bar;
5703  assert(D->isOutOfLine());
5704  EnterDeclaratorContext(S, D->getDeclContext());
5705}
5706
5707/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5708/// initializer for the out-of-line declaration 'Dcl'.
5709void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
5710  // If there is no declaration, there was an error parsing it.
5711  Decl *D = Dcl.getAs<Decl>();
5712  if (D == 0) return;
5713
5714  assert(D->isOutOfLine());
5715  ExitDeclaratorContext(S);
5716}
5717
5718/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
5719/// C++ if/switch/while/for statement.
5720/// e.g: "if (int x = f()) {...}"
5721Action::DeclResult
5722Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
5723  // C++ 6.4p2:
5724  // The declarator shall not specify a function or an array.
5725  // The type-specifier-seq shall not contain typedef and shall not declare a
5726  // new class or enumeration.
5727  assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5728         "Parser allowed 'typedef' as storage class of condition decl.");
5729
5730  TypeSourceInfo *TInfo = 0;
5731  TagDecl *OwnedTag = 0;
5732  QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
5733
5734  if (Ty->isFunctionType()) { // The declarator shall not specify a function...
5735                              // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
5736                              // would be created and CXXConditionDeclExpr wants a VarDecl.
5737    Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
5738      << D.getSourceRange();
5739    return DeclResult();
5740  } else if (OwnedTag && OwnedTag->isDefinition()) {
5741    // The type-specifier-seq shall not declare a new class or enumeration.
5742    Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
5743  }
5744
5745  DeclPtrTy Dcl = ActOnDeclarator(S, D);
5746  if (!Dcl)
5747    return DeclResult();
5748
5749  VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
5750  VD->setDeclaredInCondition(true);
5751  return Dcl;
5752}
5753
5754void Sema::MaybeMarkVirtualMembersReferenced(SourceLocation Loc,
5755                                             CXXMethodDecl *MD) {
5756  // Ignore dependent types.
5757  if (MD->isDependentContext())
5758    return;
5759
5760  CXXRecordDecl *RD = MD->getParent();
5761
5762  // Ignore classes without a vtable.
5763  if (!RD->isDynamicClass())
5764    return;
5765
5766  // Ignore declarations that are not definitions.
5767  if (!MD->isThisDeclarationADefinition())
5768    return;
5769
5770  if (isa<CXXConstructorDecl>(MD)) {
5771    switch (MD->getParent()->getTemplateSpecializationKind()) {
5772    case TSK_Undeclared:
5773    case TSK_ExplicitSpecialization:
5774      // Classes that aren't instantiations of templates don't need their
5775      // virtual methods marked until we see the definition of the key
5776      // function.
5777      return;
5778
5779    case TSK_ImplicitInstantiation:
5780    case TSK_ExplicitInstantiationDeclaration:
5781    case TSK_ExplicitInstantiationDefinition:
5782      // This is a constructor of a class template; mark all of the virtual
5783      // members as referenced to ensure that they get instantiatied.
5784      break;
5785    }
5786  } else if (!MD->isOutOfLine()) {
5787    // Consider only out-of-line definitions of member functions. When we see
5788    // an inline definition, it's too early to compute the key function.
5789    return;
5790  } else if (const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD)) {
5791    // If this is not the key function, we don't need to mark virtual members.
5792    if (KeyFunction->getCanonicalDecl() != MD->getCanonicalDecl())
5793      return;
5794  } else {
5795    // The class has no key function, so we've already noted that we need to
5796    // mark the virtual members of this class.
5797    return;
5798  }
5799
5800  // We will need to mark all of the virtual members as referenced to build the
5801  // vtable.
5802  ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(RD, Loc));
5803}
5804
5805bool Sema::ProcessPendingClassesWithUnmarkedVirtualMembers() {
5806  if (ClassesWithUnmarkedVirtualMembers.empty())
5807    return false;
5808
5809  while (!ClassesWithUnmarkedVirtualMembers.empty()) {
5810    CXXRecordDecl *RD = ClassesWithUnmarkedVirtualMembers.back().first;
5811    SourceLocation Loc = ClassesWithUnmarkedVirtualMembers.back().second;
5812    ClassesWithUnmarkedVirtualMembers.pop_back();
5813    MarkVirtualMembersReferenced(Loc, RD);
5814  }
5815
5816  return true;
5817}
5818
5819void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, CXXRecordDecl *RD) {
5820  for (CXXRecordDecl::method_iterator i = RD->method_begin(),
5821       e = RD->method_end(); i != e; ++i) {
5822    CXXMethodDecl *MD = *i;
5823
5824    // C++ [basic.def.odr]p2:
5825    //   [...] A virtual member function is used if it is not pure. [...]
5826    if (MD->isVirtual() && !MD->isPure())
5827      MarkDeclarationReferenced(Loc, MD);
5828  }
5829}
5830
5831