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