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