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