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