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