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