SemaDeclCXX.cpp revision e127abe8bbcff7fef0326d68731bc178182a9990
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    // Cast to the base class to avoid ambiguities.
1506    CXXBaseSpecifierArray BasePath;
1507    BasePath.push_back(BaseSpec);
1508    SemaRef.ImpCastExprToType(CopyCtorArg, BaseSpec->getType(),
1509                              CastExpr::CK_UncheckedDerivedToBase,
1510                              /*isLvalue=*/true, BasePath);
1511
1512    InitializationKind InitKind
1513      = InitializationKind::CreateDirect(Constructor->getLocation(),
1514                                         SourceLocation(), SourceLocation());
1515    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1516                                   &CopyCtorArg, 1);
1517    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1518                               Sema::MultiExprArg(SemaRef,
1519                                                  (void**)&CopyCtorArg, 1));
1520    break;
1521  }
1522
1523  case IIK_Move:
1524    assert(false && "Unhandled initializer kind!");
1525  }
1526
1527  BaseInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1528  if (BaseInit.isInvalid())
1529    return true;
1530
1531  CXXBaseInit =
1532    new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1533               SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1534                                                        SourceLocation()),
1535                                             BaseSpec->isVirtual(),
1536                                             SourceLocation(),
1537                                             BaseInit.takeAs<Expr>(),
1538                                             SourceLocation());
1539
1540  return false;
1541}
1542
1543static bool
1544BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
1545                               ImplicitInitializerKind ImplicitInitKind,
1546                               FieldDecl *Field,
1547                               CXXBaseOrMemberInitializer *&CXXMemberInit) {
1548  if (ImplicitInitKind == IIK_Copy) {
1549    // FIXME: We shouldn't return early here. The reason we do it is that
1550    // we don't handle copying arrays.
1551    CXXMemberInit = 0;
1552    return false;
1553
1554    ParmVarDecl *Param = Constructor->getParamDecl(0);
1555    QualType ParamType = Param->getType().getNonReferenceType();
1556
1557    Expr *MemberExprBase =
1558      DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
1559                          SourceLocation(), ParamType, 0);
1560
1561
1562    Expr *CopyCtorArg =
1563      MemberExpr::Create(SemaRef.Context, MemberExprBase, /*IsArrow=*/false,
1564                         0, SourceRange(), Field,
1565                         DeclAccessPair::make(Field, Field->getAccess()),
1566                         SourceLocation(), 0,
1567                         Field->getType().getNonReferenceType());
1568
1569    InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
1570    InitializationKind InitKind =
1571      InitializationKind::CreateDirect(Constructor->getLocation(),
1572                                       SourceLocation(), SourceLocation());
1573
1574    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1575                                   &CopyCtorArg, 1);
1576
1577    Sema::OwningExprResult MemberInit =
1578      InitSeq.Perform(SemaRef, InitEntity, InitKind,
1579                      Sema::MultiExprArg(SemaRef, (void**)&CopyCtorArg, 1), 0);
1580    if (MemberInit.isInvalid())
1581      return true;
1582
1583    CXXMemberInit = 0;
1584    return false;
1585  }
1586
1587  assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1588
1589  QualType FieldBaseElementType =
1590    SemaRef.Context.getBaseElementType(Field->getType());
1591
1592  if (FieldBaseElementType->isRecordType()) {
1593    InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
1594    InitializationKind InitKind =
1595      InitializationKind::CreateDefault(Constructor->getLocation());
1596
1597    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1598    Sema::OwningExprResult MemberInit =
1599      InitSeq.Perform(SemaRef, InitEntity, InitKind,
1600                      Sema::MultiExprArg(SemaRef, 0, 0));
1601    MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1602    if (MemberInit.isInvalid())
1603      return true;
1604
1605    CXXMemberInit =
1606      new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1607                                                       Field, SourceLocation(),
1608                                                       SourceLocation(),
1609                                                      MemberInit.takeAs<Expr>(),
1610                                                       SourceLocation());
1611    return false;
1612  }
1613
1614  if (FieldBaseElementType->isReferenceType()) {
1615    SemaRef.Diag(Constructor->getLocation(),
1616                 diag::err_uninitialized_member_in_ctor)
1617    << (int)Constructor->isImplicit()
1618    << SemaRef.Context.getTagDeclType(Constructor->getParent())
1619    << 0 << Field->getDeclName();
1620    SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1621    return true;
1622  }
1623
1624  if (FieldBaseElementType.isConstQualified()) {
1625    SemaRef.Diag(Constructor->getLocation(),
1626                 diag::err_uninitialized_member_in_ctor)
1627    << (int)Constructor->isImplicit()
1628    << SemaRef.Context.getTagDeclType(Constructor->getParent())
1629    << 1 << Field->getDeclName();
1630    SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1631    return true;
1632  }
1633
1634  // Nothing to initialize.
1635  CXXMemberInit = 0;
1636  return false;
1637}
1638
1639bool
1640Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
1641                                  CXXBaseOrMemberInitializer **Initializers,
1642                                  unsigned NumInitializers,
1643                                  bool AnyErrors) {
1644  if (Constructor->getDeclContext()->isDependentContext()) {
1645    // Just store the initializers as written, they will be checked during
1646    // instantiation.
1647    if (NumInitializers > 0) {
1648      Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1649      CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1650        new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1651      memcpy(baseOrMemberInitializers, Initializers,
1652             NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
1653      Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1654    }
1655
1656    return false;
1657  }
1658
1659  ImplicitInitializerKind ImplicitInitKind = IIK_Default;
1660
1661  // FIXME: Handle implicit move constructors.
1662  if (Constructor->isImplicit() && Constructor->isCopyConstructor())
1663    ImplicitInitKind = IIK_Copy;
1664
1665  // We need to build the initializer AST according to order of construction
1666  // and not what user specified in the Initializers list.
1667  CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
1668  if (!ClassDecl)
1669    return true;
1670
1671  llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1672  llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1673  bool HadError = false;
1674
1675  for (unsigned i = 0; i < NumInitializers; i++) {
1676    CXXBaseOrMemberInitializer *Member = Initializers[i];
1677
1678    if (Member->isBaseInitializer())
1679      AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1680    else
1681      AllBaseFields[Member->getMember()] = Member;
1682  }
1683
1684  // Keep track of the direct virtual bases.
1685  llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
1686  for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
1687       E = ClassDecl->bases_end(); I != E; ++I) {
1688    if (I->isVirtual())
1689      DirectVBases.insert(I);
1690  }
1691
1692  // Push virtual bases before others.
1693  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1694       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1695
1696    if (CXXBaseOrMemberInitializer *Value
1697        = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1698      AllToInit.push_back(Value);
1699    } else if (!AnyErrors) {
1700      bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
1701      CXXBaseOrMemberInitializer *CXXBaseInit;
1702      if (BuildImplicitBaseInitializer(*this, Constructor, ImplicitInitKind,
1703                                       VBase, IsInheritedVirtualBase,
1704                                       CXXBaseInit)) {
1705        HadError = true;
1706        continue;
1707      }
1708
1709      AllToInit.push_back(CXXBaseInit);
1710    }
1711  }
1712
1713  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1714       E = ClassDecl->bases_end(); Base != E; ++Base) {
1715    // Virtuals are in the virtual base list and already constructed.
1716    if (Base->isVirtual())
1717      continue;
1718
1719    if (CXXBaseOrMemberInitializer *Value
1720          = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1721      AllToInit.push_back(Value);
1722    } else if (!AnyErrors) {
1723      CXXBaseOrMemberInitializer *CXXBaseInit;
1724      if (BuildImplicitBaseInitializer(*this, Constructor, ImplicitInitKind,
1725                                       Base, /*IsInheritedVirtualBase=*/false,
1726                                       CXXBaseInit)) {
1727        HadError = true;
1728        continue;
1729      }
1730
1731      AllToInit.push_back(CXXBaseInit);
1732    }
1733  }
1734
1735  // non-static data members.
1736  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1737       E = ClassDecl->field_end(); Field != E; ++Field) {
1738    if ((*Field)->isAnonymousStructOrUnion()) {
1739      if (const RecordType *FieldClassType =
1740          Field->getType()->getAs<RecordType>()) {
1741        CXXRecordDecl *FieldClassDecl
1742          = cast<CXXRecordDecl>(FieldClassType->getDecl());
1743        for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1744            EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1745          if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1746            // 'Member' is the anonymous union field and 'AnonUnionMember' is
1747            // set to the anonymous union data member used in the initializer
1748            // list.
1749            Value->setMember(*Field);
1750            Value->setAnonUnionMember(*FA);
1751            AllToInit.push_back(Value);
1752            break;
1753          }
1754        }
1755      }
1756      continue;
1757    }
1758    if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1759      AllToInit.push_back(Value);
1760      continue;
1761    }
1762
1763    if (AnyErrors)
1764      continue;
1765
1766    CXXBaseOrMemberInitializer *Member;
1767    if (BuildImplicitMemberInitializer(*this, Constructor, ImplicitInitKind,
1768                                       *Field, Member)) {
1769      HadError = true;
1770      continue;
1771    }
1772
1773    // If the member doesn't need to be initialized, it will be null.
1774    if (Member)
1775      AllToInit.push_back(Member);
1776  }
1777
1778  NumInitializers = AllToInit.size();
1779  if (NumInitializers > 0) {
1780    Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1781    CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1782      new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1783    memcpy(baseOrMemberInitializers, AllToInit.data(),
1784           NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
1785    Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1786
1787    // Constructors implicitly reference the base and member
1788    // destructors.
1789    MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
1790                                           Constructor->getParent());
1791  }
1792
1793  return HadError;
1794}
1795
1796static void *GetKeyForTopLevelField(FieldDecl *Field) {
1797  // For anonymous unions, use the class declaration as the key.
1798  if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
1799    if (RT->getDecl()->isAnonymousStructOrUnion())
1800      return static_cast<void *>(RT->getDecl());
1801  }
1802  return static_cast<void *>(Field);
1803}
1804
1805static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
1806  return Context.getCanonicalType(BaseType).getTypePtr();
1807}
1808
1809static void *GetKeyForMember(ASTContext &Context,
1810                             CXXBaseOrMemberInitializer *Member,
1811                             bool MemberMaybeAnon = false) {
1812  if (!Member->isMemberInitializer())
1813    return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
1814
1815  // For fields injected into the class via declaration of an anonymous union,
1816  // use its anonymous union class declaration as the unique key.
1817  FieldDecl *Field = Member->getMember();
1818
1819  // After SetBaseOrMemberInitializers call, Field is the anonymous union
1820  // data member of the class. Data member used in the initializer list is
1821  // in AnonUnionMember field.
1822  if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1823    Field = Member->getAnonUnionMember();
1824
1825  // If the field is a member of an anonymous struct or union, our key
1826  // is the anonymous record decl that's a direct child of the class.
1827  RecordDecl *RD = Field->getParent();
1828  if (RD->isAnonymousStructOrUnion()) {
1829    while (true) {
1830      RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
1831      if (Parent->isAnonymousStructOrUnion())
1832        RD = Parent;
1833      else
1834        break;
1835    }
1836
1837    return static_cast<void *>(RD);
1838  }
1839
1840  return static_cast<void *>(Field);
1841}
1842
1843static void
1844DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
1845                                  const CXXConstructorDecl *Constructor,
1846                                  CXXBaseOrMemberInitializer **Inits,
1847                                  unsigned NumInits) {
1848  if (Constructor->getDeclContext()->isDependentContext())
1849    return;
1850
1851  if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order)
1852        == Diagnostic::Ignored)
1853    return;
1854
1855  // Build the list of bases and members in the order that they'll
1856  // actually be initialized.  The explicit initializers should be in
1857  // this same order but may be missing things.
1858  llvm::SmallVector<const void*, 32> IdealInitKeys;
1859
1860  const CXXRecordDecl *ClassDecl = Constructor->getParent();
1861
1862  // 1. Virtual bases.
1863  for (CXXRecordDecl::base_class_const_iterator VBase =
1864       ClassDecl->vbases_begin(),
1865       E = ClassDecl->vbases_end(); VBase != E; ++VBase)
1866    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
1867
1868  // 2. Non-virtual bases.
1869  for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
1870       E = ClassDecl->bases_end(); Base != E; ++Base) {
1871    if (Base->isVirtual())
1872      continue;
1873    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
1874  }
1875
1876  // 3. Direct fields.
1877  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1878       E = ClassDecl->field_end(); Field != E; ++Field)
1879    IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
1880
1881  unsigned NumIdealInits = IdealInitKeys.size();
1882  unsigned IdealIndex = 0;
1883
1884  CXXBaseOrMemberInitializer *PrevInit = 0;
1885  for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
1886    CXXBaseOrMemberInitializer *Init = Inits[InitIndex];
1887    void *InitKey = GetKeyForMember(SemaRef.Context, Init, true);
1888
1889    // Scan forward to try to find this initializer in the idealized
1890    // initializers list.
1891    for (; IdealIndex != NumIdealInits; ++IdealIndex)
1892      if (InitKey == IdealInitKeys[IdealIndex])
1893        break;
1894
1895    // If we didn't find this initializer, it must be because we
1896    // scanned past it on a previous iteration.  That can only
1897    // happen if we're out of order;  emit a warning.
1898    if (IdealIndex == NumIdealInits) {
1899      assert(PrevInit && "initializer not found in initializer list");
1900
1901      Sema::SemaDiagnosticBuilder D =
1902        SemaRef.Diag(PrevInit->getSourceLocation(),
1903                     diag::warn_initializer_out_of_order);
1904
1905      if (PrevInit->isMemberInitializer())
1906        D << 0 << PrevInit->getMember()->getDeclName();
1907      else
1908        D << 1 << PrevInit->getBaseClassInfo()->getType();
1909
1910      if (Init->isMemberInitializer())
1911        D << 0 << Init->getMember()->getDeclName();
1912      else
1913        D << 1 << Init->getBaseClassInfo()->getType();
1914
1915      // Move back to the initializer's location in the ideal list.
1916      for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
1917        if (InitKey == IdealInitKeys[IdealIndex])
1918          break;
1919
1920      assert(IdealIndex != NumIdealInits &&
1921             "initializer not found in initializer list");
1922    }
1923
1924    PrevInit = Init;
1925  }
1926}
1927
1928namespace {
1929bool CheckRedundantInit(Sema &S,
1930                        CXXBaseOrMemberInitializer *Init,
1931                        CXXBaseOrMemberInitializer *&PrevInit) {
1932  if (!PrevInit) {
1933    PrevInit = Init;
1934    return false;
1935  }
1936
1937  if (FieldDecl *Field = Init->getMember())
1938    S.Diag(Init->getSourceLocation(),
1939           diag::err_multiple_mem_initialization)
1940      << Field->getDeclName()
1941      << Init->getSourceRange();
1942  else {
1943    Type *BaseClass = Init->getBaseClass();
1944    assert(BaseClass && "neither field nor base");
1945    S.Diag(Init->getSourceLocation(),
1946           diag::err_multiple_base_initialization)
1947      << QualType(BaseClass, 0)
1948      << Init->getSourceRange();
1949  }
1950  S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
1951    << 0 << PrevInit->getSourceRange();
1952
1953  return true;
1954}
1955
1956typedef std::pair<NamedDecl *, CXXBaseOrMemberInitializer *> UnionEntry;
1957typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
1958
1959bool CheckRedundantUnionInit(Sema &S,
1960                             CXXBaseOrMemberInitializer *Init,
1961                             RedundantUnionMap &Unions) {
1962  FieldDecl *Field = Init->getMember();
1963  RecordDecl *Parent = Field->getParent();
1964  if (!Parent->isAnonymousStructOrUnion())
1965    return false;
1966
1967  NamedDecl *Child = Field;
1968  do {
1969    if (Parent->isUnion()) {
1970      UnionEntry &En = Unions[Parent];
1971      if (En.first && En.first != Child) {
1972        S.Diag(Init->getSourceLocation(),
1973               diag::err_multiple_mem_union_initialization)
1974          << Field->getDeclName()
1975          << Init->getSourceRange();
1976        S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
1977          << 0 << En.second->getSourceRange();
1978        return true;
1979      } else if (!En.first) {
1980        En.first = Child;
1981        En.second = Init;
1982      }
1983    }
1984
1985    Child = Parent;
1986    Parent = cast<RecordDecl>(Parent->getDeclContext());
1987  } while (Parent->isAnonymousStructOrUnion());
1988
1989  return false;
1990}
1991}
1992
1993/// ActOnMemInitializers - Handle the member initializers for a constructor.
1994void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
1995                                SourceLocation ColonLoc,
1996                                MemInitTy **meminits, unsigned NumMemInits,
1997                                bool AnyErrors) {
1998  if (!ConstructorDecl)
1999    return;
2000
2001  AdjustDeclIfTemplate(ConstructorDecl);
2002
2003  CXXConstructorDecl *Constructor
2004    = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
2005
2006  if (!Constructor) {
2007    Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2008    return;
2009  }
2010
2011  CXXBaseOrMemberInitializer **MemInits =
2012    reinterpret_cast<CXXBaseOrMemberInitializer **>(meminits);
2013
2014  // Mapping for the duplicate initializers check.
2015  // For member initializers, this is keyed with a FieldDecl*.
2016  // For base initializers, this is keyed with a Type*.
2017  llvm::DenseMap<void*, CXXBaseOrMemberInitializer *> Members;
2018
2019  // Mapping for the inconsistent anonymous-union initializers check.
2020  RedundantUnionMap MemberUnions;
2021
2022  bool HadError = false;
2023  for (unsigned i = 0; i < NumMemInits; i++) {
2024    CXXBaseOrMemberInitializer *Init = MemInits[i];
2025
2026    if (Init->isMemberInitializer()) {
2027      FieldDecl *Field = Init->getMember();
2028      if (CheckRedundantInit(*this, Init, Members[Field]) ||
2029          CheckRedundantUnionInit(*this, Init, MemberUnions))
2030        HadError = true;
2031    } else {
2032      void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2033      if (CheckRedundantInit(*this, Init, Members[Key]))
2034        HadError = true;
2035    }
2036  }
2037
2038  if (HadError)
2039    return;
2040
2041  DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
2042
2043  SetBaseOrMemberInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
2044}
2045
2046void
2047Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2048                                             CXXRecordDecl *ClassDecl) {
2049  // Ignore dependent contexts.
2050  if (ClassDecl->isDependentContext())
2051    return;
2052
2053  // FIXME: all the access-control diagnostics are positioned on the
2054  // field/base declaration.  That's probably good; that said, the
2055  // user might reasonably want to know why the destructor is being
2056  // emitted, and we currently don't say.
2057
2058  // Non-static data members.
2059  for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2060       E = ClassDecl->field_end(); I != E; ++I) {
2061    FieldDecl *Field = *I;
2062
2063    QualType FieldType = Context.getBaseElementType(Field->getType());
2064
2065    const RecordType* RT = FieldType->getAs<RecordType>();
2066    if (!RT)
2067      continue;
2068
2069    CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2070    if (FieldClassDecl->hasTrivialDestructor())
2071      continue;
2072
2073    CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
2074    CheckDestructorAccess(Field->getLocation(), Dtor,
2075                          PDiag(diag::err_access_dtor_field)
2076                            << Field->getDeclName()
2077                            << FieldType);
2078
2079    MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
2080  }
2081
2082  llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2083
2084  // Bases.
2085  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2086       E = ClassDecl->bases_end(); Base != E; ++Base) {
2087    // Bases are always records in a well-formed non-dependent class.
2088    const RecordType *RT = Base->getType()->getAs<RecordType>();
2089
2090    // Remember direct virtual bases.
2091    if (Base->isVirtual())
2092      DirectVirtualBases.insert(RT);
2093
2094    // Ignore trivial destructors.
2095    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2096    if (BaseClassDecl->hasTrivialDestructor())
2097      continue;
2098
2099    CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
2100
2101    // FIXME: caret should be on the start of the class name
2102    CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
2103                          PDiag(diag::err_access_dtor_base)
2104                            << Base->getType()
2105                            << Base->getSourceRange());
2106
2107    MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
2108  }
2109
2110  // Virtual bases.
2111  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2112       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2113
2114    // Bases are always records in a well-formed non-dependent class.
2115    const RecordType *RT = VBase->getType()->getAs<RecordType>();
2116
2117    // Ignore direct virtual bases.
2118    if (DirectVirtualBases.count(RT))
2119      continue;
2120
2121    // Ignore trivial destructors.
2122    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2123    if (BaseClassDecl->hasTrivialDestructor())
2124      continue;
2125
2126    CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
2127    CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
2128                          PDiag(diag::err_access_dtor_vbase)
2129                            << VBase->getType());
2130
2131    MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
2132  }
2133}
2134
2135void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
2136  if (!CDtorDecl)
2137    return;
2138
2139  if (CXXConstructorDecl *Constructor
2140      = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
2141    SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
2142}
2143
2144bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2145                                  unsigned DiagID, AbstractDiagSelID SelID,
2146                                  const CXXRecordDecl *CurrentRD) {
2147  if (SelID == -1)
2148    return RequireNonAbstractType(Loc, T,
2149                                  PDiag(DiagID), CurrentRD);
2150  else
2151    return RequireNonAbstractType(Loc, T,
2152                                  PDiag(DiagID) << SelID, CurrentRD);
2153}
2154
2155bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2156                                  const PartialDiagnostic &PD,
2157                                  const CXXRecordDecl *CurrentRD) {
2158  if (!getLangOptions().CPlusPlus)
2159    return false;
2160
2161  if (const ArrayType *AT = Context.getAsArrayType(T))
2162    return RequireNonAbstractType(Loc, AT->getElementType(), PD,
2163                                  CurrentRD);
2164
2165  if (const PointerType *PT = T->getAs<PointerType>()) {
2166    // Find the innermost pointer type.
2167    while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
2168      PT = T;
2169
2170    if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
2171      return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
2172  }
2173
2174  const RecordType *RT = T->getAs<RecordType>();
2175  if (!RT)
2176    return false;
2177
2178  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2179
2180  if (CurrentRD && CurrentRD != RD)
2181    return false;
2182
2183  // FIXME: is this reasonable?  It matches current behavior, but....
2184  if (!RD->getDefinition())
2185    return false;
2186
2187  if (!RD->isAbstract())
2188    return false;
2189
2190  Diag(Loc, PD) << RD->getDeclName();
2191
2192  // Check if we've already emitted the list of pure virtual functions for this
2193  // class.
2194  if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
2195    return true;
2196
2197  CXXFinalOverriderMap FinalOverriders;
2198  RD->getFinalOverriders(FinalOverriders);
2199
2200  for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2201                                   MEnd = FinalOverriders.end();
2202       M != MEnd;
2203       ++M) {
2204    for (OverridingMethods::iterator SO = M->second.begin(),
2205                                  SOEnd = M->second.end();
2206         SO != SOEnd; ++SO) {
2207      // C++ [class.abstract]p4:
2208      //   A class is abstract if it contains or inherits at least one
2209      //   pure virtual function for which the final overrider is pure
2210      //   virtual.
2211
2212      //
2213      if (SO->second.size() != 1)
2214        continue;
2215
2216      if (!SO->second.front().Method->isPure())
2217        continue;
2218
2219      Diag(SO->second.front().Method->getLocation(),
2220           diag::note_pure_virtual_function)
2221        << SO->second.front().Method->getDeclName();
2222    }
2223  }
2224
2225  if (!PureVirtualClassDiagSet)
2226    PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2227  PureVirtualClassDiagSet->insert(RD);
2228
2229  return true;
2230}
2231
2232namespace {
2233  class AbstractClassUsageDiagnoser
2234    : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
2235    Sema &SemaRef;
2236    CXXRecordDecl *AbstractClass;
2237
2238    bool VisitDeclContext(const DeclContext *DC) {
2239      bool Invalid = false;
2240
2241      for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
2242           E = DC->decls_end(); I != E; ++I)
2243        Invalid |= Visit(*I);
2244
2245      return Invalid;
2246    }
2247
2248  public:
2249    AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
2250      : SemaRef(SemaRef), AbstractClass(ac) {
2251        Visit(SemaRef.Context.getTranslationUnitDecl());
2252    }
2253
2254    bool VisitFunctionDecl(const FunctionDecl *FD) {
2255      if (FD->isThisDeclarationADefinition()) {
2256        // No need to do the check if we're in a definition, because it requires
2257        // that the return/param types are complete.
2258        // because that requires
2259        return VisitDeclContext(FD);
2260      }
2261
2262      // Check the return type.
2263      QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
2264      bool Invalid =
2265        SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
2266                                       diag::err_abstract_type_in_decl,
2267                                       Sema::AbstractReturnType,
2268                                       AbstractClass);
2269
2270      for (FunctionDecl::param_const_iterator I = FD->param_begin(),
2271           E = FD->param_end(); I != E; ++I) {
2272        const ParmVarDecl *VD = *I;
2273        Invalid |=
2274          SemaRef.RequireNonAbstractType(VD->getLocation(),
2275                                         VD->getOriginalType(),
2276                                         diag::err_abstract_type_in_decl,
2277                                         Sema::AbstractParamType,
2278                                         AbstractClass);
2279      }
2280
2281      return Invalid;
2282    }
2283
2284    bool VisitDecl(const Decl* D) {
2285      if (const DeclContext *DC = dyn_cast<DeclContext>(D))
2286        return VisitDeclContext(DC);
2287
2288      return false;
2289    }
2290  };
2291}
2292
2293/// \brief Perform semantic checks on a class definition that has been
2294/// completing, introducing implicitly-declared members, checking for
2295/// abstract types, etc.
2296void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
2297  if (!Record || Record->isInvalidDecl())
2298    return;
2299
2300  if (!Record->isDependentType())
2301    AddImplicitlyDeclaredMembersToClass(S, Record);
2302
2303  if (Record->isInvalidDecl())
2304    return;
2305
2306  // Set access bits correctly on the directly-declared conversions.
2307  UnresolvedSetImpl *Convs = Record->getConversionFunctions();
2308  for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I)
2309    Convs->setAccess(I, (*I)->getAccess());
2310
2311  // Determine whether we need to check for final overriders. We do
2312  // this either when there are virtual base classes (in which case we
2313  // may end up finding multiple final overriders for a given virtual
2314  // function) or any of the base classes is abstract (in which case
2315  // we might detect that this class is abstract).
2316  bool CheckFinalOverriders = false;
2317  if (Record->isPolymorphic() && !Record->isInvalidDecl() &&
2318      !Record->isDependentType()) {
2319    if (Record->getNumVBases())
2320      CheckFinalOverriders = true;
2321    else if (!Record->isAbstract()) {
2322      for (CXXRecordDecl::base_class_const_iterator B = Record->bases_begin(),
2323                                                 BEnd = Record->bases_end();
2324           B != BEnd; ++B) {
2325        CXXRecordDecl *BaseDecl
2326          = cast<CXXRecordDecl>(B->getType()->getAs<RecordType>()->getDecl());
2327        if (BaseDecl->isAbstract()) {
2328          CheckFinalOverriders = true;
2329          break;
2330        }
2331      }
2332    }
2333  }
2334
2335  if (CheckFinalOverriders) {
2336    CXXFinalOverriderMap FinalOverriders;
2337    Record->getFinalOverriders(FinalOverriders);
2338
2339    for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2340                                     MEnd = FinalOverriders.end();
2341         M != MEnd; ++M) {
2342      for (OverridingMethods::iterator SO = M->second.begin(),
2343                                    SOEnd = M->second.end();
2344           SO != SOEnd; ++SO) {
2345        assert(SO->second.size() > 0 &&
2346               "All virtual functions have overridding virtual functions");
2347        if (SO->second.size() == 1) {
2348          // C++ [class.abstract]p4:
2349          //   A class is abstract if it contains or inherits at least one
2350          //   pure virtual function for which the final overrider is pure
2351          //   virtual.
2352          if (SO->second.front().Method->isPure())
2353            Record->setAbstract(true);
2354          continue;
2355        }
2356
2357        // C++ [class.virtual]p2:
2358        //   In a derived class, if a virtual member function of a base
2359        //   class subobject has more than one final overrider the
2360        //   program is ill-formed.
2361        Diag(Record->getLocation(), diag::err_multiple_final_overriders)
2362          << (NamedDecl *)M->first << Record;
2363        Diag(M->first->getLocation(), diag::note_overridden_virtual_function);
2364        for (OverridingMethods::overriding_iterator OM = SO->second.begin(),
2365                                                 OMEnd = SO->second.end();
2366             OM != OMEnd; ++OM)
2367          Diag(OM->Method->getLocation(), diag::note_final_overrider)
2368            << (NamedDecl *)M->first << OM->Method->getParent();
2369
2370        Record->setInvalidDecl();
2371      }
2372    }
2373  }
2374
2375  if (Record->isAbstract() && !Record->isInvalidDecl())
2376    (void)AbstractClassUsageDiagnoser(*this, Record);
2377
2378  // If this is not an aggregate type and has no user-declared constructor,
2379  // complain about any non-static data members of reference or const scalar
2380  // type, since they will never get initializers.
2381  if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2382      !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2383    bool Complained = false;
2384    for (RecordDecl::field_iterator F = Record->field_begin(),
2385                                 FEnd = Record->field_end();
2386         F != FEnd; ++F) {
2387      if (F->getType()->isReferenceType() ||
2388          (F->getType().isConstQualified() && F->getType()->isScalarType())) {
2389        if (!Complained) {
2390          Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2391            << Record->getTagKind() << Record;
2392          Complained = true;
2393        }
2394
2395        Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2396          << F->getType()->isReferenceType()
2397          << F->getDeclName();
2398      }
2399    }
2400  }
2401}
2402
2403void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
2404                                             DeclPtrTy TagDecl,
2405                                             SourceLocation LBrac,
2406                                             SourceLocation RBrac,
2407                                             AttributeList *AttrList) {
2408  if (!TagDecl)
2409    return;
2410
2411  AdjustDeclIfTemplate(TagDecl);
2412
2413  ActOnFields(S, RLoc, TagDecl,
2414              (DeclPtrTy*)FieldCollector->getCurFields(),
2415              FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
2416
2417  CheckCompletedCXXClass(S,
2418                      dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
2419}
2420
2421/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2422/// special functions, such as the default constructor, copy
2423/// constructor, or destructor, to the given C++ class (C++
2424/// [special]p1).  This routine can only be executed just before the
2425/// definition of the class is complete.
2426///
2427/// The scope, if provided, is the class scope.
2428void Sema::AddImplicitlyDeclaredMembersToClass(Scope *S,
2429                                               CXXRecordDecl *ClassDecl) {
2430  CanQualType ClassType
2431    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
2432
2433  // FIXME: Implicit declarations have exception specifications, which are
2434  // the union of the specifications of the implicitly called functions.
2435
2436  if (!ClassDecl->hasUserDeclaredConstructor()) {
2437    // C++ [class.ctor]p5:
2438    //   A default constructor for a class X is a constructor of class X
2439    //   that can be called without an argument. If there is no
2440    //   user-declared constructor for class X, a default constructor is
2441    //   implicitly declared. An implicitly-declared default constructor
2442    //   is an inline public member of its class.
2443    DeclarationName Name
2444      = Context.DeclarationNames.getCXXConstructorName(ClassType);
2445    CXXConstructorDecl *DefaultCon =
2446      CXXConstructorDecl::Create(Context, ClassDecl,
2447                                 ClassDecl->getLocation(), Name,
2448                                 Context.getFunctionType(Context.VoidTy,
2449                                                         0, 0, false, 0,
2450                                                         /*FIXME*/false, false,
2451                                                         0, 0,
2452                                                       FunctionType::ExtInfo()),
2453                                 /*TInfo=*/0,
2454                                 /*isExplicit=*/false,
2455                                 /*isInline=*/true,
2456                                 /*isImplicitlyDeclared=*/true);
2457    DefaultCon->setAccess(AS_public);
2458    DefaultCon->setImplicit();
2459    DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
2460    if (S)
2461      PushOnScopeChains(DefaultCon, S, true);
2462    else
2463      ClassDecl->addDecl(DefaultCon);
2464  }
2465
2466  if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
2467    // C++ [class.copy]p4:
2468    //   If the class definition does not explicitly declare a copy
2469    //   constructor, one is declared implicitly.
2470
2471    // C++ [class.copy]p5:
2472    //   The implicitly-declared copy constructor for a class X will
2473    //   have the form
2474    //
2475    //       X::X(const X&)
2476    //
2477    //   if
2478    bool HasConstCopyConstructor = true;
2479
2480    //     -- each direct or virtual base class B of X has a copy
2481    //        constructor whose first parameter is of type const B& or
2482    //        const volatile B&, and
2483    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2484         HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2485      const CXXRecordDecl *BaseClassDecl
2486        = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2487      HasConstCopyConstructor
2488        = BaseClassDecl->hasConstCopyConstructor(Context);
2489    }
2490
2491    //     -- for all the nonstatic data members of X that are of a
2492    //        class type M (or array thereof), each such class type
2493    //        has a copy constructor whose first parameter is of type
2494    //        const M& or const volatile M&.
2495    for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2496         HasConstCopyConstructor && Field != ClassDecl->field_end();
2497         ++Field) {
2498      QualType FieldType = (*Field)->getType();
2499      if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2500        FieldType = Array->getElementType();
2501      if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
2502        const CXXRecordDecl *FieldClassDecl
2503          = cast<CXXRecordDecl>(FieldClassType->getDecl());
2504        HasConstCopyConstructor
2505          = FieldClassDecl->hasConstCopyConstructor(Context);
2506      }
2507    }
2508
2509    //   Otherwise, the implicitly declared copy constructor will have
2510    //   the form
2511    //
2512    //       X::X(X&)
2513    QualType ArgType = ClassType;
2514    if (HasConstCopyConstructor)
2515      ArgType = ArgType.withConst();
2516    ArgType = Context.getLValueReferenceType(ArgType);
2517
2518    //   An implicitly-declared copy constructor is an inline public
2519    //   member of its class.
2520    DeclarationName Name
2521      = Context.DeclarationNames.getCXXConstructorName(ClassType);
2522    CXXConstructorDecl *CopyConstructor
2523      = CXXConstructorDecl::Create(Context, ClassDecl,
2524                                   ClassDecl->getLocation(), Name,
2525                                   Context.getFunctionType(Context.VoidTy,
2526                                                           &ArgType, 1,
2527                                                           false, 0,
2528                                                           /*FIXME:*/false,
2529                                                           false, 0, 0,
2530                                                       FunctionType::ExtInfo()),
2531                                   /*TInfo=*/0,
2532                                   /*isExplicit=*/false,
2533                                   /*isInline=*/true,
2534                                   /*isImplicitlyDeclared=*/true);
2535    CopyConstructor->setAccess(AS_public);
2536    CopyConstructor->setImplicit();
2537    CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
2538
2539    // Add the parameter to the constructor.
2540    ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2541                                                 ClassDecl->getLocation(),
2542                                                 /*IdentifierInfo=*/0,
2543                                                 ArgType, /*TInfo=*/0,
2544                                                 VarDecl::None,
2545                                                 VarDecl::None, 0);
2546    CopyConstructor->setParams(&FromParam, 1);
2547    if (S)
2548      PushOnScopeChains(CopyConstructor, S, true);
2549    else
2550      ClassDecl->addDecl(CopyConstructor);
2551  }
2552
2553  if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2554    // Note: The following rules are largely analoguous to the copy
2555    // constructor rules. Note that virtual bases are not taken into account
2556    // for determining the argument type of the operator. Note also that
2557    // operators taking an object instead of a reference are allowed.
2558    //
2559    // C++ [class.copy]p10:
2560    //   If the class definition does not explicitly declare a copy
2561    //   assignment operator, one is declared implicitly.
2562    //   The implicitly-defined copy assignment operator for a class X
2563    //   will have the form
2564    //
2565    //       X& X::operator=(const X&)
2566    //
2567    //   if
2568    bool HasConstCopyAssignment = true;
2569
2570    //       -- each direct base class B of X has a copy assignment operator
2571    //          whose parameter is of type const B&, const volatile B& or B,
2572    //          and
2573    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2574         HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
2575      assert(!Base->getType()->isDependentType() &&
2576            "Cannot generate implicit members for class with dependent bases.");
2577      const CXXRecordDecl *BaseClassDecl
2578        = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2579      const CXXMethodDecl *MD = 0;
2580      HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
2581                                                                     MD);
2582    }
2583
2584    //       -- for all the nonstatic data members of X that are of a class
2585    //          type M (or array thereof), each such class type has a copy
2586    //          assignment operator whose parameter is of type const M&,
2587    //          const volatile M& or M.
2588    for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2589         HasConstCopyAssignment && Field != ClassDecl->field_end();
2590         ++Field) {
2591      QualType FieldType = (*Field)->getType();
2592      if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2593        FieldType = Array->getElementType();
2594      if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
2595        const CXXRecordDecl *FieldClassDecl
2596          = cast<CXXRecordDecl>(FieldClassType->getDecl());
2597        const CXXMethodDecl *MD = 0;
2598        HasConstCopyAssignment
2599          = FieldClassDecl->hasConstCopyAssignment(Context, MD);
2600      }
2601    }
2602
2603    //   Otherwise, the implicitly declared copy assignment operator will
2604    //   have the form
2605    //
2606    //       X& X::operator=(X&)
2607    QualType ArgType = ClassType;
2608    QualType RetType = Context.getLValueReferenceType(ArgType);
2609    if (HasConstCopyAssignment)
2610      ArgType = ArgType.withConst();
2611    ArgType = Context.getLValueReferenceType(ArgType);
2612
2613    //   An implicitly-declared copy assignment operator is an inline public
2614    //   member of its class.
2615    DeclarationName Name =
2616      Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2617    CXXMethodDecl *CopyAssignment =
2618      CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2619                            Context.getFunctionType(RetType, &ArgType, 1,
2620                                                    false, 0,
2621                                                    /*FIXME:*/false,
2622                                                    false, 0, 0,
2623                                                    FunctionType::ExtInfo()),
2624                            /*TInfo=*/0, /*isStatic=*/false,
2625                            /*StorageClassAsWritten=*/FunctionDecl::None,
2626                            /*isInline=*/true);
2627    CopyAssignment->setAccess(AS_public);
2628    CopyAssignment->setImplicit();
2629    CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
2630    CopyAssignment->setCopyAssignment(true);
2631
2632    // Add the parameter to the operator.
2633    ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2634                                                 ClassDecl->getLocation(),
2635                                                 /*IdentifierInfo=*/0,
2636                                                 ArgType, /*TInfo=*/0,
2637                                                 VarDecl::None,
2638                                                 VarDecl::None, 0);
2639    CopyAssignment->setParams(&FromParam, 1);
2640
2641    // Don't call addedAssignmentOperator. There is no way to distinguish an
2642    // implicit from an explicit assignment operator.
2643    if (S)
2644      PushOnScopeChains(CopyAssignment, S, true);
2645    else
2646      ClassDecl->addDecl(CopyAssignment);
2647    AddOverriddenMethods(ClassDecl, CopyAssignment);
2648  }
2649
2650  if (!ClassDecl->hasUserDeclaredDestructor()) {
2651    // C++ [class.dtor]p2:
2652    //   If a class has no user-declared destructor, a destructor is
2653    //   declared implicitly. An implicitly-declared destructor is an
2654    //   inline public member of its class.
2655    QualType Ty = Context.getFunctionType(Context.VoidTy,
2656                                          0, 0, false, 0,
2657                                          /*FIXME:*/false,
2658                                          false, 0, 0, FunctionType::ExtInfo());
2659
2660    DeclarationName Name
2661      = Context.DeclarationNames.getCXXDestructorName(ClassType);
2662    CXXDestructorDecl *Destructor
2663      = CXXDestructorDecl::Create(Context, ClassDecl,
2664                                  ClassDecl->getLocation(), Name, Ty,
2665                                  /*isInline=*/true,
2666                                  /*isImplicitlyDeclared=*/true);
2667    Destructor->setAccess(AS_public);
2668    Destructor->setImplicit();
2669    Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
2670    if (S)
2671      PushOnScopeChains(Destructor, S, true);
2672    else
2673      ClassDecl->addDecl(Destructor);
2674
2675    // This could be uniqued if it ever proves significant.
2676    Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
2677
2678    AddOverriddenMethods(ClassDecl, Destructor);
2679  }
2680}
2681
2682void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
2683  Decl *D = TemplateD.getAs<Decl>();
2684  if (!D)
2685    return;
2686
2687  TemplateParameterList *Params = 0;
2688  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2689    Params = Template->getTemplateParameters();
2690  else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2691           = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2692    Params = PartialSpec->getTemplateParameters();
2693  else
2694    return;
2695
2696  for (TemplateParameterList::iterator Param = Params->begin(),
2697                                    ParamEnd = Params->end();
2698       Param != ParamEnd; ++Param) {
2699    NamedDecl *Named = cast<NamedDecl>(*Param);
2700    if (Named->getDeclName()) {
2701      S->AddDecl(DeclPtrTy::make(Named));
2702      IdResolver.AddDecl(Named);
2703    }
2704  }
2705}
2706
2707void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2708  if (!RecordD) return;
2709  AdjustDeclIfTemplate(RecordD);
2710  CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>());
2711  PushDeclContext(S, Record);
2712}
2713
2714void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2715  if (!RecordD) return;
2716  PopDeclContext();
2717}
2718
2719/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2720/// parsing a top-level (non-nested) C++ class, and we are now
2721/// parsing those parts of the given Method declaration that could
2722/// not be parsed earlier (C++ [class.mem]p2), such as default
2723/// arguments. This action should enter the scope of the given
2724/// Method declaration as if we had just parsed the qualified method
2725/// name. However, it should not bring the parameters into scope;
2726/// that will be performed by ActOnDelayedCXXMethodParameter.
2727void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
2728}
2729
2730/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2731/// C++ method declaration. We're (re-)introducing the given
2732/// function parameter into scope for use in parsing later parts of
2733/// the method declaration. For example, we could see an
2734/// ActOnParamDefaultArgument event for this parameter.
2735void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
2736  if (!ParamD)
2737    return;
2738
2739  ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
2740
2741  // If this parameter has an unparsed default argument, clear it out
2742  // to make way for the parsed default argument.
2743  if (Param->hasUnparsedDefaultArg())
2744    Param->setDefaultArg(0);
2745
2746  S->AddDecl(DeclPtrTy::make(Param));
2747  if (Param->getDeclName())
2748    IdResolver.AddDecl(Param);
2749}
2750
2751/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2752/// processing the delayed method declaration for Method. The method
2753/// declaration is now considered finished. There may be a separate
2754/// ActOnStartOfFunctionDef action later (not necessarily
2755/// immediately!) for this method, if it was also defined inside the
2756/// class body.
2757void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
2758  if (!MethodD)
2759    return;
2760
2761  AdjustDeclIfTemplate(MethodD);
2762
2763  FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
2764
2765  // Now that we have our default arguments, check the constructor
2766  // again. It could produce additional diagnostics or affect whether
2767  // the class has implicitly-declared destructors, among other
2768  // things.
2769  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2770    CheckConstructor(Constructor);
2771
2772  // Check the default arguments, which we may have added.
2773  if (!Method->isInvalidDecl())
2774    CheckCXXDefaultArguments(Method);
2775}
2776
2777/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
2778/// the well-formedness of the constructor declarator @p D with type @p
2779/// R. If there are any errors in the declarator, this routine will
2780/// emit diagnostics and set the invalid bit to true.  In any case, the type
2781/// will be updated to reflect a well-formed type for the constructor and
2782/// returned.
2783QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2784                                          FunctionDecl::StorageClass &SC) {
2785  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
2786
2787  // C++ [class.ctor]p3:
2788  //   A constructor shall not be virtual (10.3) or static (9.4). A
2789  //   constructor can be invoked for a const, volatile or const
2790  //   volatile object. A constructor shall not be declared const,
2791  //   volatile, or const volatile (9.3.2).
2792  if (isVirtual) {
2793    if (!D.isInvalidType())
2794      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2795        << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2796        << SourceRange(D.getIdentifierLoc());
2797    D.setInvalidType();
2798  }
2799  if (SC == FunctionDecl::Static) {
2800    if (!D.isInvalidType())
2801      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2802        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2803        << SourceRange(D.getIdentifierLoc());
2804    D.setInvalidType();
2805    SC = FunctionDecl::None;
2806  }
2807
2808  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2809  if (FTI.TypeQuals != 0) {
2810    if (FTI.TypeQuals & Qualifiers::Const)
2811      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2812        << "const" << SourceRange(D.getIdentifierLoc());
2813    if (FTI.TypeQuals & Qualifiers::Volatile)
2814      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2815        << "volatile" << SourceRange(D.getIdentifierLoc());
2816    if (FTI.TypeQuals & Qualifiers::Restrict)
2817      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2818        << "restrict" << SourceRange(D.getIdentifierLoc());
2819  }
2820
2821  // Rebuild the function type "R" without any type qualifiers (in
2822  // case any of the errors above fired) and with "void" as the
2823  // return type, since constructors don't have return types. We
2824  // *always* have to do this, because GetTypeForDeclarator will
2825  // put in a result type of "int" when none was specified.
2826  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
2827  return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2828                                 Proto->getNumArgs(),
2829                                 Proto->isVariadic(), 0,
2830                                 Proto->hasExceptionSpec(),
2831                                 Proto->hasAnyExceptionSpec(),
2832                                 Proto->getNumExceptions(),
2833                                 Proto->exception_begin(),
2834                                 Proto->getExtInfo());
2835}
2836
2837/// CheckConstructor - Checks a fully-formed constructor for
2838/// well-formedness, issuing any diagnostics required. Returns true if
2839/// the constructor declarator is invalid.
2840void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
2841  CXXRecordDecl *ClassDecl
2842    = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2843  if (!ClassDecl)
2844    return Constructor->setInvalidDecl();
2845
2846  // C++ [class.copy]p3:
2847  //   A declaration of a constructor for a class X is ill-formed if
2848  //   its first parameter is of type (optionally cv-qualified) X and
2849  //   either there are no other parameters or else all other
2850  //   parameters have default arguments.
2851  if (!Constructor->isInvalidDecl() &&
2852      ((Constructor->getNumParams() == 1) ||
2853       (Constructor->getNumParams() > 1 &&
2854        Constructor->getParamDecl(1)->hasDefaultArg())) &&
2855      Constructor->getTemplateSpecializationKind()
2856                                              != TSK_ImplicitInstantiation) {
2857    QualType ParamType = Constructor->getParamDecl(0)->getType();
2858    QualType ClassTy = Context.getTagDeclType(ClassDecl);
2859    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
2860      SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2861      Diag(ParamLoc, diag::err_constructor_byvalue_arg)
2862        << FixItHint::CreateInsertion(ParamLoc, " const &");
2863
2864      // FIXME: Rather that making the constructor invalid, we should endeavor
2865      // to fix the type.
2866      Constructor->setInvalidDecl();
2867    }
2868  }
2869
2870  // Notify the class that we've added a constructor.  In principle we
2871  // don't need to do this for out-of-line declarations; in practice
2872  // we only instantiate the most recent declaration of a method, so
2873  // we have to call this for everything but friends.
2874  if (!Constructor->getFriendObjectKind())
2875    ClassDecl->addedConstructor(Context, Constructor);
2876}
2877
2878/// CheckDestructor - Checks a fully-formed destructor for well-formedness,
2879/// issuing any diagnostics required. Returns true on error.
2880bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
2881  CXXRecordDecl *RD = Destructor->getParent();
2882
2883  if (Destructor->isVirtual()) {
2884    SourceLocation Loc;
2885
2886    if (!Destructor->isImplicit())
2887      Loc = Destructor->getLocation();
2888    else
2889      Loc = RD->getLocation();
2890
2891    // If we have a virtual destructor, look up the deallocation function
2892    FunctionDecl *OperatorDelete = 0;
2893    DeclarationName Name =
2894    Context.DeclarationNames.getCXXOperatorName(OO_Delete);
2895    if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2896      return true;
2897
2898    Destructor->setOperatorDelete(OperatorDelete);
2899  }
2900
2901  return false;
2902}
2903
2904static inline bool
2905FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2906  return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2907          FTI.ArgInfo[0].Param &&
2908          FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2909}
2910
2911/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2912/// the well-formednes of the destructor declarator @p D with type @p
2913/// R. If there are any errors in the declarator, this routine will
2914/// emit diagnostics and set the declarator to invalid.  Even if this happens,
2915/// will be updated to reflect a well-formed type for the destructor and
2916/// returned.
2917QualType Sema::CheckDestructorDeclarator(Declarator &D,
2918                                         FunctionDecl::StorageClass& SC) {
2919  // C++ [class.dtor]p1:
2920  //   [...] A typedef-name that names a class is a class-name
2921  //   (7.1.3); however, a typedef-name that names a class shall not
2922  //   be used as the identifier in the declarator for a destructor
2923  //   declaration.
2924  QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
2925  if (isa<TypedefType>(DeclaratorType)) {
2926    Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
2927      << DeclaratorType;
2928    D.setInvalidType();
2929  }
2930
2931  // C++ [class.dtor]p2:
2932  //   A destructor is used to destroy objects of its class type. A
2933  //   destructor takes no parameters, and no return type can be
2934  //   specified for it (not even void). The address of a destructor
2935  //   shall not be taken. A destructor shall not be static. A
2936  //   destructor can be invoked for a const, volatile or const
2937  //   volatile object. A destructor shall not be declared const,
2938  //   volatile or const volatile (9.3.2).
2939  if (SC == FunctionDecl::Static) {
2940    if (!D.isInvalidType())
2941      Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2942        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2943        << SourceRange(D.getIdentifierLoc());
2944    SC = FunctionDecl::None;
2945    D.setInvalidType();
2946  }
2947  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
2948    // Destructors don't have return types, but the parser will
2949    // happily parse something like:
2950    //
2951    //   class X {
2952    //     float ~X();
2953    //   };
2954    //
2955    // The return type will be eliminated later.
2956    Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2957      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2958      << SourceRange(D.getIdentifierLoc());
2959  }
2960
2961  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2962  if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
2963    if (FTI.TypeQuals & Qualifiers::Const)
2964      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2965        << "const" << SourceRange(D.getIdentifierLoc());
2966    if (FTI.TypeQuals & Qualifiers::Volatile)
2967      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2968        << "volatile" << SourceRange(D.getIdentifierLoc());
2969    if (FTI.TypeQuals & Qualifiers::Restrict)
2970      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2971        << "restrict" << SourceRange(D.getIdentifierLoc());
2972    D.setInvalidType();
2973  }
2974
2975  // Make sure we don't have any parameters.
2976  if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
2977    Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2978
2979    // Delete the parameters.
2980    FTI.freeArgs();
2981    D.setInvalidType();
2982  }
2983
2984  // Make sure the destructor isn't variadic.
2985  if (FTI.isVariadic) {
2986    Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
2987    D.setInvalidType();
2988  }
2989
2990  // Rebuild the function type "R" without any type qualifiers or
2991  // parameters (in case any of the errors above fired) and with
2992  // "void" as the return type, since destructors don't have return
2993  // types. We *always* have to do this, because GetTypeForDeclarator
2994  // will put in a result type of "int" when none was specified.
2995  // FIXME: Exceptions!
2996  return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0,
2997                                 false, false, 0, 0, FunctionType::ExtInfo());
2998}
2999
3000/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3001/// well-formednes of the conversion function declarator @p D with
3002/// type @p R. If there are any errors in the declarator, this routine
3003/// will emit diagnostics and return true. Otherwise, it will return
3004/// false. Either way, the type @p R will be updated to reflect a
3005/// well-formed type for the conversion operator.
3006void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
3007                                     FunctionDecl::StorageClass& SC) {
3008  // C++ [class.conv.fct]p1:
3009  //   Neither parameter types nor return type can be specified. The
3010  //   type of a conversion function (8.3.5) is "function taking no
3011  //   parameter returning conversion-type-id."
3012  if (SC == FunctionDecl::Static) {
3013    if (!D.isInvalidType())
3014      Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3015        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3016        << SourceRange(D.getIdentifierLoc());
3017    D.setInvalidType();
3018    SC = FunctionDecl::None;
3019  }
3020
3021  QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3022
3023  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
3024    // Conversion functions don't have return types, but the parser will
3025    // happily parse something like:
3026    //
3027    //   class X {
3028    //     float operator bool();
3029    //   };
3030    //
3031    // The return type will be changed later anyway.
3032    Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3033      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3034      << SourceRange(D.getIdentifierLoc());
3035    D.setInvalidType();
3036  }
3037
3038  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3039
3040  // Make sure we don't have any parameters.
3041  if (Proto->getNumArgs() > 0) {
3042    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3043
3044    // Delete the parameters.
3045    D.getTypeObject(0).Fun.freeArgs();
3046    D.setInvalidType();
3047  } else if (Proto->isVariadic()) {
3048    Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
3049    D.setInvalidType();
3050  }
3051
3052  // Diagnose "&operator bool()" and other such nonsense.  This
3053  // is actually a gcc extension which we don't support.
3054  if (Proto->getResultType() != ConvType) {
3055    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3056      << Proto->getResultType();
3057    D.setInvalidType();
3058    ConvType = Proto->getResultType();
3059  }
3060
3061  // C++ [class.conv.fct]p4:
3062  //   The conversion-type-id shall not represent a function type nor
3063  //   an array type.
3064  if (ConvType->isArrayType()) {
3065    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3066    ConvType = Context.getPointerType(ConvType);
3067    D.setInvalidType();
3068  } else if (ConvType->isFunctionType()) {
3069    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3070    ConvType = Context.getPointerType(ConvType);
3071    D.setInvalidType();
3072  }
3073
3074  // Rebuild the function type "R" without any parameters (in case any
3075  // of the errors above fired) and with the conversion type as the
3076  // return type.
3077  if (D.isInvalidType()) {
3078    R = Context.getFunctionType(ConvType, 0, 0, false,
3079                                Proto->getTypeQuals(),
3080                                Proto->hasExceptionSpec(),
3081                                Proto->hasAnyExceptionSpec(),
3082                                Proto->getNumExceptions(),
3083                                Proto->exception_begin(),
3084                                Proto->getExtInfo());
3085  }
3086
3087  // C++0x explicit conversion operators.
3088  if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
3089    Diag(D.getDeclSpec().getExplicitSpecLoc(),
3090         diag::warn_explicit_conversion_functions)
3091      << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
3092}
3093
3094/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3095/// the declaration of the given C++ conversion function. This routine
3096/// is responsible for recording the conversion function in the C++
3097/// class, if possible.
3098Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
3099  assert(Conversion && "Expected to receive a conversion function declaration");
3100
3101  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
3102
3103  // Make sure we aren't redeclaring the conversion function.
3104  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
3105
3106  // C++ [class.conv.fct]p1:
3107  //   [...] A conversion function is never used to convert a
3108  //   (possibly cv-qualified) object to the (possibly cv-qualified)
3109  //   same object type (or a reference to it), to a (possibly
3110  //   cv-qualified) base class of that type (or a reference to it),
3111  //   or to (possibly cv-qualified) void.
3112  // FIXME: Suppress this warning if the conversion function ends up being a
3113  // virtual function that overrides a virtual function in a base class.
3114  QualType ClassType
3115    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
3116  if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
3117    ConvType = ConvTypeRef->getPointeeType();
3118  if (ConvType->isRecordType()) {
3119    ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3120    if (ConvType == ClassType)
3121      Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
3122        << ClassType;
3123    else if (IsDerivedFrom(ClassType, ConvType))
3124      Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
3125        <<  ClassType << ConvType;
3126  } else if (ConvType->isVoidType()) {
3127    Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
3128      << ClassType << ConvType;
3129  }
3130
3131  if (Conversion->getPrimaryTemplate()) {
3132    // ignore specializations
3133  } else if (Conversion->getPreviousDeclaration()) {
3134    if (FunctionTemplateDecl *ConversionTemplate
3135                                  = Conversion->getDescribedFunctionTemplate()) {
3136      if (ClassDecl->replaceConversion(
3137                                   ConversionTemplate->getPreviousDeclaration(),
3138                                       ConversionTemplate))
3139        return DeclPtrTy::make(ConversionTemplate);
3140    } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(),
3141                                            Conversion))
3142      return DeclPtrTy::make(Conversion);
3143    assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
3144  } else if (FunctionTemplateDecl *ConversionTemplate
3145               = Conversion->getDescribedFunctionTemplate())
3146    ClassDecl->addConversionFunction(ConversionTemplate);
3147  else
3148    ClassDecl->addConversionFunction(Conversion);
3149
3150  return DeclPtrTy::make(Conversion);
3151}
3152
3153//===----------------------------------------------------------------------===//
3154// Namespace Handling
3155//===----------------------------------------------------------------------===//
3156
3157/// ActOnStartNamespaceDef - This is called at the start of a namespace
3158/// definition.
3159Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
3160                                             SourceLocation IdentLoc,
3161                                             IdentifierInfo *II,
3162                                             SourceLocation LBrace,
3163                                             AttributeList *AttrList) {
3164  NamespaceDecl *Namespc =
3165      NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
3166  Namespc->setLBracLoc(LBrace);
3167
3168  Scope *DeclRegionScope = NamespcScope->getParent();
3169
3170  ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3171
3172  if (II) {
3173    // C++ [namespace.def]p2:
3174    // The identifier in an original-namespace-definition shall not have been
3175    // previously defined in the declarative region in which the
3176    // original-namespace-definition appears. The identifier in an
3177    // original-namespace-definition is the name of the namespace. Subsequently
3178    // in that declarative region, it is treated as an original-namespace-name.
3179
3180    NamedDecl *PrevDecl
3181      = LookupSingleName(DeclRegionScope, II, IdentLoc, LookupOrdinaryName,
3182                         ForRedeclaration);
3183
3184    if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3185      // This is an extended namespace definition.
3186      // Attach this namespace decl to the chain of extended namespace
3187      // definitions.
3188      OrigNS->setNextNamespace(Namespc);
3189      Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
3190
3191      // Remove the previous declaration from the scope.
3192      if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
3193        IdResolver.RemoveDecl(OrigNS);
3194        DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
3195      }
3196    } else if (PrevDecl) {
3197      // This is an invalid name redefinition.
3198      Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3199       << Namespc->getDeclName();
3200      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3201      Namespc->setInvalidDecl();
3202      // Continue on to push Namespc as current DeclContext and return it.
3203    } else if (II->isStr("std") &&
3204               CurContext->getLookupContext()->isTranslationUnit()) {
3205      // This is the first "real" definition of the namespace "std", so update
3206      // our cache of the "std" namespace to point at this definition.
3207      if (StdNamespace) {
3208        // We had already defined a dummy namespace "std". Link this new
3209        // namespace definition to the dummy namespace "std".
3210        StdNamespace->setNextNamespace(Namespc);
3211        StdNamespace->setLocation(IdentLoc);
3212        Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
3213      }
3214
3215      // Make our StdNamespace cache point at the first real definition of the
3216      // "std" namespace.
3217      StdNamespace = Namespc;
3218    }
3219
3220    PushOnScopeChains(Namespc, DeclRegionScope);
3221  } else {
3222    // Anonymous namespaces.
3223    assert(Namespc->isAnonymousNamespace());
3224
3225    // Link the anonymous namespace into its parent.
3226    NamespaceDecl *PrevDecl;
3227    DeclContext *Parent = CurContext->getLookupContext();
3228    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3229      PrevDecl = TU->getAnonymousNamespace();
3230      TU->setAnonymousNamespace(Namespc);
3231    } else {
3232      NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3233      PrevDecl = ND->getAnonymousNamespace();
3234      ND->setAnonymousNamespace(Namespc);
3235    }
3236
3237    // Link the anonymous namespace with its previous declaration.
3238    if (PrevDecl) {
3239      assert(PrevDecl->isAnonymousNamespace());
3240      assert(!PrevDecl->getNextNamespace());
3241      Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3242      PrevDecl->setNextNamespace(Namespc);
3243    }
3244
3245    CurContext->addDecl(Namespc);
3246
3247    // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
3248    //   behaves as if it were replaced by
3249    //     namespace unique { /* empty body */ }
3250    //     using namespace unique;
3251    //     namespace unique { namespace-body }
3252    //   where all occurrences of 'unique' in a translation unit are
3253    //   replaced by the same identifier and this identifier differs
3254    //   from all other identifiers in the entire program.
3255
3256    // We just create the namespace with an empty name and then add an
3257    // implicit using declaration, just like the standard suggests.
3258    //
3259    // CodeGen enforces the "universally unique" aspect by giving all
3260    // declarations semantically contained within an anonymous
3261    // namespace internal linkage.
3262
3263    if (!PrevDecl) {
3264      UsingDirectiveDecl* UD
3265        = UsingDirectiveDecl::Create(Context, CurContext,
3266                                     /* 'using' */ LBrace,
3267                                     /* 'namespace' */ SourceLocation(),
3268                                     /* qualifier */ SourceRange(),
3269                                     /* NNS */ NULL,
3270                                     /* identifier */ SourceLocation(),
3271                                     Namespc,
3272                                     /* Ancestor */ CurContext);
3273      UD->setImplicit();
3274      CurContext->addDecl(UD);
3275    }
3276  }
3277
3278  // Although we could have an invalid decl (i.e. the namespace name is a
3279  // redefinition), push it as current DeclContext and try to continue parsing.
3280  // FIXME: We should be able to push Namespc here, so that the each DeclContext
3281  // for the namespace has the declarations that showed up in that particular
3282  // namespace definition.
3283  PushDeclContext(NamespcScope, Namespc);
3284  return DeclPtrTy::make(Namespc);
3285}
3286
3287/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3288/// is a namespace alias, returns the namespace it points to.
3289static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3290  if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3291    return AD->getNamespace();
3292  return dyn_cast_or_null<NamespaceDecl>(D);
3293}
3294
3295/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3296/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
3297void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
3298  Decl *Dcl = D.getAs<Decl>();
3299  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3300  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3301  Namespc->setRBracLoc(RBrace);
3302  PopDeclContext();
3303}
3304
3305Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
3306                                          SourceLocation UsingLoc,
3307                                          SourceLocation NamespcLoc,
3308                                          CXXScopeSpec &SS,
3309                                          SourceLocation IdentLoc,
3310                                          IdentifierInfo *NamespcName,
3311                                          AttributeList *AttrList) {
3312  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3313  assert(NamespcName && "Invalid NamespcName.");
3314  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
3315  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
3316
3317  UsingDirectiveDecl *UDir = 0;
3318
3319  // Lookup namespace name.
3320  LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3321  LookupParsedName(R, S, &SS);
3322  if (R.isAmbiguous())
3323    return DeclPtrTy();
3324
3325  if (!R.empty()) {
3326    NamedDecl *Named = R.getFoundDecl();
3327    assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3328        && "expected namespace decl");
3329    // C++ [namespace.udir]p1:
3330    //   A using-directive specifies that the names in the nominated
3331    //   namespace can be used in the scope in which the
3332    //   using-directive appears after the using-directive. During
3333    //   unqualified name lookup (3.4.1), the names appear as if they
3334    //   were declared in the nearest enclosing namespace which
3335    //   contains both the using-directive and the nominated
3336    //   namespace. [Note: in this context, "contains" means "contains
3337    //   directly or indirectly". ]
3338
3339    // Find enclosing context containing both using-directive and
3340    // nominated namespace.
3341    NamespaceDecl *NS = getNamespaceDecl(Named);
3342    DeclContext *CommonAncestor = cast<DeclContext>(NS);
3343    while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3344      CommonAncestor = CommonAncestor->getParent();
3345
3346    UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
3347                                      SS.getRange(),
3348                                      (NestedNameSpecifier *)SS.getScopeRep(),
3349                                      IdentLoc, Named, CommonAncestor);
3350    PushUsingDirective(S, UDir);
3351  } else {
3352    Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
3353  }
3354
3355  // FIXME: We ignore attributes for now.
3356  delete AttrList;
3357  return DeclPtrTy::make(UDir);
3358}
3359
3360void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3361  // If scope has associated entity, then using directive is at namespace
3362  // or translation unit scope. We add UsingDirectiveDecls, into
3363  // it's lookup structure.
3364  if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
3365    Ctx->addDecl(UDir);
3366  else
3367    // Otherwise it is block-sope. using-directives will affect lookup
3368    // only to the end of scope.
3369    S->PushUsingDirective(DeclPtrTy::make(UDir));
3370}
3371
3372
3373Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
3374                                            AccessSpecifier AS,
3375                                            bool HasUsingKeyword,
3376                                            SourceLocation UsingLoc,
3377                                            CXXScopeSpec &SS,
3378                                            UnqualifiedId &Name,
3379                                            AttributeList *AttrList,
3380                                            bool IsTypeName,
3381                                            SourceLocation TypenameLoc) {
3382  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
3383
3384  switch (Name.getKind()) {
3385  case UnqualifiedId::IK_Identifier:
3386  case UnqualifiedId::IK_OperatorFunctionId:
3387  case UnqualifiedId::IK_LiteralOperatorId:
3388  case UnqualifiedId::IK_ConversionFunctionId:
3389    break;
3390
3391  case UnqualifiedId::IK_ConstructorName:
3392  case UnqualifiedId::IK_ConstructorTemplateId:
3393    // C++0x inherited constructors.
3394    if (getLangOptions().CPlusPlus0x) break;
3395
3396    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3397      << SS.getRange();
3398    return DeclPtrTy();
3399
3400  case UnqualifiedId::IK_DestructorName:
3401    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3402      << SS.getRange();
3403    return DeclPtrTy();
3404
3405  case UnqualifiedId::IK_TemplateId:
3406    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3407      << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
3408    return DeclPtrTy();
3409  }
3410
3411  DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
3412  if (!TargetName)
3413    return DeclPtrTy();
3414
3415  // Warn about using declarations.
3416  // TODO: store that the declaration was written without 'using' and
3417  // talk about access decls instead of using decls in the
3418  // diagnostics.
3419  if (!HasUsingKeyword) {
3420    UsingLoc = Name.getSourceRange().getBegin();
3421
3422    Diag(UsingLoc, diag::warn_access_decl_deprecated)
3423      << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
3424  }
3425
3426  NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
3427                                        Name.getSourceRange().getBegin(),
3428                                        TargetName, AttrList,
3429                                        /* IsInstantiation */ false,
3430                                        IsTypeName, TypenameLoc);
3431  if (UD)
3432    PushOnScopeChains(UD, S, /*AddToContext*/ false);
3433
3434  return DeclPtrTy::make(UD);
3435}
3436
3437/// Determines whether to create a using shadow decl for a particular
3438/// decl, given the set of decls existing prior to this using lookup.
3439bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3440                                const LookupResult &Previous) {
3441  // Diagnose finding a decl which is not from a base class of the
3442  // current class.  We do this now because there are cases where this
3443  // function will silently decide not to build a shadow decl, which
3444  // will pre-empt further diagnostics.
3445  //
3446  // We don't need to do this in C++0x because we do the check once on
3447  // the qualifier.
3448  //
3449  // FIXME: diagnose the following if we care enough:
3450  //   struct A { int foo; };
3451  //   struct B : A { using A::foo; };
3452  //   template <class T> struct C : A {};
3453  //   template <class T> struct D : C<T> { using B::foo; } // <---
3454  // This is invalid (during instantiation) in C++03 because B::foo
3455  // resolves to the using decl in B, which is not a base class of D<T>.
3456  // We can't diagnose it immediately because C<T> is an unknown
3457  // specialization.  The UsingShadowDecl in D<T> then points directly
3458  // to A::foo, which will look well-formed when we instantiate.
3459  // The right solution is to not collapse the shadow-decl chain.
3460  if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3461    DeclContext *OrigDC = Orig->getDeclContext();
3462
3463    // Handle enums and anonymous structs.
3464    if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3465    CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3466    while (OrigRec->isAnonymousStructOrUnion())
3467      OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3468
3469    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3470      if (OrigDC == CurContext) {
3471        Diag(Using->getLocation(),
3472             diag::err_using_decl_nested_name_specifier_is_current_class)
3473          << Using->getNestedNameRange();
3474        Diag(Orig->getLocation(), diag::note_using_decl_target);
3475        return true;
3476      }
3477
3478      Diag(Using->getNestedNameRange().getBegin(),
3479           diag::err_using_decl_nested_name_specifier_is_not_base_class)
3480        << Using->getTargetNestedNameDecl()
3481        << cast<CXXRecordDecl>(CurContext)
3482        << Using->getNestedNameRange();
3483      Diag(Orig->getLocation(), diag::note_using_decl_target);
3484      return true;
3485    }
3486  }
3487
3488  if (Previous.empty()) return false;
3489
3490  NamedDecl *Target = Orig;
3491  if (isa<UsingShadowDecl>(Target))
3492    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3493
3494  // If the target happens to be one of the previous declarations, we
3495  // don't have a conflict.
3496  //
3497  // FIXME: but we might be increasing its access, in which case we
3498  // should redeclare it.
3499  NamedDecl *NonTag = 0, *Tag = 0;
3500  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3501         I != E; ++I) {
3502    NamedDecl *D = (*I)->getUnderlyingDecl();
3503    if (D->getCanonicalDecl() == Target->getCanonicalDecl())
3504      return false;
3505
3506    (isa<TagDecl>(D) ? Tag : NonTag) = D;
3507  }
3508
3509  if (Target->isFunctionOrFunctionTemplate()) {
3510    FunctionDecl *FD;
3511    if (isa<FunctionTemplateDecl>(Target))
3512      FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3513    else
3514      FD = cast<FunctionDecl>(Target);
3515
3516    NamedDecl *OldDecl = 0;
3517    switch (CheckOverload(FD, Previous, OldDecl)) {
3518    case Ovl_Overload:
3519      return false;
3520
3521    case Ovl_NonFunction:
3522      Diag(Using->getLocation(), diag::err_using_decl_conflict);
3523      break;
3524
3525    // We found a decl with the exact signature.
3526    case Ovl_Match:
3527      if (isa<UsingShadowDecl>(OldDecl)) {
3528        // Silently ignore the possible conflict.
3529        return false;
3530      }
3531
3532      // If we're in a record, we want to hide the target, so we
3533      // return true (without a diagnostic) to tell the caller not to
3534      // build a shadow decl.
3535      if (CurContext->isRecord())
3536        return true;
3537
3538      // If we're not in a record, this is an error.
3539      Diag(Using->getLocation(), diag::err_using_decl_conflict);
3540      break;
3541    }
3542
3543    Diag(Target->getLocation(), diag::note_using_decl_target);
3544    Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3545    return true;
3546  }
3547
3548  // Target is not a function.
3549
3550  if (isa<TagDecl>(Target)) {
3551    // No conflict between a tag and a non-tag.
3552    if (!Tag) return false;
3553
3554    Diag(Using->getLocation(), diag::err_using_decl_conflict);
3555    Diag(Target->getLocation(), diag::note_using_decl_target);
3556    Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3557    return true;
3558  }
3559
3560  // No conflict between a tag and a non-tag.
3561  if (!NonTag) return false;
3562
3563  Diag(Using->getLocation(), diag::err_using_decl_conflict);
3564  Diag(Target->getLocation(), diag::note_using_decl_target);
3565  Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3566  return true;
3567}
3568
3569/// Builds a shadow declaration corresponding to a 'using' declaration.
3570UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
3571                                            UsingDecl *UD,
3572                                            NamedDecl *Orig) {
3573
3574  // If we resolved to another shadow declaration, just coalesce them.
3575  NamedDecl *Target = Orig;
3576  if (isa<UsingShadowDecl>(Target)) {
3577    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3578    assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
3579  }
3580
3581  UsingShadowDecl *Shadow
3582    = UsingShadowDecl::Create(Context, CurContext,
3583                              UD->getLocation(), UD, Target);
3584  UD->addShadowDecl(Shadow);
3585
3586  if (S)
3587    PushOnScopeChains(Shadow, S);
3588  else
3589    CurContext->addDecl(Shadow);
3590  Shadow->setAccess(UD->getAccess());
3591
3592  // Register it as a conversion if appropriate.
3593  if (Shadow->getDeclName().getNameKind()
3594        == DeclarationName::CXXConversionFunctionName)
3595    cast<CXXRecordDecl>(CurContext)->addConversionFunction(Shadow);
3596
3597  if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3598    Shadow->setInvalidDecl();
3599
3600  return Shadow;
3601}
3602
3603/// Hides a using shadow declaration.  This is required by the current
3604/// using-decl implementation when a resolvable using declaration in a
3605/// class is followed by a declaration which would hide or override
3606/// one or more of the using decl's targets; for example:
3607///
3608///   struct Base { void foo(int); };
3609///   struct Derived : Base {
3610///     using Base::foo;
3611///     void foo(int);
3612///   };
3613///
3614/// The governing language is C++03 [namespace.udecl]p12:
3615///
3616///   When a using-declaration brings names from a base class into a
3617///   derived class scope, member functions in the derived class
3618///   override and/or hide member functions with the same name and
3619///   parameter types in a base class (rather than conflicting).
3620///
3621/// There are two ways to implement this:
3622///   (1) optimistically create shadow decls when they're not hidden
3623///       by existing declarations, or
3624///   (2) don't create any shadow decls (or at least don't make them
3625///       visible) until we've fully parsed/instantiated the class.
3626/// The problem with (1) is that we might have to retroactively remove
3627/// a shadow decl, which requires several O(n) operations because the
3628/// decl structures are (very reasonably) not designed for removal.
3629/// (2) avoids this but is very fiddly and phase-dependent.
3630void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
3631  if (Shadow->getDeclName().getNameKind() ==
3632        DeclarationName::CXXConversionFunctionName)
3633    cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3634
3635  // Remove it from the DeclContext...
3636  Shadow->getDeclContext()->removeDecl(Shadow);
3637
3638  // ...and the scope, if applicable...
3639  if (S) {
3640    S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow)));
3641    IdResolver.RemoveDecl(Shadow);
3642  }
3643
3644  // ...and the using decl.
3645  Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3646
3647  // TODO: complain somehow if Shadow was used.  It shouldn't
3648  // be possible for this to happen, because...?
3649}
3650
3651/// Builds a using declaration.
3652///
3653/// \param IsInstantiation - Whether this call arises from an
3654///   instantiation of an unresolved using declaration.  We treat
3655///   the lookup differently for these declarations.
3656NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3657                                       SourceLocation UsingLoc,
3658                                       CXXScopeSpec &SS,
3659                                       SourceLocation IdentLoc,
3660                                       DeclarationName Name,
3661                                       AttributeList *AttrList,
3662                                       bool IsInstantiation,
3663                                       bool IsTypeName,
3664                                       SourceLocation TypenameLoc) {
3665  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3666  assert(IdentLoc.isValid() && "Invalid TargetName location.");
3667
3668  // FIXME: We ignore attributes for now.
3669  delete AttrList;
3670
3671  if (SS.isEmpty()) {
3672    Diag(IdentLoc, diag::err_using_requires_qualname);
3673    return 0;
3674  }
3675
3676  // Do the redeclaration lookup in the current scope.
3677  LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName,
3678                        ForRedeclaration);
3679  Previous.setHideTags(false);
3680  if (S) {
3681    LookupName(Previous, S);
3682
3683    // It is really dumb that we have to do this.
3684    LookupResult::Filter F = Previous.makeFilter();
3685    while (F.hasNext()) {
3686      NamedDecl *D = F.next();
3687      if (!isDeclInScope(D, CurContext, S))
3688        F.erase();
3689    }
3690    F.done();
3691  } else {
3692    assert(IsInstantiation && "no scope in non-instantiation");
3693    assert(CurContext->isRecord() && "scope not record in instantiation");
3694    LookupQualifiedName(Previous, CurContext);
3695  }
3696
3697  NestedNameSpecifier *NNS =
3698    static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3699
3700  // Check for invalid redeclarations.
3701  if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3702    return 0;
3703
3704  // Check for bad qualifiers.
3705  if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3706    return 0;
3707
3708  DeclContext *LookupContext = computeDeclContext(SS);
3709  NamedDecl *D;
3710  if (!LookupContext) {
3711    if (IsTypeName) {
3712      // FIXME: not all declaration name kinds are legal here
3713      D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3714                                              UsingLoc, TypenameLoc,
3715                                              SS.getRange(), NNS,
3716                                              IdentLoc, Name);
3717    } else {
3718      D = UnresolvedUsingValueDecl::Create(Context, CurContext,
3719                                           UsingLoc, SS.getRange(), NNS,
3720                                           IdentLoc, Name);
3721    }
3722  } else {
3723    D = UsingDecl::Create(Context, CurContext, IdentLoc,
3724                          SS.getRange(), UsingLoc, NNS, Name,
3725                          IsTypeName);
3726  }
3727  D->setAccess(AS);
3728  CurContext->addDecl(D);
3729
3730  if (!LookupContext) return D;
3731  UsingDecl *UD = cast<UsingDecl>(D);
3732
3733  if (RequireCompleteDeclContext(SS)) {
3734    UD->setInvalidDecl();
3735    return UD;
3736  }
3737
3738  // Look up the target name.
3739
3740  LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
3741
3742  // Unlike most lookups, we don't always want to hide tag
3743  // declarations: tag names are visible through the using declaration
3744  // even if hidden by ordinary names, *except* in a dependent context
3745  // where it's important for the sanity of two-phase lookup.
3746  if (!IsInstantiation)
3747    R.setHideTags(false);
3748
3749  LookupQualifiedName(R, LookupContext);
3750
3751  if (R.empty()) {
3752    Diag(IdentLoc, diag::err_no_member)
3753      << Name << LookupContext << SS.getRange();
3754    UD->setInvalidDecl();
3755    return UD;
3756  }
3757
3758  if (R.isAmbiguous()) {
3759    UD->setInvalidDecl();
3760    return UD;
3761  }
3762
3763  if (IsTypeName) {
3764    // If we asked for a typename and got a non-type decl, error out.
3765    if (!R.getAsSingle<TypeDecl>()) {
3766      Diag(IdentLoc, diag::err_using_typename_non_type);
3767      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3768        Diag((*I)->getUnderlyingDecl()->getLocation(),
3769             diag::note_using_decl_target);
3770      UD->setInvalidDecl();
3771      return UD;
3772    }
3773  } else {
3774    // If we asked for a non-typename and we got a type, error out,
3775    // but only if this is an instantiation of an unresolved using
3776    // decl.  Otherwise just silently find the type name.
3777    if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
3778      Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3779      Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
3780      UD->setInvalidDecl();
3781      return UD;
3782    }
3783  }
3784
3785  // C++0x N2914 [namespace.udecl]p6:
3786  // A using-declaration shall not name a namespace.
3787  if (R.getAsSingle<NamespaceDecl>()) {
3788    Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3789      << SS.getRange();
3790    UD->setInvalidDecl();
3791    return UD;
3792  }
3793
3794  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3795    if (!CheckUsingShadowDecl(UD, *I, Previous))
3796      BuildUsingShadowDecl(S, UD, *I);
3797  }
3798
3799  return UD;
3800}
3801
3802/// Checks that the given using declaration is not an invalid
3803/// redeclaration.  Note that this is checking only for the using decl
3804/// itself, not for any ill-formedness among the UsingShadowDecls.
3805bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3806                                       bool isTypeName,
3807                                       const CXXScopeSpec &SS,
3808                                       SourceLocation NameLoc,
3809                                       const LookupResult &Prev) {
3810  // C++03 [namespace.udecl]p8:
3811  // C++0x [namespace.udecl]p10:
3812  //   A using-declaration is a declaration and can therefore be used
3813  //   repeatedly where (and only where) multiple declarations are
3814  //   allowed.
3815  // That's only in file contexts.
3816  if (CurContext->getLookupContext()->isFileContext())
3817    return false;
3818
3819  NestedNameSpecifier *Qual
3820    = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3821
3822  for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3823    NamedDecl *D = *I;
3824
3825    bool DTypename;
3826    NestedNameSpecifier *DQual;
3827    if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3828      DTypename = UD->isTypeName();
3829      DQual = UD->getTargetNestedNameDecl();
3830    } else if (UnresolvedUsingValueDecl *UD
3831                 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3832      DTypename = false;
3833      DQual = UD->getTargetNestedNameSpecifier();
3834    } else if (UnresolvedUsingTypenameDecl *UD
3835                 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3836      DTypename = true;
3837      DQual = UD->getTargetNestedNameSpecifier();
3838    } else continue;
3839
3840    // using decls differ if one says 'typename' and the other doesn't.
3841    // FIXME: non-dependent using decls?
3842    if (isTypeName != DTypename) continue;
3843
3844    // using decls differ if they name different scopes (but note that
3845    // template instantiation can cause this check to trigger when it
3846    // didn't before instantiation).
3847    if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3848        Context.getCanonicalNestedNameSpecifier(DQual))
3849      continue;
3850
3851    Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
3852    Diag(D->getLocation(), diag::note_using_decl) << 1;
3853    return true;
3854  }
3855
3856  return false;
3857}
3858
3859
3860/// Checks that the given nested-name qualifier used in a using decl
3861/// in the current context is appropriately related to the current
3862/// scope.  If an error is found, diagnoses it and returns true.
3863bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3864                                   const CXXScopeSpec &SS,
3865                                   SourceLocation NameLoc) {
3866  DeclContext *NamedContext = computeDeclContext(SS);
3867
3868  if (!CurContext->isRecord()) {
3869    // C++03 [namespace.udecl]p3:
3870    // C++0x [namespace.udecl]p8:
3871    //   A using-declaration for a class member shall be a member-declaration.
3872
3873    // If we weren't able to compute a valid scope, it must be a
3874    // dependent class scope.
3875    if (!NamedContext || NamedContext->isRecord()) {
3876      Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
3877        << SS.getRange();
3878      return true;
3879    }
3880
3881    // Otherwise, everything is known to be fine.
3882    return false;
3883  }
3884
3885  // The current scope is a record.
3886
3887  // If the named context is dependent, we can't decide much.
3888  if (!NamedContext) {
3889    // FIXME: in C++0x, we can diagnose if we can prove that the
3890    // nested-name-specifier does not refer to a base class, which is
3891    // still possible in some cases.
3892
3893    // Otherwise we have to conservatively report that things might be
3894    // okay.
3895    return false;
3896  }
3897
3898  if (!NamedContext->isRecord()) {
3899    // Ideally this would point at the last name in the specifier,
3900    // but we don't have that level of source info.
3901    Diag(SS.getRange().getBegin(),
3902         diag::err_using_decl_nested_name_specifier_is_not_class)
3903      << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
3904    return true;
3905  }
3906
3907  if (getLangOptions().CPlusPlus0x) {
3908    // C++0x [namespace.udecl]p3:
3909    //   In a using-declaration used as a member-declaration, the
3910    //   nested-name-specifier shall name a base class of the class
3911    //   being defined.
3912
3913    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
3914                                 cast<CXXRecordDecl>(NamedContext))) {
3915      if (CurContext == NamedContext) {
3916        Diag(NameLoc,
3917             diag::err_using_decl_nested_name_specifier_is_current_class)
3918          << SS.getRange();
3919        return true;
3920      }
3921
3922      Diag(SS.getRange().getBegin(),
3923           diag::err_using_decl_nested_name_specifier_is_not_base_class)
3924        << (NestedNameSpecifier*) SS.getScopeRep()
3925        << cast<CXXRecordDecl>(CurContext)
3926        << SS.getRange();
3927      return true;
3928    }
3929
3930    return false;
3931  }
3932
3933  // C++03 [namespace.udecl]p4:
3934  //   A using-declaration used as a member-declaration shall refer
3935  //   to a member of a base class of the class being defined [etc.].
3936
3937  // Salient point: SS doesn't have to name a base class as long as
3938  // lookup only finds members from base classes.  Therefore we can
3939  // diagnose here only if we can prove that that can't happen,
3940  // i.e. if the class hierarchies provably don't intersect.
3941
3942  // TODO: it would be nice if "definitely valid" results were cached
3943  // in the UsingDecl and UsingShadowDecl so that these checks didn't
3944  // need to be repeated.
3945
3946  struct UserData {
3947    llvm::DenseSet<const CXXRecordDecl*> Bases;
3948
3949    static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
3950      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3951      Data->Bases.insert(Base);
3952      return true;
3953    }
3954
3955    bool hasDependentBases(const CXXRecordDecl *Class) {
3956      return !Class->forallBases(collect, this);
3957    }
3958
3959    /// Returns true if the base is dependent or is one of the
3960    /// accumulated base classes.
3961    static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
3962      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3963      return !Data->Bases.count(Base);
3964    }
3965
3966    bool mightShareBases(const CXXRecordDecl *Class) {
3967      return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
3968    }
3969  };
3970
3971  UserData Data;
3972
3973  // Returns false if we find a dependent base.
3974  if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
3975    return false;
3976
3977  // Returns false if the class has a dependent base or if it or one
3978  // of its bases is present in the base set of the current context.
3979  if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
3980    return false;
3981
3982  Diag(SS.getRange().getBegin(),
3983       diag::err_using_decl_nested_name_specifier_is_not_base_class)
3984    << (NestedNameSpecifier*) SS.getScopeRep()
3985    << cast<CXXRecordDecl>(CurContext)
3986    << SS.getRange();
3987
3988  return true;
3989}
3990
3991Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
3992                                             SourceLocation NamespaceLoc,
3993                                             SourceLocation AliasLoc,
3994                                             IdentifierInfo *Alias,
3995                                             CXXScopeSpec &SS,
3996                                             SourceLocation IdentLoc,
3997                                             IdentifierInfo *Ident) {
3998
3999  // Lookup the namespace name.
4000  LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4001  LookupParsedName(R, S, &SS);
4002
4003  // Check if we have a previous declaration with the same name.
4004  if (NamedDecl *PrevDecl
4005        = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4006                           ForRedeclaration)) {
4007    if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
4008      // We already have an alias with the same name that points to the same
4009      // namespace, so don't create a new one.
4010      // FIXME: At some point, we'll want to create the (redundant)
4011      // declaration to maintain better source information.
4012      if (!R.isAmbiguous() && !R.empty() &&
4013          AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
4014        return DeclPtrTy();
4015    }
4016
4017    unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4018      diag::err_redefinition_different_kind;
4019    Diag(AliasLoc, DiagID) << Alias;
4020    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4021    return DeclPtrTy();
4022  }
4023
4024  if (R.isAmbiguous())
4025    return DeclPtrTy();
4026
4027  if (R.empty()) {
4028    Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
4029    return DeclPtrTy();
4030  }
4031
4032  NamespaceAliasDecl *AliasDecl =
4033    NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4034                               Alias, SS.getRange(),
4035                               (NestedNameSpecifier *)SS.getScopeRep(),
4036                               IdentLoc, R.getFoundDecl());
4037
4038  PushOnScopeChains(AliasDecl, S);
4039  return DeclPtrTy::make(AliasDecl);
4040}
4041
4042void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4043                                            CXXConstructorDecl *Constructor) {
4044  assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
4045          !Constructor->isUsed()) &&
4046    "DefineImplicitDefaultConstructor - call it for implicit default ctor");
4047
4048  CXXRecordDecl *ClassDecl = Constructor->getParent();
4049  assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
4050
4051  DeclContext *PreviousContext = CurContext;
4052  CurContext = Constructor;
4053  if (SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false)) {
4054    Diag(CurrentLocation, diag::note_member_synthesized_at)
4055      << CXXConstructor << Context.getTagDeclType(ClassDecl);
4056    Constructor->setInvalidDecl();
4057  } else {
4058    Constructor->setUsed();
4059  }
4060  CurContext = PreviousContext;
4061}
4062
4063void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
4064                                    CXXDestructorDecl *Destructor) {
4065  assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
4066         "DefineImplicitDestructor - call it for implicit default dtor");
4067  CXXRecordDecl *ClassDecl = Destructor->getParent();
4068  assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
4069
4070  DeclContext *PreviousContext = CurContext;
4071  CurContext = Destructor;
4072
4073  MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4074                                         Destructor->getParent());
4075
4076  // FIXME: If CheckDestructor fails, we should emit a note about where the
4077  // implicit destructor was needed.
4078  if (CheckDestructor(Destructor)) {
4079    Diag(CurrentLocation, diag::note_member_synthesized_at)
4080      << CXXDestructor << Context.getTagDeclType(ClassDecl);
4081
4082    Destructor->setInvalidDecl();
4083    CurContext = PreviousContext;
4084
4085    return;
4086  }
4087  CurContext = PreviousContext;
4088
4089  Destructor->setUsed();
4090}
4091
4092void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
4093                                          CXXMethodDecl *MethodDecl) {
4094  assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
4095          MethodDecl->getOverloadedOperator() == OO_Equal &&
4096          !MethodDecl->isUsed()) &&
4097         "DefineImplicitOverloadedAssign - call it for implicit assignment op");
4098
4099  CXXRecordDecl *ClassDecl
4100    = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
4101
4102  DeclContext *PreviousContext = CurContext;
4103  CurContext = MethodDecl;
4104
4105  // C++[class.copy] p12
4106  // Before the implicitly-declared copy assignment operator for a class is
4107  // implicitly defined, all implicitly-declared copy assignment operators
4108  // for its direct base classes and its nonstatic data members shall have
4109  // been implicitly defined.
4110  bool err = false;
4111  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4112       E = ClassDecl->bases_end(); Base != E; ++Base) {
4113    CXXRecordDecl *BaseClassDecl
4114      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
4115    if (CXXMethodDecl *BaseAssignOpMethod =
4116          getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
4117                                  BaseClassDecl)) {
4118      CheckDirectMemberAccess(Base->getSourceRange().getBegin(),
4119                              BaseAssignOpMethod,
4120                              PDiag(diag::err_access_assign_base)
4121                                << Base->getType());
4122
4123      MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
4124    }
4125  }
4126  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4127       E = ClassDecl->field_end(); Field != E; ++Field) {
4128    QualType FieldType = Context.getCanonicalType((*Field)->getType());
4129    if (const ArrayType *Array = Context.getAsArrayType(FieldType))
4130      FieldType = Array->getElementType();
4131    if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
4132      CXXRecordDecl *FieldClassDecl
4133        = cast<CXXRecordDecl>(FieldClassType->getDecl());
4134      if (CXXMethodDecl *FieldAssignOpMethod =
4135          getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
4136                                  FieldClassDecl)) {
4137        CheckDirectMemberAccess(Field->getLocation(),
4138                                FieldAssignOpMethod,
4139                                PDiag(diag::err_access_assign_field)
4140                                  << Field->getDeclName() << Field->getType());
4141
4142        MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
4143      }
4144    } else if (FieldType->isReferenceType()) {
4145      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4146      << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
4147      Diag(Field->getLocation(), diag::note_declared_at);
4148      Diag(CurrentLocation, diag::note_first_required_here);
4149      err = true;
4150    } else if (FieldType.isConstQualified()) {
4151      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4152      << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
4153      Diag(Field->getLocation(), diag::note_declared_at);
4154      Diag(CurrentLocation, diag::note_first_required_here);
4155      err = true;
4156    }
4157  }
4158  if (!err)
4159    MethodDecl->setUsed();
4160
4161  CurContext = PreviousContext;
4162}
4163
4164CXXMethodDecl *
4165Sema::getAssignOperatorMethod(SourceLocation CurrentLocation,
4166                              ParmVarDecl *ParmDecl,
4167                              CXXRecordDecl *ClassDecl) {
4168  QualType LHSType = Context.getTypeDeclType(ClassDecl);
4169  QualType RHSType(LHSType);
4170  // If class's assignment operator argument is const/volatile qualified,
4171  // look for operator = (const/volatile B&). Otherwise, look for
4172  // operator = (B&).
4173  RHSType = Context.getCVRQualifiedType(RHSType,
4174                                     ParmDecl->getType().getCVRQualifiers());
4175  ExprOwningPtr<Expr> LHS(this,  new (Context) DeclRefExpr(ParmDecl,
4176                                                           LHSType,
4177                                                           SourceLocation()));
4178  ExprOwningPtr<Expr> RHS(this,  new (Context) DeclRefExpr(ParmDecl,
4179                                                           RHSType,
4180                                                           CurrentLocation));
4181  Expr *Args[2] = { &*LHS, &*RHS };
4182  OverloadCandidateSet CandidateSet(CurrentLocation);
4183  AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
4184                              CandidateSet);
4185  OverloadCandidateSet::iterator Best;
4186  if (BestViableFunction(CandidateSet, CurrentLocation, Best) == OR_Success)
4187    return cast<CXXMethodDecl>(Best->Function);
4188  assert(false &&
4189         "getAssignOperatorMethod - copy assignment operator method not found");
4190  return 0;
4191}
4192
4193void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4194                                   CXXConstructorDecl *CopyConstructor,
4195                                   unsigned TypeQuals) {
4196  assert((CopyConstructor->isImplicit() &&
4197          CopyConstructor->isCopyConstructor(TypeQuals) &&
4198          !CopyConstructor->isUsed()) &&
4199         "DefineImplicitCopyConstructor - call it for implicit copy ctor");
4200
4201  CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
4202  assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
4203
4204  DeclContext *PreviousContext = CurContext;
4205  CurContext = CopyConstructor;
4206
4207  if (SetBaseOrMemberInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false)) {
4208    Diag(CurrentLocation, diag::note_member_synthesized_at)
4209    << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
4210    CopyConstructor->setInvalidDecl();
4211  } else {
4212    CopyConstructor->setUsed();
4213  }
4214
4215  // FIXME: Once we teach SetBaseOrMemberInitializers to copy fields, we can
4216  // get rid of this code.
4217  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4218                                  FieldEnd = ClassDecl->field_end();
4219       Field != FieldEnd; ++Field) {
4220    QualType FieldType = Context.getCanonicalType((*Field)->getType());
4221    if (const ArrayType *Array = Context.getAsArrayType(FieldType))
4222      FieldType = Array->getElementType();
4223    if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
4224      CXXRecordDecl *FieldClassDecl
4225        = cast<CXXRecordDecl>(FieldClassType->getDecl());
4226      if (CXXConstructorDecl *FieldCopyCtor =
4227          FieldClassDecl->getCopyConstructor(Context, TypeQuals)) {
4228        CheckDirectMemberAccess(Field->getLocation(),
4229                                FieldCopyCtor,
4230                                PDiag(diag::err_access_copy_field)
4231                                  << Field->getDeclName() << Field->getType());
4232
4233        MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
4234      }
4235    }
4236  }
4237  CopyConstructor->setUsed();
4238
4239  CurContext = PreviousContext;
4240}
4241
4242Sema::OwningExprResult
4243Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4244                            CXXConstructorDecl *Constructor,
4245                            MultiExprArg ExprArgs,
4246                            bool RequiresZeroInit,
4247                            bool BaseInitialization) {
4248  bool Elidable = false;
4249
4250  // C++0x [class.copy]p34:
4251  //   When certain criteria are met, an implementation is allowed to
4252  //   omit the copy/move construction of a class object, even if the
4253  //   copy/move constructor and/or destructor for the object have
4254  //   side effects. [...]
4255  //     - when a temporary class object that has not been bound to a
4256  //       reference (12.2) would be copied/moved to a class object
4257  //       with the same cv-unqualified type, the copy/move operation
4258  //       can be omitted by constructing the temporary object
4259  //       directly into the target of the omitted copy/move
4260  if (Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
4261    Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
4262    Elidable = SubExpr->isTemporaryObject() &&
4263      Context.hasSameUnqualifiedType(SubExpr->getType(),
4264                           Context.getTypeDeclType(Constructor->getParent()));
4265  }
4266
4267  return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
4268                               Elidable, move(ExprArgs), RequiresZeroInit,
4269                               BaseInitialization);
4270}
4271
4272/// BuildCXXConstructExpr - Creates a complete call to a constructor,
4273/// including handling of its default argument expressions.
4274Sema::OwningExprResult
4275Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4276                            CXXConstructorDecl *Constructor, bool Elidable,
4277                            MultiExprArg ExprArgs,
4278                            bool RequiresZeroInit,
4279                            bool BaseInitialization) {
4280  unsigned NumExprs = ExprArgs.size();
4281  Expr **Exprs = (Expr **)ExprArgs.release();
4282
4283  MarkDeclarationReferenced(ConstructLoc, Constructor);
4284  return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
4285                                        Constructor, Elidable, Exprs, NumExprs,
4286                                        RequiresZeroInit, BaseInitialization));
4287}
4288
4289bool Sema::InitializeVarWithConstructor(VarDecl *VD,
4290                                        CXXConstructorDecl *Constructor,
4291                                        MultiExprArg Exprs) {
4292  OwningExprResult TempResult =
4293    BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
4294                          move(Exprs));
4295  if (TempResult.isInvalid())
4296    return true;
4297
4298  Expr *Temp = TempResult.takeAs<Expr>();
4299  MarkDeclarationReferenced(VD->getLocation(), Constructor);
4300  Temp = MaybeCreateCXXExprWithTemporaries(Temp);
4301  VD->setInit(Temp);
4302
4303  return false;
4304}
4305
4306void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
4307  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
4308  if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
4309      !ClassDecl->hasTrivialDestructor()) {
4310    CXXDestructorDecl *Destructor = ClassDecl->getDestructor(Context);
4311    MarkDeclarationReferenced(VD->getLocation(), Destructor);
4312    CheckDestructorAccess(VD->getLocation(), Destructor,
4313                          PDiag(diag::err_access_dtor_var)
4314                            << VD->getDeclName()
4315                            << VD->getType());
4316  }
4317}
4318
4319/// AddCXXDirectInitializerToDecl - This action is called immediately after
4320/// ActOnDeclarator, when a C++ direct initializer is present.
4321/// e.g: "int x(1);"
4322void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
4323                                         SourceLocation LParenLoc,
4324                                         MultiExprArg Exprs,
4325                                         SourceLocation *CommaLocs,
4326                                         SourceLocation RParenLoc) {
4327  assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
4328  Decl *RealDecl = Dcl.getAs<Decl>();
4329
4330  // If there is no declaration, there was an error parsing it.  Just ignore
4331  // the initializer.
4332  if (RealDecl == 0)
4333    return;
4334
4335  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
4336  if (!VDecl) {
4337    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
4338    RealDecl->setInvalidDecl();
4339    return;
4340  }
4341
4342  // We will represent direct-initialization similarly to copy-initialization:
4343  //    int x(1);  -as-> int x = 1;
4344  //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
4345  //
4346  // Clients that want to distinguish between the two forms, can check for
4347  // direct initializer using VarDecl::hasCXXDirectInitializer().
4348  // A major benefit is that clients that don't particularly care about which
4349  // exactly form was it (like the CodeGen) can handle both cases without
4350  // special case code.
4351
4352  // C++ 8.5p11:
4353  // The form of initialization (using parentheses or '=') is generally
4354  // insignificant, but does matter when the entity being initialized has a
4355  // class type.
4356  QualType DeclInitType = VDecl->getType();
4357  if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
4358    DeclInitType = Context.getBaseElementType(Array);
4359
4360  if (!VDecl->getType()->isDependentType() &&
4361      RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
4362                          diag::err_typecheck_decl_incomplete_type)) {
4363    VDecl->setInvalidDecl();
4364    return;
4365  }
4366
4367  // The variable can not have an abstract class type.
4368  if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
4369                             diag::err_abstract_type_in_decl,
4370                             AbstractVariableType))
4371    VDecl->setInvalidDecl();
4372
4373  const VarDecl *Def;
4374  if ((Def = VDecl->getDefinition()) && Def != VDecl) {
4375    Diag(VDecl->getLocation(), diag::err_redefinition)
4376    << VDecl->getDeclName();
4377    Diag(Def->getLocation(), diag::note_previous_definition);
4378    VDecl->setInvalidDecl();
4379    return;
4380  }
4381
4382  // If either the declaration has a dependent type or if any of the
4383  // expressions is type-dependent, we represent the initialization
4384  // via a ParenListExpr for later use during template instantiation.
4385  if (VDecl->getType()->isDependentType() ||
4386      Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
4387    // Let clients know that initialization was done with a direct initializer.
4388    VDecl->setCXXDirectInitializer(true);
4389
4390    // Store the initialization expressions as a ParenListExpr.
4391    unsigned NumExprs = Exprs.size();
4392    VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
4393                                               (Expr **)Exprs.release(),
4394                                               NumExprs, RParenLoc));
4395    return;
4396  }
4397
4398  // Capture the variable that is being initialized and the style of
4399  // initialization.
4400  InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
4401
4402  // FIXME: Poor source location information.
4403  InitializationKind Kind
4404    = InitializationKind::CreateDirect(VDecl->getLocation(),
4405                                       LParenLoc, RParenLoc);
4406
4407  InitializationSequence InitSeq(*this, Entity, Kind,
4408                                 (Expr**)Exprs.get(), Exprs.size());
4409  OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
4410  if (Result.isInvalid()) {
4411    VDecl->setInvalidDecl();
4412    return;
4413  }
4414
4415  Result = MaybeCreateCXXExprWithTemporaries(move(Result));
4416  VDecl->setInit(Result.takeAs<Expr>());
4417  VDecl->setCXXDirectInitializer(true);
4418
4419  if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
4420    FinalizeVarWithDestructor(VDecl, Record);
4421}
4422
4423/// \brief Given a constructor and the set of arguments provided for the
4424/// constructor, convert the arguments and add any required default arguments
4425/// to form a proper call to this constructor.
4426///
4427/// \returns true if an error occurred, false otherwise.
4428bool
4429Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
4430                              MultiExprArg ArgsPtr,
4431                              SourceLocation Loc,
4432                     ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
4433  // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
4434  unsigned NumArgs = ArgsPtr.size();
4435  Expr **Args = (Expr **)ArgsPtr.get();
4436
4437  const FunctionProtoType *Proto
4438    = Constructor->getType()->getAs<FunctionProtoType>();
4439  assert(Proto && "Constructor without a prototype?");
4440  unsigned NumArgsInProto = Proto->getNumArgs();
4441
4442  // If too few arguments are available, we'll fill in the rest with defaults.
4443  if (NumArgs < NumArgsInProto)
4444    ConvertedArgs.reserve(NumArgsInProto);
4445  else
4446    ConvertedArgs.reserve(NumArgs);
4447
4448  VariadicCallType CallType =
4449    Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4450  llvm::SmallVector<Expr *, 8> AllArgs;
4451  bool Invalid = GatherArgumentsForCall(Loc, Constructor,
4452                                        Proto, 0, Args, NumArgs, AllArgs,
4453                                        CallType);
4454  for (unsigned i =0, size = AllArgs.size(); i < size; i++)
4455    ConvertedArgs.push_back(AllArgs[i]);
4456  return Invalid;
4457}
4458
4459static inline bool
4460CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
4461                                       const FunctionDecl *FnDecl) {
4462  const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
4463  if (isa<NamespaceDecl>(DC)) {
4464    return SemaRef.Diag(FnDecl->getLocation(),
4465                        diag::err_operator_new_delete_declared_in_namespace)
4466      << FnDecl->getDeclName();
4467  }
4468
4469  if (isa<TranslationUnitDecl>(DC) &&
4470      FnDecl->getStorageClass() == FunctionDecl::Static) {
4471    return SemaRef.Diag(FnDecl->getLocation(),
4472                        diag::err_operator_new_delete_declared_static)
4473      << FnDecl->getDeclName();
4474  }
4475
4476  return false;
4477}
4478
4479static inline bool
4480CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
4481                            CanQualType ExpectedResultType,
4482                            CanQualType ExpectedFirstParamType,
4483                            unsigned DependentParamTypeDiag,
4484                            unsigned InvalidParamTypeDiag) {
4485  QualType ResultType =
4486    FnDecl->getType()->getAs<FunctionType>()->getResultType();
4487
4488  // Check that the result type is not dependent.
4489  if (ResultType->isDependentType())
4490    return SemaRef.Diag(FnDecl->getLocation(),
4491                        diag::err_operator_new_delete_dependent_result_type)
4492    << FnDecl->getDeclName() << ExpectedResultType;
4493
4494  // Check that the result type is what we expect.
4495  if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
4496    return SemaRef.Diag(FnDecl->getLocation(),
4497                        diag::err_operator_new_delete_invalid_result_type)
4498    << FnDecl->getDeclName() << ExpectedResultType;
4499
4500  // A function template must have at least 2 parameters.
4501  if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
4502    return SemaRef.Diag(FnDecl->getLocation(),
4503                      diag::err_operator_new_delete_template_too_few_parameters)
4504        << FnDecl->getDeclName();
4505
4506  // The function decl must have at least 1 parameter.
4507  if (FnDecl->getNumParams() == 0)
4508    return SemaRef.Diag(FnDecl->getLocation(),
4509                        diag::err_operator_new_delete_too_few_parameters)
4510      << FnDecl->getDeclName();
4511
4512  // Check the the first parameter type is not dependent.
4513  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4514  if (FirstParamType->isDependentType())
4515    return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
4516      << FnDecl->getDeclName() << ExpectedFirstParamType;
4517
4518  // Check that the first parameter type is what we expect.
4519  if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
4520      ExpectedFirstParamType)
4521    return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
4522    << FnDecl->getDeclName() << ExpectedFirstParamType;
4523
4524  return false;
4525}
4526
4527static bool
4528CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
4529  // C++ [basic.stc.dynamic.allocation]p1:
4530  //   A program is ill-formed if an allocation function is declared in a
4531  //   namespace scope other than global scope or declared static in global
4532  //   scope.
4533  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4534    return true;
4535
4536  CanQualType SizeTy =
4537    SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
4538
4539  // C++ [basic.stc.dynamic.allocation]p1:
4540  //  The return type shall be void*. The first parameter shall have type
4541  //  std::size_t.
4542  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
4543                                  SizeTy,
4544                                  diag::err_operator_new_dependent_param_type,
4545                                  diag::err_operator_new_param_type))
4546    return true;
4547
4548  // C++ [basic.stc.dynamic.allocation]p1:
4549  //  The first parameter shall not have an associated default argument.
4550  if (FnDecl->getParamDecl(0)->hasDefaultArg())
4551    return SemaRef.Diag(FnDecl->getLocation(),
4552                        diag::err_operator_new_default_arg)
4553      << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
4554
4555  return false;
4556}
4557
4558static bool
4559CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
4560  // C++ [basic.stc.dynamic.deallocation]p1:
4561  //   A program is ill-formed if deallocation functions are declared in a
4562  //   namespace scope other than global scope or declared static in global
4563  //   scope.
4564  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4565    return true;
4566
4567  // C++ [basic.stc.dynamic.deallocation]p2:
4568  //   Each deallocation function shall return void and its first parameter
4569  //   shall be void*.
4570  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
4571                                  SemaRef.Context.VoidPtrTy,
4572                                 diag::err_operator_delete_dependent_param_type,
4573                                 diag::err_operator_delete_param_type))
4574    return true;
4575
4576  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4577  if (FirstParamType->isDependentType())
4578    return SemaRef.Diag(FnDecl->getLocation(),
4579                        diag::err_operator_delete_dependent_param_type)
4580    << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
4581
4582  if (SemaRef.Context.getCanonicalType(FirstParamType) !=
4583      SemaRef.Context.VoidPtrTy)
4584    return SemaRef.Diag(FnDecl->getLocation(),
4585                        diag::err_operator_delete_param_type)
4586      << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
4587
4588  return false;
4589}
4590
4591/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4592/// of this overloaded operator is well-formed. If so, returns false;
4593/// otherwise, emits appropriate diagnostics and returns true.
4594bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
4595  assert(FnDecl && FnDecl->isOverloadedOperator() &&
4596         "Expected an overloaded operator declaration");
4597
4598  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4599
4600  // C++ [over.oper]p5:
4601  //   The allocation and deallocation functions, operator new,
4602  //   operator new[], operator delete and operator delete[], are
4603  //   described completely in 3.7.3. The attributes and restrictions
4604  //   found in the rest of this subclause do not apply to them unless
4605  //   explicitly stated in 3.7.3.
4606  if (Op == OO_Delete || Op == OO_Array_Delete)
4607    return CheckOperatorDeleteDeclaration(*this, FnDecl);
4608
4609  if (Op == OO_New || Op == OO_Array_New)
4610    return CheckOperatorNewDeclaration(*this, FnDecl);
4611
4612  // C++ [over.oper]p6:
4613  //   An operator function shall either be a non-static member
4614  //   function or be a non-member function and have at least one
4615  //   parameter whose type is a class, a reference to a class, an
4616  //   enumeration, or a reference to an enumeration.
4617  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4618    if (MethodDecl->isStatic())
4619      return Diag(FnDecl->getLocation(),
4620                  diag::err_operator_overload_static) << FnDecl->getDeclName();
4621  } else {
4622    bool ClassOrEnumParam = false;
4623    for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4624                                   ParamEnd = FnDecl->param_end();
4625         Param != ParamEnd; ++Param) {
4626      QualType ParamType = (*Param)->getType().getNonReferenceType();
4627      if (ParamType->isDependentType() || ParamType->isRecordType() ||
4628          ParamType->isEnumeralType()) {
4629        ClassOrEnumParam = true;
4630        break;
4631      }
4632    }
4633
4634    if (!ClassOrEnumParam)
4635      return Diag(FnDecl->getLocation(),
4636                  diag::err_operator_overload_needs_class_or_enum)
4637        << FnDecl->getDeclName();
4638  }
4639
4640  // C++ [over.oper]p8:
4641  //   An operator function cannot have default arguments (8.3.6),
4642  //   except where explicitly stated below.
4643  //
4644  // Only the function-call operator allows default arguments
4645  // (C++ [over.call]p1).
4646  if (Op != OO_Call) {
4647    for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4648         Param != FnDecl->param_end(); ++Param) {
4649      if ((*Param)->hasDefaultArg())
4650        return Diag((*Param)->getLocation(),
4651                    diag::err_operator_overload_default_arg)
4652          << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
4653    }
4654  }
4655
4656  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4657    { false, false, false }
4658#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4659    , { Unary, Binary, MemberOnly }
4660#include "clang/Basic/OperatorKinds.def"
4661  };
4662
4663  bool CanBeUnaryOperator = OperatorUses[Op][0];
4664  bool CanBeBinaryOperator = OperatorUses[Op][1];
4665  bool MustBeMemberOperator = OperatorUses[Op][2];
4666
4667  // C++ [over.oper]p8:
4668  //   [...] Operator functions cannot have more or fewer parameters
4669  //   than the number required for the corresponding operator, as
4670  //   described in the rest of this subclause.
4671  unsigned NumParams = FnDecl->getNumParams()
4672                     + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
4673  if (Op != OO_Call &&
4674      ((NumParams == 1 && !CanBeUnaryOperator) ||
4675       (NumParams == 2 && !CanBeBinaryOperator) ||
4676       (NumParams < 1) || (NumParams > 2))) {
4677    // We have the wrong number of parameters.
4678    unsigned ErrorKind;
4679    if (CanBeUnaryOperator && CanBeBinaryOperator) {
4680      ErrorKind = 2;  // 2 -> unary or binary.
4681    } else if (CanBeUnaryOperator) {
4682      ErrorKind = 0;  // 0 -> unary
4683    } else {
4684      assert(CanBeBinaryOperator &&
4685             "All non-call overloaded operators are unary or binary!");
4686      ErrorKind = 1;  // 1 -> binary
4687    }
4688
4689    return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
4690      << FnDecl->getDeclName() << NumParams << ErrorKind;
4691  }
4692
4693  // Overloaded operators other than operator() cannot be variadic.
4694  if (Op != OO_Call &&
4695      FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
4696    return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
4697      << FnDecl->getDeclName();
4698  }
4699
4700  // Some operators must be non-static member functions.
4701  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4702    return Diag(FnDecl->getLocation(),
4703                diag::err_operator_overload_must_be_member)
4704      << FnDecl->getDeclName();
4705  }
4706
4707  // C++ [over.inc]p1:
4708  //   The user-defined function called operator++ implements the
4709  //   prefix and postfix ++ operator. If this function is a member
4710  //   function with no parameters, or a non-member function with one
4711  //   parameter of class or enumeration type, it defines the prefix
4712  //   increment operator ++ for objects of that type. If the function
4713  //   is a member function with one parameter (which shall be of type
4714  //   int) or a non-member function with two parameters (the second
4715  //   of which shall be of type int), it defines the postfix
4716  //   increment operator ++ for objects of that type.
4717  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
4718    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
4719    bool ParamIsInt = false;
4720    if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
4721      ParamIsInt = BT->getKind() == BuiltinType::Int;
4722
4723    if (!ParamIsInt)
4724      return Diag(LastParam->getLocation(),
4725                  diag::err_operator_overload_post_incdec_must_be_int)
4726        << LastParam->getType() << (Op == OO_MinusMinus);
4727  }
4728
4729  // Notify the class if it got an assignment operator.
4730  if (Op == OO_Equal) {
4731    // Would have returned earlier otherwise.
4732    assert(isa<CXXMethodDecl>(FnDecl) &&
4733      "Overloaded = not member, but not filtered.");
4734    CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
4735    Method->getParent()->addedAssignmentOperator(Context, Method);
4736  }
4737
4738  return false;
4739}
4740
4741/// CheckLiteralOperatorDeclaration - Check whether the declaration
4742/// of this literal operator function is well-formed. If so, returns
4743/// false; otherwise, emits appropriate diagnostics and returns true.
4744bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
4745  DeclContext *DC = FnDecl->getDeclContext();
4746  Decl::Kind Kind = DC->getDeclKind();
4747  if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
4748      Kind != Decl::LinkageSpec) {
4749    Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
4750      << FnDecl->getDeclName();
4751    return true;
4752  }
4753
4754  bool Valid = false;
4755
4756  // template <char...> type operator "" name() is the only valid template
4757  // signature, and the only valid signature with no parameters.
4758  if (FnDecl->param_size() == 0) {
4759    if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
4760      // Must have only one template parameter
4761      TemplateParameterList *Params = TpDecl->getTemplateParameters();
4762      if (Params->size() == 1) {
4763        NonTypeTemplateParmDecl *PmDecl =
4764          cast<NonTypeTemplateParmDecl>(Params->getParam(0));
4765
4766        // The template parameter must be a char parameter pack.
4767        // FIXME: This test will always fail because non-type parameter packs
4768        //   have not been implemented.
4769        if (PmDecl && PmDecl->isTemplateParameterPack() &&
4770            Context.hasSameType(PmDecl->getType(), Context.CharTy))
4771          Valid = true;
4772      }
4773    }
4774  } else {
4775    // Check the first parameter
4776    FunctionDecl::param_iterator Param = FnDecl->param_begin();
4777
4778    QualType T = (*Param)->getType();
4779
4780    // unsigned long long int, long double, and any character type are allowed
4781    // as the only parameters.
4782    if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
4783        Context.hasSameType(T, Context.LongDoubleTy) ||
4784        Context.hasSameType(T, Context.CharTy) ||
4785        Context.hasSameType(T, Context.WCharTy) ||
4786        Context.hasSameType(T, Context.Char16Ty) ||
4787        Context.hasSameType(T, Context.Char32Ty)) {
4788      if (++Param == FnDecl->param_end())
4789        Valid = true;
4790      goto FinishedParams;
4791    }
4792
4793    // Otherwise it must be a pointer to const; let's strip those qualifiers.
4794    const PointerType *PT = T->getAs<PointerType>();
4795    if (!PT)
4796      goto FinishedParams;
4797    T = PT->getPointeeType();
4798    if (!T.isConstQualified())
4799      goto FinishedParams;
4800    T = T.getUnqualifiedType();
4801
4802    // Move on to the second parameter;
4803    ++Param;
4804
4805    // If there is no second parameter, the first must be a const char *
4806    if (Param == FnDecl->param_end()) {
4807      if (Context.hasSameType(T, Context.CharTy))
4808        Valid = true;
4809      goto FinishedParams;
4810    }
4811
4812    // const char *, const wchar_t*, const char16_t*, and const char32_t*
4813    // are allowed as the first parameter to a two-parameter function
4814    if (!(Context.hasSameType(T, Context.CharTy) ||
4815          Context.hasSameType(T, Context.WCharTy) ||
4816          Context.hasSameType(T, Context.Char16Ty) ||
4817          Context.hasSameType(T, Context.Char32Ty)))
4818      goto FinishedParams;
4819
4820    // The second and final parameter must be an std::size_t
4821    T = (*Param)->getType().getUnqualifiedType();
4822    if (Context.hasSameType(T, Context.getSizeType()) &&
4823        ++Param == FnDecl->param_end())
4824      Valid = true;
4825  }
4826
4827  // FIXME: This diagnostic is absolutely terrible.
4828FinishedParams:
4829  if (!Valid) {
4830    Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
4831      << FnDecl->getDeclName();
4832    return true;
4833  }
4834
4835  return false;
4836}
4837
4838/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
4839/// linkage specification, including the language and (if present)
4840/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
4841/// the location of the language string literal, which is provided
4842/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
4843/// the '{' brace. Otherwise, this linkage specification does not
4844/// have any braces.
4845Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
4846                                                     SourceLocation ExternLoc,
4847                                                     SourceLocation LangLoc,
4848                                                     const char *Lang,
4849                                                     unsigned StrSize,
4850                                                     SourceLocation LBraceLoc) {
4851  LinkageSpecDecl::LanguageIDs Language;
4852  if (strncmp(Lang, "\"C\"", StrSize) == 0)
4853    Language = LinkageSpecDecl::lang_c;
4854  else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
4855    Language = LinkageSpecDecl::lang_cxx;
4856  else {
4857    Diag(LangLoc, diag::err_bad_language);
4858    return DeclPtrTy();
4859  }
4860
4861  // FIXME: Add all the various semantics of linkage specifications
4862
4863  LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
4864                                               LangLoc, Language,
4865                                               LBraceLoc.isValid());
4866  CurContext->addDecl(D);
4867  PushDeclContext(S, D);
4868  return DeclPtrTy::make(D);
4869}
4870
4871/// ActOnFinishLinkageSpecification - Completely the definition of
4872/// the C++ linkage specification LinkageSpec. If RBraceLoc is
4873/// valid, it's the position of the closing '}' brace in a linkage
4874/// specification that uses braces.
4875Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
4876                                                      DeclPtrTy LinkageSpec,
4877                                                      SourceLocation RBraceLoc) {
4878  if (LinkageSpec)
4879    PopDeclContext();
4880  return LinkageSpec;
4881}
4882
4883/// \brief Perform semantic analysis for the variable declaration that
4884/// occurs within a C++ catch clause, returning the newly-created
4885/// variable.
4886VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
4887                                         TypeSourceInfo *TInfo,
4888                                         IdentifierInfo *Name,
4889                                         SourceLocation Loc,
4890                                         SourceRange Range) {
4891  bool Invalid = false;
4892
4893  // Arrays and functions decay.
4894  if (ExDeclType->isArrayType())
4895    ExDeclType = Context.getArrayDecayedType(ExDeclType);
4896  else if (ExDeclType->isFunctionType())
4897    ExDeclType = Context.getPointerType(ExDeclType);
4898
4899  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
4900  // The exception-declaration shall not denote a pointer or reference to an
4901  // incomplete type, other than [cv] void*.
4902  // N2844 forbids rvalue references.
4903  if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
4904    Diag(Loc, diag::err_catch_rvalue_ref) << Range;
4905    Invalid = true;
4906  }
4907
4908  // GCC allows catching pointers and references to incomplete types
4909  // as an extension; so do we, but we warn by default.
4910
4911  QualType BaseType = ExDeclType;
4912  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
4913  unsigned DK = diag::err_catch_incomplete;
4914  bool IncompleteCatchIsInvalid = true;
4915  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
4916    BaseType = Ptr->getPointeeType();
4917    Mode = 1;
4918    DK = diag::ext_catch_incomplete_ptr;
4919    IncompleteCatchIsInvalid = false;
4920  } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
4921    // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
4922    BaseType = Ref->getPointeeType();
4923    Mode = 2;
4924    DK = diag::ext_catch_incomplete_ref;
4925    IncompleteCatchIsInvalid = false;
4926  }
4927  if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
4928      !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
4929      IncompleteCatchIsInvalid)
4930    Invalid = true;
4931
4932  if (!Invalid && !ExDeclType->isDependentType() &&
4933      RequireNonAbstractType(Loc, ExDeclType,
4934                             diag::err_abstract_type_in_decl,
4935                             AbstractVariableType))
4936    Invalid = true;
4937
4938  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
4939                                    Name, ExDeclType, TInfo, VarDecl::None,
4940                                    VarDecl::None);
4941
4942  if (!Invalid) {
4943    if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
4944      // C++ [except.handle]p16:
4945      //   The object declared in an exception-declaration or, if the
4946      //   exception-declaration does not specify a name, a temporary (12.2) is
4947      //   copy-initialized (8.5) from the exception object. [...]
4948      //   The object is destroyed when the handler exits, after the destruction
4949      //   of any automatic objects initialized within the handler.
4950      //
4951      // We just pretend to initialize the object with itself, then make sure
4952      // it can be destroyed later.
4953      InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
4954      Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
4955                                            Loc, ExDeclType, 0);
4956      InitializationKind Kind = InitializationKind::CreateCopy(Loc,
4957                                                               SourceLocation());
4958      InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
4959      OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
4960                                    MultiExprArg(*this, (void**)&ExDeclRef, 1));
4961      if (Result.isInvalid())
4962        Invalid = true;
4963      else
4964        FinalizeVarWithDestructor(ExDecl, RecordTy);
4965    }
4966  }
4967
4968  if (Invalid)
4969    ExDecl->setInvalidDecl();
4970
4971  return ExDecl;
4972}
4973
4974/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
4975/// handler.
4976Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
4977  TypeSourceInfo *TInfo = 0;
4978  QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo);
4979
4980  bool Invalid = D.isInvalidType();
4981  IdentifierInfo *II = D.getIdentifier();
4982  if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
4983                                             LookupOrdinaryName,
4984                                             ForRedeclaration)) {
4985    // The scope should be freshly made just for us. There is just no way
4986    // it contains any previous declaration.
4987    assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
4988    if (PrevDecl->isTemplateParameter()) {
4989      // Maybe we will complain about the shadowed template parameter.
4990      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
4991    }
4992  }
4993
4994  if (D.getCXXScopeSpec().isSet() && !Invalid) {
4995    Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
4996      << D.getCXXScopeSpec().getRange();
4997    Invalid = true;
4998  }
4999
5000  VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
5001                                              D.getIdentifier(),
5002                                              D.getIdentifierLoc(),
5003                                            D.getDeclSpec().getSourceRange());
5004
5005  if (Invalid)
5006    ExDecl->setInvalidDecl();
5007
5008  // Add the exception declaration into this scope.
5009  if (II)
5010    PushOnScopeChains(ExDecl, S);
5011  else
5012    CurContext->addDecl(ExDecl);
5013
5014  ProcessDeclAttributes(S, ExDecl, D);
5015  return DeclPtrTy::make(ExDecl);
5016}
5017
5018Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
5019                                                   ExprArg assertexpr,
5020                                                   ExprArg assertmessageexpr) {
5021  Expr *AssertExpr = (Expr *)assertexpr.get();
5022  StringLiteral *AssertMessage =
5023    cast<StringLiteral>((Expr *)assertmessageexpr.get());
5024
5025  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
5026    llvm::APSInt Value(32);
5027    if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
5028      Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
5029        AssertExpr->getSourceRange();
5030      return DeclPtrTy();
5031    }
5032
5033    if (Value == 0) {
5034      Diag(AssertLoc, diag::err_static_assert_failed)
5035        << AssertMessage->getString() << AssertExpr->getSourceRange();
5036    }
5037  }
5038
5039  assertexpr.release();
5040  assertmessageexpr.release();
5041  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
5042                                        AssertExpr, AssertMessage);
5043
5044  CurContext->addDecl(Decl);
5045  return DeclPtrTy::make(Decl);
5046}
5047
5048/// \brief Perform semantic analysis of the given friend type declaration.
5049///
5050/// \returns A friend declaration that.
5051FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
5052                                      TypeSourceInfo *TSInfo) {
5053  assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
5054
5055  QualType T = TSInfo->getType();
5056  SourceRange TypeRange = TSInfo->getTypeLoc().getSourceRange();
5057
5058  if (!getLangOptions().CPlusPlus0x) {
5059    // C++03 [class.friend]p2:
5060    //   An elaborated-type-specifier shall be used in a friend declaration
5061    //   for a class.*
5062    //
5063    //   * The class-key of the elaborated-type-specifier is required.
5064    if (!ActiveTemplateInstantiations.empty()) {
5065      // Do not complain about the form of friend template types during
5066      // template instantiation; we will already have complained when the
5067      // template was declared.
5068    } else if (!T->isElaboratedTypeSpecifier()) {
5069      // If we evaluated the type to a record type, suggest putting
5070      // a tag in front.
5071      if (const RecordType *RT = T->getAs<RecordType>()) {
5072        RecordDecl *RD = RT->getDecl();
5073
5074        std::string InsertionText = std::string(" ") + RD->getKindName();
5075
5076        Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
5077          << (unsigned) RD->getTagKind()
5078          << T
5079          << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
5080                                        InsertionText);
5081      } else {
5082        Diag(FriendLoc, diag::ext_nonclass_type_friend)
5083          << T
5084          << SourceRange(FriendLoc, TypeRange.getEnd());
5085      }
5086    } else if (T->getAs<EnumType>()) {
5087      Diag(FriendLoc, diag::ext_enum_friend)
5088        << T
5089        << SourceRange(FriendLoc, TypeRange.getEnd());
5090    }
5091  }
5092
5093  // C++0x [class.friend]p3:
5094  //   If the type specifier in a friend declaration designates a (possibly
5095  //   cv-qualified) class type, that class is declared as a friend; otherwise,
5096  //   the friend declaration is ignored.
5097
5098  // FIXME: C++0x has some syntactic restrictions on friend type declarations
5099  // in [class.friend]p3 that we do not implement.
5100
5101  return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
5102}
5103
5104/// Handle a friend type declaration.  This works in tandem with
5105/// ActOnTag.
5106///
5107/// Notes on friend class templates:
5108///
5109/// We generally treat friend class declarations as if they were
5110/// declaring a class.  So, for example, the elaborated type specifier
5111/// in a friend declaration is required to obey the restrictions of a
5112/// class-head (i.e. no typedefs in the scope chain), template
5113/// parameters are required to match up with simple template-ids, &c.
5114/// However, unlike when declaring a template specialization, it's
5115/// okay to refer to a template specialization without an empty
5116/// template parameter declaration, e.g.
5117///   friend class A<T>::B<unsigned>;
5118/// We permit this as a special case; if there are any template
5119/// parameters present at all, require proper matching, i.e.
5120///   template <> template <class T> friend class A<int>::B;
5121Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
5122                                          MultiTemplateParamsArg TempParams) {
5123  SourceLocation Loc = DS.getSourceRange().getBegin();
5124
5125  assert(DS.isFriendSpecified());
5126  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5127
5128  // Try to convert the decl specifier to a type.  This works for
5129  // friend templates because ActOnTag never produces a ClassTemplateDecl
5130  // for a TUK_Friend.
5131  Declarator TheDeclarator(DS, Declarator::MemberContext);
5132  TypeSourceInfo *TSI;
5133  QualType T = GetTypeForDeclarator(TheDeclarator, S, &TSI);
5134  if (TheDeclarator.isInvalidType())
5135    return DeclPtrTy();
5136
5137  if (!TSI)
5138    TSI = Context.getTrivialTypeSourceInfo(T, DS.getSourceRange().getBegin());
5139
5140  // This is definitely an error in C++98.  It's probably meant to
5141  // be forbidden in C++0x, too, but the specification is just
5142  // poorly written.
5143  //
5144  // The problem is with declarations like the following:
5145  //   template <T> friend A<T>::foo;
5146  // where deciding whether a class C is a friend or not now hinges
5147  // on whether there exists an instantiation of A that causes
5148  // 'foo' to equal C.  There are restrictions on class-heads
5149  // (which we declare (by fiat) elaborated friend declarations to
5150  // be) that makes this tractable.
5151  //
5152  // FIXME: handle "template <> friend class A<T>;", which
5153  // is possibly well-formed?  Who even knows?
5154  if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
5155    Diag(Loc, diag::err_tagless_friend_type_template)
5156      << DS.getSourceRange();
5157    return DeclPtrTy();
5158  }
5159
5160  // C++98 [class.friend]p1: A friend of a class is a function
5161  //   or class that is not a member of the class . . .
5162  // This is fixed in DR77, which just barely didn't make the C++03
5163  // deadline.  It's also a very silly restriction that seriously
5164  // affects inner classes and which nobody else seems to implement;
5165  // thus we never diagnose it, not even in -pedantic.
5166  //
5167  // But note that we could warn about it: it's always useless to
5168  // friend one of your own members (it's not, however, worthless to
5169  // friend a member of an arbitrary specialization of your template).
5170
5171  Decl *D;
5172  if (unsigned NumTempParamLists = TempParams.size())
5173    D = FriendTemplateDecl::Create(Context, CurContext, Loc,
5174                                   NumTempParamLists,
5175                                 (TemplateParameterList**) TempParams.release(),
5176                                   TSI,
5177                                   DS.getFriendSpecLoc());
5178  else
5179    D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
5180
5181  if (!D)
5182    return DeclPtrTy();
5183
5184  D->setAccess(AS_public);
5185  CurContext->addDecl(D);
5186
5187  return DeclPtrTy::make(D);
5188}
5189
5190Sema::DeclPtrTy
5191Sema::ActOnFriendFunctionDecl(Scope *S,
5192                              Declarator &D,
5193                              bool IsDefinition,
5194                              MultiTemplateParamsArg TemplateParams) {
5195  const DeclSpec &DS = D.getDeclSpec();
5196
5197  assert(DS.isFriendSpecified());
5198  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5199
5200  SourceLocation Loc = D.getIdentifierLoc();
5201  TypeSourceInfo *TInfo = 0;
5202  QualType T = GetTypeForDeclarator(D, S, &TInfo);
5203
5204  // C++ [class.friend]p1
5205  //   A friend of a class is a function or class....
5206  // Note that this sees through typedefs, which is intended.
5207  // It *doesn't* see through dependent types, which is correct
5208  // according to [temp.arg.type]p3:
5209  //   If a declaration acquires a function type through a
5210  //   type dependent on a template-parameter and this causes
5211  //   a declaration that does not use the syntactic form of a
5212  //   function declarator to have a function type, the program
5213  //   is ill-formed.
5214  if (!T->isFunctionType()) {
5215    Diag(Loc, diag::err_unexpected_friend);
5216
5217    // It might be worthwhile to try to recover by creating an
5218    // appropriate declaration.
5219    return DeclPtrTy();
5220  }
5221
5222  // C++ [namespace.memdef]p3
5223  //  - If a friend declaration in a non-local class first declares a
5224  //    class or function, the friend class or function is a member
5225  //    of the innermost enclosing namespace.
5226  //  - The name of the friend is not found by simple name lookup
5227  //    until a matching declaration is provided in that namespace
5228  //    scope (either before or after the class declaration granting
5229  //    friendship).
5230  //  - If a friend function is called, its name may be found by the
5231  //    name lookup that considers functions from namespaces and
5232  //    classes associated with the types of the function arguments.
5233  //  - When looking for a prior declaration of a class or a function
5234  //    declared as a friend, scopes outside the innermost enclosing
5235  //    namespace scope are not considered.
5236
5237  CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
5238  DeclarationName Name = GetNameForDeclarator(D);
5239  assert(Name);
5240
5241  // The context we found the declaration in, or in which we should
5242  // create the declaration.
5243  DeclContext *DC;
5244
5245  // FIXME: handle local classes
5246
5247  // Recover from invalid scope qualifiers as if they just weren't there.
5248  LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
5249                        ForRedeclaration);
5250  if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
5251    // FIXME: RequireCompleteDeclContext
5252    DC = computeDeclContext(ScopeQual);
5253
5254    // FIXME: handle dependent contexts
5255    if (!DC) return DeclPtrTy();
5256
5257    LookupQualifiedName(Previous, DC);
5258
5259    // If searching in that context implicitly found a declaration in
5260    // a different context, treat it like it wasn't found at all.
5261    // TODO: better diagnostics for this case.  Suggesting the right
5262    // qualified scope would be nice...
5263    // FIXME: getRepresentativeDecl() is not right here at all
5264    if (Previous.empty() ||
5265        !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
5266      D.setInvalidType();
5267      Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
5268      return DeclPtrTy();
5269    }
5270
5271    // C++ [class.friend]p1: A friend of a class is a function or
5272    //   class that is not a member of the class . . .
5273    if (DC->Equals(CurContext))
5274      Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5275
5276  // Otherwise walk out to the nearest namespace scope looking for matches.
5277  } else {
5278    // TODO: handle local class contexts.
5279
5280    DC = CurContext;
5281    while (true) {
5282      // Skip class contexts.  If someone can cite chapter and verse
5283      // for this behavior, that would be nice --- it's what GCC and
5284      // EDG do, and it seems like a reasonable intent, but the spec
5285      // really only says that checks for unqualified existing
5286      // declarations should stop at the nearest enclosing namespace,
5287      // not that they should only consider the nearest enclosing
5288      // namespace.
5289      while (DC->isRecord())
5290        DC = DC->getParent();
5291
5292      LookupQualifiedName(Previous, DC);
5293
5294      // TODO: decide what we think about using declarations.
5295      if (!Previous.empty())
5296        break;
5297
5298      if (DC->isFileContext()) break;
5299      DC = DC->getParent();
5300    }
5301
5302    // C++ [class.friend]p1: A friend of a class is a function or
5303    //   class that is not a member of the class . . .
5304    // C++0x changes this for both friend types and functions.
5305    // Most C++ 98 compilers do seem to give an error here, so
5306    // we do, too.
5307    if (!Previous.empty() && DC->Equals(CurContext)
5308        && !getLangOptions().CPlusPlus0x)
5309      Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5310  }
5311
5312  if (DC->isFileContext()) {
5313    // This implies that it has to be an operator or function.
5314    if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
5315        D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
5316        D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
5317      Diag(Loc, diag::err_introducing_special_friend) <<
5318        (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
5319         D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
5320      return DeclPtrTy();
5321    }
5322  }
5323
5324  bool Redeclaration = false;
5325  NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
5326                                          move(TemplateParams),
5327                                          IsDefinition,
5328                                          Redeclaration);
5329  if (!ND) return DeclPtrTy();
5330
5331  assert(ND->getDeclContext() == DC);
5332  assert(ND->getLexicalDeclContext() == CurContext);
5333
5334  // Add the function declaration to the appropriate lookup tables,
5335  // adjusting the redeclarations list as necessary.  We don't
5336  // want to do this yet if the friending class is dependent.
5337  //
5338  // Also update the scope-based lookup if the target context's
5339  // lookup context is in lexical scope.
5340  if (!CurContext->isDependentContext()) {
5341    DC = DC->getLookupContext();
5342    DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
5343    if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
5344      PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
5345  }
5346
5347  FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
5348                                       D.getIdentifierLoc(), ND,
5349                                       DS.getFriendSpecLoc());
5350  FrD->setAccess(AS_public);
5351  CurContext->addDecl(FrD);
5352
5353  return DeclPtrTy::make(ND);
5354}
5355
5356void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
5357  AdjustDeclIfTemplate(dcl);
5358
5359  Decl *Dcl = dcl.getAs<Decl>();
5360  FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
5361  if (!Fn) {
5362    Diag(DelLoc, diag::err_deleted_non_function);
5363    return;
5364  }
5365  if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
5366    Diag(DelLoc, diag::err_deleted_decl_not_first);
5367    Diag(Prev->getLocation(), diag::note_previous_declaration);
5368    // If the declaration wasn't the first, we delete the function anyway for
5369    // recovery.
5370  }
5371  Fn->setDeleted();
5372}
5373
5374static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
5375  for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
5376       ++CI) {
5377    Stmt *SubStmt = *CI;
5378    if (!SubStmt)
5379      continue;
5380    if (isa<ReturnStmt>(SubStmt))
5381      Self.Diag(SubStmt->getSourceRange().getBegin(),
5382           diag::err_return_in_constructor_handler);
5383    if (!isa<Expr>(SubStmt))
5384      SearchForReturnInStmt(Self, SubStmt);
5385  }
5386}
5387
5388void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
5389  for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
5390    CXXCatchStmt *Handler = TryBlock->getHandler(I);
5391    SearchForReturnInStmt(*this, Handler);
5392  }
5393}
5394
5395bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
5396                                             const CXXMethodDecl *Old) {
5397  QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
5398  QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
5399
5400  if (Context.hasSameType(NewTy, OldTy) ||
5401      NewTy->isDependentType() || OldTy->isDependentType())
5402    return false;
5403
5404  // Check if the return types are covariant
5405  QualType NewClassTy, OldClassTy;
5406
5407  /// Both types must be pointers or references to classes.
5408  if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
5409    if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
5410      NewClassTy = NewPT->getPointeeType();
5411      OldClassTy = OldPT->getPointeeType();
5412    }
5413  } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
5414    if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
5415      if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
5416        NewClassTy = NewRT->getPointeeType();
5417        OldClassTy = OldRT->getPointeeType();
5418      }
5419    }
5420  }
5421
5422  // The return types aren't either both pointers or references to a class type.
5423  if (NewClassTy.isNull()) {
5424    Diag(New->getLocation(),
5425         diag::err_different_return_type_for_overriding_virtual_function)
5426      << New->getDeclName() << NewTy << OldTy;
5427    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5428
5429    return true;
5430  }
5431
5432  // C++ [class.virtual]p6:
5433  //   If the return type of D::f differs from the return type of B::f, the
5434  //   class type in the return type of D::f shall be complete at the point of
5435  //   declaration of D::f or shall be the class type D.
5436  if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
5437    if (!RT->isBeingDefined() &&
5438        RequireCompleteType(New->getLocation(), NewClassTy,
5439                            PDiag(diag::err_covariant_return_incomplete)
5440                              << New->getDeclName()))
5441    return true;
5442  }
5443
5444  if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
5445    // Check if the new class derives from the old class.
5446    if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
5447      Diag(New->getLocation(),
5448           diag::err_covariant_return_not_derived)
5449      << New->getDeclName() << NewTy << OldTy;
5450      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5451      return true;
5452    }
5453
5454    // Check if we the conversion from derived to base is valid.
5455    if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
5456                    diag::err_covariant_return_inaccessible_base,
5457                    diag::err_covariant_return_ambiguous_derived_to_base_conv,
5458                    // FIXME: Should this point to the return type?
5459                    New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
5460      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5461      return true;
5462    }
5463  }
5464
5465  // The qualifiers of the return types must be the same.
5466  if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
5467    Diag(New->getLocation(),
5468         diag::err_covariant_return_type_different_qualifications)
5469    << New->getDeclName() << NewTy << OldTy;
5470    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5471    return true;
5472  };
5473
5474
5475  // The new class type must have the same or less qualifiers as the old type.
5476  if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
5477    Diag(New->getLocation(),
5478         diag::err_covariant_return_type_class_type_more_qualified)
5479    << New->getDeclName() << NewTy << OldTy;
5480    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5481    return true;
5482  };
5483
5484  return false;
5485}
5486
5487bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5488                                             const CXXMethodDecl *Old)
5489{
5490  if (Old->hasAttr<FinalAttr>()) {
5491    Diag(New->getLocation(), diag::err_final_function_overridden)
5492      << New->getDeclName();
5493    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5494    return true;
5495  }
5496
5497  return false;
5498}
5499
5500/// \brief Mark the given method pure.
5501///
5502/// \param Method the method to be marked pure.
5503///
5504/// \param InitRange the source range that covers the "0" initializer.
5505bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
5506  if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
5507    Method->setPure();
5508
5509    // A class is abstract if at least one function is pure virtual.
5510    Method->getParent()->setAbstract(true);
5511    return false;
5512  }
5513
5514  if (!Method->isInvalidDecl())
5515    Diag(Method->getLocation(), diag::err_non_virtual_pure)
5516      << Method->getDeclName() << InitRange;
5517  return true;
5518}
5519
5520/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
5521/// an initializer for the out-of-line declaration 'Dcl'.  The scope
5522/// is a fresh scope pushed for just this purpose.
5523///
5524/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5525/// static data member of class X, names should be looked up in the scope of
5526/// class X.
5527void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
5528  // If there is no declaration, there was an error parsing it.
5529  Decl *D = Dcl.getAs<Decl>();
5530  if (D == 0) return;
5531
5532  // We should only get called for declarations with scope specifiers, like:
5533  //   int foo::bar;
5534  assert(D->isOutOfLine());
5535  EnterDeclaratorContext(S, D->getDeclContext());
5536}
5537
5538/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5539/// initializer for the out-of-line declaration 'Dcl'.
5540void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
5541  // If there is no declaration, there was an error parsing it.
5542  Decl *D = Dcl.getAs<Decl>();
5543  if (D == 0) return;
5544
5545  assert(D->isOutOfLine());
5546  ExitDeclaratorContext(S);
5547}
5548
5549/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
5550/// C++ if/switch/while/for statement.
5551/// e.g: "if (int x = f()) {...}"
5552Action::DeclResult
5553Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
5554  // C++ 6.4p2:
5555  // The declarator shall not specify a function or an array.
5556  // The type-specifier-seq shall not contain typedef and shall not declare a
5557  // new class or enumeration.
5558  assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5559         "Parser allowed 'typedef' as storage class of condition decl.");
5560
5561  TypeSourceInfo *TInfo = 0;
5562  TagDecl *OwnedTag = 0;
5563  QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
5564
5565  if (Ty->isFunctionType()) { // The declarator shall not specify a function...
5566                              // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
5567                              // would be created and CXXConditionDeclExpr wants a VarDecl.
5568    Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
5569      << D.getSourceRange();
5570    return DeclResult();
5571  } else if (OwnedTag && OwnedTag->isDefinition()) {
5572    // The type-specifier-seq shall not declare a new class or enumeration.
5573    Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
5574  }
5575
5576  DeclPtrTy Dcl = ActOnDeclarator(S, D);
5577  if (!Dcl)
5578    return DeclResult();
5579
5580  VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
5581  VD->setDeclaredInCondition(true);
5582  return Dcl;
5583}
5584
5585static bool needsVTable(CXXMethodDecl *MD, ASTContext &Context) {
5586  // Ignore dependent types.
5587  if (MD->isDependentContext())
5588    return false;
5589
5590  // Ignore declarations that are not definitions.
5591  if (!MD->isThisDeclarationADefinition())
5592    return false;
5593
5594  CXXRecordDecl *RD = MD->getParent();
5595
5596  // Ignore classes without a vtable.
5597  if (!RD->isDynamicClass())
5598    return false;
5599
5600  switch (MD->getParent()->getTemplateSpecializationKind()) {
5601  case TSK_Undeclared:
5602  case TSK_ExplicitSpecialization:
5603    // Classes that aren't instantiations of templates don't need their
5604    // virtual methods marked until we see the definition of the key
5605    // function.
5606    break;
5607
5608  case TSK_ImplicitInstantiation:
5609    // This is a constructor of a class template; mark all of the virtual
5610    // members as referenced to ensure that they get instantiatied.
5611    if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD))
5612      return true;
5613    break;
5614
5615  case TSK_ExplicitInstantiationDeclaration:
5616    return false;
5617
5618  case TSK_ExplicitInstantiationDefinition:
5619    // This is method of a explicit instantiation; mark all of the virtual
5620    // members as referenced to ensure that they get instantiatied.
5621    return true;
5622  }
5623
5624  // Consider only out-of-line definitions of member functions. When we see
5625  // an inline definition, it's too early to compute the key function.
5626  if (!MD->isOutOfLine())
5627    return false;
5628
5629  const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD);
5630
5631  // If there is no key function, we will need a copy of the vtable.
5632  if (!KeyFunction)
5633    return true;
5634
5635  // If this is the key function, we need to mark virtual members.
5636  if (KeyFunction->getCanonicalDecl() == MD->getCanonicalDecl())
5637    return true;
5638
5639  return false;
5640}
5641
5642void Sema::MaybeMarkVirtualMembersReferenced(SourceLocation Loc,
5643                                             CXXMethodDecl *MD) {
5644  CXXRecordDecl *RD = MD->getParent();
5645
5646  // We will need to mark all of the virtual members as referenced to build the
5647  // vtable.
5648  if (!needsVTable(MD, Context))
5649    return;
5650
5651  TemplateSpecializationKind kind = RD->getTemplateSpecializationKind();
5652  if (kind == TSK_ImplicitInstantiation)
5653    ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(RD, Loc));
5654  else
5655    MarkVirtualMembersReferenced(Loc, RD);
5656}
5657
5658bool Sema::ProcessPendingClassesWithUnmarkedVirtualMembers() {
5659  if (ClassesWithUnmarkedVirtualMembers.empty())
5660    return false;
5661
5662  while (!ClassesWithUnmarkedVirtualMembers.empty()) {
5663    CXXRecordDecl *RD = ClassesWithUnmarkedVirtualMembers.back().first;
5664    SourceLocation Loc = ClassesWithUnmarkedVirtualMembers.back().second;
5665    ClassesWithUnmarkedVirtualMembers.pop_back();
5666    MarkVirtualMembersReferenced(Loc, RD);
5667  }
5668
5669  return true;
5670}
5671
5672void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
5673                                        const CXXRecordDecl *RD) {
5674  for (CXXRecordDecl::method_iterator i = RD->method_begin(),
5675       e = RD->method_end(); i != e; ++i) {
5676    CXXMethodDecl *MD = *i;
5677
5678    // C++ [basic.def.odr]p2:
5679    //   [...] A virtual member function is used if it is not pure. [...]
5680    if (MD->isVirtual() && !MD->isPure())
5681      MarkDeclarationReferenced(Loc, MD);
5682  }
5683
5684  // Only classes that have virtual bases need a VTT.
5685  if (RD->getNumVBases() == 0)
5686    return;
5687
5688  for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
5689           e = RD->bases_end(); i != e; ++i) {
5690    const CXXRecordDecl *Base =
5691        cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
5692    if (i->isVirtual())
5693      continue;
5694    if (Base->getNumVBases() == 0)
5695      continue;
5696    MarkVirtualMembersReferenced(Loc, Base);
5697  }
5698}
5699