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