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