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