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