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