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