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