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