SemaDeclCXX.cpp revision 9f853df0d3c25c646907a7b7ef22398370def00f
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 "Sema.h"
15#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/CXXInheritance.h"
18#include "clang/AST/DeclVisitor.h"
19#include "clang/AST/TypeOrdering.h"
20#include "clang/AST/StmtVisitor.h"
21#include "clang/Parse/DeclSpec.h"
22#include "clang/Parse/Template.h"
23#include "clang/Basic/PartialDiagnostic.h"
24#include "clang/Lex/Preprocessor.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/Support/Compiler.h"
27#include <algorithm> // for std::equal
28#include <map>
29#include <set>
30
31using namespace clang;
32
33//===----------------------------------------------------------------------===//
34// CheckDefaultArgumentVisitor
35//===----------------------------------------------------------------------===//
36
37namespace {
38  /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
39  /// the default argument of a parameter to determine whether it
40  /// contains any ill-formed subexpressions. For example, this will
41  /// diagnose the use of local variables or parameters within the
42  /// default argument expression.
43  class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
44    : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
45    Expr *DefaultArg;
46    Sema *S;
47
48  public:
49    CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
50      : DefaultArg(defarg), S(s) {}
51
52    bool VisitExpr(Expr *Node);
53    bool VisitDeclRefExpr(DeclRefExpr *DRE);
54    bool VisitCXXThisExpr(CXXThisExpr *ThisE);
55  };
56
57  /// VisitExpr - Visit all of the children of this expression.
58  bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
59    bool IsInvalid = false;
60    for (Stmt::child_iterator I = Node->child_begin(),
61         E = Node->child_end(); I != E; ++I)
62      IsInvalid |= Visit(*I);
63    return IsInvalid;
64  }
65
66  /// VisitDeclRefExpr - Visit a reference to a declaration, to
67  /// determine whether this declaration can be used in the default
68  /// argument expression.
69  bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
70    NamedDecl *Decl = DRE->getDecl();
71    if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
72      // C++ [dcl.fct.default]p9
73      //   Default arguments are evaluated each time the function is
74      //   called. The order of evaluation of function arguments is
75      //   unspecified. Consequently, parameters of a function shall not
76      //   be used in default argument expressions, even if they are not
77      //   evaluated. Parameters of a function declared before a default
78      //   argument expression are in scope and can hide namespace and
79      //   class member names.
80      return S->Diag(DRE->getSourceRange().getBegin(),
81                     diag::err_param_default_argument_references_param)
82         << Param->getDeclName() << DefaultArg->getSourceRange();
83    } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
84      // C++ [dcl.fct.default]p7
85      //   Local variables shall not be used in default argument
86      //   expressions.
87      if (VDecl->isBlockVarDecl())
88        return S->Diag(DRE->getSourceRange().getBegin(),
89                       diag::err_param_default_argument_references_local)
90          << VDecl->getDeclName() << DefaultArg->getSourceRange();
91    }
92
93    return false;
94  }
95
96  /// VisitCXXThisExpr - Visit a C++ "this" expression.
97  bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
98    // C++ [dcl.fct.default]p8:
99    //   The keyword this shall not be used in a default argument of a
100    //   member function.
101    return S->Diag(ThisE->getSourceRange().getBegin(),
102                   diag::err_param_default_argument_references_this)
103               << ThisE->getSourceRange();
104  }
105}
106
107bool
108Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
109                              SourceLocation EqualLoc) {
110  QualType ParamType = Param->getType();
111
112  if (RequireCompleteType(Param->getLocation(), Param->getType(),
113                          diag::err_typecheck_decl_incomplete_type)) {
114    Param->setInvalidDecl();
115    return true;
116  }
117
118  Expr *Arg = (Expr *)DefaultArg.get();
119
120  // C++ [dcl.fct.default]p5
121  //   A default argument expression is implicitly converted (clause
122  //   4) to the parameter type. The default argument expression has
123  //   the same semantic constraints as the initializer expression in
124  //   a declaration of a variable of the parameter type, using the
125  //   copy-initialization semantics (8.5).
126  if (CheckInitializerTypes(Arg, ParamType, EqualLoc,
127                            Param->getDeclName(), /*DirectInit=*/false))
128    return true;
129
130  Arg = MaybeCreateCXXExprWithTemporaries(Arg, /*DestroyTemps=*/false);
131
132  // Okay: add the default argument to the parameter
133  Param->setDefaultArg(Arg);
134
135  DefaultArg.release();
136
137  return false;
138}
139
140/// ActOnParamDefaultArgument - Check whether the default argument
141/// provided for a function parameter is well-formed. If so, attach it
142/// to the parameter declaration.
143void
144Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
145                                ExprArg defarg) {
146  if (!param || !defarg.get())
147    return;
148
149  ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
150  UnparsedDefaultArgLocs.erase(Param);
151
152  ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
153  QualType ParamType = Param->getType();
154
155  // Default arguments are only permitted in C++
156  if (!getLangOptions().CPlusPlus) {
157    Diag(EqualLoc, diag::err_param_default_argument)
158      << DefaultArg->getSourceRange();
159    Param->setInvalidDecl();
160    return;
161  }
162
163  // Check that the default argument is well-formed
164  CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
165  if (DefaultArgChecker.Visit(DefaultArg.get())) {
166    Param->setInvalidDecl();
167    return;
168  }
169
170  SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
171}
172
173/// ActOnParamUnparsedDefaultArgument - We've seen a default
174/// argument for a function parameter, but we can't parse it yet
175/// because we're inside a class definition. Note that this default
176/// argument will be parsed later.
177void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
178                                             SourceLocation EqualLoc,
179                                             SourceLocation ArgLoc) {
180  if (!param)
181    return;
182
183  ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
184  if (Param)
185    Param->setUnparsedDefaultArg();
186
187  UnparsedDefaultArgLocs[Param] = ArgLoc;
188}
189
190/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
191/// the default argument for the parameter param failed.
192void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
193  if (!param)
194    return;
195
196  ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
197
198  Param->setInvalidDecl();
199
200  UnparsedDefaultArgLocs.erase(Param);
201}
202
203/// CheckExtraCXXDefaultArguments - Check for any extra default
204/// arguments in the declarator, which is not a function declaration
205/// or definition and therefore is not permitted to have default
206/// arguments. This routine should be invoked for every declarator
207/// that is not a function declaration or definition.
208void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
209  // C++ [dcl.fct.default]p3
210  //   A default argument expression shall be specified only in the
211  //   parameter-declaration-clause of a function declaration or in a
212  //   template-parameter (14.1). It shall not be specified for a
213  //   parameter pack. If it is specified in a
214  //   parameter-declaration-clause, it shall not occur within a
215  //   declarator or abstract-declarator of a parameter-declaration.
216  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
217    DeclaratorChunk &chunk = D.getTypeObject(i);
218    if (chunk.Kind == DeclaratorChunk::Function) {
219      for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
220        ParmVarDecl *Param =
221          cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
222        if (Param->hasUnparsedDefaultArg()) {
223          CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
224          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
225            << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
226          delete Toks;
227          chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
228        } else if (Param->getDefaultArg()) {
229          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
230            << Param->getDefaultArg()->getSourceRange();
231          Param->setDefaultArg(0);
232        }
233      }
234    }
235  }
236}
237
238// MergeCXXFunctionDecl - Merge two declarations of the same C++
239// function, once we already know that they have the same
240// type. Subroutine of MergeFunctionDecl. Returns true if there was an
241// error, false otherwise.
242bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
243  bool Invalid = false;
244
245  // C++ [dcl.fct.default]p4:
246  //   For non-template functions, default arguments can be added in
247  //   later declarations of a function in the same
248  //   scope. Declarations in different scopes have completely
249  //   distinct sets of default arguments. That is, declarations in
250  //   inner scopes do not acquire default arguments from
251  //   declarations in outer scopes, and vice versa. In a given
252  //   function declaration, all parameters subsequent to a
253  //   parameter with a default argument shall have default
254  //   arguments supplied in this or previous declarations. A
255  //   default argument shall not be redefined by a later
256  //   declaration (not even to the same value).
257  //
258  // C++ [dcl.fct.default]p6:
259  //   Except for member functions of class templates, the default arguments
260  //   in a member function definition that appears outside of the class
261  //   definition are added to the set of default arguments provided by the
262  //   member function declaration in the class definition.
263  for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
264    ParmVarDecl *OldParam = Old->getParamDecl(p);
265    ParmVarDecl *NewParam = New->getParamDecl(p);
266
267    if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
268      // FIXME: If the parameter doesn't have an identifier then the location
269      // points to the '=' which means that the fixit hint won't remove any
270      // extra spaces between the type and the '='.
271      SourceLocation Begin = NewParam->getLocation();
272      if (NewParam->getIdentifier())
273        Begin = PP.getLocForEndOfToken(Begin);
274
275      Diag(NewParam->getLocation(),
276           diag::err_param_default_argument_redefinition)
277        << NewParam->getDefaultArgRange()
278        << CodeModificationHint::CreateRemoval(SourceRange(Begin,
279                                                        NewParam->getLocEnd()));
280
281      // Look for the function declaration where the default argument was
282      // actually written, which may be a declaration prior to Old.
283      for (FunctionDecl *Older = Old->getPreviousDeclaration();
284           Older; Older = Older->getPreviousDeclaration()) {
285        if (!Older->getParamDecl(p)->hasDefaultArg())
286          break;
287
288        OldParam = Older->getParamDecl(p);
289      }
290
291      Diag(OldParam->getLocation(), diag::note_previous_definition)
292        << OldParam->getDefaultArgRange();
293      Invalid = true;
294    } else if (OldParam->hasDefaultArg()) {
295      // Merge the old default argument into the new parameter
296      if (OldParam->hasUninstantiatedDefaultArg())
297        NewParam->setUninstantiatedDefaultArg(
298                                      OldParam->getUninstantiatedDefaultArg());
299      else
300        NewParam->setDefaultArg(OldParam->getDefaultArg());
301    } else if (NewParam->hasDefaultArg()) {
302      if (New->getDescribedFunctionTemplate()) {
303        // Paragraph 4, quoted above, only applies to non-template functions.
304        Diag(NewParam->getLocation(),
305             diag::err_param_default_argument_template_redecl)
306          << NewParam->getDefaultArgRange();
307        Diag(Old->getLocation(), diag::note_template_prev_declaration)
308          << false;
309      } else if (New->getTemplateSpecializationKind()
310                   != TSK_ImplicitInstantiation &&
311                 New->getTemplateSpecializationKind() != TSK_Undeclared) {
312        // C++ [temp.expr.spec]p21:
313        //   Default function arguments shall not be specified in a declaration
314        //   or a definition for one of the following explicit specializations:
315        //     - the explicit specialization of a function template;
316        //     - the explicit specialization of a member function template;
317        //     - the explicit specialization of a member function of a class
318        //       template where the class template specialization to which the
319        //       member function specialization belongs is implicitly
320        //       instantiated.
321        Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
322          << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
323          << New->getDeclName()
324          << NewParam->getDefaultArgRange();
325      } else if (New->getDeclContext()->isDependentContext()) {
326        // C++ [dcl.fct.default]p6 (DR217):
327        //   Default arguments for a member function of a class template shall
328        //   be specified on the initial declaration of the member function
329        //   within the class template.
330        //
331        // Reading the tea leaves a bit in DR217 and its reference to DR205
332        // leads me to the conclusion that one cannot add default function
333        // arguments for an out-of-line definition of a member function of a
334        // dependent type.
335        int WhichKind = 2;
336        if (CXXRecordDecl *Record
337              = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
338          if (Record->getDescribedClassTemplate())
339            WhichKind = 0;
340          else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
341            WhichKind = 1;
342          else
343            WhichKind = 2;
344        }
345
346        Diag(NewParam->getLocation(),
347             diag::err_param_default_argument_member_template_redecl)
348          << WhichKind
349          << NewParam->getDefaultArgRange();
350      }
351    }
352  }
353
354  if (CheckEquivalentExceptionSpec(
355          Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
356          New->getType()->getAs<FunctionProtoType>(), New->getLocation())) {
357    Invalid = true;
358  }
359
360  return Invalid;
361}
362
363/// CheckCXXDefaultArguments - Verify that the default arguments for a
364/// function declaration are well-formed according to C++
365/// [dcl.fct.default].
366void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
367  unsigned NumParams = FD->getNumParams();
368  unsigned p;
369
370  // Find first parameter with a default argument
371  for (p = 0; p < NumParams; ++p) {
372    ParmVarDecl *Param = FD->getParamDecl(p);
373    if (Param->hasDefaultArg())
374      break;
375  }
376
377  // C++ [dcl.fct.default]p4:
378  //   In a given function declaration, all parameters
379  //   subsequent to a parameter with a default argument shall
380  //   have default arguments supplied in this or previous
381  //   declarations. A default argument shall not be redefined
382  //   by a later declaration (not even to the same value).
383  unsigned LastMissingDefaultArg = 0;
384  for (; p < NumParams; ++p) {
385    ParmVarDecl *Param = FD->getParamDecl(p);
386    if (!Param->hasDefaultArg()) {
387      if (Param->isInvalidDecl())
388        /* We already complained about this parameter. */;
389      else if (Param->getIdentifier())
390        Diag(Param->getLocation(),
391             diag::err_param_default_argument_missing_name)
392          << Param->getIdentifier();
393      else
394        Diag(Param->getLocation(),
395             diag::err_param_default_argument_missing);
396
397      LastMissingDefaultArg = p;
398    }
399  }
400
401  if (LastMissingDefaultArg > 0) {
402    // Some default arguments were missing. Clear out all of the
403    // default arguments up to (and including) the last missing
404    // default argument, so that we leave the function parameters
405    // in a semantically valid state.
406    for (p = 0; p <= LastMissingDefaultArg; ++p) {
407      ParmVarDecl *Param = FD->getParamDecl(p);
408      if (Param->hasDefaultArg()) {
409        if (!Param->hasUnparsedDefaultArg())
410          Param->getDefaultArg()->Destroy(Context);
411        Param->setDefaultArg(0);
412      }
413    }
414  }
415}
416
417/// isCurrentClassName - Determine whether the identifier II is the
418/// name of the class type currently being defined. In the case of
419/// nested classes, this will only return true if II is the name of
420/// the innermost class.
421bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
422                              const CXXScopeSpec *SS) {
423  CXXRecordDecl *CurDecl;
424  if (SS && SS->isSet() && !SS->isInvalid()) {
425    DeclContext *DC = computeDeclContext(*SS, true);
426    CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
427  } else
428    CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
429
430  if (CurDecl)
431    return &II == CurDecl->getIdentifier();
432  else
433    return false;
434}
435
436/// \brief Check the validity of a C++ base class specifier.
437///
438/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
439/// and returns NULL otherwise.
440CXXBaseSpecifier *
441Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
442                         SourceRange SpecifierRange,
443                         bool Virtual, AccessSpecifier Access,
444                         QualType BaseType,
445                         SourceLocation BaseLoc) {
446  // C++ [class.union]p1:
447  //   A union shall not have base classes.
448  if (Class->isUnion()) {
449    Diag(Class->getLocation(), diag::err_base_clause_on_union)
450      << SpecifierRange;
451    return 0;
452  }
453
454  if (BaseType->isDependentType())
455    return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
456                                Class->getTagKind() == RecordDecl::TK_class,
457                                Access, BaseType);
458
459  // Base specifiers must be record types.
460  if (!BaseType->isRecordType()) {
461    Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
462    return 0;
463  }
464
465  // C++ [class.union]p1:
466  //   A union shall not be used as a base class.
467  if (BaseType->isUnionType()) {
468    Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
469    return 0;
470  }
471
472  // C++ [class.derived]p2:
473  //   The class-name in a base-specifier shall not be an incompletely
474  //   defined class.
475  if (RequireCompleteType(BaseLoc, BaseType,
476                          PDiag(diag::err_incomplete_base_class)
477                            << SpecifierRange))
478    return 0;
479
480  // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
481  RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
482  assert(BaseDecl && "Record type has no declaration");
483  BaseDecl = BaseDecl->getDefinition(Context);
484  assert(BaseDecl && "Base type is not incomplete, but has no definition");
485  CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
486  assert(CXXBaseDecl && "Base type is not a C++ type");
487  if (!CXXBaseDecl->isEmpty())
488    Class->setEmpty(false);
489  if (CXXBaseDecl->isPolymorphic())
490    Class->setPolymorphic(true);
491
492  // C++ [dcl.init.aggr]p1:
493  //   An aggregate is [...] a class with [...] no base classes [...].
494  Class->setAggregate(false);
495  Class->setPOD(false);
496
497  if (Virtual) {
498    // C++ [class.ctor]p5:
499    //   A constructor is trivial if its class has no virtual base classes.
500    Class->setHasTrivialConstructor(false);
501
502    // C++ [class.copy]p6:
503    //   A copy constructor is trivial if its class has no virtual base classes.
504    Class->setHasTrivialCopyConstructor(false);
505
506    // C++ [class.copy]p11:
507    //   A copy assignment operator is trivial if its class has no virtual
508    //   base classes.
509    Class->setHasTrivialCopyAssignment(false);
510
511    // C++0x [meta.unary.prop] is_empty:
512    //    T is a class type, but not a union type, with ... no virtual base
513    //    classes
514    Class->setEmpty(false);
515  } else {
516    // C++ [class.ctor]p5:
517    //   A constructor is trivial if all the direct base classes of its
518    //   class have trivial constructors.
519    if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialConstructor())
520      Class->setHasTrivialConstructor(false);
521
522    // C++ [class.copy]p6:
523    //   A copy constructor is trivial if all the direct base classes of its
524    //   class have trivial copy constructors.
525    if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyConstructor())
526      Class->setHasTrivialCopyConstructor(false);
527
528    // C++ [class.copy]p11:
529    //   A copy assignment operator is trivial if all the direct base classes
530    //   of its class have trivial copy assignment operators.
531    if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyAssignment())
532      Class->setHasTrivialCopyAssignment(false);
533  }
534
535  // C++ [class.ctor]p3:
536  //   A destructor is trivial if all the direct base classes of its class
537  //   have trivial destructors.
538  if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialDestructor())
539    Class->setHasTrivialDestructor(false);
540
541  // Create the base specifier.
542  // FIXME: Allocate via ASTContext?
543  return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
544                              Class->getTagKind() == RecordDecl::TK_class,
545                              Access, BaseType);
546}
547
548/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
549/// one entry in the base class list of a class specifier, for
550/// example:
551///    class foo : public bar, virtual private baz {
552/// 'public bar' and 'virtual private baz' are each base-specifiers.
553Sema::BaseResult
554Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
555                         bool Virtual, AccessSpecifier Access,
556                         TypeTy *basetype, SourceLocation BaseLoc) {
557  if (!classdecl)
558    return true;
559
560  AdjustDeclIfTemplate(classdecl);
561  CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
562  QualType BaseType = GetTypeFromParser(basetype);
563  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
564                                                      Virtual, Access,
565                                                      BaseType, BaseLoc))
566    return BaseSpec;
567
568  return true;
569}
570
571/// \brief Performs the actual work of attaching the given base class
572/// specifiers to a C++ class.
573bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
574                                unsigned NumBases) {
575 if (NumBases == 0)
576    return false;
577
578  // Used to keep track of which base types we have already seen, so
579  // that we can properly diagnose redundant direct base types. Note
580  // that the key is always the unqualified canonical type of the base
581  // class.
582  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
583
584  // Copy non-redundant base specifiers into permanent storage.
585  unsigned NumGoodBases = 0;
586  bool Invalid = false;
587  for (unsigned idx = 0; idx < NumBases; ++idx) {
588    QualType NewBaseType
589      = Context.getCanonicalType(Bases[idx]->getType());
590    NewBaseType = NewBaseType.getLocalUnqualifiedType();
591
592    if (KnownBaseTypes[NewBaseType]) {
593      // C++ [class.mi]p3:
594      //   A class shall not be specified as a direct base class of a
595      //   derived class more than once.
596      Diag(Bases[idx]->getSourceRange().getBegin(),
597           diag::err_duplicate_base_class)
598        << KnownBaseTypes[NewBaseType]->getType()
599        << Bases[idx]->getSourceRange();
600
601      // Delete the duplicate base class specifier; we're going to
602      // overwrite its pointer later.
603      Context.Deallocate(Bases[idx]);
604
605      Invalid = true;
606    } else {
607      // Okay, add this new base class.
608      KnownBaseTypes[NewBaseType] = Bases[idx];
609      Bases[NumGoodBases++] = Bases[idx];
610    }
611  }
612
613  // Attach the remaining base class specifiers to the derived class.
614  Class->setBases(Context, Bases, NumGoodBases);
615
616  // Delete the remaining (good) base class specifiers, since their
617  // data has been copied into the CXXRecordDecl.
618  for (unsigned idx = 0; idx < NumGoodBases; ++idx)
619    Context.Deallocate(Bases[idx]);
620
621  return Invalid;
622}
623
624/// ActOnBaseSpecifiers - Attach the given base specifiers to the
625/// class, after checking whether there are any duplicate base
626/// classes.
627void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
628                               unsigned NumBases) {
629  if (!ClassDecl || !Bases || !NumBases)
630    return;
631
632  AdjustDeclIfTemplate(ClassDecl);
633  AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
634                       (CXXBaseSpecifier**)(Bases), NumBases);
635}
636
637/// \brief Determine whether the type \p Derived is a C++ class that is
638/// derived from the type \p Base.
639bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
640  if (!getLangOptions().CPlusPlus)
641    return false;
642
643  const RecordType *DerivedRT = Derived->getAs<RecordType>();
644  if (!DerivedRT)
645    return false;
646
647  const RecordType *BaseRT = Base->getAs<RecordType>();
648  if (!BaseRT)
649    return false;
650
651  CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
652  CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
653  return DerivedRD->isDerivedFrom(BaseRD);
654}
655
656/// \brief Determine whether the type \p Derived is a C++ class that is
657/// derived from the type \p Base.
658bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
659  if (!getLangOptions().CPlusPlus)
660    return false;
661
662  const RecordType *DerivedRT = Derived->getAs<RecordType>();
663  if (!DerivedRT)
664    return false;
665
666  const RecordType *BaseRT = Base->getAs<RecordType>();
667  if (!BaseRT)
668    return false;
669
670  CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
671  CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
672  return DerivedRD->isDerivedFrom(BaseRD, Paths);
673}
674
675/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
676/// conversion (where Derived and Base are class types) is
677/// well-formed, meaning that the conversion is unambiguous (and
678/// that all of the base classes are accessible). Returns true
679/// and emits a diagnostic if the code is ill-formed, returns false
680/// otherwise. Loc is the location where this routine should point to
681/// if there is an error, and Range is the source range to highlight
682/// if there is an error.
683bool
684Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
685                                   unsigned InaccessibleBaseID,
686                                   unsigned AmbigiousBaseConvID,
687                                   SourceLocation Loc, SourceRange Range,
688                                   DeclarationName Name) {
689  // First, determine whether the path from Derived to Base is
690  // ambiguous. This is slightly more expensive than checking whether
691  // the Derived to Base conversion exists, because here we need to
692  // explore multiple paths to determine if there is an ambiguity.
693  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
694                     /*DetectVirtual=*/false);
695  bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
696  assert(DerivationOkay &&
697         "Can only be used with a derived-to-base conversion");
698  (void)DerivationOkay;
699
700  if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
701    if (InaccessibleBaseID == 0)
702      return false;
703    // Check that the base class can be accessed.
704    return CheckBaseClassAccess(Derived, Base, InaccessibleBaseID, Paths, Loc,
705                                Name);
706  }
707
708  // We know that the derived-to-base conversion is ambiguous, and
709  // we're going to produce a diagnostic. Perform the derived-to-base
710  // search just one more time to compute all of the possible paths so
711  // that we can print them out. This is more expensive than any of
712  // the previous derived-to-base checks we've done, but at this point
713  // performance isn't as much of an issue.
714  Paths.clear();
715  Paths.setRecordingPaths(true);
716  bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
717  assert(StillOkay && "Can only be used with a derived-to-base conversion");
718  (void)StillOkay;
719
720  // Build up a textual representation of the ambiguous paths, e.g.,
721  // D -> B -> A, that will be used to illustrate the ambiguous
722  // conversions in the diagnostic. We only print one of the paths
723  // to each base class subobject.
724  std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
725
726  Diag(Loc, AmbigiousBaseConvID)
727  << Derived << Base << PathDisplayStr << Range << Name;
728  return true;
729}
730
731bool
732Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
733                                   SourceLocation Loc, SourceRange Range,
734                                   bool IgnoreAccess) {
735  return CheckDerivedToBaseConversion(Derived, Base,
736                                      IgnoreAccess ? 0 :
737                                        diag::err_conv_to_inaccessible_base,
738                                      diag::err_ambiguous_derived_to_base_conv,
739                                      Loc, Range, DeclarationName());
740}
741
742
743/// @brief Builds a string representing ambiguous paths from a
744/// specific derived class to different subobjects of the same base
745/// class.
746///
747/// This function builds a string that can be used in error messages
748/// to show the different paths that one can take through the
749/// inheritance hierarchy to go from the derived class to different
750/// subobjects of a base class. The result looks something like this:
751/// @code
752/// struct D -> struct B -> struct A
753/// struct D -> struct C -> struct A
754/// @endcode
755std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
756  std::string PathDisplayStr;
757  std::set<unsigned> DisplayedPaths;
758  for (CXXBasePaths::paths_iterator Path = Paths.begin();
759       Path != Paths.end(); ++Path) {
760    if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
761      // We haven't displayed a path to this particular base
762      // class subobject yet.
763      PathDisplayStr += "\n    ";
764      PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
765      for (CXXBasePath::const_iterator Element = Path->begin();
766           Element != Path->end(); ++Element)
767        PathDisplayStr += " -> " + Element->Base->getType().getAsString();
768    }
769  }
770
771  return PathDisplayStr;
772}
773
774//===----------------------------------------------------------------------===//
775// C++ class member Handling
776//===----------------------------------------------------------------------===//
777
778/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
779/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
780/// bitfield width if there is one and 'InitExpr' specifies the initializer if
781/// any.
782Sema::DeclPtrTy
783Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
784                               MultiTemplateParamsArg TemplateParameterLists,
785                               ExprTy *BW, ExprTy *InitExpr, bool Deleted) {
786  const DeclSpec &DS = D.getDeclSpec();
787  DeclarationName Name = GetNameForDeclarator(D);
788  Expr *BitWidth = static_cast<Expr*>(BW);
789  Expr *Init = static_cast<Expr*>(InitExpr);
790  SourceLocation Loc = D.getIdentifierLoc();
791
792  bool isFunc = D.isFunctionDeclarator();
793
794  assert(!DS.isFriendSpecified());
795
796  // C++ 9.2p6: A member shall not be declared to have automatic storage
797  // duration (auto, register) or with the extern storage-class-specifier.
798  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
799  // data members and cannot be applied to names declared const or static,
800  // and cannot be applied to reference members.
801  switch (DS.getStorageClassSpec()) {
802    case DeclSpec::SCS_unspecified:
803    case DeclSpec::SCS_typedef:
804    case DeclSpec::SCS_static:
805      // FALL THROUGH.
806      break;
807    case DeclSpec::SCS_mutable:
808      if (isFunc) {
809        if (DS.getStorageClassSpecLoc().isValid())
810          Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
811        else
812          Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
813
814        // FIXME: It would be nicer if the keyword was ignored only for this
815        // declarator. Otherwise we could get follow-up errors.
816        D.getMutableDeclSpec().ClearStorageClassSpecs();
817      } else {
818        QualType T = GetTypeForDeclarator(D, S);
819        diag::kind err = static_cast<diag::kind>(0);
820        if (T->isReferenceType())
821          err = diag::err_mutable_reference;
822        else if (T.isConstQualified())
823          err = diag::err_mutable_const;
824        if (err != 0) {
825          if (DS.getStorageClassSpecLoc().isValid())
826            Diag(DS.getStorageClassSpecLoc(), err);
827          else
828            Diag(DS.getThreadSpecLoc(), err);
829          // FIXME: It would be nicer if the keyword was ignored only for this
830          // declarator. Otherwise we could get follow-up errors.
831          D.getMutableDeclSpec().ClearStorageClassSpecs();
832        }
833      }
834      break;
835    default:
836      if (DS.getStorageClassSpecLoc().isValid())
837        Diag(DS.getStorageClassSpecLoc(),
838             diag::err_storageclass_invalid_for_member);
839      else
840        Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
841      D.getMutableDeclSpec().ClearStorageClassSpecs();
842  }
843
844  if (!isFunc &&
845      D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
846      D.getNumTypeObjects() == 0) {
847    // Check also for this case:
848    //
849    // typedef int f();
850    // f a;
851    //
852    QualType TDType = GetTypeFromParser(DS.getTypeRep());
853    isFunc = TDType->isFunctionType();
854  }
855
856  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
857                       DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
858                      !isFunc);
859
860  Decl *Member;
861  if (isInstField) {
862    // FIXME: Check for template parameters!
863    Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
864                         AS);
865    assert(Member && "HandleField never returns null");
866  } else {
867    Member = HandleDeclarator(S, D, move(TemplateParameterLists), false)
868               .getAs<Decl>();
869    if (!Member) {
870      if (BitWidth) DeleteExpr(BitWidth);
871      return DeclPtrTy();
872    }
873
874    // Non-instance-fields can't have a bitfield.
875    if (BitWidth) {
876      if (Member->isInvalidDecl()) {
877        // don't emit another diagnostic.
878      } else if (isa<VarDecl>(Member)) {
879        // C++ 9.6p3: A bit-field shall not be a static member.
880        // "static member 'A' cannot be a bit-field"
881        Diag(Loc, diag::err_static_not_bitfield)
882          << Name << BitWidth->getSourceRange();
883      } else if (isa<TypedefDecl>(Member)) {
884        // "typedef member 'x' cannot be a bit-field"
885        Diag(Loc, diag::err_typedef_not_bitfield)
886          << Name << BitWidth->getSourceRange();
887      } else {
888        // A function typedef ("typedef int f(); f a;").
889        // C++ 9.6p3: A bit-field shall have integral or enumeration type.
890        Diag(Loc, diag::err_not_integral_type_bitfield)
891          << Name << cast<ValueDecl>(Member)->getType()
892          << BitWidth->getSourceRange();
893      }
894
895      DeleteExpr(BitWidth);
896      BitWidth = 0;
897      Member->setInvalidDecl();
898    }
899
900    Member->setAccess(AS);
901
902    // If we have declared a member function template, set the access of the
903    // templated declaration as well.
904    if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
905      FunTmpl->getTemplatedDecl()->setAccess(AS);
906  }
907
908  assert((Name || isInstField) && "No identifier for non-field ?");
909
910  if (Init)
911    AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
912  if (Deleted) // FIXME: Source location is not very good.
913    SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
914
915  if (isInstField) {
916    FieldCollector->Add(cast<FieldDecl>(Member));
917    return DeclPtrTy();
918  }
919  return DeclPtrTy::make(Member);
920}
921
922/// ActOnMemInitializer - Handle a C++ member initializer.
923Sema::MemInitResult
924Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
925                          Scope *S,
926                          const CXXScopeSpec &SS,
927                          IdentifierInfo *MemberOrBase,
928                          TypeTy *TemplateTypeTy,
929                          SourceLocation IdLoc,
930                          SourceLocation LParenLoc,
931                          ExprTy **Args, unsigned NumArgs,
932                          SourceLocation *CommaLocs,
933                          SourceLocation RParenLoc) {
934  if (!ConstructorD)
935    return true;
936
937  AdjustDeclIfTemplate(ConstructorD);
938
939  CXXConstructorDecl *Constructor
940    = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
941  if (!Constructor) {
942    // The user wrote a constructor initializer on a function that is
943    // not a C++ constructor. Ignore the error for now, because we may
944    // have more member initializers coming; we'll diagnose it just
945    // once in ActOnMemInitializers.
946    return true;
947  }
948
949  CXXRecordDecl *ClassDecl = Constructor->getParent();
950
951  // C++ [class.base.init]p2:
952  //   Names in a mem-initializer-id are looked up in the scope of the
953  //   constructor’s class and, if not found in that scope, are looked
954  //   up in the scope containing the constructor’s
955  //   definition. [Note: if the constructor’s class contains a member
956  //   with the same name as a direct or virtual base class of the
957  //   class, a mem-initializer-id naming the member or base class and
958  //   composed of a single identifier refers to the class member. A
959  //   mem-initializer-id for the hidden base class may be specified
960  //   using a qualified name. ]
961  if (!SS.getScopeRep() && !TemplateTypeTy) {
962    // Look for a member, first.
963    FieldDecl *Member = 0;
964    DeclContext::lookup_result Result
965      = ClassDecl->lookup(MemberOrBase);
966    if (Result.first != Result.second)
967      Member = dyn_cast<FieldDecl>(*Result.first);
968
969    // FIXME: Handle members of an anonymous union.
970
971    if (Member)
972      return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
973                                    RParenLoc);
974  }
975  // It didn't name a member, so see if it names a class.
976  TypeTy *BaseTy = TemplateTypeTy ? TemplateTypeTy
977                     : getTypeName(*MemberOrBase, IdLoc, S, &SS);
978  if (!BaseTy)
979    return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
980      << MemberOrBase << SourceRange(IdLoc, RParenLoc);
981
982  QualType BaseType = GetTypeFromParser(BaseTy);
983
984  return BuildBaseInitializer(BaseType, (Expr **)Args, NumArgs, IdLoc,
985                              RParenLoc, ClassDecl);
986}
987
988/// Checks an initializer expression for use of uninitialized fields, such as
989/// containing the field that is being initialized. Returns true if there is an
990/// uninitialized field was used an updates the SourceLocation parameter; false
991/// otherwise.
992static bool InitExprContainsUninitializedFields(const Stmt* S,
993                                                const FieldDecl* LhsField,
994                                                SourceLocation* L) {
995  const MemberExpr* ME = dyn_cast<MemberExpr>(S);
996  if (ME) {
997    const NamedDecl* RhsField = ME->getMemberDecl();
998    if (RhsField == LhsField) {
999      // Initializing a field with itself. Throw a warning.
1000      // But wait; there are exceptions!
1001      // Exception #1:  The field may not belong to this record.
1002      // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1003      const Expr* base = ME->getBase();
1004      if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1005        // Even though the field matches, it does not belong to this record.
1006        return false;
1007      }
1008      // None of the exceptions triggered; return true to indicate an
1009      // uninitialized field was used.
1010      *L = ME->getMemberLoc();
1011      return true;
1012    }
1013  }
1014  bool found = false;
1015  for (Stmt::const_child_iterator it = S->child_begin();
1016       it != S->child_end() && found == false;
1017       ++it) {
1018    if (isa<CallExpr>(S)) {
1019      // Do not descend into function calls or constructors, as the use
1020      // of an uninitialized field may be valid. One would have to inspect
1021      // the contents of the function/ctor to determine if it is safe or not.
1022      // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1023      // may be safe, depending on what the function/ctor does.
1024      continue;
1025    }
1026    found = InitExprContainsUninitializedFields(*it, LhsField, L);
1027  }
1028  return found;
1029}
1030
1031Sema::MemInitResult
1032Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1033                             unsigned NumArgs, SourceLocation IdLoc,
1034                             SourceLocation RParenLoc) {
1035  // FIXME: CXXBaseOrMemberInitializer should only contain a single
1036  // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1037  ExprTemporaries.clear();
1038
1039  // Diagnose value-uses of fields to initialize themselves, e.g.
1040  //   foo(foo)
1041  // where foo is not also a parameter to the constructor.
1042  // TODO: implement -Wuninitialized and fold this into that framework.
1043  for (unsigned i = 0; i < NumArgs; ++i) {
1044    SourceLocation L;
1045    if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1046      // FIXME: Return true in the case when other fields are used before being
1047      // uninitialized. For example, let this field be the i'th field. When
1048      // initializing the i'th field, throw a warning if any of the >= i'th
1049      // fields are used, as they are not yet initialized.
1050      // Right now we are only handling the case where the i'th field uses
1051      // itself in its initializer.
1052      Diag(L, diag::warn_field_is_uninit);
1053    }
1054  }
1055
1056  bool HasDependentArg = false;
1057  for (unsigned i = 0; i < NumArgs; i++)
1058    HasDependentArg |= Args[i]->isTypeDependent();
1059
1060  CXXConstructorDecl *C = 0;
1061  QualType FieldType = Member->getType();
1062  if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1063    FieldType = Array->getElementType();
1064  if (FieldType->isDependentType()) {
1065    // Can't check init for dependent type.
1066  } else if (FieldType->isRecordType()) {
1067    // Member is a record (struct/union/class), so pass the initializer
1068    // arguments down to the record's constructor.
1069    if (!HasDependentArg) {
1070      ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1071
1072      C = PerformInitializationByConstructor(FieldType,
1073                                             MultiExprArg(*this,
1074                                                          (void**)Args,
1075                                                          NumArgs),
1076                                             IdLoc,
1077                                             SourceRange(IdLoc, RParenLoc),
1078                                             Member->getDeclName(), IK_Direct,
1079                                             ConstructorArgs);
1080
1081      if (C) {
1082        // Take over the constructor arguments as our own.
1083        NumArgs = ConstructorArgs.size();
1084        Args = (Expr **)ConstructorArgs.take();
1085      }
1086    }
1087  } else if (NumArgs != 1 && NumArgs != 0) {
1088    // The member type is not a record type (or an array of record
1089    // types), so it can be only be default- or copy-initialized.
1090    return Diag(IdLoc, diag::err_mem_initializer_mismatch)
1091                << Member->getDeclName() << SourceRange(IdLoc, RParenLoc);
1092  } else if (!HasDependentArg) {
1093    Expr *NewExp;
1094    if (NumArgs == 0) {
1095      if (FieldType->isReferenceType()) {
1096        Diag(IdLoc, diag::err_null_intialized_reference_member)
1097              << Member->getDeclName();
1098        return Diag(Member->getLocation(), diag::note_declared_at);
1099      }
1100      NewExp = new (Context) CXXZeroInitValueExpr(FieldType, IdLoc, RParenLoc);
1101      NumArgs = 1;
1102    }
1103    else
1104      NewExp = (Expr*)Args[0];
1105    if (PerformCopyInitialization(NewExp, FieldType, "passing"))
1106      return true;
1107    Args[0] = NewExp;
1108  }
1109
1110  // FIXME: CXXBaseOrMemberInitializer should only contain a single
1111  // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1112  ExprTemporaries.clear();
1113
1114  // FIXME: Perform direct initialization of the member.
1115  return new (Context) CXXBaseOrMemberInitializer(Member, (Expr **)Args,
1116                                                  NumArgs, C, IdLoc, RParenLoc);
1117}
1118
1119Sema::MemInitResult
1120Sema::BuildBaseInitializer(QualType BaseType, Expr **Args,
1121                           unsigned NumArgs, SourceLocation IdLoc,
1122                           SourceLocation RParenLoc, CXXRecordDecl *ClassDecl) {
1123  bool HasDependentArg = false;
1124  for (unsigned i = 0; i < NumArgs; i++)
1125    HasDependentArg |= Args[i]->isTypeDependent();
1126
1127  if (!BaseType->isDependentType()) {
1128    if (!BaseType->isRecordType())
1129      return Diag(IdLoc, diag::err_base_init_does_not_name_class)
1130        << BaseType << SourceRange(IdLoc, RParenLoc);
1131
1132    // C++ [class.base.init]p2:
1133    //   [...] Unless the mem-initializer-id names a nonstatic data
1134    //   member of the constructor’s class or a direct or virtual base
1135    //   of that class, the mem-initializer is ill-formed. A
1136    //   mem-initializer-list can initialize a base class using any
1137    //   name that denotes that base class type.
1138
1139    // First, check for a direct base class.
1140    const CXXBaseSpecifier *DirectBaseSpec = 0;
1141    for (CXXRecordDecl::base_class_const_iterator Base =
1142         ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) {
1143      if (Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1144        // We found a direct base of this type. That's what we're
1145        // initializing.
1146        DirectBaseSpec = &*Base;
1147        break;
1148      }
1149    }
1150
1151    // Check for a virtual base class.
1152    // FIXME: We might be able to short-circuit this if we know in advance that
1153    // there are no virtual bases.
1154    const CXXBaseSpecifier *VirtualBaseSpec = 0;
1155    if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1156      // We haven't found a base yet; search the class hierarchy for a
1157      // virtual base class.
1158      CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1159                         /*DetectVirtual=*/false);
1160      if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
1161        for (CXXBasePaths::paths_iterator Path = Paths.begin();
1162             Path != Paths.end(); ++Path) {
1163          if (Path->back().Base->isVirtual()) {
1164            VirtualBaseSpec = Path->back().Base;
1165            break;
1166          }
1167        }
1168      }
1169    }
1170
1171    // C++ [base.class.init]p2:
1172    //   If a mem-initializer-id is ambiguous because it designates both
1173    //   a direct non-virtual base class and an inherited virtual base
1174    //   class, the mem-initializer is ill-formed.
1175    if (DirectBaseSpec && VirtualBaseSpec)
1176      return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
1177        << BaseType << SourceRange(IdLoc, RParenLoc);
1178    // C++ [base.class.init]p2:
1179    // Unless the mem-initializer-id names a nonstatic data membeer of the
1180    // constructor's class ot a direst or virtual base of that class, the
1181    // mem-initializer is ill-formed.
1182    if (!DirectBaseSpec && !VirtualBaseSpec)
1183      return Diag(IdLoc, diag::err_not_direct_base_or_virtual)
1184      << BaseType << ClassDecl->getNameAsCString()
1185      << SourceRange(IdLoc, RParenLoc);
1186  }
1187
1188  CXXConstructorDecl *C = 0;
1189  if (!BaseType->isDependentType() && !HasDependentArg) {
1190    DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
1191                      Context.getCanonicalType(BaseType).getUnqualifiedType());
1192    ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1193
1194    C = PerformInitializationByConstructor(BaseType,
1195                                           MultiExprArg(*this,
1196                                                        (void**)Args, NumArgs),
1197                                           IdLoc, SourceRange(IdLoc, RParenLoc),
1198                                           Name, IK_Direct,
1199                                           ConstructorArgs);
1200    if (C) {
1201      // Take over the constructor arguments as our own.
1202      NumArgs = ConstructorArgs.size();
1203      Args = (Expr **)ConstructorArgs.take();
1204    }
1205  }
1206
1207  // FIXME: CXXBaseOrMemberInitializer should only contain a single
1208  // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1209  ExprTemporaries.clear();
1210
1211  return new (Context) CXXBaseOrMemberInitializer(BaseType, (Expr **)Args,
1212                                                  NumArgs, C, IdLoc, RParenLoc);
1213}
1214
1215bool
1216Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
1217                              CXXBaseOrMemberInitializer **Initializers,
1218                              unsigned NumInitializers,
1219                              bool IsImplicitConstructor) {
1220  // We need to build the initializer AST according to order of construction
1221  // and not what user specified in the Initializers list.
1222  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1223  llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1224  llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1225  bool HasDependentBaseInit = false;
1226  bool HadError = false;
1227
1228  for (unsigned i = 0; i < NumInitializers; i++) {
1229    CXXBaseOrMemberInitializer *Member = Initializers[i];
1230    if (Member->isBaseInitializer()) {
1231      if (Member->getBaseClass()->isDependentType())
1232        HasDependentBaseInit = true;
1233      AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1234    } else {
1235      AllBaseFields[Member->getMember()] = Member;
1236    }
1237  }
1238
1239  if (HasDependentBaseInit) {
1240    // FIXME. This does not preserve the ordering of the initializers.
1241    // Try (with -Wreorder)
1242    // template<class X> struct A {};
1243    // template<class X> struct B : A<X> {
1244    //   B() : x1(10), A<X>() {}
1245    //   int x1;
1246    // };
1247    // B<int> x;
1248    // On seeing one dependent type, we should essentially exit this routine
1249    // while preserving user-declared initializer list. When this routine is
1250    // called during instantiatiation process, this routine will rebuild the
1251    // ordered initializer list correctly.
1252
1253    // If we have a dependent base initialization, we can't determine the
1254    // association between initializers and bases; just dump the known
1255    // initializers into the list, and don't try to deal with other bases.
1256    for (unsigned i = 0; i < NumInitializers; i++) {
1257      CXXBaseOrMemberInitializer *Member = Initializers[i];
1258      if (Member->isBaseInitializer())
1259        AllToInit.push_back(Member);
1260    }
1261  } else {
1262    // Push virtual bases before others.
1263    for (CXXRecordDecl::base_class_iterator VBase =
1264         ClassDecl->vbases_begin(),
1265         E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1266      if (VBase->getType()->isDependentType())
1267        continue;
1268      if (CXXBaseOrMemberInitializer *Value
1269            = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1270        AllToInit.push_back(Value);
1271      }
1272      else {
1273        CXXRecordDecl *VBaseDecl =
1274        cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1275        assert(VBaseDecl && "SetBaseOrMemberInitializers - VBaseDecl null");
1276        CXXConstructorDecl *Ctor = VBaseDecl->getDefaultConstructor(Context);
1277        if (!Ctor) {
1278          Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1279            << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1280            << 0 << VBase->getType();
1281          Diag(VBaseDecl->getLocation(), diag::note_previous_class_decl)
1282            << Context.getTagDeclType(VBaseDecl);
1283          HadError = true;
1284          continue;
1285        }
1286
1287        ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1288        if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1289                                    Constructor->getLocation(), CtorArgs))
1290          continue;
1291
1292        MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1293
1294        // FIXME: CXXBaseOrMemberInitializer should only contain a single
1295        // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1296        ExprTemporaries.clear();
1297        CXXBaseOrMemberInitializer *Member =
1298          new (Context) CXXBaseOrMemberInitializer(VBase->getType(),
1299                                                   CtorArgs.takeAs<Expr>(),
1300                                                   CtorArgs.size(), Ctor,
1301                                                   SourceLocation(),
1302                                                   SourceLocation());
1303        AllToInit.push_back(Member);
1304      }
1305    }
1306
1307    for (CXXRecordDecl::base_class_iterator Base =
1308         ClassDecl->bases_begin(),
1309         E = ClassDecl->bases_end(); Base != E; ++Base) {
1310      // Virtuals are in the virtual base list and already constructed.
1311      if (Base->isVirtual())
1312        continue;
1313      // Skip dependent types.
1314      if (Base->getType()->isDependentType())
1315        continue;
1316      if (CXXBaseOrMemberInitializer *Value
1317            = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1318        AllToInit.push_back(Value);
1319      }
1320      else {
1321        CXXRecordDecl *BaseDecl =
1322          cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1323        assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null");
1324         CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context);
1325        if (!Ctor) {
1326          Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1327            << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1328            << 0 << Base->getType();
1329          Diag(BaseDecl->getLocation(), diag::note_previous_class_decl)
1330            << Context.getTagDeclType(BaseDecl);
1331          HadError = true;
1332          continue;
1333        }
1334
1335        ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1336        if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1337                                     Constructor->getLocation(), CtorArgs))
1338          continue;
1339
1340        MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1341
1342        // FIXME: CXXBaseOrMemberInitializer should only contain a single
1343        // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1344        ExprTemporaries.clear();
1345        CXXBaseOrMemberInitializer *Member =
1346          new (Context) CXXBaseOrMemberInitializer(Base->getType(),
1347                                                   CtorArgs.takeAs<Expr>(),
1348                                                   CtorArgs.size(), Ctor,
1349                                                   SourceLocation(),
1350                                                   SourceLocation());
1351        AllToInit.push_back(Member);
1352      }
1353    }
1354  }
1355
1356  // non-static data members.
1357  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1358       E = ClassDecl->field_end(); Field != E; ++Field) {
1359    if ((*Field)->isAnonymousStructOrUnion()) {
1360      if (const RecordType *FieldClassType =
1361          Field->getType()->getAs<RecordType>()) {
1362        CXXRecordDecl *FieldClassDecl
1363          = cast<CXXRecordDecl>(FieldClassType->getDecl());
1364        for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1365            EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1366          if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1367            // 'Member' is the anonymous union field and 'AnonUnionMember' is
1368            // set to the anonymous union data member used in the initializer
1369            // list.
1370            Value->setMember(*Field);
1371            Value->setAnonUnionMember(*FA);
1372            AllToInit.push_back(Value);
1373            break;
1374          }
1375        }
1376      }
1377      continue;
1378    }
1379    if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1380      AllToInit.push_back(Value);
1381      continue;
1382    }
1383
1384    if ((*Field)->getType()->isDependentType())
1385      continue;
1386
1387    QualType FT = Context.getBaseElementType((*Field)->getType());
1388    if (const RecordType* RT = FT->getAs<RecordType>()) {
1389      CXXConstructorDecl *Ctor =
1390        cast<CXXRecordDecl>(RT->getDecl())->getDefaultConstructor(Context);
1391      if (!Ctor) {
1392        Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1393          << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1394          << 1 << (*Field)->getDeclName();
1395        Diag(Field->getLocation(), diag::note_field_decl);
1396        Diag(RT->getDecl()->getLocation(), diag::note_previous_class_decl)
1397          << Context.getTagDeclType(RT->getDecl());
1398        HadError = true;
1399        continue;
1400      }
1401
1402      if (FT.isConstQualified() && Ctor->isTrivial()) {
1403        Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1404          << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1405          << 1 << (*Field)->getDeclName();
1406        Diag((*Field)->getLocation(), diag::note_declared_at);
1407        HadError = true;
1408      }
1409
1410      // Don't create initializers for trivial constructors, since they don't
1411      // actually need to be run.
1412      if (Ctor->isTrivial())
1413        continue;
1414
1415      ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1416      if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1417                                  Constructor->getLocation(), CtorArgs))
1418        continue;
1419
1420      // FIXME: CXXBaseOrMemberInitializer should only contain a single
1421      // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1422      ExprTemporaries.clear();
1423      CXXBaseOrMemberInitializer *Member =
1424        new (Context) CXXBaseOrMemberInitializer(*Field,CtorArgs.takeAs<Expr>(),
1425                                                 CtorArgs.size(), Ctor,
1426                                                 SourceLocation(),
1427                                                 SourceLocation());
1428
1429      AllToInit.push_back(Member);
1430      MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1431    }
1432    else if (FT->isReferenceType()) {
1433      Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1434        << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1435        << 0 << (*Field)->getDeclName();
1436      Diag((*Field)->getLocation(), diag::note_declared_at);
1437      HadError = true;
1438    }
1439    else if (FT.isConstQualified()) {
1440      Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1441        << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1442        << 1 << (*Field)->getDeclName();
1443      Diag((*Field)->getLocation(), diag::note_declared_at);
1444      HadError = true;
1445    }
1446  }
1447
1448  NumInitializers = AllToInit.size();
1449  if (NumInitializers > 0) {
1450    Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1451    CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1452      new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1453
1454    Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1455    for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1456      baseOrMemberInitializers[Idx] = AllToInit[Idx];
1457  }
1458
1459  return HadError;
1460}
1461
1462static void *GetKeyForTopLevelField(FieldDecl *Field) {
1463  // For anonymous unions, use the class declaration as the key.
1464  if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
1465    if (RT->getDecl()->isAnonymousStructOrUnion())
1466      return static_cast<void *>(RT->getDecl());
1467  }
1468  return static_cast<void *>(Field);
1469}
1470
1471static void *GetKeyForBase(QualType BaseType) {
1472  if (const RecordType *RT = BaseType->getAs<RecordType>())
1473    return (void *)RT;
1474
1475  assert(0 && "Unexpected base type!");
1476  return 0;
1477}
1478
1479static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
1480                             bool MemberMaybeAnon = false) {
1481  // For fields injected into the class via declaration of an anonymous union,
1482  // use its anonymous union class declaration as the unique key.
1483  if (Member->isMemberInitializer()) {
1484    FieldDecl *Field = Member->getMember();
1485
1486    // After SetBaseOrMemberInitializers call, Field is the anonymous union
1487    // data member of the class. Data member used in the initializer list is
1488    // in AnonUnionMember field.
1489    if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1490      Field = Member->getAnonUnionMember();
1491    if (Field->getDeclContext()->isRecord()) {
1492      RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1493      if (RD->isAnonymousStructOrUnion())
1494        return static_cast<void *>(RD);
1495    }
1496    return static_cast<void *>(Field);
1497  }
1498
1499  return GetKeyForBase(QualType(Member->getBaseClass(), 0));
1500}
1501
1502/// ActOnMemInitializers - Handle the member initializers for a constructor.
1503void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
1504                                SourceLocation ColonLoc,
1505                                MemInitTy **MemInits, unsigned NumMemInits) {
1506  if (!ConstructorDecl)
1507    return;
1508
1509  AdjustDeclIfTemplate(ConstructorDecl);
1510
1511  CXXConstructorDecl *Constructor
1512    = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
1513
1514  if (!Constructor) {
1515    Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1516    return;
1517  }
1518
1519  if (!Constructor->isDependentContext()) {
1520    llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1521    bool err = false;
1522    for (unsigned i = 0; i < NumMemInits; i++) {
1523      CXXBaseOrMemberInitializer *Member =
1524        static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1525      void *KeyToMember = GetKeyForMember(Member);
1526      CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1527      if (!PrevMember) {
1528        PrevMember = Member;
1529        continue;
1530      }
1531      if (FieldDecl *Field = Member->getMember())
1532        Diag(Member->getSourceLocation(),
1533             diag::error_multiple_mem_initialization)
1534        << Field->getNameAsString();
1535      else {
1536        Type *BaseClass = Member->getBaseClass();
1537        assert(BaseClass && "ActOnMemInitializers - neither field or base");
1538        Diag(Member->getSourceLocation(),
1539             diag::error_multiple_base_initialization)
1540          << QualType(BaseClass, 0);
1541      }
1542      Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1543        << 0;
1544      err = true;
1545    }
1546
1547    if (err)
1548      return;
1549  }
1550
1551  SetBaseOrMemberInitializers(Constructor,
1552                      reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
1553                      NumMemInits, false);
1554
1555  if (Constructor->isDependentContext())
1556    return;
1557
1558  if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
1559      Diagnostic::Ignored &&
1560      Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
1561      Diagnostic::Ignored)
1562    return;
1563
1564  // Also issue warning if order of ctor-initializer list does not match order
1565  // of 1) base class declarations and 2) order of non-static data members.
1566  llvm::SmallVector<const void*, 32> AllBaseOrMembers;
1567
1568  CXXRecordDecl *ClassDecl
1569    = cast<CXXRecordDecl>(Constructor->getDeclContext());
1570  // Push virtual bases before others.
1571  for (CXXRecordDecl::base_class_iterator VBase =
1572       ClassDecl->vbases_begin(),
1573       E = ClassDecl->vbases_end(); VBase != E; ++VBase)
1574    AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
1575
1576  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1577       E = ClassDecl->bases_end(); Base != E; ++Base) {
1578    // Virtuals are alread in the virtual base list and are constructed
1579    // first.
1580    if (Base->isVirtual())
1581      continue;
1582    AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
1583  }
1584
1585  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1586       E = ClassDecl->field_end(); Field != E; ++Field)
1587    AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
1588
1589  int Last = AllBaseOrMembers.size();
1590  int curIndex = 0;
1591  CXXBaseOrMemberInitializer *PrevMember = 0;
1592  for (unsigned i = 0; i < NumMemInits; i++) {
1593    CXXBaseOrMemberInitializer *Member =
1594      static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1595    void *MemberInCtorList = GetKeyForMember(Member, true);
1596
1597    for (; curIndex < Last; curIndex++)
1598      if (MemberInCtorList == AllBaseOrMembers[curIndex])
1599        break;
1600    if (curIndex == Last) {
1601      assert(PrevMember && "Member not in member list?!");
1602      // Initializer as specified in ctor-initializer list is out of order.
1603      // Issue a warning diagnostic.
1604      if (PrevMember->isBaseInitializer()) {
1605        // Diagnostics is for an initialized base class.
1606        Type *BaseClass = PrevMember->getBaseClass();
1607        Diag(PrevMember->getSourceLocation(),
1608             diag::warn_base_initialized)
1609          << QualType(BaseClass, 0);
1610      } else {
1611        FieldDecl *Field = PrevMember->getMember();
1612        Diag(PrevMember->getSourceLocation(),
1613             diag::warn_field_initialized)
1614          << Field->getNameAsString();
1615      }
1616      // Also the note!
1617      if (FieldDecl *Field = Member->getMember())
1618        Diag(Member->getSourceLocation(),
1619             diag::note_fieldorbase_initialized_here) << 0
1620          << Field->getNameAsString();
1621      else {
1622        Type *BaseClass = Member->getBaseClass();
1623        Diag(Member->getSourceLocation(),
1624             diag::note_fieldorbase_initialized_here) << 1
1625          << QualType(BaseClass, 0);
1626      }
1627      for (curIndex = 0; curIndex < Last; curIndex++)
1628        if (MemberInCtorList == AllBaseOrMembers[curIndex])
1629          break;
1630    }
1631    PrevMember = Member;
1632  }
1633}
1634
1635void
1636Sema::MarkBaseAndMemberDestructorsReferenced(CXXDestructorDecl *Destructor) {
1637  // Ignore dependent destructors.
1638  if (Destructor->isDependentContext())
1639    return;
1640
1641  CXXRecordDecl *ClassDecl = Destructor->getParent();
1642
1643  // Non-static data members.
1644  for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1645       E = ClassDecl->field_end(); I != E; ++I) {
1646    FieldDecl *Field = *I;
1647
1648    QualType FieldType = Context.getBaseElementType(Field->getType());
1649
1650    const RecordType* RT = FieldType->getAs<RecordType>();
1651    if (!RT)
1652      continue;
1653
1654    CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1655    if (FieldClassDecl->hasTrivialDestructor())
1656      continue;
1657
1658    const CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
1659    MarkDeclarationReferenced(Destructor->getLocation(),
1660                              const_cast<CXXDestructorDecl*>(Dtor));
1661  }
1662
1663  // Bases.
1664  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1665       E = ClassDecl->bases_end(); Base != E; ++Base) {
1666    // Ignore virtual bases.
1667    if (Base->isVirtual())
1668      continue;
1669
1670    // Ignore trivial destructors.
1671    CXXRecordDecl *BaseClassDecl
1672      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1673    if (BaseClassDecl->hasTrivialDestructor())
1674      continue;
1675
1676    const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1677    MarkDeclarationReferenced(Destructor->getLocation(),
1678                              const_cast<CXXDestructorDecl*>(Dtor));
1679  }
1680
1681  // Virtual bases.
1682  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1683       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1684    // Ignore trivial destructors.
1685    CXXRecordDecl *BaseClassDecl
1686      = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1687    if (BaseClassDecl->hasTrivialDestructor())
1688      continue;
1689
1690    const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1691    MarkDeclarationReferenced(Destructor->getLocation(),
1692                              const_cast<CXXDestructorDecl*>(Dtor));
1693  }
1694}
1695
1696void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
1697  if (!CDtorDecl)
1698    return;
1699
1700  AdjustDeclIfTemplate(CDtorDecl);
1701
1702  if (CXXConstructorDecl *Constructor
1703      = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
1704    SetBaseOrMemberInitializers(Constructor, 0, 0, false);
1705}
1706
1707namespace {
1708  /// PureVirtualMethodCollector - traverses a class and its superclasses
1709  /// and determines if it has any pure virtual methods.
1710  class VISIBILITY_HIDDEN PureVirtualMethodCollector {
1711    ASTContext &Context;
1712
1713  public:
1714    typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
1715
1716  private:
1717    MethodList Methods;
1718
1719    void Collect(const CXXRecordDecl* RD, MethodList& Methods);
1720
1721  public:
1722    PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
1723      : Context(Ctx) {
1724
1725      MethodList List;
1726      Collect(RD, List);
1727
1728      // Copy the temporary list to methods, and make sure to ignore any
1729      // null entries.
1730      for (size_t i = 0, e = List.size(); i != e; ++i) {
1731        if (List[i])
1732          Methods.push_back(List[i]);
1733      }
1734    }
1735
1736    bool empty() const { return Methods.empty(); }
1737
1738    MethodList::const_iterator methods_begin() { return Methods.begin(); }
1739    MethodList::const_iterator methods_end() { return Methods.end(); }
1740  };
1741
1742  void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
1743                                           MethodList& Methods) {
1744    // First, collect the pure virtual methods for the base classes.
1745    for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1746         BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
1747      if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
1748        const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
1749        if (BaseDecl && BaseDecl->isAbstract())
1750          Collect(BaseDecl, Methods);
1751      }
1752    }
1753
1754    // Next, zero out any pure virtual methods that this class overrides.
1755    typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
1756
1757    MethodSetTy OverriddenMethods;
1758    size_t MethodsSize = Methods.size();
1759
1760    for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
1761         i != e; ++i) {
1762      // Traverse the record, looking for methods.
1763      if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
1764        // If the method is pure virtual, add it to the methods vector.
1765        if (MD->isPure())
1766          Methods.push_back(MD);
1767
1768        // Record all the overridden methods in our set.
1769        for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1770             E = MD->end_overridden_methods(); I != E; ++I) {
1771          // Keep track of the overridden methods.
1772          OverriddenMethods.insert(*I);
1773        }
1774      }
1775    }
1776
1777    // Now go through the methods and zero out all the ones we know are
1778    // overridden.
1779    for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1780      if (OverriddenMethods.count(Methods[i]))
1781        Methods[i] = 0;
1782    }
1783
1784  }
1785}
1786
1787
1788bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1789                                  unsigned DiagID, AbstractDiagSelID SelID,
1790                                  const CXXRecordDecl *CurrentRD) {
1791  if (SelID == -1)
1792    return RequireNonAbstractType(Loc, T,
1793                                  PDiag(DiagID), CurrentRD);
1794  else
1795    return RequireNonAbstractType(Loc, T,
1796                                  PDiag(DiagID) << SelID, CurrentRD);
1797}
1798
1799bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1800                                  const PartialDiagnostic &PD,
1801                                  const CXXRecordDecl *CurrentRD) {
1802  if (!getLangOptions().CPlusPlus)
1803    return false;
1804
1805  if (const ArrayType *AT = Context.getAsArrayType(T))
1806    return RequireNonAbstractType(Loc, AT->getElementType(), PD,
1807                                  CurrentRD);
1808
1809  if (const PointerType *PT = T->getAs<PointerType>()) {
1810    // Find the innermost pointer type.
1811    while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
1812      PT = T;
1813
1814    if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
1815      return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
1816  }
1817
1818  const RecordType *RT = T->getAs<RecordType>();
1819  if (!RT)
1820    return false;
1821
1822  const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
1823  if (!RD)
1824    return false;
1825
1826  if (CurrentRD && CurrentRD != RD)
1827    return false;
1828
1829  if (!RD->isAbstract())
1830    return false;
1831
1832  Diag(Loc, PD) << RD->getDeclName();
1833
1834  // Check if we've already emitted the list of pure virtual functions for this
1835  // class.
1836  if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
1837    return true;
1838
1839  PureVirtualMethodCollector Collector(Context, RD);
1840
1841  for (PureVirtualMethodCollector::MethodList::const_iterator I =
1842       Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
1843    const CXXMethodDecl *MD = *I;
1844
1845    Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
1846      MD->getDeclName();
1847  }
1848
1849  if (!PureVirtualClassDiagSet)
1850    PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
1851  PureVirtualClassDiagSet->insert(RD);
1852
1853  return true;
1854}
1855
1856namespace {
1857  class VISIBILITY_HIDDEN AbstractClassUsageDiagnoser
1858    : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
1859    Sema &SemaRef;
1860    CXXRecordDecl *AbstractClass;
1861
1862    bool VisitDeclContext(const DeclContext *DC) {
1863      bool Invalid = false;
1864
1865      for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
1866           E = DC->decls_end(); I != E; ++I)
1867        Invalid |= Visit(*I);
1868
1869      return Invalid;
1870    }
1871
1872  public:
1873    AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
1874      : SemaRef(SemaRef), AbstractClass(ac) {
1875        Visit(SemaRef.Context.getTranslationUnitDecl());
1876    }
1877
1878    bool VisitFunctionDecl(const FunctionDecl *FD) {
1879      if (FD->isThisDeclarationADefinition()) {
1880        // No need to do the check if we're in a definition, because it requires
1881        // that the return/param types are complete.
1882        // because that requires
1883        return VisitDeclContext(FD);
1884      }
1885
1886      // Check the return type.
1887      QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
1888      bool Invalid =
1889        SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
1890                                       diag::err_abstract_type_in_decl,
1891                                       Sema::AbstractReturnType,
1892                                       AbstractClass);
1893
1894      for (FunctionDecl::param_const_iterator I = FD->param_begin(),
1895           E = FD->param_end(); I != E; ++I) {
1896        const ParmVarDecl *VD = *I;
1897        Invalid |=
1898          SemaRef.RequireNonAbstractType(VD->getLocation(),
1899                                         VD->getOriginalType(),
1900                                         diag::err_abstract_type_in_decl,
1901                                         Sema::AbstractParamType,
1902                                         AbstractClass);
1903      }
1904
1905      return Invalid;
1906    }
1907
1908    bool VisitDecl(const Decl* D) {
1909      if (const DeclContext *DC = dyn_cast<DeclContext>(D))
1910        return VisitDeclContext(DC);
1911
1912      return false;
1913    }
1914  };
1915}
1916
1917void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
1918                                             DeclPtrTy TagDecl,
1919                                             SourceLocation LBrac,
1920                                             SourceLocation RBrac) {
1921  if (!TagDecl)
1922    return;
1923
1924  AdjustDeclIfTemplate(TagDecl);
1925  ActOnFields(S, RLoc, TagDecl,
1926              (DeclPtrTy*)FieldCollector->getCurFields(),
1927              FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
1928
1929  CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>());
1930  if (!RD->isAbstract()) {
1931    // Collect all the pure virtual methods and see if this is an abstract
1932    // class after all.
1933    PureVirtualMethodCollector Collector(Context, RD);
1934    if (!Collector.empty())
1935      RD->setAbstract(true);
1936  }
1937
1938  if (RD->isAbstract())
1939    AbstractClassUsageDiagnoser(*this, RD);
1940
1941  if (!RD->isDependentType() && !RD->isInvalidDecl())
1942    AddImplicitlyDeclaredMembersToClass(RD);
1943}
1944
1945/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
1946/// special functions, such as the default constructor, copy
1947/// constructor, or destructor, to the given C++ class (C++
1948/// [special]p1).  This routine can only be executed just before the
1949/// definition of the class is complete.
1950void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
1951  CanQualType ClassType
1952    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
1953
1954  // FIXME: Implicit declarations have exception specifications, which are
1955  // the union of the specifications of the implicitly called functions.
1956
1957  if (!ClassDecl->hasUserDeclaredConstructor()) {
1958    // C++ [class.ctor]p5:
1959    //   A default constructor for a class X is a constructor of class X
1960    //   that can be called without an argument. If there is no
1961    //   user-declared constructor for class X, a default constructor is
1962    //   implicitly declared. An implicitly-declared default constructor
1963    //   is an inline public member of its class.
1964    DeclarationName Name
1965      = Context.DeclarationNames.getCXXConstructorName(ClassType);
1966    CXXConstructorDecl *DefaultCon =
1967      CXXConstructorDecl::Create(Context, ClassDecl,
1968                                 ClassDecl->getLocation(), Name,
1969                                 Context.getFunctionType(Context.VoidTy,
1970                                                         0, 0, false, 0),
1971                                 /*DInfo=*/0,
1972                                 /*isExplicit=*/false,
1973                                 /*isInline=*/true,
1974                                 /*isImplicitlyDeclared=*/true);
1975    DefaultCon->setAccess(AS_public);
1976    DefaultCon->setImplicit();
1977    DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
1978    ClassDecl->addDecl(DefaultCon);
1979  }
1980
1981  if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
1982    // C++ [class.copy]p4:
1983    //   If the class definition does not explicitly declare a copy
1984    //   constructor, one is declared implicitly.
1985
1986    // C++ [class.copy]p5:
1987    //   The implicitly-declared copy constructor for a class X will
1988    //   have the form
1989    //
1990    //       X::X(const X&)
1991    //
1992    //   if
1993    bool HasConstCopyConstructor = true;
1994
1995    //     -- each direct or virtual base class B of X has a copy
1996    //        constructor whose first parameter is of type const B& or
1997    //        const volatile B&, and
1998    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1999         HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2000      const CXXRecordDecl *BaseClassDecl
2001        = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2002      HasConstCopyConstructor
2003        = BaseClassDecl->hasConstCopyConstructor(Context);
2004    }
2005
2006    //     -- for all the nonstatic data members of X that are of a
2007    //        class type M (or array thereof), each such class type
2008    //        has a copy constructor whose first parameter is of type
2009    //        const M& or const volatile M&.
2010    for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2011         HasConstCopyConstructor && Field != ClassDecl->field_end();
2012         ++Field) {
2013      QualType FieldType = (*Field)->getType();
2014      if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2015        FieldType = Array->getElementType();
2016      if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
2017        const CXXRecordDecl *FieldClassDecl
2018          = cast<CXXRecordDecl>(FieldClassType->getDecl());
2019        HasConstCopyConstructor
2020          = FieldClassDecl->hasConstCopyConstructor(Context);
2021      }
2022    }
2023
2024    //   Otherwise, the implicitly declared copy constructor will have
2025    //   the form
2026    //
2027    //       X::X(X&)
2028    QualType ArgType = ClassType;
2029    if (HasConstCopyConstructor)
2030      ArgType = ArgType.withConst();
2031    ArgType = Context.getLValueReferenceType(ArgType);
2032
2033    //   An implicitly-declared copy constructor is an inline public
2034    //   member of its class.
2035    DeclarationName Name
2036      = Context.DeclarationNames.getCXXConstructorName(ClassType);
2037    CXXConstructorDecl *CopyConstructor
2038      = CXXConstructorDecl::Create(Context, ClassDecl,
2039                                   ClassDecl->getLocation(), Name,
2040                                   Context.getFunctionType(Context.VoidTy,
2041                                                           &ArgType, 1,
2042                                                           false, 0),
2043                                   /*DInfo=*/0,
2044                                   /*isExplicit=*/false,
2045                                   /*isInline=*/true,
2046                                   /*isImplicitlyDeclared=*/true);
2047    CopyConstructor->setAccess(AS_public);
2048    CopyConstructor->setImplicit();
2049    CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
2050
2051    // Add the parameter to the constructor.
2052    ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2053                                                 ClassDecl->getLocation(),
2054                                                 /*IdentifierInfo=*/0,
2055                                                 ArgType, /*DInfo=*/0,
2056                                                 VarDecl::None, 0);
2057    CopyConstructor->setParams(Context, &FromParam, 1);
2058    ClassDecl->addDecl(CopyConstructor);
2059  }
2060
2061  if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2062    // Note: The following rules are largely analoguous to the copy
2063    // constructor rules. Note that virtual bases are not taken into account
2064    // for determining the argument type of the operator. Note also that
2065    // operators taking an object instead of a reference are allowed.
2066    //
2067    // C++ [class.copy]p10:
2068    //   If the class definition does not explicitly declare a copy
2069    //   assignment operator, one is declared implicitly.
2070    //   The implicitly-defined copy assignment operator for a class X
2071    //   will have the form
2072    //
2073    //       X& X::operator=(const X&)
2074    //
2075    //   if
2076    bool HasConstCopyAssignment = true;
2077
2078    //       -- each direct base class B of X has a copy assignment operator
2079    //          whose parameter is of type const B&, const volatile B& or B,
2080    //          and
2081    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2082         HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
2083      assert(!Base->getType()->isDependentType() &&
2084            "Cannot generate implicit members for class with dependent bases.");
2085      const CXXRecordDecl *BaseClassDecl
2086        = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2087      const CXXMethodDecl *MD = 0;
2088      HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
2089                                                                     MD);
2090    }
2091
2092    //       -- for all the nonstatic data members of X that are of a class
2093    //          type M (or array thereof), each such class type has a copy
2094    //          assignment operator whose parameter is of type const M&,
2095    //          const volatile M& or M.
2096    for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2097         HasConstCopyAssignment && Field != ClassDecl->field_end();
2098         ++Field) {
2099      QualType FieldType = (*Field)->getType();
2100      if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2101        FieldType = Array->getElementType();
2102      if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
2103        const CXXRecordDecl *FieldClassDecl
2104          = cast<CXXRecordDecl>(FieldClassType->getDecl());
2105        const CXXMethodDecl *MD = 0;
2106        HasConstCopyAssignment
2107          = FieldClassDecl->hasConstCopyAssignment(Context, MD);
2108      }
2109    }
2110
2111    //   Otherwise, the implicitly declared copy assignment operator will
2112    //   have the form
2113    //
2114    //       X& X::operator=(X&)
2115    QualType ArgType = ClassType;
2116    QualType RetType = Context.getLValueReferenceType(ArgType);
2117    if (HasConstCopyAssignment)
2118      ArgType = ArgType.withConst();
2119    ArgType = Context.getLValueReferenceType(ArgType);
2120
2121    //   An implicitly-declared copy assignment operator is an inline public
2122    //   member of its class.
2123    DeclarationName Name =
2124      Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2125    CXXMethodDecl *CopyAssignment =
2126      CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2127                            Context.getFunctionType(RetType, &ArgType, 1,
2128                                                    false, 0),
2129                            /*DInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
2130    CopyAssignment->setAccess(AS_public);
2131    CopyAssignment->setImplicit();
2132    CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
2133    CopyAssignment->setCopyAssignment(true);
2134
2135    // Add the parameter to the operator.
2136    ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2137                                                 ClassDecl->getLocation(),
2138                                                 /*IdentifierInfo=*/0,
2139                                                 ArgType, /*DInfo=*/0,
2140                                                 VarDecl::None, 0);
2141    CopyAssignment->setParams(Context, &FromParam, 1);
2142
2143    // Don't call addedAssignmentOperator. There is no way to distinguish an
2144    // implicit from an explicit assignment operator.
2145    ClassDecl->addDecl(CopyAssignment);
2146  }
2147
2148  if (!ClassDecl->hasUserDeclaredDestructor()) {
2149    // C++ [class.dtor]p2:
2150    //   If a class has no user-declared destructor, a destructor is
2151    //   declared implicitly. An implicitly-declared destructor is an
2152    //   inline public member of its class.
2153    DeclarationName Name
2154      = Context.DeclarationNames.getCXXDestructorName(ClassType);
2155    CXXDestructorDecl *Destructor
2156      = CXXDestructorDecl::Create(Context, ClassDecl,
2157                                  ClassDecl->getLocation(), Name,
2158                                  Context.getFunctionType(Context.VoidTy,
2159                                                          0, 0, false, 0),
2160                                  /*isInline=*/true,
2161                                  /*isImplicitlyDeclared=*/true);
2162    Destructor->setAccess(AS_public);
2163    Destructor->setImplicit();
2164    Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
2165    ClassDecl->addDecl(Destructor);
2166  }
2167}
2168
2169void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
2170  Decl *D = TemplateD.getAs<Decl>();
2171  if (!D)
2172    return;
2173
2174  TemplateParameterList *Params = 0;
2175  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2176    Params = Template->getTemplateParameters();
2177  else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2178           = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2179    Params = PartialSpec->getTemplateParameters();
2180  else
2181    return;
2182
2183  for (TemplateParameterList::iterator Param = Params->begin(),
2184                                    ParamEnd = Params->end();
2185       Param != ParamEnd; ++Param) {
2186    NamedDecl *Named = cast<NamedDecl>(*Param);
2187    if (Named->getDeclName()) {
2188      S->AddDecl(DeclPtrTy::make(Named));
2189      IdResolver.AddDecl(Named);
2190    }
2191  }
2192}
2193
2194/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2195/// parsing a top-level (non-nested) C++ class, and we are now
2196/// parsing those parts of the given Method declaration that could
2197/// not be parsed earlier (C++ [class.mem]p2), such as default
2198/// arguments. This action should enter the scope of the given
2199/// Method declaration as if we had just parsed the qualified method
2200/// name. However, it should not bring the parameters into scope;
2201/// that will be performed by ActOnDelayedCXXMethodParameter.
2202void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
2203  if (!MethodD)
2204    return;
2205
2206  AdjustDeclIfTemplate(MethodD);
2207
2208  CXXScopeSpec SS;
2209  FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
2210  QualType ClassTy
2211    = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2212  SS.setScopeRep(
2213    NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
2214  ActOnCXXEnterDeclaratorScope(S, SS);
2215}
2216
2217/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2218/// C++ method declaration. We're (re-)introducing the given
2219/// function parameter into scope for use in parsing later parts of
2220/// the method declaration. For example, we could see an
2221/// ActOnParamDefaultArgument event for this parameter.
2222void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
2223  if (!ParamD)
2224    return;
2225
2226  ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
2227
2228  // If this parameter has an unparsed default argument, clear it out
2229  // to make way for the parsed default argument.
2230  if (Param->hasUnparsedDefaultArg())
2231    Param->setDefaultArg(0);
2232
2233  S->AddDecl(DeclPtrTy::make(Param));
2234  if (Param->getDeclName())
2235    IdResolver.AddDecl(Param);
2236}
2237
2238/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2239/// processing the delayed method declaration for Method. The method
2240/// declaration is now considered finished. There may be a separate
2241/// ActOnStartOfFunctionDef action later (not necessarily
2242/// immediately!) for this method, if it was also defined inside the
2243/// class body.
2244void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
2245  if (!MethodD)
2246    return;
2247
2248  AdjustDeclIfTemplate(MethodD);
2249
2250  FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
2251  CXXScopeSpec SS;
2252  QualType ClassTy
2253    = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2254  SS.setScopeRep(
2255    NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
2256  ActOnCXXExitDeclaratorScope(S, SS);
2257
2258  // Now that we have our default arguments, check the constructor
2259  // again. It could produce additional diagnostics or affect whether
2260  // the class has implicitly-declared destructors, among other
2261  // things.
2262  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2263    CheckConstructor(Constructor);
2264
2265  // Check the default arguments, which we may have added.
2266  if (!Method->isInvalidDecl())
2267    CheckCXXDefaultArguments(Method);
2268}
2269
2270/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
2271/// the well-formedness of the constructor declarator @p D with type @p
2272/// R. If there are any errors in the declarator, this routine will
2273/// emit diagnostics and set the invalid bit to true.  In any case, the type
2274/// will be updated to reflect a well-formed type for the constructor and
2275/// returned.
2276QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2277                                          FunctionDecl::StorageClass &SC) {
2278  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
2279
2280  // C++ [class.ctor]p3:
2281  //   A constructor shall not be virtual (10.3) or static (9.4). A
2282  //   constructor can be invoked for a const, volatile or const
2283  //   volatile object. A constructor shall not be declared const,
2284  //   volatile, or const volatile (9.3.2).
2285  if (isVirtual) {
2286    if (!D.isInvalidType())
2287      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2288        << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2289        << SourceRange(D.getIdentifierLoc());
2290    D.setInvalidType();
2291  }
2292  if (SC == FunctionDecl::Static) {
2293    if (!D.isInvalidType())
2294      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2295        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2296        << SourceRange(D.getIdentifierLoc());
2297    D.setInvalidType();
2298    SC = FunctionDecl::None;
2299  }
2300
2301  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2302  if (FTI.TypeQuals != 0) {
2303    if (FTI.TypeQuals & Qualifiers::Const)
2304      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2305        << "const" << SourceRange(D.getIdentifierLoc());
2306    if (FTI.TypeQuals & Qualifiers::Volatile)
2307      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2308        << "volatile" << SourceRange(D.getIdentifierLoc());
2309    if (FTI.TypeQuals & Qualifiers::Restrict)
2310      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2311        << "restrict" << SourceRange(D.getIdentifierLoc());
2312  }
2313
2314  // Rebuild the function type "R" without any type qualifiers (in
2315  // case any of the errors above fired) and with "void" as the
2316  // return type, since constructors don't have return types. We
2317  // *always* have to do this, because GetTypeForDeclarator will
2318  // put in a result type of "int" when none was specified.
2319  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
2320  return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2321                                 Proto->getNumArgs(),
2322                                 Proto->isVariadic(), 0);
2323}
2324
2325/// CheckConstructor - Checks a fully-formed constructor for
2326/// well-formedness, issuing any diagnostics required. Returns true if
2327/// the constructor declarator is invalid.
2328void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
2329  CXXRecordDecl *ClassDecl
2330    = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2331  if (!ClassDecl)
2332    return Constructor->setInvalidDecl();
2333
2334  // C++ [class.copy]p3:
2335  //   A declaration of a constructor for a class X is ill-formed if
2336  //   its first parameter is of type (optionally cv-qualified) X and
2337  //   either there are no other parameters or else all other
2338  //   parameters have default arguments.
2339  if (!Constructor->isInvalidDecl() &&
2340      ((Constructor->getNumParams() == 1) ||
2341       (Constructor->getNumParams() > 1 &&
2342        Constructor->getParamDecl(1)->hasDefaultArg())) &&
2343      Constructor->getTemplateSpecializationKind()
2344                                              != TSK_ImplicitInstantiation) {
2345    QualType ParamType = Constructor->getParamDecl(0)->getType();
2346    QualType ClassTy = Context.getTagDeclType(ClassDecl);
2347    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
2348      SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2349      Diag(ParamLoc, diag::err_constructor_byvalue_arg)
2350        << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
2351
2352      // FIXME: Rather that making the constructor invalid, we should endeavor
2353      // to fix the type.
2354      Constructor->setInvalidDecl();
2355    }
2356  }
2357
2358  // Notify the class that we've added a constructor.
2359  ClassDecl->addedConstructor(Context, Constructor);
2360}
2361
2362/// CheckDestructor - Checks a fully-formed destructor for
2363/// well-formedness, issuing any diagnostics required.
2364void Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
2365  CXXRecordDecl *RD = Destructor->getParent();
2366
2367  if (Destructor->isVirtual()) {
2368    SourceLocation Loc;
2369
2370    if (!Destructor->isImplicit())
2371      Loc = Destructor->getLocation();
2372    else
2373      Loc = RD->getLocation();
2374
2375    // If we have a virtual destructor, look up the deallocation function
2376    FunctionDecl *OperatorDelete = 0;
2377    DeclarationName Name =
2378    Context.DeclarationNames.getCXXOperatorName(OO_Delete);
2379    if (!FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2380      Destructor->setOperatorDelete(OperatorDelete);
2381  }
2382}
2383
2384static inline bool
2385FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2386  return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2387          FTI.ArgInfo[0].Param &&
2388          FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2389}
2390
2391/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2392/// the well-formednes of the destructor declarator @p D with type @p
2393/// R. If there are any errors in the declarator, this routine will
2394/// emit diagnostics and set the declarator to invalid.  Even if this happens,
2395/// will be updated to reflect a well-formed type for the destructor and
2396/// returned.
2397QualType Sema::CheckDestructorDeclarator(Declarator &D,
2398                                         FunctionDecl::StorageClass& SC) {
2399  // C++ [class.dtor]p1:
2400  //   [...] A typedef-name that names a class is a class-name
2401  //   (7.1.3); however, a typedef-name that names a class shall not
2402  //   be used as the identifier in the declarator for a destructor
2403  //   declaration.
2404  QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
2405  if (isa<TypedefType>(DeclaratorType)) {
2406    Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
2407      << DeclaratorType;
2408    D.setInvalidType();
2409  }
2410
2411  // C++ [class.dtor]p2:
2412  //   A destructor is used to destroy objects of its class type. A
2413  //   destructor takes no parameters, and no return type can be
2414  //   specified for it (not even void). The address of a destructor
2415  //   shall not be taken. A destructor shall not be static. A
2416  //   destructor can be invoked for a const, volatile or const
2417  //   volatile object. A destructor shall not be declared const,
2418  //   volatile or const volatile (9.3.2).
2419  if (SC == FunctionDecl::Static) {
2420    if (!D.isInvalidType())
2421      Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2422        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2423        << SourceRange(D.getIdentifierLoc());
2424    SC = FunctionDecl::None;
2425    D.setInvalidType();
2426  }
2427  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
2428    // Destructors don't have return types, but the parser will
2429    // happily parse something like:
2430    //
2431    //   class X {
2432    //     float ~X();
2433    //   };
2434    //
2435    // The return type will be eliminated later.
2436    Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2437      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2438      << SourceRange(D.getIdentifierLoc());
2439  }
2440
2441  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2442  if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
2443    if (FTI.TypeQuals & Qualifiers::Const)
2444      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2445        << "const" << SourceRange(D.getIdentifierLoc());
2446    if (FTI.TypeQuals & Qualifiers::Volatile)
2447      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2448        << "volatile" << SourceRange(D.getIdentifierLoc());
2449    if (FTI.TypeQuals & Qualifiers::Restrict)
2450      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2451        << "restrict" << SourceRange(D.getIdentifierLoc());
2452    D.setInvalidType();
2453  }
2454
2455  // Make sure we don't have any parameters.
2456  if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
2457    Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2458
2459    // Delete the parameters.
2460    FTI.freeArgs();
2461    D.setInvalidType();
2462  }
2463
2464  // Make sure the destructor isn't variadic.
2465  if (FTI.isVariadic) {
2466    Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
2467    D.setInvalidType();
2468  }
2469
2470  // Rebuild the function type "R" without any type qualifiers or
2471  // parameters (in case any of the errors above fired) and with
2472  // "void" as the return type, since destructors don't have return
2473  // types. We *always* have to do this, because GetTypeForDeclarator
2474  // will put in a result type of "int" when none was specified.
2475  return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
2476}
2477
2478/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2479/// well-formednes of the conversion function declarator @p D with
2480/// type @p R. If there are any errors in the declarator, this routine
2481/// will emit diagnostics and return true. Otherwise, it will return
2482/// false. Either way, the type @p R will be updated to reflect a
2483/// well-formed type for the conversion operator.
2484void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
2485                                     FunctionDecl::StorageClass& SC) {
2486  // C++ [class.conv.fct]p1:
2487  //   Neither parameter types nor return type can be specified. The
2488  //   type of a conversion function (8.3.5) is "function taking no
2489  //   parameter returning conversion-type-id."
2490  if (SC == FunctionDecl::Static) {
2491    if (!D.isInvalidType())
2492      Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2493        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2494        << SourceRange(D.getIdentifierLoc());
2495    D.setInvalidType();
2496    SC = FunctionDecl::None;
2497  }
2498  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
2499    // Conversion functions don't have return types, but the parser will
2500    // happily parse something like:
2501    //
2502    //   class X {
2503    //     float operator bool();
2504    //   };
2505    //
2506    // The return type will be changed later anyway.
2507    Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2508      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2509      << SourceRange(D.getIdentifierLoc());
2510  }
2511
2512  // Make sure we don't have any parameters.
2513  if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
2514    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2515
2516    // Delete the parameters.
2517    D.getTypeObject(0).Fun.freeArgs();
2518    D.setInvalidType();
2519  }
2520
2521  // Make sure the conversion function isn't variadic.
2522  if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
2523    Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
2524    D.setInvalidType();
2525  }
2526
2527  // C++ [class.conv.fct]p4:
2528  //   The conversion-type-id shall not represent a function type nor
2529  //   an array type.
2530  QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
2531  if (ConvType->isArrayType()) {
2532    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2533    ConvType = Context.getPointerType(ConvType);
2534    D.setInvalidType();
2535  } else if (ConvType->isFunctionType()) {
2536    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2537    ConvType = Context.getPointerType(ConvType);
2538    D.setInvalidType();
2539  }
2540
2541  // Rebuild the function type "R" without any parameters (in case any
2542  // of the errors above fired) and with the conversion type as the
2543  // return type.
2544  R = Context.getFunctionType(ConvType, 0, 0, false,
2545                              R->getAs<FunctionProtoType>()->getTypeQuals());
2546
2547  // C++0x explicit conversion operators.
2548  if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
2549    Diag(D.getDeclSpec().getExplicitSpecLoc(),
2550         diag::warn_explicit_conversion_functions)
2551      << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
2552}
2553
2554/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2555/// the declaration of the given C++ conversion function. This routine
2556/// is responsible for recording the conversion function in the C++
2557/// class, if possible.
2558Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
2559  assert(Conversion && "Expected to receive a conversion function declaration");
2560
2561  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
2562
2563  // Make sure we aren't redeclaring the conversion function.
2564  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
2565
2566  // C++ [class.conv.fct]p1:
2567  //   [...] A conversion function is never used to convert a
2568  //   (possibly cv-qualified) object to the (possibly cv-qualified)
2569  //   same object type (or a reference to it), to a (possibly
2570  //   cv-qualified) base class of that type (or a reference to it),
2571  //   or to (possibly cv-qualified) void.
2572  // FIXME: Suppress this warning if the conversion function ends up being a
2573  // virtual function that overrides a virtual function in a base class.
2574  QualType ClassType
2575    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
2576  if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
2577    ConvType = ConvTypeRef->getPointeeType();
2578  if (ConvType->isRecordType()) {
2579    ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2580    if (ConvType == ClassType)
2581      Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
2582        << ClassType;
2583    else if (IsDerivedFrom(ClassType, ConvType))
2584      Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
2585        <<  ClassType << ConvType;
2586  } else if (ConvType->isVoidType()) {
2587    Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
2588      << ClassType << ConvType;
2589  }
2590
2591  if (Conversion->getPreviousDeclaration()) {
2592    const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration();
2593    if (FunctionTemplateDecl *ConversionTemplate
2594          = Conversion->getDescribedFunctionTemplate())
2595      ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration();
2596    OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
2597    for (OverloadedFunctionDecl::function_iterator
2598           Conv = Conversions->function_begin(),
2599           ConvEnd = Conversions->function_end();
2600         Conv != ConvEnd; ++Conv) {
2601      if (*Conv == ExpectedPrevDecl) {
2602        *Conv = Conversion;
2603        return DeclPtrTy::make(Conversion);
2604      }
2605    }
2606    assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
2607  } else if (FunctionTemplateDecl *ConversionTemplate
2608               = Conversion->getDescribedFunctionTemplate())
2609    ClassDecl->addConversionFunction(ConversionTemplate);
2610  else if (!Conversion->getPrimaryTemplate()) // ignore specializations
2611    ClassDecl->addConversionFunction(Conversion);
2612
2613  return DeclPtrTy::make(Conversion);
2614}
2615
2616//===----------------------------------------------------------------------===//
2617// Namespace Handling
2618//===----------------------------------------------------------------------===//
2619
2620/// ActOnStartNamespaceDef - This is called at the start of a namespace
2621/// definition.
2622Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2623                                             SourceLocation IdentLoc,
2624                                             IdentifierInfo *II,
2625                                             SourceLocation LBrace) {
2626  NamespaceDecl *Namespc =
2627      NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2628  Namespc->setLBracLoc(LBrace);
2629
2630  Scope *DeclRegionScope = NamespcScope->getParent();
2631
2632  if (II) {
2633    // C++ [namespace.def]p2:
2634    // The identifier in an original-namespace-definition shall not have been
2635    // previously defined in the declarative region in which the
2636    // original-namespace-definition appears. The identifier in an
2637    // original-namespace-definition is the name of the namespace. Subsequently
2638    // in that declarative region, it is treated as an original-namespace-name.
2639
2640    NamedDecl *PrevDecl
2641      = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName,
2642                         LookupResult::ForRedeclaration);
2643
2644    if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2645      // This is an extended namespace definition.
2646      // Attach this namespace decl to the chain of extended namespace
2647      // definitions.
2648      OrigNS->setNextNamespace(Namespc);
2649      Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
2650
2651      // Remove the previous declaration from the scope.
2652      if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
2653        IdResolver.RemoveDecl(OrigNS);
2654        DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
2655      }
2656    } else if (PrevDecl) {
2657      // This is an invalid name redefinition.
2658      Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2659       << Namespc->getDeclName();
2660      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2661      Namespc->setInvalidDecl();
2662      // Continue on to push Namespc as current DeclContext and return it.
2663    } else if (II->isStr("std") &&
2664               CurContext->getLookupContext()->isTranslationUnit()) {
2665      // This is the first "real" definition of the namespace "std", so update
2666      // our cache of the "std" namespace to point at this definition.
2667      if (StdNamespace) {
2668        // We had already defined a dummy namespace "std". Link this new
2669        // namespace definition to the dummy namespace "std".
2670        StdNamespace->setNextNamespace(Namespc);
2671        StdNamespace->setLocation(IdentLoc);
2672        Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2673      }
2674
2675      // Make our StdNamespace cache point at the first real definition of the
2676      // "std" namespace.
2677      StdNamespace = Namespc;
2678    }
2679
2680    PushOnScopeChains(Namespc, DeclRegionScope);
2681  } else {
2682    // Anonymous namespaces.
2683
2684    // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
2685    //   behaves as if it were replaced by
2686    //     namespace unique { /* empty body */ }
2687    //     using namespace unique;
2688    //     namespace unique { namespace-body }
2689    //   where all occurrences of 'unique' in a translation unit are
2690    //   replaced by the same identifier and this identifier differs
2691    //   from all other identifiers in the entire program.
2692
2693    // We just create the namespace with an empty name and then add an
2694    // implicit using declaration, just like the standard suggests.
2695    //
2696    // CodeGen enforces the "universally unique" aspect by giving all
2697    // declarations semantically contained within an anonymous
2698    // namespace internal linkage.
2699
2700    assert(Namespc->isAnonymousNamespace());
2701    CurContext->addDecl(Namespc);
2702
2703    UsingDirectiveDecl* UD
2704      = UsingDirectiveDecl::Create(Context, CurContext,
2705                                   /* 'using' */ LBrace,
2706                                   /* 'namespace' */ SourceLocation(),
2707                                   /* qualifier */ SourceRange(),
2708                                   /* NNS */ NULL,
2709                                   /* identifier */ SourceLocation(),
2710                                   Namespc,
2711                                   /* Ancestor */ CurContext);
2712    UD->setImplicit();
2713    CurContext->addDecl(UD);
2714  }
2715
2716  // Although we could have an invalid decl (i.e. the namespace name is a
2717  // redefinition), push it as current DeclContext and try to continue parsing.
2718  // FIXME: We should be able to push Namespc here, so that the each DeclContext
2719  // for the namespace has the declarations that showed up in that particular
2720  // namespace definition.
2721  PushDeclContext(NamespcScope, Namespc);
2722  return DeclPtrTy::make(Namespc);
2723}
2724
2725/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2726/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
2727void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2728  Decl *Dcl = D.getAs<Decl>();
2729  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2730  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2731  Namespc->setRBracLoc(RBrace);
2732  PopDeclContext();
2733}
2734
2735Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2736                                          SourceLocation UsingLoc,
2737                                          SourceLocation NamespcLoc,
2738                                          const CXXScopeSpec &SS,
2739                                          SourceLocation IdentLoc,
2740                                          IdentifierInfo *NamespcName,
2741                                          AttributeList *AttrList) {
2742  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2743  assert(NamespcName && "Invalid NamespcName.");
2744  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
2745  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
2746
2747  UsingDirectiveDecl *UDir = 0;
2748
2749  // Lookup namespace name.
2750  LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
2751  LookupParsedName(R, S, &SS);
2752  if (R.isAmbiguous())
2753    return DeclPtrTy();
2754
2755  if (!R.empty()) {
2756    NamedDecl *NS = R.getFoundDecl();
2757    // FIXME: Namespace aliases!
2758    assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
2759    // C++ [namespace.udir]p1:
2760    //   A using-directive specifies that the names in the nominated
2761    //   namespace can be used in the scope in which the
2762    //   using-directive appears after the using-directive. During
2763    //   unqualified name lookup (3.4.1), the names appear as if they
2764    //   were declared in the nearest enclosing namespace which
2765    //   contains both the using-directive and the nominated
2766    //   namespace. [Note: in this context, "contains" means "contains
2767    //   directly or indirectly". ]
2768
2769    // Find enclosing context containing both using-directive and
2770    // nominated namespace.
2771    DeclContext *CommonAncestor = cast<DeclContext>(NS);
2772    while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2773      CommonAncestor = CommonAncestor->getParent();
2774
2775    UDir = UsingDirectiveDecl::Create(Context,
2776                                      CurContext, UsingLoc,
2777                                      NamespcLoc,
2778                                      SS.getRange(),
2779                                      (NestedNameSpecifier *)SS.getScopeRep(),
2780                                      IdentLoc,
2781                                      cast<NamespaceDecl>(NS),
2782                                      CommonAncestor);
2783    PushUsingDirective(S, UDir);
2784  } else {
2785    Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
2786  }
2787
2788  // FIXME: We ignore attributes for now.
2789  delete AttrList;
2790  return DeclPtrTy::make(UDir);
2791}
2792
2793void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
2794  // If scope has associated entity, then using directive is at namespace
2795  // or translation unit scope. We add UsingDirectiveDecls, into
2796  // it's lookup structure.
2797  if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
2798    Ctx->addDecl(UDir);
2799  else
2800    // Otherwise it is block-sope. using-directives will affect lookup
2801    // only to the end of scope.
2802    S->PushUsingDirective(DeclPtrTy::make(UDir));
2803}
2804
2805
2806Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
2807                                            AccessSpecifier AS,
2808                                            SourceLocation UsingLoc,
2809                                            const CXXScopeSpec &SS,
2810                                            UnqualifiedId &Name,
2811                                            AttributeList *AttrList,
2812                                            bool IsTypeName) {
2813  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
2814
2815  switch (Name.getKind()) {
2816  case UnqualifiedId::IK_Identifier:
2817  case UnqualifiedId::IK_OperatorFunctionId:
2818  case UnqualifiedId::IK_ConversionFunctionId:
2819    break;
2820
2821  case UnqualifiedId::IK_ConstructorName:
2822    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
2823      << SS.getRange();
2824    return DeclPtrTy();
2825
2826  case UnqualifiedId::IK_DestructorName:
2827    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
2828      << SS.getRange();
2829    return DeclPtrTy();
2830
2831  case UnqualifiedId::IK_TemplateId:
2832    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
2833      << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
2834    return DeclPtrTy();
2835  }
2836
2837  DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
2838  NamedDecl *UD = BuildUsingDeclaration(UsingLoc, SS,
2839                                        Name.getSourceRange().getBegin(),
2840                                        TargetName, AttrList, IsTypeName);
2841  if (UD) {
2842    PushOnScopeChains(UD, S);
2843    UD->setAccess(AS);
2844  }
2845
2846  return DeclPtrTy::make(UD);
2847}
2848
2849NamedDecl *Sema::BuildUsingDeclaration(SourceLocation UsingLoc,
2850                                       const CXXScopeSpec &SS,
2851                                       SourceLocation IdentLoc,
2852                                       DeclarationName Name,
2853                                       AttributeList *AttrList,
2854                                       bool IsTypeName) {
2855  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2856  assert(IdentLoc.isValid() && "Invalid TargetName location.");
2857
2858  // FIXME: We ignore attributes for now.
2859  delete AttrList;
2860
2861  if (SS.isEmpty()) {
2862    Diag(IdentLoc, diag::err_using_requires_qualname);
2863    return 0;
2864  }
2865
2866  NestedNameSpecifier *NNS =
2867    static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2868
2869  DeclContext *LookupContext = computeDeclContext(SS);
2870  if (!LookupContext) {
2871    return UnresolvedUsingDecl::Create(Context, CurContext, UsingLoc,
2872                                       SS.getRange(), NNS,
2873                                       IdentLoc, Name, IsTypeName);
2874  }
2875
2876  if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
2877    // C++0x N2914 [namespace.udecl]p3:
2878    // A using-declaration used as a member-declaration shall refer to a member
2879    // of a base class of the class being defined, shall refer to a member of an
2880    // anonymous union that is a member of a base class of the class being
2881    // defined, or shall refer to an enumerator for an enumeration type that is
2882    // a member of a base class of the class being defined.
2883
2884    CXXRecordDecl *LookupRD = dyn_cast<CXXRecordDecl>(LookupContext);
2885    if (!LookupRD || !RD->isDerivedFrom(LookupRD)) {
2886      Diag(SS.getRange().getBegin(),
2887           diag::err_using_decl_nested_name_specifier_is_not_a_base_class)
2888        << NNS << RD->getDeclName();
2889      return 0;
2890    }
2891  } else {
2892    // C++0x N2914 [namespace.udecl]p8:
2893    // A using-declaration for a class member shall be a member-declaration.
2894    if (isa<CXXRecordDecl>(LookupContext)) {
2895      Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_class_member)
2896        << SS.getRange();
2897      return 0;
2898    }
2899  }
2900
2901  // Lookup target name.
2902  LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
2903  LookupQualifiedName(R, LookupContext);
2904
2905  if (R.empty()) {
2906    Diag(IdentLoc, diag::err_no_member)
2907      << Name << LookupContext << SS.getRange();
2908    return 0;
2909  }
2910
2911  // FIXME: handle ambiguity?
2912  NamedDecl *ND = R.getAsSingleDecl(Context);
2913
2914  if (IsTypeName && !isa<TypeDecl>(ND)) {
2915    Diag(IdentLoc, diag::err_using_typename_non_type);
2916    return 0;
2917  }
2918
2919  // C++0x N2914 [namespace.udecl]p6:
2920  // A using-declaration shall not name a namespace.
2921  if (isa<NamespaceDecl>(ND)) {
2922    Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
2923      << SS.getRange();
2924    return 0;
2925  }
2926
2927  return UsingDecl::Create(Context, CurContext, IdentLoc, SS.getRange(),
2928                           ND->getLocation(), UsingLoc, ND, NNS, IsTypeName);
2929}
2930
2931/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2932/// is a namespace alias, returns the namespace it points to.
2933static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2934  if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2935    return AD->getNamespace();
2936  return dyn_cast_or_null<NamespaceDecl>(D);
2937}
2938
2939Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
2940                                             SourceLocation NamespaceLoc,
2941                                             SourceLocation AliasLoc,
2942                                             IdentifierInfo *Alias,
2943                                             const CXXScopeSpec &SS,
2944                                             SourceLocation IdentLoc,
2945                                             IdentifierInfo *Ident) {
2946
2947  // Lookup the namespace name.
2948  LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
2949  LookupParsedName(R, S, &SS);
2950
2951  // Check if we have a previous declaration with the same name.
2952  if (NamedDecl *PrevDecl
2953        = LookupSingleName(S, Alias, LookupOrdinaryName,
2954                           LookupResult::ForRedeclaration)) {
2955    if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
2956      // We already have an alias with the same name that points to the same
2957      // namespace, so don't create a new one.
2958      if (!R.isAmbiguous() && !R.empty() &&
2959          AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
2960        return DeclPtrTy();
2961    }
2962
2963    unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
2964      diag::err_redefinition_different_kind;
2965    Diag(AliasLoc, DiagID) << Alias;
2966    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2967    return DeclPtrTy();
2968  }
2969
2970  if (R.isAmbiguous())
2971    return DeclPtrTy();
2972
2973  if (R.empty()) {
2974    Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
2975    return DeclPtrTy();
2976  }
2977
2978  NamespaceAliasDecl *AliasDecl =
2979    NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
2980                               Alias, SS.getRange(),
2981                               (NestedNameSpecifier *)SS.getScopeRep(),
2982                               IdentLoc, R.getFoundDecl());
2983
2984  CurContext->addDecl(AliasDecl);
2985  return DeclPtrTy::make(AliasDecl);
2986}
2987
2988void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
2989                                            CXXConstructorDecl *Constructor) {
2990  assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
2991          !Constructor->isUsed()) &&
2992    "DefineImplicitDefaultConstructor - call it for implicit default ctor");
2993
2994  CXXRecordDecl *ClassDecl
2995    = cast<CXXRecordDecl>(Constructor->getDeclContext());
2996  assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
2997
2998  if (SetBaseOrMemberInitializers(Constructor, 0, 0, true)) {
2999    Diag(CurrentLocation, diag::note_ctor_synthesized_at)
3000      << Context.getTagDeclType(ClassDecl);
3001    Constructor->setInvalidDecl();
3002  } else {
3003    Constructor->setUsed();
3004  }
3005  return;
3006}
3007
3008void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
3009                                    CXXDestructorDecl *Destructor) {
3010  assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
3011         "DefineImplicitDestructor - call it for implicit default dtor");
3012  CXXRecordDecl *ClassDecl = Destructor->getParent();
3013  assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
3014  // C++ [class.dtor] p5
3015  // Before the implicitly-declared default destructor for a class is
3016  // implicitly defined, all the implicitly-declared default destructors
3017  // for its base class and its non-static data members shall have been
3018  // implicitly defined.
3019  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3020       E = ClassDecl->bases_end(); Base != E; ++Base) {
3021    CXXRecordDecl *BaseClassDecl
3022      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3023    if (!BaseClassDecl->hasTrivialDestructor()) {
3024      if (CXXDestructorDecl *BaseDtor =
3025          const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3026        MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3027      else
3028        assert(false &&
3029               "DefineImplicitDestructor - missing dtor in a base class");
3030    }
3031  }
3032
3033  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3034       E = ClassDecl->field_end(); Field != E; ++Field) {
3035    QualType FieldType = Context.getCanonicalType((*Field)->getType());
3036    if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3037      FieldType = Array->getElementType();
3038    if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
3039      CXXRecordDecl *FieldClassDecl
3040        = cast<CXXRecordDecl>(FieldClassType->getDecl());
3041      if (!FieldClassDecl->hasTrivialDestructor()) {
3042        if (CXXDestructorDecl *FieldDtor =
3043            const_cast<CXXDestructorDecl*>(
3044                                        FieldClassDecl->getDestructor(Context)))
3045          MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3046        else
3047          assert(false &&
3048          "DefineImplicitDestructor - missing dtor in class of a data member");
3049      }
3050    }
3051  }
3052  Destructor->setUsed();
3053}
3054
3055void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3056                                          CXXMethodDecl *MethodDecl) {
3057  assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3058          MethodDecl->getOverloadedOperator() == OO_Equal &&
3059          !MethodDecl->isUsed()) &&
3060         "DefineImplicitOverloadedAssign - call it for implicit assignment op");
3061
3062  CXXRecordDecl *ClassDecl
3063    = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
3064
3065  // C++[class.copy] p12
3066  // Before the implicitly-declared copy assignment operator for a class is
3067  // implicitly defined, all implicitly-declared copy assignment operators
3068  // for its direct base classes and its nonstatic data members shall have
3069  // been implicitly defined.
3070  bool err = false;
3071  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3072       E = ClassDecl->bases_end(); Base != E; ++Base) {
3073    CXXRecordDecl *BaseClassDecl
3074      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3075    if (CXXMethodDecl *BaseAssignOpMethod =
3076          getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl))
3077      MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3078  }
3079  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3080       E = ClassDecl->field_end(); Field != E; ++Field) {
3081    QualType FieldType = Context.getCanonicalType((*Field)->getType());
3082    if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3083      FieldType = Array->getElementType();
3084    if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
3085      CXXRecordDecl *FieldClassDecl
3086        = cast<CXXRecordDecl>(FieldClassType->getDecl());
3087      if (CXXMethodDecl *FieldAssignOpMethod =
3088          getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl))
3089        MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
3090    } else if (FieldType->isReferenceType()) {
3091      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
3092      << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3093      Diag(Field->getLocation(), diag::note_declared_at);
3094      Diag(CurrentLocation, diag::note_first_required_here);
3095      err = true;
3096    } else if (FieldType.isConstQualified()) {
3097      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
3098      << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3099      Diag(Field->getLocation(), diag::note_declared_at);
3100      Diag(CurrentLocation, diag::note_first_required_here);
3101      err = true;
3102    }
3103  }
3104  if (!err)
3105    MethodDecl->setUsed();
3106}
3107
3108CXXMethodDecl *
3109Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl,
3110                              CXXRecordDecl *ClassDecl) {
3111  QualType LHSType = Context.getTypeDeclType(ClassDecl);
3112  QualType RHSType(LHSType);
3113  // If class's assignment operator argument is const/volatile qualified,
3114  // look for operator = (const/volatile B&). Otherwise, look for
3115  // operator = (B&).
3116  RHSType = Context.getCVRQualifiedType(RHSType,
3117                                     ParmDecl->getType().getCVRQualifiers());
3118  ExprOwningPtr<Expr> LHS(this,  new (Context) DeclRefExpr(ParmDecl,
3119                                                          LHSType,
3120                                                          SourceLocation()));
3121  ExprOwningPtr<Expr> RHS(this,  new (Context) DeclRefExpr(ParmDecl,
3122                                                          RHSType,
3123                                                          SourceLocation()));
3124  Expr *Args[2] = { &*LHS, &*RHS };
3125  OverloadCandidateSet CandidateSet;
3126  AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
3127                              CandidateSet);
3128  OverloadCandidateSet::iterator Best;
3129  if (BestViableFunction(CandidateSet,
3130                         ClassDecl->getLocation(), Best) == OR_Success)
3131    return cast<CXXMethodDecl>(Best->Function);
3132  assert(false &&
3133         "getAssignOperatorMethod - copy assignment operator method not found");
3134  return 0;
3135}
3136
3137void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3138                                   CXXConstructorDecl *CopyConstructor,
3139                                   unsigned TypeQuals) {
3140  assert((CopyConstructor->isImplicit() &&
3141          CopyConstructor->isCopyConstructor(Context, TypeQuals) &&
3142          !CopyConstructor->isUsed()) &&
3143         "DefineImplicitCopyConstructor - call it for implicit copy ctor");
3144
3145  CXXRecordDecl *ClassDecl
3146    = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3147  assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
3148  // C++ [class.copy] p209
3149  // Before the implicitly-declared copy constructor for a class is
3150  // implicitly defined, all the implicitly-declared copy constructors
3151  // for its base class and its non-static data members shall have been
3152  // implicitly defined.
3153  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3154       Base != ClassDecl->bases_end(); ++Base) {
3155    CXXRecordDecl *BaseClassDecl
3156      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3157    if (CXXConstructorDecl *BaseCopyCtor =
3158        BaseClassDecl->getCopyConstructor(Context, TypeQuals))
3159      MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
3160  }
3161  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3162                                  FieldEnd = ClassDecl->field_end();
3163       Field != FieldEnd; ++Field) {
3164    QualType FieldType = Context.getCanonicalType((*Field)->getType());
3165    if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3166      FieldType = Array->getElementType();
3167    if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
3168      CXXRecordDecl *FieldClassDecl
3169        = cast<CXXRecordDecl>(FieldClassType->getDecl());
3170      if (CXXConstructorDecl *FieldCopyCtor =
3171          FieldClassDecl->getCopyConstructor(Context, TypeQuals))
3172        MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
3173    }
3174  }
3175  CopyConstructor->setUsed();
3176}
3177
3178Sema::OwningExprResult
3179Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3180                            CXXConstructorDecl *Constructor,
3181                            MultiExprArg ExprArgs) {
3182  bool Elidable = false;
3183
3184  // C++ [class.copy]p15:
3185  //   Whenever a temporary class object is copied using a copy constructor, and
3186  //   this object and the copy have the same cv-unqualified type, an
3187  //   implementation is permitted to treat the original and the copy as two
3188  //   different ways of referring to the same object and not perform a copy at
3189  //   all, even if the class copy constructor or destructor have side effects.
3190
3191  // FIXME: Is this enough?
3192  if (Constructor->isCopyConstructor(Context)) {
3193    Expr *E = ((Expr **)ExprArgs.get())[0];
3194    while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3195      E = BE->getSubExpr();
3196    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3197      if (ICE->getCastKind() == CastExpr::CK_NoOp)
3198        E = ICE->getSubExpr();
3199
3200    if (isa<CallExpr>(E) || isa<CXXTemporaryObjectExpr>(E))
3201      Elidable = true;
3202  }
3203
3204  return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
3205                               Elidable, move(ExprArgs));
3206}
3207
3208/// BuildCXXConstructExpr - Creates a complete call to a constructor,
3209/// including handling of its default argument expressions.
3210Sema::OwningExprResult
3211Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3212                            CXXConstructorDecl *Constructor, bool Elidable,
3213                            MultiExprArg ExprArgs) {
3214  unsigned NumExprs = ExprArgs.size();
3215  Expr **Exprs = (Expr **)ExprArgs.release();
3216
3217  return Owned(CXXConstructExpr::Create(Context, DeclInitType, Constructor,
3218                                        Elidable, Exprs, NumExprs));
3219}
3220
3221Sema::OwningExprResult
3222Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor,
3223                                  QualType Ty,
3224                                  SourceLocation TyBeginLoc,
3225                                  MultiExprArg Args,
3226                                  SourceLocation RParenLoc) {
3227  unsigned NumExprs = Args.size();
3228  Expr **Exprs = (Expr **)Args.release();
3229
3230  return Owned(new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty,
3231                                                    TyBeginLoc, Exprs,
3232                                                    NumExprs, RParenLoc));
3233}
3234
3235
3236bool Sema::InitializeVarWithConstructor(VarDecl *VD,
3237                                        CXXConstructorDecl *Constructor,
3238                                        MultiExprArg Exprs) {
3239  OwningExprResult TempResult =
3240    BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
3241                          move(Exprs));
3242  if (TempResult.isInvalid())
3243    return true;
3244
3245  Expr *Temp = TempResult.takeAs<Expr>();
3246  MarkDeclarationReferenced(VD->getLocation(), Constructor);
3247  Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true);
3248  VD->setInit(Context, Temp);
3249
3250  return false;
3251}
3252
3253void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) {
3254  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
3255                                  DeclInitType->getAs<RecordType>()->getDecl());
3256  if (!ClassDecl->hasTrivialDestructor())
3257    if (CXXDestructorDecl *Destructor =
3258        const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
3259      MarkDeclarationReferenced(VD->getLocation(), Destructor);
3260}
3261
3262/// AddCXXDirectInitializerToDecl - This action is called immediately after
3263/// ActOnDeclarator, when a C++ direct initializer is present.
3264/// e.g: "int x(1);"
3265void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
3266                                         SourceLocation LParenLoc,
3267                                         MultiExprArg Exprs,
3268                                         SourceLocation *CommaLocs,
3269                                         SourceLocation RParenLoc) {
3270  unsigned NumExprs = Exprs.size();
3271  assert(NumExprs != 0 && Exprs.get() && "missing expressions");
3272  Decl *RealDecl = Dcl.getAs<Decl>();
3273
3274  // If there is no declaration, there was an error parsing it.  Just ignore
3275  // the initializer.
3276  if (RealDecl == 0)
3277    return;
3278
3279  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3280  if (!VDecl) {
3281    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3282    RealDecl->setInvalidDecl();
3283    return;
3284  }
3285
3286  // We will represent direct-initialization similarly to copy-initialization:
3287  //    int x(1);  -as-> int x = 1;
3288  //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
3289  //
3290  // Clients that want to distinguish between the two forms, can check for
3291  // direct initializer using VarDecl::hasCXXDirectInitializer().
3292  // A major benefit is that clients that don't particularly care about which
3293  // exactly form was it (like the CodeGen) can handle both cases without
3294  // special case code.
3295
3296  // If either the declaration has a dependent type or if any of the expressions
3297  // is type-dependent, we represent the initialization via a ParenListExpr for
3298  // later use during template instantiation.
3299  if (VDecl->getType()->isDependentType() ||
3300      Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
3301    // Let clients know that initialization was done with a direct initializer.
3302    VDecl->setCXXDirectInitializer(true);
3303
3304    // Store the initialization expressions as a ParenListExpr.
3305    unsigned NumExprs = Exprs.size();
3306    VDecl->setInit(Context,
3307                   new (Context) ParenListExpr(Context, LParenLoc,
3308                                               (Expr **)Exprs.release(),
3309                                               NumExprs, RParenLoc));
3310    return;
3311  }
3312
3313
3314  // C++ 8.5p11:
3315  // The form of initialization (using parentheses or '=') is generally
3316  // insignificant, but does matter when the entity being initialized has a
3317  // class type.
3318  QualType DeclInitType = VDecl->getType();
3319  if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
3320    DeclInitType = Context.getBaseElementType(Array);
3321
3322  // FIXME: This isn't the right place to complete the type.
3323  if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
3324                          diag::err_typecheck_decl_incomplete_type)) {
3325    VDecl->setInvalidDecl();
3326    return;
3327  }
3328
3329  if (VDecl->getType()->isRecordType()) {
3330    ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
3331
3332    CXXConstructorDecl *Constructor
3333      = PerformInitializationByConstructor(DeclInitType,
3334                                           move(Exprs),
3335                                           VDecl->getLocation(),
3336                                           SourceRange(VDecl->getLocation(),
3337                                                       RParenLoc),
3338                                           VDecl->getDeclName(),
3339                                           IK_Direct,
3340                                           ConstructorArgs);
3341    if (!Constructor)
3342      RealDecl->setInvalidDecl();
3343    else {
3344      VDecl->setCXXDirectInitializer(true);
3345      if (InitializeVarWithConstructor(VDecl, Constructor,
3346                                       move_arg(ConstructorArgs)))
3347        RealDecl->setInvalidDecl();
3348      FinalizeVarWithDestructor(VDecl, DeclInitType);
3349    }
3350    return;
3351  }
3352
3353  if (NumExprs > 1) {
3354    Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
3355      << SourceRange(VDecl->getLocation(), RParenLoc);
3356    RealDecl->setInvalidDecl();
3357    return;
3358  }
3359
3360  // Let clients know that initialization was done with a direct initializer.
3361  VDecl->setCXXDirectInitializer(true);
3362
3363  assert(NumExprs == 1 && "Expected 1 expression");
3364  // Set the init expression, handles conversions.
3365  AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
3366                       /*DirectInit=*/true);
3367}
3368
3369/// \brief Add the applicable constructor candidates for an initialization
3370/// by constructor.
3371static void AddConstructorInitializationCandidates(Sema &SemaRef,
3372                                                   QualType ClassType,
3373                                                   Expr **Args,
3374                                                   unsigned NumArgs,
3375                                                  Sema::InitializationKind Kind,
3376                                           OverloadCandidateSet &CandidateSet) {
3377  // C++ [dcl.init]p14:
3378  //   If the initialization is direct-initialization, or if it is
3379  //   copy-initialization where the cv-unqualified version of the
3380  //   source type is the same class as, or a derived class of, the
3381  //   class of the destination, constructors are considered. The
3382  //   applicable constructors are enumerated (13.3.1.3), and the
3383  //   best one is chosen through overload resolution (13.3). The
3384  //   constructor so selected is called to initialize the object,
3385  //   with the initializer expression(s) as its argument(s). If no
3386  //   constructor applies, or the overload resolution is ambiguous,
3387  //   the initialization is ill-formed.
3388  const RecordType *ClassRec = ClassType->getAs<RecordType>();
3389  assert(ClassRec && "Can only initialize a class type here");
3390
3391  // FIXME: When we decide not to synthesize the implicitly-declared
3392  // constructors, we'll need to make them appear here.
3393
3394  const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
3395  DeclarationName ConstructorName
3396    = SemaRef.Context.DeclarationNames.getCXXConstructorName(
3397              SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType());
3398  DeclContext::lookup_const_iterator Con, ConEnd;
3399  for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
3400       Con != ConEnd; ++Con) {
3401    // Find the constructor (which may be a template).
3402    CXXConstructorDecl *Constructor = 0;
3403    FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
3404    if (ConstructorTmpl)
3405      Constructor
3406      = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3407    else
3408      Constructor = cast<CXXConstructorDecl>(*Con);
3409
3410    if ((Kind == Sema::IK_Direct) ||
3411        (Kind == Sema::IK_Copy &&
3412         Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
3413        (Kind == Sema::IK_Default && Constructor->isDefaultConstructor())) {
3414      if (ConstructorTmpl)
3415        SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0,
3416                                             Args, NumArgs, CandidateSet);
3417      else
3418        SemaRef.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
3419    }
3420  }
3421}
3422
3423/// \brief Attempt to perform initialization by constructor
3424/// (C++ [dcl.init]p14), which may occur as part of direct-initialization or
3425/// copy-initialization.
3426///
3427/// This routine determines whether initialization by constructor is possible,
3428/// but it does not emit any diagnostics in the case where the initialization
3429/// is ill-formed.
3430///
3431/// \param ClassType the type of the object being initialized, which must have
3432/// class type.
3433///
3434/// \param Args the arguments provided to initialize the object
3435///
3436/// \param NumArgs the number of arguments provided to initialize the object
3437///
3438/// \param Kind the type of initialization being performed
3439///
3440/// \returns the constructor used to initialize the object, if successful.
3441/// Otherwise, emits a diagnostic and returns NULL.
3442CXXConstructorDecl *
3443Sema::TryInitializationByConstructor(QualType ClassType,
3444                                     Expr **Args, unsigned NumArgs,
3445                                     SourceLocation Loc,
3446                                     InitializationKind Kind) {
3447  // Build the overload candidate set
3448  OverloadCandidateSet CandidateSet;
3449  AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
3450                                         CandidateSet);
3451
3452  // Determine whether we found a constructor we can use.
3453  OverloadCandidateSet::iterator Best;
3454  switch (BestViableFunction(CandidateSet, Loc, Best)) {
3455    case OR_Success:
3456    case OR_Deleted:
3457      // We found a constructor. Return it.
3458      return cast<CXXConstructorDecl>(Best->Function);
3459
3460    case OR_No_Viable_Function:
3461    case OR_Ambiguous:
3462      // Overload resolution failed. Return nothing.
3463      return 0;
3464  }
3465
3466  // Silence GCC warning
3467  return 0;
3468}
3469
3470/// \brief Perform initialization by constructor (C++ [dcl.init]p14), which
3471/// may occur as part of direct-initialization or copy-initialization.
3472///
3473/// \param ClassType the type of the object being initialized, which must have
3474/// class type.
3475///
3476/// \param ArgsPtr the arguments provided to initialize the object
3477///
3478/// \param Loc the source location where the initialization occurs
3479///
3480/// \param Range the source range that covers the entire initialization
3481///
3482/// \param InitEntity the name of the entity being initialized, if known
3483///
3484/// \param Kind the type of initialization being performed
3485///
3486/// \param ConvertedArgs a vector that will be filled in with the
3487/// appropriately-converted arguments to the constructor (if initialization
3488/// succeeded).
3489///
3490/// \returns the constructor used to initialize the object, if successful.
3491/// Otherwise, emits a diagnostic and returns NULL.
3492CXXConstructorDecl *
3493Sema::PerformInitializationByConstructor(QualType ClassType,
3494                                         MultiExprArg ArgsPtr,
3495                                         SourceLocation Loc, SourceRange Range,
3496                                         DeclarationName InitEntity,
3497                                         InitializationKind Kind,
3498                      ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
3499
3500  // Build the overload candidate set
3501  Expr **Args = (Expr **)ArgsPtr.get();
3502  unsigned NumArgs = ArgsPtr.size();
3503  OverloadCandidateSet CandidateSet;
3504  AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
3505                                         CandidateSet);
3506
3507  OverloadCandidateSet::iterator Best;
3508  switch (BestViableFunction(CandidateSet, Loc, Best)) {
3509  case OR_Success:
3510    // We found a constructor. Break out so that we can convert the arguments
3511    // appropriately.
3512    break;
3513
3514  case OR_No_Viable_Function:
3515    if (InitEntity)
3516      Diag(Loc, diag::err_ovl_no_viable_function_in_init)
3517        << InitEntity << Range;
3518    else
3519      Diag(Loc, diag::err_ovl_no_viable_function_in_init)
3520        << ClassType << Range;
3521    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3522    return 0;
3523
3524  case OR_Ambiguous:
3525    if (InitEntity)
3526      Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
3527    else
3528      Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
3529    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3530    return 0;
3531
3532  case OR_Deleted:
3533    if (InitEntity)
3534      Diag(Loc, diag::err_ovl_deleted_init)
3535        << Best->Function->isDeleted()
3536        << InitEntity << Range;
3537    else
3538      Diag(Loc, diag::err_ovl_deleted_init)
3539        << Best->Function->isDeleted()
3540        << InitEntity << Range;
3541    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3542    return 0;
3543  }
3544
3545  // Convert the arguments, fill in default arguments, etc.
3546  CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3547  if (CompleteConstructorCall(Constructor, move(ArgsPtr), Loc, ConvertedArgs))
3548    return 0;
3549
3550  return Constructor;
3551}
3552
3553/// \brief Given a constructor and the set of arguments provided for the
3554/// constructor, convert the arguments and add any required default arguments
3555/// to form a proper call to this constructor.
3556///
3557/// \returns true if an error occurred, false otherwise.
3558bool
3559Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
3560                              MultiExprArg ArgsPtr,
3561                              SourceLocation Loc,
3562                     ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
3563  // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
3564  unsigned NumArgs = ArgsPtr.size();
3565  Expr **Args = (Expr **)ArgsPtr.get();
3566
3567  const FunctionProtoType *Proto
3568    = Constructor->getType()->getAs<FunctionProtoType>();
3569  assert(Proto && "Constructor without a prototype?");
3570  unsigned NumArgsInProto = Proto->getNumArgs();
3571  unsigned NumArgsToCheck = NumArgs;
3572
3573  // If too few arguments are available, we'll fill in the rest with defaults.
3574  if (NumArgs < NumArgsInProto) {
3575    NumArgsToCheck = NumArgsInProto;
3576    ConvertedArgs.reserve(NumArgsInProto);
3577  } else {
3578    ConvertedArgs.reserve(NumArgs);
3579    if (NumArgs > NumArgsInProto)
3580      NumArgsToCheck = NumArgsInProto;
3581  }
3582
3583  // Convert arguments
3584  for (unsigned i = 0; i != NumArgsToCheck; i++) {
3585    QualType ProtoArgType = Proto->getArgType(i);
3586
3587    Expr *Arg;
3588    if (i < NumArgs) {
3589      Arg = Args[i];
3590
3591      // Pass the argument.
3592      if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3593        return true;
3594
3595      Args[i] = 0;
3596    } else {
3597      ParmVarDecl *Param = Constructor->getParamDecl(i);
3598
3599      OwningExprResult DefArg = BuildCXXDefaultArgExpr(Loc, Constructor, Param);
3600      if (DefArg.isInvalid())
3601        return true;
3602
3603      Arg = DefArg.takeAs<Expr>();
3604    }
3605
3606    ConvertedArgs.push_back(Arg);
3607  }
3608
3609  // If this is a variadic call, handle args passed through "...".
3610  if (Proto->isVariadic()) {
3611    // Promote the arguments (C99 6.5.2.2p7).
3612    for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
3613      Expr *Arg = Args[i];
3614      if (DefaultVariadicArgumentPromotion(Arg, VariadicConstructor))
3615        return true;
3616
3617      ConvertedArgs.push_back(Arg);
3618      Args[i] = 0;
3619    }
3620  }
3621
3622  return false;
3623}
3624
3625/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3626/// determine whether they are reference-related,
3627/// reference-compatible, reference-compatible with added
3628/// qualification, or incompatible, for use in C++ initialization by
3629/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3630/// type, and the first type (T1) is the pointee type of the reference
3631/// type being initialized.
3632Sema::ReferenceCompareResult
3633Sema::CompareReferenceRelationship(SourceLocation Loc,
3634                                   QualType OrigT1, QualType OrigT2,
3635                                   bool& DerivedToBase) {
3636  assert(!OrigT1->isReferenceType() &&
3637    "T1 must be the pointee type of the reference type");
3638  assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3639
3640  QualType T1 = Context.getCanonicalType(OrigT1);
3641  QualType T2 = Context.getCanonicalType(OrigT2);
3642  QualType UnqualT1 = T1.getLocalUnqualifiedType();
3643  QualType UnqualT2 = T2.getLocalUnqualifiedType();
3644
3645  // C++ [dcl.init.ref]p4:
3646  //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3647  //   reference-related to "cv2 T2" if T1 is the same type as T2, or
3648  //   T1 is a base class of T2.
3649  if (UnqualT1 == UnqualT2)
3650    DerivedToBase = false;
3651  else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
3652           !RequireCompleteType(Loc, OrigT2, PDiag()) &&
3653           IsDerivedFrom(UnqualT2, UnqualT1))
3654    DerivedToBase = true;
3655  else
3656    return Ref_Incompatible;
3657
3658  // At this point, we know that T1 and T2 are reference-related (at
3659  // least).
3660
3661  // C++ [dcl.init.ref]p4:
3662  //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3663  //   reference-related to T2 and cv1 is the same cv-qualification
3664  //   as, or greater cv-qualification than, cv2. For purposes of
3665  //   overload resolution, cases for which cv1 is greater
3666  //   cv-qualification than cv2 are identified as
3667  //   reference-compatible with added qualification (see 13.3.3.2).
3668  if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3669    return Ref_Compatible;
3670  else if (T1.isMoreQualifiedThan(T2))
3671    return Ref_Compatible_With_Added_Qualification;
3672  else
3673    return Ref_Related;
3674}
3675
3676/// CheckReferenceInit - Check the initialization of a reference
3677/// variable with the given initializer (C++ [dcl.init.ref]). Init is
3678/// the initializer (either a simple initializer or an initializer
3679/// list), and DeclType is the type of the declaration. When ICS is
3680/// non-null, this routine will compute the implicit conversion
3681/// sequence according to C++ [over.ics.ref] and will not produce any
3682/// diagnostics; when ICS is null, it will emit diagnostics when any
3683/// errors are found. Either way, a return value of true indicates
3684/// that there was a failure, a return value of false indicates that
3685/// the reference initialization succeeded.
3686///
3687/// When @p SuppressUserConversions, user-defined conversions are
3688/// suppressed.
3689/// When @p AllowExplicit, we also permit explicit user-defined
3690/// conversion functions.
3691/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
3692/// When @p IgnoreBaseAccess, we don't do access control on to-base conversion.
3693/// This is used when this is called from a C-style cast.
3694bool
3695Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
3696                         SourceLocation DeclLoc,
3697                         bool SuppressUserConversions,
3698                         bool AllowExplicit, bool ForceRValue,
3699                         ImplicitConversionSequence *ICS,
3700                         bool IgnoreBaseAccess) {
3701  assert(DeclType->isReferenceType() && "Reference init needs a reference");
3702
3703  QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3704  QualType T2 = Init->getType();
3705
3706  // If the initializer is the address of an overloaded function, try
3707  // to resolve the overloaded function. If all goes well, T2 is the
3708  // type of the resulting function.
3709  if (Context.getCanonicalType(T2) == Context.OverloadTy) {
3710    FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
3711                                                          ICS != 0);
3712    if (Fn) {
3713      // Since we're performing this reference-initialization for
3714      // real, update the initializer with the resulting function.
3715      if (!ICS) {
3716        if (DiagnoseUseOfDecl(Fn, DeclLoc))
3717          return true;
3718
3719        Init = FixOverloadedFunctionReference(Init, Fn);
3720      }
3721
3722      T2 = Fn->getType();
3723    }
3724  }
3725
3726  // Compute some basic properties of the types and the initializer.
3727  bool isRValRef = DeclType->isRValueReferenceType();
3728  bool DerivedToBase = false;
3729  Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
3730                                                  Init->isLvalue(Context);
3731  ReferenceCompareResult RefRelationship
3732    = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
3733
3734  // Most paths end in a failed conversion.
3735  if (ICS)
3736    ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
3737
3738  // C++ [dcl.init.ref]p5:
3739  //   A reference to type "cv1 T1" is initialized by an expression
3740  //   of type "cv2 T2" as follows:
3741
3742  //     -- If the initializer expression
3743
3744  // Rvalue references cannot bind to lvalues (N2812).
3745  // There is absolutely no situation where they can. In particular, note that
3746  // this is ill-formed, even if B has a user-defined conversion to A&&:
3747  //   B b;
3748  //   A&& r = b;
3749  if (isRValRef && InitLvalue == Expr::LV_Valid) {
3750    if (!ICS)
3751      Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
3752        << Init->getSourceRange();
3753    return true;
3754  }
3755
3756  bool BindsDirectly = false;
3757  //       -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3758  //          reference-compatible with "cv2 T2," or
3759  //
3760  // Note that the bit-field check is skipped if we are just computing
3761  // the implicit conversion sequence (C++ [over.best.ics]p2).
3762  if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
3763      RefRelationship >= Ref_Compatible_With_Added_Qualification) {
3764    BindsDirectly = true;
3765
3766    if (ICS) {
3767      // C++ [over.ics.ref]p1:
3768      //   When a parameter of reference type binds directly (8.5.3)
3769      //   to an argument expression, the implicit conversion sequence
3770      //   is the identity conversion, unless the argument expression
3771      //   has a type that is a derived class of the parameter type,
3772      //   in which case the implicit conversion sequence is a
3773      //   derived-to-base Conversion (13.3.3.1).
3774      ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3775      ICS->Standard.First = ICK_Identity;
3776      ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3777      ICS->Standard.Third = ICK_Identity;
3778      ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3779      ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
3780      ICS->Standard.ReferenceBinding = true;
3781      ICS->Standard.DirectBinding = true;
3782      ICS->Standard.RRefBinding = false;
3783      ICS->Standard.CopyConstructor = 0;
3784
3785      // Nothing more to do: the inaccessibility/ambiguity check for
3786      // derived-to-base conversions is suppressed when we're
3787      // computing the implicit conversion sequence (C++
3788      // [over.best.ics]p2).
3789      return false;
3790    } else {
3791      // Perform the conversion.
3792      CastExpr::CastKind CK = CastExpr::CK_NoOp;
3793      if (DerivedToBase)
3794        CK = CastExpr::CK_DerivedToBase;
3795      else if(CheckExceptionSpecCompatibility(Init, T1))
3796        return true;
3797      ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
3798    }
3799  }
3800
3801  //       -- has a class type (i.e., T2 is a class type) and can be
3802  //          implicitly converted to an lvalue of type "cv3 T3,"
3803  //          where "cv1 T1" is reference-compatible with "cv3 T3"
3804  //          92) (this conversion is selected by enumerating the
3805  //          applicable conversion functions (13.3.1.6) and choosing
3806  //          the best one through overload resolution (13.3)),
3807  if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
3808      !RequireCompleteType(DeclLoc, T2, 0)) {
3809    CXXRecordDecl *T2RecordDecl
3810      = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3811
3812    OverloadCandidateSet CandidateSet;
3813    OverloadedFunctionDecl *Conversions
3814      = T2RecordDecl->getVisibleConversionFunctions();
3815    for (OverloadedFunctionDecl::function_iterator Func
3816           = Conversions->function_begin();
3817         Func != Conversions->function_end(); ++Func) {
3818      FunctionTemplateDecl *ConvTemplate
3819        = dyn_cast<FunctionTemplateDecl>(*Func);
3820      CXXConversionDecl *Conv;
3821      if (ConvTemplate)
3822        Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3823      else
3824        Conv = cast<CXXConversionDecl>(*Func);
3825
3826      // If the conversion function doesn't return a reference type,
3827      // it can't be considered for this conversion.
3828      if (Conv->getConversionType()->isLValueReferenceType() &&
3829          (AllowExplicit || !Conv->isExplicit())) {
3830        if (ConvTemplate)
3831          AddTemplateConversionCandidate(ConvTemplate, Init, DeclType,
3832                                         CandidateSet);
3833        else
3834          AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
3835      }
3836    }
3837
3838    OverloadCandidateSet::iterator Best;
3839    switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
3840    case OR_Success:
3841      // This is a direct binding.
3842      BindsDirectly = true;
3843
3844      if (ICS) {
3845        // C++ [over.ics.ref]p1:
3846        //
3847        //   [...] If the parameter binds directly to the result of
3848        //   applying a conversion function to the argument
3849        //   expression, the implicit conversion sequence is a
3850        //   user-defined conversion sequence (13.3.3.1.2), with the
3851        //   second standard conversion sequence either an identity
3852        //   conversion or, if the conversion function returns an
3853        //   entity of a type that is a derived class of the parameter
3854        //   type, a derived-to-base Conversion.
3855        ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
3856        ICS->UserDefined.Before = Best->Conversions[0].Standard;
3857        ICS->UserDefined.After = Best->FinalConversion;
3858        ICS->UserDefined.ConversionFunction = Best->Function;
3859        ICS->UserDefined.EllipsisConversion = false;
3860        assert(ICS->UserDefined.After.ReferenceBinding &&
3861               ICS->UserDefined.After.DirectBinding &&
3862               "Expected a direct reference binding!");
3863        return false;
3864      } else {
3865        OwningExprResult InitConversion =
3866          BuildCXXCastArgument(DeclLoc, QualType(),
3867                               CastExpr::CK_UserDefinedConversion,
3868                               cast<CXXMethodDecl>(Best->Function),
3869                               Owned(Init));
3870        Init = InitConversion.takeAs<Expr>();
3871
3872        if (CheckExceptionSpecCompatibility(Init, T1))
3873          return true;
3874        ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
3875                          /*isLvalue=*/true);
3876      }
3877      break;
3878
3879    case OR_Ambiguous:
3880      if (ICS) {
3881        for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3882             Cand != CandidateSet.end(); ++Cand)
3883          if (Cand->Viable)
3884            ICS->ConversionFunctionSet.push_back(Cand->Function);
3885        break;
3886      }
3887      Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
3888            << Init->getSourceRange();
3889      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3890      return true;
3891
3892    case OR_No_Viable_Function:
3893    case OR_Deleted:
3894      // There was no suitable conversion, or we found a deleted
3895      // conversion; continue with other checks.
3896      break;
3897    }
3898  }
3899
3900  if (BindsDirectly) {
3901    // C++ [dcl.init.ref]p4:
3902    //   [...] In all cases where the reference-related or
3903    //   reference-compatible relationship of two types is used to
3904    //   establish the validity of a reference binding, and T1 is a
3905    //   base class of T2, a program that necessitates such a binding
3906    //   is ill-formed if T1 is an inaccessible (clause 11) or
3907    //   ambiguous (10.2) base class of T2.
3908    //
3909    // Note that we only check this condition when we're allowed to
3910    // complain about errors, because we should not be checking for
3911    // ambiguity (or inaccessibility) unless the reference binding
3912    // actually happens.
3913    if (DerivedToBase)
3914      return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
3915                                          Init->getSourceRange(),
3916                                          IgnoreBaseAccess);
3917    else
3918      return false;
3919  }
3920
3921  //     -- Otherwise, the reference shall be to a non-volatile const
3922  //        type (i.e., cv1 shall be const), or the reference shall be an
3923  //        rvalue reference and the initializer expression shall be an rvalue.
3924  if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
3925    if (!ICS)
3926      Diag(DeclLoc, diag::err_not_reference_to_const_init)
3927        << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3928        << T2 << Init->getSourceRange();
3929    return true;
3930  }
3931
3932  //       -- If the initializer expression is an rvalue, with T2 a
3933  //          class type, and "cv1 T1" is reference-compatible with
3934  //          "cv2 T2," the reference is bound in one of the
3935  //          following ways (the choice is implementation-defined):
3936  //
3937  //          -- The reference is bound to the object represented by
3938  //             the rvalue (see 3.10) or to a sub-object within that
3939  //             object.
3940  //
3941  //          -- A temporary of type "cv1 T2" [sic] is created, and
3942  //             a constructor is called to copy the entire rvalue
3943  //             object into the temporary. The reference is bound to
3944  //             the temporary or to a sub-object within the
3945  //             temporary.
3946  //
3947  //          The constructor that would be used to make the copy
3948  //          shall be callable whether or not the copy is actually
3949  //          done.
3950  //
3951  // Note that C++0x [dcl.init.ref]p5 takes away this implementation
3952  // freedom, so we will always take the first option and never build
3953  // a temporary in this case. FIXME: We will, however, have to check
3954  // for the presence of a copy constructor in C++98/03 mode.
3955  if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
3956      RefRelationship >= Ref_Compatible_With_Added_Qualification) {
3957    if (ICS) {
3958      ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3959      ICS->Standard.First = ICK_Identity;
3960      ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3961      ICS->Standard.Third = ICK_Identity;
3962      ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3963      ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
3964      ICS->Standard.ReferenceBinding = true;
3965      ICS->Standard.DirectBinding = false;
3966      ICS->Standard.RRefBinding = isRValRef;
3967      ICS->Standard.CopyConstructor = 0;
3968    } else {
3969      CastExpr::CastKind CK = CastExpr::CK_NoOp;
3970      if (DerivedToBase)
3971        CK = CastExpr::CK_DerivedToBase;
3972      else if(CheckExceptionSpecCompatibility(Init, T1))
3973        return true;
3974      ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
3975    }
3976    return false;
3977  }
3978
3979  //       -- Otherwise, a temporary of type "cv1 T1" is created and
3980  //          initialized from the initializer expression using the
3981  //          rules for a non-reference copy initialization (8.5). The
3982  //          reference is then bound to the temporary. If T1 is
3983  //          reference-related to T2, cv1 must be the same
3984  //          cv-qualification as, or greater cv-qualification than,
3985  //          cv2; otherwise, the program is ill-formed.
3986  if (RefRelationship == Ref_Related) {
3987    // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3988    // we would be reference-compatible or reference-compatible with
3989    // added qualification. But that wasn't the case, so the reference
3990    // initialization fails.
3991    if (!ICS)
3992      Diag(DeclLoc, diag::err_reference_init_drops_quals)
3993        << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3994        << T2 << Init->getSourceRange();
3995    return true;
3996  }
3997
3998  // If at least one of the types is a class type, the types are not
3999  // related, and we aren't allowed any user conversions, the
4000  // reference binding fails. This case is important for breaking
4001  // recursion, since TryImplicitConversion below will attempt to
4002  // create a temporary through the use of a copy constructor.
4003  if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
4004      (T1->isRecordType() || T2->isRecordType())) {
4005    if (!ICS)
4006      Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
4007        << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
4008    return true;
4009  }
4010
4011  // Actually try to convert the initializer to T1.
4012  if (ICS) {
4013    // C++ [over.ics.ref]p2:
4014    //
4015    //   When a parameter of reference type is not bound directly to
4016    //   an argument expression, the conversion sequence is the one
4017    //   required to convert the argument expression to the
4018    //   underlying type of the reference according to
4019    //   13.3.3.1. Conceptually, this conversion sequence corresponds
4020    //   to copy-initializing a temporary of the underlying type with
4021    //   the argument expression. Any difference in top-level
4022    //   cv-qualification is subsumed by the initialization itself
4023    //   and does not constitute a conversion.
4024    *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
4025                                 /*AllowExplicit=*/false,
4026                                 /*ForceRValue=*/false,
4027                                 /*InOverloadResolution=*/false);
4028
4029    // Of course, that's still a reference binding.
4030    if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
4031      ICS->Standard.ReferenceBinding = true;
4032      ICS->Standard.RRefBinding = isRValRef;
4033    } else if (ICS->ConversionKind ==
4034              ImplicitConversionSequence::UserDefinedConversion) {
4035      ICS->UserDefined.After.ReferenceBinding = true;
4036      ICS->UserDefined.After.RRefBinding = isRValRef;
4037    }
4038    return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
4039  } else {
4040    ImplicitConversionSequence Conversions;
4041    bool badConversion = PerformImplicitConversion(Init, T1, "initializing",
4042                                                   false, false,
4043                                                   Conversions);
4044    if (badConversion) {
4045      if ((Conversions.ConversionKind  ==
4046            ImplicitConversionSequence::BadConversion)
4047          && !Conversions.ConversionFunctionSet.empty()) {
4048        Diag(DeclLoc,
4049             diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
4050        for (int j = Conversions.ConversionFunctionSet.size()-1;
4051             j >= 0; j--) {
4052          FunctionDecl *Func = Conversions.ConversionFunctionSet[j];
4053          Diag(Func->getLocation(), diag::err_ovl_candidate);
4054        }
4055      }
4056      else {
4057        if (isRValRef)
4058          Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4059            << Init->getSourceRange();
4060        else
4061          Diag(DeclLoc, diag::err_invalid_initialization)
4062            << DeclType << Init->getType() << Init->getSourceRange();
4063      }
4064    }
4065    return badConversion;
4066  }
4067}
4068
4069/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4070/// of this overloaded operator is well-formed. If so, returns false;
4071/// otherwise, emits appropriate diagnostics and returns true.
4072bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
4073  assert(FnDecl && FnDecl->isOverloadedOperator() &&
4074         "Expected an overloaded operator declaration");
4075
4076  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4077
4078  // C++ [over.oper]p5:
4079  //   The allocation and deallocation functions, operator new,
4080  //   operator new[], operator delete and operator delete[], are
4081  //   described completely in 3.7.3. The attributes and restrictions
4082  //   found in the rest of this subclause do not apply to them unless
4083  //   explicitly stated in 3.7.3.
4084  // FIXME: Write a separate routine for checking this. For now, just allow it.
4085  if (Op == OO_Delete || Op == OO_Array_Delete)
4086    return false;
4087
4088  if (Op == OO_New || Op == OO_Array_New) {
4089    bool ret = false;
4090    if (FunctionDecl::param_iterator Param = FnDecl->param_begin()) {
4091      QualType SizeTy = Context.getCanonicalType(Context.getSizeType());
4092      QualType T = Context.getCanonicalType((*Param)->getType());
4093      if (!T->isDependentType() && SizeTy != T) {
4094        Diag(FnDecl->getLocation(),
4095             diag::err_operator_new_param_type) << FnDecl->getDeclName()
4096              << SizeTy;
4097        ret = true;
4098      }
4099    }
4100    QualType ResultTy = Context.getCanonicalType(FnDecl->getResultType());
4101    if (!ResultTy->isDependentType() && ResultTy != Context.VoidPtrTy)
4102      return Diag(FnDecl->getLocation(),
4103                  diag::err_operator_new_result_type) << FnDecl->getDeclName()
4104                  << static_cast<QualType>(Context.VoidPtrTy);
4105    return ret;
4106  }
4107
4108  // C++ [over.oper]p6:
4109  //   An operator function shall either be a non-static member
4110  //   function or be a non-member function and have at least one
4111  //   parameter whose type is a class, a reference to a class, an
4112  //   enumeration, or a reference to an enumeration.
4113  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4114    if (MethodDecl->isStatic())
4115      return Diag(FnDecl->getLocation(),
4116                  diag::err_operator_overload_static) << FnDecl->getDeclName();
4117  } else {
4118    bool ClassOrEnumParam = false;
4119    for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4120                                   ParamEnd = FnDecl->param_end();
4121         Param != ParamEnd; ++Param) {
4122      QualType ParamType = (*Param)->getType().getNonReferenceType();
4123      if (ParamType->isDependentType() || ParamType->isRecordType() ||
4124          ParamType->isEnumeralType()) {
4125        ClassOrEnumParam = true;
4126        break;
4127      }
4128    }
4129
4130    if (!ClassOrEnumParam)
4131      return Diag(FnDecl->getLocation(),
4132                  diag::err_operator_overload_needs_class_or_enum)
4133        << FnDecl->getDeclName();
4134  }
4135
4136  // C++ [over.oper]p8:
4137  //   An operator function cannot have default arguments (8.3.6),
4138  //   except where explicitly stated below.
4139  //
4140  // Only the function-call operator allows default arguments
4141  // (C++ [over.call]p1).
4142  if (Op != OO_Call) {
4143    for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4144         Param != FnDecl->param_end(); ++Param) {
4145      if ((*Param)->hasUnparsedDefaultArg())
4146        return Diag((*Param)->getLocation(),
4147                    diag::err_operator_overload_default_arg)
4148          << FnDecl->getDeclName();
4149      else if (Expr *DefArg = (*Param)->getDefaultArg())
4150        return Diag((*Param)->getLocation(),
4151                    diag::err_operator_overload_default_arg)
4152          << FnDecl->getDeclName() << DefArg->getSourceRange();
4153    }
4154  }
4155
4156  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4157    { false, false, false }
4158#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4159    , { Unary, Binary, MemberOnly }
4160#include "clang/Basic/OperatorKinds.def"
4161  };
4162
4163  bool CanBeUnaryOperator = OperatorUses[Op][0];
4164  bool CanBeBinaryOperator = OperatorUses[Op][1];
4165  bool MustBeMemberOperator = OperatorUses[Op][2];
4166
4167  // C++ [over.oper]p8:
4168  //   [...] Operator functions cannot have more or fewer parameters
4169  //   than the number required for the corresponding operator, as
4170  //   described in the rest of this subclause.
4171  unsigned NumParams = FnDecl->getNumParams()
4172                     + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
4173  if (Op != OO_Call &&
4174      ((NumParams == 1 && !CanBeUnaryOperator) ||
4175       (NumParams == 2 && !CanBeBinaryOperator) ||
4176       (NumParams < 1) || (NumParams > 2))) {
4177    // We have the wrong number of parameters.
4178    unsigned ErrorKind;
4179    if (CanBeUnaryOperator && CanBeBinaryOperator) {
4180      ErrorKind = 2;  // 2 -> unary or binary.
4181    } else if (CanBeUnaryOperator) {
4182      ErrorKind = 0;  // 0 -> unary
4183    } else {
4184      assert(CanBeBinaryOperator &&
4185             "All non-call overloaded operators are unary or binary!");
4186      ErrorKind = 1;  // 1 -> binary
4187    }
4188
4189    return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
4190      << FnDecl->getDeclName() << NumParams << ErrorKind;
4191  }
4192
4193  // Overloaded operators other than operator() cannot be variadic.
4194  if (Op != OO_Call &&
4195      FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
4196    return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
4197      << FnDecl->getDeclName();
4198  }
4199
4200  // Some operators must be non-static member functions.
4201  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4202    return Diag(FnDecl->getLocation(),
4203                diag::err_operator_overload_must_be_member)
4204      << FnDecl->getDeclName();
4205  }
4206
4207  // C++ [over.inc]p1:
4208  //   The user-defined function called operator++ implements the
4209  //   prefix and postfix ++ operator. If this function is a member
4210  //   function with no parameters, or a non-member function with one
4211  //   parameter of class or enumeration type, it defines the prefix
4212  //   increment operator ++ for objects of that type. If the function
4213  //   is a member function with one parameter (which shall be of type
4214  //   int) or a non-member function with two parameters (the second
4215  //   of which shall be of type int), it defines the postfix
4216  //   increment operator ++ for objects of that type.
4217  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
4218    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
4219    bool ParamIsInt = false;
4220    if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
4221      ParamIsInt = BT->getKind() == BuiltinType::Int;
4222
4223    if (!ParamIsInt)
4224      return Diag(LastParam->getLocation(),
4225                  diag::err_operator_overload_post_incdec_must_be_int)
4226        << LastParam->getType() << (Op == OO_MinusMinus);
4227  }
4228
4229  // Notify the class if it got an assignment operator.
4230  if (Op == OO_Equal) {
4231    // Would have returned earlier otherwise.
4232    assert(isa<CXXMethodDecl>(FnDecl) &&
4233      "Overloaded = not member, but not filtered.");
4234    CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
4235    Method->getParent()->addedAssignmentOperator(Context, Method);
4236  }
4237
4238  return false;
4239}
4240
4241/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
4242/// linkage specification, including the language and (if present)
4243/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
4244/// the location of the language string literal, which is provided
4245/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
4246/// the '{' brace. Otherwise, this linkage specification does not
4247/// have any braces.
4248Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
4249                                                     SourceLocation ExternLoc,
4250                                                     SourceLocation LangLoc,
4251                                                     const char *Lang,
4252                                                     unsigned StrSize,
4253                                                     SourceLocation LBraceLoc) {
4254  LinkageSpecDecl::LanguageIDs Language;
4255  if (strncmp(Lang, "\"C\"", StrSize) == 0)
4256    Language = LinkageSpecDecl::lang_c;
4257  else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
4258    Language = LinkageSpecDecl::lang_cxx;
4259  else {
4260    Diag(LangLoc, diag::err_bad_language);
4261    return DeclPtrTy();
4262  }
4263
4264  // FIXME: Add all the various semantics of linkage specifications
4265
4266  LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
4267                                               LangLoc, Language,
4268                                               LBraceLoc.isValid());
4269  CurContext->addDecl(D);
4270  PushDeclContext(S, D);
4271  return DeclPtrTy::make(D);
4272}
4273
4274/// ActOnFinishLinkageSpecification - Completely the definition of
4275/// the C++ linkage specification LinkageSpec. If RBraceLoc is
4276/// valid, it's the position of the closing '}' brace in a linkage
4277/// specification that uses braces.
4278Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
4279                                                      DeclPtrTy LinkageSpec,
4280                                                      SourceLocation RBraceLoc) {
4281  if (LinkageSpec)
4282    PopDeclContext();
4283  return LinkageSpec;
4284}
4285
4286/// \brief Perform semantic analysis for the variable declaration that
4287/// occurs within a C++ catch clause, returning the newly-created
4288/// variable.
4289VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
4290                                         DeclaratorInfo *DInfo,
4291                                         IdentifierInfo *Name,
4292                                         SourceLocation Loc,
4293                                         SourceRange Range) {
4294  bool Invalid = false;
4295
4296  // Arrays and functions decay.
4297  if (ExDeclType->isArrayType())
4298    ExDeclType = Context.getArrayDecayedType(ExDeclType);
4299  else if (ExDeclType->isFunctionType())
4300    ExDeclType = Context.getPointerType(ExDeclType);
4301
4302  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
4303  // The exception-declaration shall not denote a pointer or reference to an
4304  // incomplete type, other than [cv] void*.
4305  // N2844 forbids rvalue references.
4306  if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
4307    Diag(Loc, diag::err_catch_rvalue_ref) << Range;
4308    Invalid = true;
4309  }
4310
4311  QualType BaseType = ExDeclType;
4312  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
4313  unsigned DK = diag::err_catch_incomplete;
4314  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
4315    BaseType = Ptr->getPointeeType();
4316    Mode = 1;
4317    DK = diag::err_catch_incomplete_ptr;
4318  } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
4319    // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
4320    BaseType = Ref->getPointeeType();
4321    Mode = 2;
4322    DK = diag::err_catch_incomplete_ref;
4323  }
4324  if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
4325      !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
4326    Invalid = true;
4327
4328  if (!Invalid && !ExDeclType->isDependentType() &&
4329      RequireNonAbstractType(Loc, ExDeclType,
4330                             diag::err_abstract_type_in_decl,
4331                             AbstractVariableType))
4332    Invalid = true;
4333
4334  // FIXME: Need to test for ability to copy-construct and destroy the
4335  // exception variable.
4336
4337  // FIXME: Need to check for abstract classes.
4338
4339  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
4340                                    Name, ExDeclType, DInfo, VarDecl::None);
4341
4342  if (Invalid)
4343    ExDecl->setInvalidDecl();
4344
4345  return ExDecl;
4346}
4347
4348/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
4349/// handler.
4350Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
4351  DeclaratorInfo *DInfo = 0;
4352  QualType ExDeclType = GetTypeForDeclarator(D, S, &DInfo);
4353
4354  bool Invalid = D.isInvalidType();
4355  IdentifierInfo *II = D.getIdentifier();
4356  if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
4357    // The scope should be freshly made just for us. There is just no way
4358    // it contains any previous declaration.
4359    assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
4360    if (PrevDecl->isTemplateParameter()) {
4361      // Maybe we will complain about the shadowed template parameter.
4362      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
4363    }
4364  }
4365
4366  if (D.getCXXScopeSpec().isSet() && !Invalid) {
4367    Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
4368      << D.getCXXScopeSpec().getRange();
4369    Invalid = true;
4370  }
4371
4372  VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, DInfo,
4373                                              D.getIdentifier(),
4374                                              D.getIdentifierLoc(),
4375                                            D.getDeclSpec().getSourceRange());
4376
4377  if (Invalid)
4378    ExDecl->setInvalidDecl();
4379
4380  // Add the exception declaration into this scope.
4381  if (II)
4382    PushOnScopeChains(ExDecl, S);
4383  else
4384    CurContext->addDecl(ExDecl);
4385
4386  ProcessDeclAttributes(S, ExDecl, D);
4387  return DeclPtrTy::make(ExDecl);
4388}
4389
4390Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
4391                                                   ExprArg assertexpr,
4392                                                   ExprArg assertmessageexpr) {
4393  Expr *AssertExpr = (Expr *)assertexpr.get();
4394  StringLiteral *AssertMessage =
4395    cast<StringLiteral>((Expr *)assertmessageexpr.get());
4396
4397  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
4398    llvm::APSInt Value(32);
4399    if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
4400      Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
4401        AssertExpr->getSourceRange();
4402      return DeclPtrTy();
4403    }
4404
4405    if (Value == 0) {
4406      std::string str(AssertMessage->getStrData(),
4407                      AssertMessage->getByteLength());
4408      Diag(AssertLoc, diag::err_static_assert_failed)
4409        << str << AssertExpr->getSourceRange();
4410    }
4411  }
4412
4413  assertexpr.release();
4414  assertmessageexpr.release();
4415  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
4416                                        AssertExpr, AssertMessage);
4417
4418  CurContext->addDecl(Decl);
4419  return DeclPtrTy::make(Decl);
4420}
4421
4422/// Handle a friend type declaration.  This works in tandem with
4423/// ActOnTag.
4424///
4425/// Notes on friend class templates:
4426///
4427/// We generally treat friend class declarations as if they were
4428/// declaring a class.  So, for example, the elaborated type specifier
4429/// in a friend declaration is required to obey the restrictions of a
4430/// class-head (i.e. no typedefs in the scope chain), template
4431/// parameters are required to match up with simple template-ids, &c.
4432/// However, unlike when declaring a template specialization, it's
4433/// okay to refer to a template specialization without an empty
4434/// template parameter declaration, e.g.
4435///   friend class A<T>::B<unsigned>;
4436/// We permit this as a special case; if there are any template
4437/// parameters present at all, require proper matching, i.e.
4438///   template <> template <class T> friend class A<int>::B;
4439Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
4440                                          MultiTemplateParamsArg TempParams) {
4441  SourceLocation Loc = DS.getSourceRange().getBegin();
4442
4443  assert(DS.isFriendSpecified());
4444  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4445
4446  // Try to convert the decl specifier to a type.  This works for
4447  // friend templates because ActOnTag never produces a ClassTemplateDecl
4448  // for a TUK_Friend.
4449  Declarator TheDeclarator(DS, Declarator::MemberContext);
4450  QualType T = GetTypeForDeclarator(TheDeclarator, S);
4451  if (TheDeclarator.isInvalidType())
4452    return DeclPtrTy();
4453
4454  // This is definitely an error in C++98.  It's probably meant to
4455  // be forbidden in C++0x, too, but the specification is just
4456  // poorly written.
4457  //
4458  // The problem is with declarations like the following:
4459  //   template <T> friend A<T>::foo;
4460  // where deciding whether a class C is a friend or not now hinges
4461  // on whether there exists an instantiation of A that causes
4462  // 'foo' to equal C.  There are restrictions on class-heads
4463  // (which we declare (by fiat) elaborated friend declarations to
4464  // be) that makes this tractable.
4465  //
4466  // FIXME: handle "template <> friend class A<T>;", which
4467  // is possibly well-formed?  Who even knows?
4468  if (TempParams.size() && !isa<ElaboratedType>(T)) {
4469    Diag(Loc, diag::err_tagless_friend_type_template)
4470      << DS.getSourceRange();
4471    return DeclPtrTy();
4472  }
4473
4474  // C++ [class.friend]p2:
4475  //   An elaborated-type-specifier shall be used in a friend declaration
4476  //   for a class.*
4477  //   * The class-key of the elaborated-type-specifier is required.
4478  // This is one of the rare places in Clang where it's legitimate to
4479  // ask about the "spelling" of the type.
4480  if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
4481    // If we evaluated the type to a record type, suggest putting
4482    // a tag in front.
4483    if (const RecordType *RT = T->getAs<RecordType>()) {
4484      RecordDecl *RD = RT->getDecl();
4485
4486      std::string InsertionText = std::string(" ") + RD->getKindName();
4487
4488      Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
4489        << (unsigned) RD->getTagKind()
4490        << T
4491        << SourceRange(DS.getFriendSpecLoc())
4492        << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
4493                                                 InsertionText);
4494      return DeclPtrTy();
4495    }else {
4496      Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
4497          << DS.getSourceRange();
4498      return DeclPtrTy();
4499    }
4500  }
4501
4502  // Enum types cannot be friends.
4503  if (T->getAs<EnumType>()) {
4504    Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
4505      << SourceRange(DS.getFriendSpecLoc());
4506    return DeclPtrTy();
4507  }
4508
4509  // C++98 [class.friend]p1: A friend of a class is a function
4510  //   or class that is not a member of the class . . .
4511  // But that's a silly restriction which nobody implements for
4512  // inner classes, and C++0x removes it anyway, so we only report
4513  // this (as a warning) if we're being pedantic.
4514  if (!getLangOptions().CPlusPlus0x)
4515    if (const RecordType *RT = T->getAs<RecordType>())
4516      if (RT->getDecl()->getDeclContext() == CurContext)
4517        Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class);
4518
4519  Decl *D;
4520  if (TempParams.size())
4521    D = FriendTemplateDecl::Create(Context, CurContext, Loc,
4522                                   TempParams.size(),
4523                                 (TemplateParameterList**) TempParams.release(),
4524                                   T.getTypePtr(),
4525                                   DS.getFriendSpecLoc());
4526  else
4527    D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
4528                           DS.getFriendSpecLoc());
4529  D->setAccess(AS_public);
4530  CurContext->addDecl(D);
4531
4532  return DeclPtrTy::make(D);
4533}
4534
4535Sema::DeclPtrTy
4536Sema::ActOnFriendFunctionDecl(Scope *S,
4537                              Declarator &D,
4538                              bool IsDefinition,
4539                              MultiTemplateParamsArg TemplateParams) {
4540  const DeclSpec &DS = D.getDeclSpec();
4541
4542  assert(DS.isFriendSpecified());
4543  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4544
4545  SourceLocation Loc = D.getIdentifierLoc();
4546  DeclaratorInfo *DInfo = 0;
4547  QualType T = GetTypeForDeclarator(D, S, &DInfo);
4548
4549  // C++ [class.friend]p1
4550  //   A friend of a class is a function or class....
4551  // Note that this sees through typedefs, which is intended.
4552  // It *doesn't* see through dependent types, which is correct
4553  // according to [temp.arg.type]p3:
4554  //   If a declaration acquires a function type through a
4555  //   type dependent on a template-parameter and this causes
4556  //   a declaration that does not use the syntactic form of a
4557  //   function declarator to have a function type, the program
4558  //   is ill-formed.
4559  if (!T->isFunctionType()) {
4560    Diag(Loc, diag::err_unexpected_friend);
4561
4562    // It might be worthwhile to try to recover by creating an
4563    // appropriate declaration.
4564    return DeclPtrTy();
4565  }
4566
4567  // C++ [namespace.memdef]p3
4568  //  - If a friend declaration in a non-local class first declares a
4569  //    class or function, the friend class or function is a member
4570  //    of the innermost enclosing namespace.
4571  //  - The name of the friend is not found by simple name lookup
4572  //    until a matching declaration is provided in that namespace
4573  //    scope (either before or after the class declaration granting
4574  //    friendship).
4575  //  - If a friend function is called, its name may be found by the
4576  //    name lookup that considers functions from namespaces and
4577  //    classes associated with the types of the function arguments.
4578  //  - When looking for a prior declaration of a class or a function
4579  //    declared as a friend, scopes outside the innermost enclosing
4580  //    namespace scope are not considered.
4581
4582  CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
4583  DeclarationName Name = GetNameForDeclarator(D);
4584  assert(Name);
4585
4586  // The context we found the declaration in, or in which we should
4587  // create the declaration.
4588  DeclContext *DC;
4589
4590  // FIXME: handle local classes
4591
4592  // Recover from invalid scope qualifiers as if they just weren't there.
4593  NamedDecl *PrevDecl = 0;
4594  if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
4595    // FIXME: RequireCompleteDeclContext
4596    DC = computeDeclContext(ScopeQual);
4597
4598    // FIXME: handle dependent contexts
4599    if (!DC) return DeclPtrTy();
4600
4601    LookupResult R(*this, Name, Loc, LookupOrdinaryName,
4602                   LookupResult::ForRedeclaration);
4603    LookupQualifiedName(R, DC);
4604    PrevDecl = R.getAsSingleDecl(Context);
4605
4606    // If searching in that context implicitly found a declaration in
4607    // a different context, treat it like it wasn't found at all.
4608    // TODO: better diagnostics for this case.  Suggesting the right
4609    // qualified scope would be nice...
4610    if (!PrevDecl || !PrevDecl->getDeclContext()->Equals(DC)) {
4611      D.setInvalidType();
4612      Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
4613      return DeclPtrTy();
4614    }
4615
4616    // C++ [class.friend]p1: A friend of a class is a function or
4617    //   class that is not a member of the class . . .
4618    if (DC->Equals(CurContext))
4619      Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4620
4621  // Otherwise walk out to the nearest namespace scope looking for matches.
4622  } else {
4623    // TODO: handle local class contexts.
4624
4625    DC = CurContext;
4626    while (true) {
4627      // Skip class contexts.  If someone can cite chapter and verse
4628      // for this behavior, that would be nice --- it's what GCC and
4629      // EDG do, and it seems like a reasonable intent, but the spec
4630      // really only says that checks for unqualified existing
4631      // declarations should stop at the nearest enclosing namespace,
4632      // not that they should only consider the nearest enclosing
4633      // namespace.
4634      while (DC->isRecord())
4635        DC = DC->getParent();
4636
4637      LookupResult R(*this, Name, Loc, LookupOrdinaryName,
4638                     LookupResult::ForRedeclaration);
4639      LookupQualifiedName(R, DC);
4640      PrevDecl = R.getAsSingleDecl(Context);
4641
4642      // TODO: decide what we think about using declarations.
4643      if (PrevDecl)
4644        break;
4645
4646      if (DC->isFileContext()) break;
4647      DC = DC->getParent();
4648    }
4649
4650    // C++ [class.friend]p1: A friend of a class is a function or
4651    //   class that is not a member of the class . . .
4652    // C++0x changes this for both friend types and functions.
4653    // Most C++ 98 compilers do seem to give an error here, so
4654    // we do, too.
4655    if (PrevDecl && DC->Equals(CurContext) && !getLangOptions().CPlusPlus0x)
4656      Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4657  }
4658
4659  if (DC->isFileContext()) {
4660    // This implies that it has to be an operator or function.
4661    if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
4662        D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
4663        D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
4664      Diag(Loc, diag::err_introducing_special_friend) <<
4665        (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
4666         D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
4667      return DeclPtrTy();
4668    }
4669  }
4670
4671  bool Redeclaration = false;
4672  NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, DInfo, PrevDecl,
4673                                          move(TemplateParams),
4674                                          IsDefinition,
4675                                          Redeclaration);
4676  if (!ND) return DeclPtrTy();
4677
4678  assert(ND->getDeclContext() == DC);
4679  assert(ND->getLexicalDeclContext() == CurContext);
4680
4681  // Add the function declaration to the appropriate lookup tables,
4682  // adjusting the redeclarations list as necessary.  We don't
4683  // want to do this yet if the friending class is dependent.
4684  //
4685  // Also update the scope-based lookup if the target context's
4686  // lookup context is in lexical scope.
4687  if (!CurContext->isDependentContext()) {
4688    DC = DC->getLookupContext();
4689    DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
4690    if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
4691      PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
4692  }
4693
4694  FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
4695                                       D.getIdentifierLoc(), ND,
4696                                       DS.getFriendSpecLoc());
4697  FrD->setAccess(AS_public);
4698  CurContext->addDecl(FrD);
4699
4700  return DeclPtrTy::make(ND);
4701}
4702
4703void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
4704  AdjustDeclIfTemplate(dcl);
4705
4706  Decl *Dcl = dcl.getAs<Decl>();
4707  FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
4708  if (!Fn) {
4709    Diag(DelLoc, diag::err_deleted_non_function);
4710    return;
4711  }
4712  if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
4713    Diag(DelLoc, diag::err_deleted_decl_not_first);
4714    Diag(Prev->getLocation(), diag::note_previous_declaration);
4715    // If the declaration wasn't the first, we delete the function anyway for
4716    // recovery.
4717  }
4718  Fn->setDeleted();
4719}
4720
4721static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
4722  for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
4723       ++CI) {
4724    Stmt *SubStmt = *CI;
4725    if (!SubStmt)
4726      continue;
4727    if (isa<ReturnStmt>(SubStmt))
4728      Self.Diag(SubStmt->getSourceRange().getBegin(),
4729           diag::err_return_in_constructor_handler);
4730    if (!isa<Expr>(SubStmt))
4731      SearchForReturnInStmt(Self, SubStmt);
4732  }
4733}
4734
4735void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
4736  for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
4737    CXXCatchStmt *Handler = TryBlock->getHandler(I);
4738    SearchForReturnInStmt(*this, Handler);
4739  }
4740}
4741
4742bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
4743                                             const CXXMethodDecl *Old) {
4744  QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
4745  QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
4746
4747  QualType CNewTy = Context.getCanonicalType(NewTy);
4748  QualType COldTy = Context.getCanonicalType(OldTy);
4749
4750  if (CNewTy == COldTy &&
4751      CNewTy.getLocalCVRQualifiers() == COldTy.getLocalCVRQualifiers())
4752    return false;
4753
4754  // Check if the return types are covariant
4755  QualType NewClassTy, OldClassTy;
4756
4757  /// Both types must be pointers or references to classes.
4758  if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
4759    if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
4760      NewClassTy = NewPT->getPointeeType();
4761      OldClassTy = OldPT->getPointeeType();
4762    }
4763  } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
4764    if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
4765      NewClassTy = NewRT->getPointeeType();
4766      OldClassTy = OldRT->getPointeeType();
4767    }
4768  }
4769
4770  // The return types aren't either both pointers or references to a class type.
4771  if (NewClassTy.isNull()) {
4772    Diag(New->getLocation(),
4773         diag::err_different_return_type_for_overriding_virtual_function)
4774      << New->getDeclName() << NewTy << OldTy;
4775    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4776
4777    return true;
4778  }
4779
4780  if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
4781    // Check if the new class derives from the old class.
4782    if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
4783      Diag(New->getLocation(),
4784           diag::err_covariant_return_not_derived)
4785      << New->getDeclName() << NewTy << OldTy;
4786      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4787      return true;
4788    }
4789
4790    // Check if we the conversion from derived to base is valid.
4791    if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
4792                      diag::err_covariant_return_inaccessible_base,
4793                      diag::err_covariant_return_ambiguous_derived_to_base_conv,
4794                      // FIXME: Should this point to the return type?
4795                      New->getLocation(), SourceRange(), New->getDeclName())) {
4796      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4797      return true;
4798    }
4799  }
4800
4801  // The qualifiers of the return types must be the same.
4802  if (CNewTy.getLocalCVRQualifiers() != COldTy.getLocalCVRQualifiers()) {
4803    Diag(New->getLocation(),
4804         diag::err_covariant_return_type_different_qualifications)
4805    << New->getDeclName() << NewTy << OldTy;
4806    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4807    return true;
4808  };
4809
4810
4811  // The new class type must have the same or less qualifiers as the old type.
4812  if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
4813    Diag(New->getLocation(),
4814         diag::err_covariant_return_type_class_type_more_qualified)
4815    << New->getDeclName() << NewTy << OldTy;
4816    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4817    return true;
4818  };
4819
4820  return false;
4821}
4822
4823/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4824/// initializer for the declaration 'Dcl'.
4825/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4826/// static data member of class X, names should be looked up in the scope of
4827/// class X.
4828void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
4829  AdjustDeclIfTemplate(Dcl);
4830
4831  Decl *D = Dcl.getAs<Decl>();
4832  // If there is no declaration, there was an error parsing it.
4833  if (D == 0)
4834    return;
4835
4836  // Check whether it is a declaration with a nested name specifier like
4837  // int foo::bar;
4838  if (!D->isOutOfLine())
4839    return;
4840
4841  // C++ [basic.lookup.unqual]p13
4842  //
4843  // A name used in the definition of a static data member of class X
4844  // (after the qualified-id of the static member) is looked up as if the name
4845  // was used in a member function of X.
4846
4847  // Change current context into the context of the initializing declaration.
4848  EnterDeclaratorContext(S, D->getDeclContext());
4849}
4850
4851/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4852/// initializer for the declaration 'Dcl'.
4853void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
4854  AdjustDeclIfTemplate(Dcl);
4855
4856  Decl *D = Dcl.getAs<Decl>();
4857  // If there is no declaration, there was an error parsing it.
4858  if (D == 0)
4859    return;
4860
4861  // Check whether it is a declaration with a nested name specifier like
4862  // int foo::bar;
4863  if (!D->isOutOfLine())
4864    return;
4865
4866  assert(S->getEntity() == D->getDeclContext() && "Context imbalance!");
4867  ExitDeclaratorContext(S);
4868}
4869