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