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