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