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