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