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