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