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