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