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