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