SemaDeclCXX.cpp revision a4923eb7c4b04d360cb2747641a5e92818edf804
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      ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1403      if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1404                                  Constructor->getLocation(), CtorArgs))
1405        continue;
1406
1407      // FIXME: CXXBaseOrMemberInitializer should only contain a single
1408      // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1409      ExprTemporaries.clear();
1410      CXXBaseOrMemberInitializer *Member =
1411        new (Context) CXXBaseOrMemberInitializer(*Field,CtorArgs.takeAs<Expr>(),
1412                                                 CtorArgs.size(), Ctor,
1413                                                 SourceLocation(),
1414                                                 SourceLocation());
1415
1416      AllToInit.push_back(Member);
1417      MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1418      if (FT.isConstQualified() && Ctor->isTrivial()) {
1419        Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1420          << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1421          << 1 << (*Field)->getDeclName();
1422        Diag((*Field)->getLocation(), diag::note_declared_at);
1423        HadError = true;
1424      }
1425    }
1426    else if (FT->isReferenceType()) {
1427      Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1428        << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1429        << 0 << (*Field)->getDeclName();
1430      Diag((*Field)->getLocation(), diag::note_declared_at);
1431      HadError = true;
1432    }
1433    else if (FT.isConstQualified()) {
1434      Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1435        << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1436        << 1 << (*Field)->getDeclName();
1437      Diag((*Field)->getLocation(), diag::note_declared_at);
1438      HadError = true;
1439    }
1440  }
1441
1442  NumInitializers = AllToInit.size();
1443  if (NumInitializers > 0) {
1444    Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1445    CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1446      new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1447
1448    Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1449    for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1450      baseOrMemberInitializers[Idx] = AllToInit[Idx];
1451  }
1452
1453  return HadError;
1454}
1455
1456static void *GetKeyForTopLevelField(FieldDecl *Field) {
1457  // For anonymous unions, use the class declaration as the key.
1458  if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
1459    if (RT->getDecl()->isAnonymousStructOrUnion())
1460      return static_cast<void *>(RT->getDecl());
1461  }
1462  return static_cast<void *>(Field);
1463}
1464
1465static void *GetKeyForBase(QualType BaseType) {
1466  if (const RecordType *RT = BaseType->getAs<RecordType>())
1467    return (void *)RT;
1468
1469  assert(0 && "Unexpected base type!");
1470  return 0;
1471}
1472
1473static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
1474                             bool MemberMaybeAnon = false) {
1475  // For fields injected into the class via declaration of an anonymous union,
1476  // use its anonymous union class declaration as the unique key.
1477  if (Member->isMemberInitializer()) {
1478    FieldDecl *Field = Member->getMember();
1479
1480    // After SetBaseOrMemberInitializers call, Field is the anonymous union
1481    // data member of the class. Data member used in the initializer list is
1482    // in AnonUnionMember field.
1483    if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1484      Field = Member->getAnonUnionMember();
1485    if (Field->getDeclContext()->isRecord()) {
1486      RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1487      if (RD->isAnonymousStructOrUnion())
1488        return static_cast<void *>(RD);
1489    }
1490    return static_cast<void *>(Field);
1491  }
1492
1493  return GetKeyForBase(QualType(Member->getBaseClass(), 0));
1494}
1495
1496/// ActOnMemInitializers - Handle the member initializers for a constructor.
1497void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
1498                                SourceLocation ColonLoc,
1499                                MemInitTy **MemInits, unsigned NumMemInits) {
1500  if (!ConstructorDecl)
1501    return;
1502
1503  AdjustDeclIfTemplate(ConstructorDecl);
1504
1505  CXXConstructorDecl *Constructor
1506    = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
1507
1508  if (!Constructor) {
1509    Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1510    return;
1511  }
1512
1513  if (!Constructor->isDependentContext()) {
1514    llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1515    bool err = false;
1516    for (unsigned i = 0; i < NumMemInits; i++) {
1517      CXXBaseOrMemberInitializer *Member =
1518        static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1519      void *KeyToMember = GetKeyForMember(Member);
1520      CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1521      if (!PrevMember) {
1522        PrevMember = Member;
1523        continue;
1524      }
1525      if (FieldDecl *Field = Member->getMember())
1526        Diag(Member->getSourceLocation(),
1527             diag::error_multiple_mem_initialization)
1528        << Field->getNameAsString();
1529      else {
1530        Type *BaseClass = Member->getBaseClass();
1531        assert(BaseClass && "ActOnMemInitializers - neither field or base");
1532        Diag(Member->getSourceLocation(),
1533             diag::error_multiple_base_initialization)
1534          << QualType(BaseClass, 0);
1535      }
1536      Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1537        << 0;
1538      err = true;
1539    }
1540
1541    if (err)
1542      return;
1543  }
1544
1545  SetBaseOrMemberInitializers(Constructor,
1546                      reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
1547                      NumMemInits, false);
1548
1549  if (Constructor->isDependentContext())
1550    return;
1551
1552  if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
1553      Diagnostic::Ignored &&
1554      Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
1555      Diagnostic::Ignored)
1556    return;
1557
1558  // Also issue warning if order of ctor-initializer list does not match order
1559  // of 1) base class declarations and 2) order of non-static data members.
1560  llvm::SmallVector<const void*, 32> AllBaseOrMembers;
1561
1562  CXXRecordDecl *ClassDecl
1563    = cast<CXXRecordDecl>(Constructor->getDeclContext());
1564  // Push virtual bases before others.
1565  for (CXXRecordDecl::base_class_iterator VBase =
1566       ClassDecl->vbases_begin(),
1567       E = ClassDecl->vbases_end(); VBase != E; ++VBase)
1568    AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
1569
1570  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1571       E = ClassDecl->bases_end(); Base != E; ++Base) {
1572    // Virtuals are alread in the virtual base list and are constructed
1573    // first.
1574    if (Base->isVirtual())
1575      continue;
1576    AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
1577  }
1578
1579  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1580       E = ClassDecl->field_end(); Field != E; ++Field)
1581    AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
1582
1583  int Last = AllBaseOrMembers.size();
1584  int curIndex = 0;
1585  CXXBaseOrMemberInitializer *PrevMember = 0;
1586  for (unsigned i = 0; i < NumMemInits; i++) {
1587    CXXBaseOrMemberInitializer *Member =
1588      static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1589    void *MemberInCtorList = GetKeyForMember(Member, true);
1590
1591    for (; curIndex < Last; curIndex++)
1592      if (MemberInCtorList == AllBaseOrMembers[curIndex])
1593        break;
1594    if (curIndex == Last) {
1595      assert(PrevMember && "Member not in member list?!");
1596      // Initializer as specified in ctor-initializer list is out of order.
1597      // Issue a warning diagnostic.
1598      if (PrevMember->isBaseInitializer()) {
1599        // Diagnostics is for an initialized base class.
1600        Type *BaseClass = PrevMember->getBaseClass();
1601        Diag(PrevMember->getSourceLocation(),
1602             diag::warn_base_initialized)
1603          << QualType(BaseClass, 0);
1604      } else {
1605        FieldDecl *Field = PrevMember->getMember();
1606        Diag(PrevMember->getSourceLocation(),
1607             diag::warn_field_initialized)
1608          << Field->getNameAsString();
1609      }
1610      // Also the note!
1611      if (FieldDecl *Field = Member->getMember())
1612        Diag(Member->getSourceLocation(),
1613             diag::note_fieldorbase_initialized_here) << 0
1614          << Field->getNameAsString();
1615      else {
1616        Type *BaseClass = Member->getBaseClass();
1617        Diag(Member->getSourceLocation(),
1618             diag::note_fieldorbase_initialized_here) << 1
1619          << QualType(BaseClass, 0);
1620      }
1621      for (curIndex = 0; curIndex < Last; curIndex++)
1622        if (MemberInCtorList == AllBaseOrMembers[curIndex])
1623          break;
1624    }
1625    PrevMember = Member;
1626  }
1627}
1628
1629void
1630Sema::computeBaseOrMembersToDestroy(CXXDestructorDecl *Destructor) {
1631  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Destructor->getDeclContext());
1632  llvm::SmallVector<uintptr_t, 32> AllToDestruct;
1633
1634  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1635       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1636    if (VBase->getType()->isDependentType())
1637      continue;
1638    // Skip over virtual bases which have trivial destructors.
1639    CXXRecordDecl *BaseClassDecl
1640      = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1641    if (BaseClassDecl->hasTrivialDestructor())
1642      continue;
1643    if (const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context))
1644      MarkDeclarationReferenced(Destructor->getLocation(),
1645                                const_cast<CXXDestructorDecl*>(Dtor));
1646
1647    uintptr_t Member =
1648    reinterpret_cast<uintptr_t>(VBase->getType().getTypePtr())
1649      | CXXDestructorDecl::VBASE;
1650    AllToDestruct.push_back(Member);
1651  }
1652  for (CXXRecordDecl::base_class_iterator Base =
1653       ClassDecl->bases_begin(),
1654       E = ClassDecl->bases_end(); Base != E; ++Base) {
1655    if (Base->isVirtual())
1656      continue;
1657    if (Base->getType()->isDependentType())
1658      continue;
1659    // Skip over virtual bases which have trivial destructors.
1660    CXXRecordDecl *BaseClassDecl
1661    = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1662    if (BaseClassDecl->hasTrivialDestructor())
1663      continue;
1664    if (const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context))
1665      MarkDeclarationReferenced(Destructor->getLocation(),
1666                                const_cast<CXXDestructorDecl*>(Dtor));
1667    uintptr_t Member =
1668    reinterpret_cast<uintptr_t>(Base->getType().getTypePtr())
1669      | CXXDestructorDecl::DRCTNONVBASE;
1670    AllToDestruct.push_back(Member);
1671  }
1672
1673  // non-static data members.
1674  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1675       E = ClassDecl->field_end(); Field != E; ++Field) {
1676    QualType FieldType = Context.getBaseElementType((*Field)->getType());
1677
1678    if (const RecordType* RT = FieldType->getAs<RecordType>()) {
1679      // Skip over virtual bases which have trivial destructors.
1680      CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1681      if (FieldClassDecl->hasTrivialDestructor())
1682        continue;
1683      if (const CXXDestructorDecl *Dtor =
1684            FieldClassDecl->getDestructor(Context))
1685        MarkDeclarationReferenced(Destructor->getLocation(),
1686                                  const_cast<CXXDestructorDecl*>(Dtor));
1687      uintptr_t Member = reinterpret_cast<uintptr_t>(*Field);
1688      AllToDestruct.push_back(Member);
1689    }
1690  }
1691
1692  unsigned NumDestructions = AllToDestruct.size();
1693  if (NumDestructions > 0) {
1694    Destructor->setNumBaseOrMemberDestructions(NumDestructions);
1695    uintptr_t *BaseOrMemberDestructions =
1696      new (Context) uintptr_t [NumDestructions];
1697    // Insert in reverse order.
1698    for (int Idx = NumDestructions-1, i=0 ; Idx >= 0; --Idx)
1699      BaseOrMemberDestructions[i++] = AllToDestruct[Idx];
1700    Destructor->setBaseOrMemberDestructions(BaseOrMemberDestructions);
1701  }
1702}
1703
1704void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
1705  if (!CDtorDecl)
1706    return;
1707
1708  AdjustDeclIfTemplate(CDtorDecl);
1709
1710  if (CXXConstructorDecl *Constructor
1711      = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
1712    SetBaseOrMemberInitializers(Constructor, 0, 0, false);
1713}
1714
1715namespace {
1716  /// PureVirtualMethodCollector - traverses a class and its superclasses
1717  /// and determines if it has any pure virtual methods.
1718  class VISIBILITY_HIDDEN PureVirtualMethodCollector {
1719    ASTContext &Context;
1720
1721  public:
1722    typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
1723
1724  private:
1725    MethodList Methods;
1726
1727    void Collect(const CXXRecordDecl* RD, MethodList& Methods);
1728
1729  public:
1730    PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
1731      : Context(Ctx) {
1732
1733      MethodList List;
1734      Collect(RD, List);
1735
1736      // Copy the temporary list to methods, and make sure to ignore any
1737      // null entries.
1738      for (size_t i = 0, e = List.size(); i != e; ++i) {
1739        if (List[i])
1740          Methods.push_back(List[i]);
1741      }
1742    }
1743
1744    bool empty() const { return Methods.empty(); }
1745
1746    MethodList::const_iterator methods_begin() { return Methods.begin(); }
1747    MethodList::const_iterator methods_end() { return Methods.end(); }
1748  };
1749
1750  void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
1751                                           MethodList& Methods) {
1752    // First, collect the pure virtual methods for the base classes.
1753    for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1754         BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
1755      if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
1756        const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
1757        if (BaseDecl && BaseDecl->isAbstract())
1758          Collect(BaseDecl, Methods);
1759      }
1760    }
1761
1762    // Next, zero out any pure virtual methods that this class overrides.
1763    typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
1764
1765    MethodSetTy OverriddenMethods;
1766    size_t MethodsSize = Methods.size();
1767
1768    for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
1769         i != e; ++i) {
1770      // Traverse the record, looking for methods.
1771      if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
1772        // If the method is pure virtual, add it to the methods vector.
1773        if (MD->isPure())
1774          Methods.push_back(MD);
1775
1776        // Record all the overridden methods in our set.
1777        for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1778             E = MD->end_overridden_methods(); I != E; ++I) {
1779          // Keep track of the overridden methods.
1780          OverriddenMethods.insert(*I);
1781        }
1782      }
1783    }
1784
1785    // Now go through the methods and zero out all the ones we know are
1786    // overridden.
1787    for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1788      if (OverriddenMethods.count(Methods[i]))
1789        Methods[i] = 0;
1790    }
1791
1792  }
1793}
1794
1795
1796bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1797                                  unsigned DiagID, AbstractDiagSelID SelID,
1798                                  const CXXRecordDecl *CurrentRD) {
1799  if (SelID == -1)
1800    return RequireNonAbstractType(Loc, T,
1801                                  PDiag(DiagID), CurrentRD);
1802  else
1803    return RequireNonAbstractType(Loc, T,
1804                                  PDiag(DiagID) << SelID, CurrentRD);
1805}
1806
1807bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1808                                  const PartialDiagnostic &PD,
1809                                  const CXXRecordDecl *CurrentRD) {
1810  if (!getLangOptions().CPlusPlus)
1811    return false;
1812
1813  if (const ArrayType *AT = Context.getAsArrayType(T))
1814    return RequireNonAbstractType(Loc, AT->getElementType(), PD,
1815                                  CurrentRD);
1816
1817  if (const PointerType *PT = T->getAs<PointerType>()) {
1818    // Find the innermost pointer type.
1819    while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
1820      PT = T;
1821
1822    if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
1823      return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
1824  }
1825
1826  const RecordType *RT = T->getAs<RecordType>();
1827  if (!RT)
1828    return false;
1829
1830  const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
1831  if (!RD)
1832    return false;
1833
1834  if (CurrentRD && CurrentRD != RD)
1835    return false;
1836
1837  if (!RD->isAbstract())
1838    return false;
1839
1840  Diag(Loc, PD) << RD->getDeclName();
1841
1842  // Check if we've already emitted the list of pure virtual functions for this
1843  // class.
1844  if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
1845    return true;
1846
1847  PureVirtualMethodCollector Collector(Context, RD);
1848
1849  for (PureVirtualMethodCollector::MethodList::const_iterator I =
1850       Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
1851    const CXXMethodDecl *MD = *I;
1852
1853    Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
1854      MD->getDeclName();
1855  }
1856
1857  if (!PureVirtualClassDiagSet)
1858    PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
1859  PureVirtualClassDiagSet->insert(RD);
1860
1861  return true;
1862}
1863
1864namespace {
1865  class VISIBILITY_HIDDEN AbstractClassUsageDiagnoser
1866    : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
1867    Sema &SemaRef;
1868    CXXRecordDecl *AbstractClass;
1869
1870    bool VisitDeclContext(const DeclContext *DC) {
1871      bool Invalid = false;
1872
1873      for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
1874           E = DC->decls_end(); I != E; ++I)
1875        Invalid |= Visit(*I);
1876
1877      return Invalid;
1878    }
1879
1880  public:
1881    AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
1882      : SemaRef(SemaRef), AbstractClass(ac) {
1883        Visit(SemaRef.Context.getTranslationUnitDecl());
1884    }
1885
1886    bool VisitFunctionDecl(const FunctionDecl *FD) {
1887      if (FD->isThisDeclarationADefinition()) {
1888        // No need to do the check if we're in a definition, because it requires
1889        // that the return/param types are complete.
1890        // because that requires
1891        return VisitDeclContext(FD);
1892      }
1893
1894      // Check the return type.
1895      QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
1896      bool Invalid =
1897        SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
1898                                       diag::err_abstract_type_in_decl,
1899                                       Sema::AbstractReturnType,
1900                                       AbstractClass);
1901
1902      for (FunctionDecl::param_const_iterator I = FD->param_begin(),
1903           E = FD->param_end(); I != E; ++I) {
1904        const ParmVarDecl *VD = *I;
1905        Invalid |=
1906          SemaRef.RequireNonAbstractType(VD->getLocation(),
1907                                         VD->getOriginalType(),
1908                                         diag::err_abstract_type_in_decl,
1909                                         Sema::AbstractParamType,
1910                                         AbstractClass);
1911      }
1912
1913      return Invalid;
1914    }
1915
1916    bool VisitDecl(const Decl* D) {
1917      if (const DeclContext *DC = dyn_cast<DeclContext>(D))
1918        return VisitDeclContext(DC);
1919
1920      return false;
1921    }
1922  };
1923}
1924
1925void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
1926                                             DeclPtrTy TagDecl,
1927                                             SourceLocation LBrac,
1928                                             SourceLocation RBrac) {
1929  if (!TagDecl)
1930    return;
1931
1932  AdjustDeclIfTemplate(TagDecl);
1933  ActOnFields(S, RLoc, TagDecl,
1934              (DeclPtrTy*)FieldCollector->getCurFields(),
1935              FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
1936
1937  CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>());
1938  if (!RD->isAbstract()) {
1939    // Collect all the pure virtual methods and see if this is an abstract
1940    // class after all.
1941    PureVirtualMethodCollector Collector(Context, RD);
1942    if (!Collector.empty())
1943      RD->setAbstract(true);
1944  }
1945
1946  if (RD->isAbstract())
1947    AbstractClassUsageDiagnoser(*this, RD);
1948
1949  if (!RD->isDependentType() && !RD->isInvalidDecl())
1950    AddImplicitlyDeclaredMembersToClass(RD);
1951}
1952
1953/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
1954/// special functions, such as the default constructor, copy
1955/// constructor, or destructor, to the given C++ class (C++
1956/// [special]p1).  This routine can only be executed just before the
1957/// definition of the class is complete.
1958void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
1959  CanQualType ClassType
1960    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
1961
1962  // FIXME: Implicit declarations have exception specifications, which are
1963  // the union of the specifications of the implicitly called functions.
1964
1965  if (!ClassDecl->hasUserDeclaredConstructor()) {
1966    // C++ [class.ctor]p5:
1967    //   A default constructor for a class X is a constructor of class X
1968    //   that can be called without an argument. If there is no
1969    //   user-declared constructor for class X, a default constructor is
1970    //   implicitly declared. An implicitly-declared default constructor
1971    //   is an inline public member of its class.
1972    DeclarationName Name
1973      = Context.DeclarationNames.getCXXConstructorName(ClassType);
1974    CXXConstructorDecl *DefaultCon =
1975      CXXConstructorDecl::Create(Context, ClassDecl,
1976                                 ClassDecl->getLocation(), Name,
1977                                 Context.getFunctionType(Context.VoidTy,
1978                                                         0, 0, false, 0),
1979                                 /*DInfo=*/0,
1980                                 /*isExplicit=*/false,
1981                                 /*isInline=*/true,
1982                                 /*isImplicitlyDeclared=*/true);
1983    DefaultCon->setAccess(AS_public);
1984    DefaultCon->setImplicit();
1985    DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
1986    ClassDecl->addDecl(DefaultCon);
1987  }
1988
1989  if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
1990    // C++ [class.copy]p4:
1991    //   If the class definition does not explicitly declare a copy
1992    //   constructor, one is declared implicitly.
1993
1994    // C++ [class.copy]p5:
1995    //   The implicitly-declared copy constructor for a class X will
1996    //   have the form
1997    //
1998    //       X::X(const X&)
1999    //
2000    //   if
2001    bool HasConstCopyConstructor = true;
2002
2003    //     -- each direct or virtual base class B of X has a copy
2004    //        constructor whose first parameter is of type const B& or
2005    //        const volatile B&, and
2006    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2007         HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2008      const CXXRecordDecl *BaseClassDecl
2009        = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2010      HasConstCopyConstructor
2011        = BaseClassDecl->hasConstCopyConstructor(Context);
2012    }
2013
2014    //     -- for all the nonstatic data members of X that are of a
2015    //        class type M (or array thereof), each such class type
2016    //        has a copy constructor whose first parameter is of type
2017    //        const M& or const volatile M&.
2018    for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2019         HasConstCopyConstructor && Field != ClassDecl->field_end();
2020         ++Field) {
2021      QualType FieldType = (*Field)->getType();
2022      if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2023        FieldType = Array->getElementType();
2024      if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
2025        const CXXRecordDecl *FieldClassDecl
2026          = cast<CXXRecordDecl>(FieldClassType->getDecl());
2027        HasConstCopyConstructor
2028          = FieldClassDecl->hasConstCopyConstructor(Context);
2029      }
2030    }
2031
2032    //   Otherwise, the implicitly declared copy constructor will have
2033    //   the form
2034    //
2035    //       X::X(X&)
2036    QualType ArgType = ClassType;
2037    if (HasConstCopyConstructor)
2038      ArgType = ArgType.withConst();
2039    ArgType = Context.getLValueReferenceType(ArgType);
2040
2041    //   An implicitly-declared copy constructor is an inline public
2042    //   member of its class.
2043    DeclarationName Name
2044      = Context.DeclarationNames.getCXXConstructorName(ClassType);
2045    CXXConstructorDecl *CopyConstructor
2046      = CXXConstructorDecl::Create(Context, ClassDecl,
2047                                   ClassDecl->getLocation(), Name,
2048                                   Context.getFunctionType(Context.VoidTy,
2049                                                           &ArgType, 1,
2050                                                           false, 0),
2051                                   /*DInfo=*/0,
2052                                   /*isExplicit=*/false,
2053                                   /*isInline=*/true,
2054                                   /*isImplicitlyDeclared=*/true);
2055    CopyConstructor->setAccess(AS_public);
2056    CopyConstructor->setImplicit();
2057    CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
2058
2059    // Add the parameter to the constructor.
2060    ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2061                                                 ClassDecl->getLocation(),
2062                                                 /*IdentifierInfo=*/0,
2063                                                 ArgType, /*DInfo=*/0,
2064                                                 VarDecl::None, 0);
2065    CopyConstructor->setParams(Context, &FromParam, 1);
2066    ClassDecl->addDecl(CopyConstructor);
2067  }
2068
2069  if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2070    // Note: The following rules are largely analoguous to the copy
2071    // constructor rules. Note that virtual bases are not taken into account
2072    // for determining the argument type of the operator. Note also that
2073    // operators taking an object instead of a reference are allowed.
2074    //
2075    // C++ [class.copy]p10:
2076    //   If the class definition does not explicitly declare a copy
2077    //   assignment operator, one is declared implicitly.
2078    //   The implicitly-defined copy assignment operator for a class X
2079    //   will have the form
2080    //
2081    //       X& X::operator=(const X&)
2082    //
2083    //   if
2084    bool HasConstCopyAssignment = true;
2085
2086    //       -- each direct base class B of X has a copy assignment operator
2087    //          whose parameter is of type const B&, const volatile B& or B,
2088    //          and
2089    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2090         HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
2091      assert(!Base->getType()->isDependentType() &&
2092            "Cannot generate implicit members for class with dependent bases.");
2093      const CXXRecordDecl *BaseClassDecl
2094        = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2095      const CXXMethodDecl *MD = 0;
2096      HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
2097                                                                     MD);
2098    }
2099
2100    //       -- for all the nonstatic data members of X that are of a class
2101    //          type M (or array thereof), each such class type has a copy
2102    //          assignment operator whose parameter is of type const M&,
2103    //          const volatile M& or M.
2104    for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2105         HasConstCopyAssignment && Field != ClassDecl->field_end();
2106         ++Field) {
2107      QualType FieldType = (*Field)->getType();
2108      if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2109        FieldType = Array->getElementType();
2110      if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
2111        const CXXRecordDecl *FieldClassDecl
2112          = cast<CXXRecordDecl>(FieldClassType->getDecl());
2113        const CXXMethodDecl *MD = 0;
2114        HasConstCopyAssignment
2115          = FieldClassDecl->hasConstCopyAssignment(Context, MD);
2116      }
2117    }
2118
2119    //   Otherwise, the implicitly declared copy assignment operator will
2120    //   have the form
2121    //
2122    //       X& X::operator=(X&)
2123    QualType ArgType = ClassType;
2124    QualType RetType = Context.getLValueReferenceType(ArgType);
2125    if (HasConstCopyAssignment)
2126      ArgType = ArgType.withConst();
2127    ArgType = Context.getLValueReferenceType(ArgType);
2128
2129    //   An implicitly-declared copy assignment operator is an inline public
2130    //   member of its class.
2131    DeclarationName Name =
2132      Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2133    CXXMethodDecl *CopyAssignment =
2134      CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2135                            Context.getFunctionType(RetType, &ArgType, 1,
2136                                                    false, 0),
2137                            /*DInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
2138    CopyAssignment->setAccess(AS_public);
2139    CopyAssignment->setImplicit();
2140    CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
2141    CopyAssignment->setCopyAssignment(true);
2142
2143    // Add the parameter to the operator.
2144    ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2145                                                 ClassDecl->getLocation(),
2146                                                 /*IdentifierInfo=*/0,
2147                                                 ArgType, /*DInfo=*/0,
2148                                                 VarDecl::None, 0);
2149    CopyAssignment->setParams(Context, &FromParam, 1);
2150
2151    // Don't call addedAssignmentOperator. There is no way to distinguish an
2152    // implicit from an explicit assignment operator.
2153    ClassDecl->addDecl(CopyAssignment);
2154  }
2155
2156  if (!ClassDecl->hasUserDeclaredDestructor()) {
2157    // C++ [class.dtor]p2:
2158    //   If a class has no user-declared destructor, a destructor is
2159    //   declared implicitly. An implicitly-declared destructor is an
2160    //   inline public member of its class.
2161    DeclarationName Name
2162      = Context.DeclarationNames.getCXXDestructorName(ClassType);
2163    CXXDestructorDecl *Destructor
2164      = CXXDestructorDecl::Create(Context, ClassDecl,
2165                                  ClassDecl->getLocation(), Name,
2166                                  Context.getFunctionType(Context.VoidTy,
2167                                                          0, 0, false, 0),
2168                                  /*isInline=*/true,
2169                                  /*isImplicitlyDeclared=*/true);
2170    Destructor->setAccess(AS_public);
2171    Destructor->setImplicit();
2172    Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
2173    ClassDecl->addDecl(Destructor);
2174  }
2175}
2176
2177void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
2178  Decl *D = TemplateD.getAs<Decl>();
2179  if (!D)
2180    return;
2181
2182  TemplateParameterList *Params = 0;
2183  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2184    Params = Template->getTemplateParameters();
2185  else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2186           = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2187    Params = PartialSpec->getTemplateParameters();
2188  else
2189    return;
2190
2191  for (TemplateParameterList::iterator Param = Params->begin(),
2192                                    ParamEnd = Params->end();
2193       Param != ParamEnd; ++Param) {
2194    NamedDecl *Named = cast<NamedDecl>(*Param);
2195    if (Named->getDeclName()) {
2196      S->AddDecl(DeclPtrTy::make(Named));
2197      IdResolver.AddDecl(Named);
2198    }
2199  }
2200}
2201
2202/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2203/// parsing a top-level (non-nested) C++ class, and we are now
2204/// parsing those parts of the given Method declaration that could
2205/// not be parsed earlier (C++ [class.mem]p2), such as default
2206/// arguments. This action should enter the scope of the given
2207/// Method declaration as if we had just parsed the qualified method
2208/// name. However, it should not bring the parameters into scope;
2209/// that will be performed by ActOnDelayedCXXMethodParameter.
2210void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
2211  if (!MethodD)
2212    return;
2213
2214  AdjustDeclIfTemplate(MethodD);
2215
2216  CXXScopeSpec SS;
2217  FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
2218  QualType ClassTy
2219    = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2220  SS.setScopeRep(
2221    NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
2222  ActOnCXXEnterDeclaratorScope(S, SS);
2223}
2224
2225/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2226/// C++ method declaration. We're (re-)introducing the given
2227/// function parameter into scope for use in parsing later parts of
2228/// the method declaration. For example, we could see an
2229/// ActOnParamDefaultArgument event for this parameter.
2230void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
2231  if (!ParamD)
2232    return;
2233
2234  ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
2235
2236  // If this parameter has an unparsed default argument, clear it out
2237  // to make way for the parsed default argument.
2238  if (Param->hasUnparsedDefaultArg())
2239    Param->setDefaultArg(0);
2240
2241  S->AddDecl(DeclPtrTy::make(Param));
2242  if (Param->getDeclName())
2243    IdResolver.AddDecl(Param);
2244}
2245
2246/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2247/// processing the delayed method declaration for Method. The method
2248/// declaration is now considered finished. There may be a separate
2249/// ActOnStartOfFunctionDef action later (not necessarily
2250/// immediately!) for this method, if it was also defined inside the
2251/// class body.
2252void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
2253  if (!MethodD)
2254    return;
2255
2256  AdjustDeclIfTemplate(MethodD);
2257
2258  FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
2259  CXXScopeSpec SS;
2260  QualType ClassTy
2261    = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2262  SS.setScopeRep(
2263    NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
2264  ActOnCXXExitDeclaratorScope(S, SS);
2265
2266  // Now that we have our default arguments, check the constructor
2267  // again. It could produce additional diagnostics or affect whether
2268  // the class has implicitly-declared destructors, among other
2269  // things.
2270  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2271    CheckConstructor(Constructor);
2272
2273  // Check the default arguments, which we may have added.
2274  if (!Method->isInvalidDecl())
2275    CheckCXXDefaultArguments(Method);
2276}
2277
2278/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
2279/// the well-formedness of the constructor declarator @p D with type @p
2280/// R. If there are any errors in the declarator, this routine will
2281/// emit diagnostics and set the invalid bit to true.  In any case, the type
2282/// will be updated to reflect a well-formed type for the constructor and
2283/// returned.
2284QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2285                                          FunctionDecl::StorageClass &SC) {
2286  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
2287
2288  // C++ [class.ctor]p3:
2289  //   A constructor shall not be virtual (10.3) or static (9.4). A
2290  //   constructor can be invoked for a const, volatile or const
2291  //   volatile object. A constructor shall not be declared const,
2292  //   volatile, or const volatile (9.3.2).
2293  if (isVirtual) {
2294    if (!D.isInvalidType())
2295      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2296        << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2297        << SourceRange(D.getIdentifierLoc());
2298    D.setInvalidType();
2299  }
2300  if (SC == FunctionDecl::Static) {
2301    if (!D.isInvalidType())
2302      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2303        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2304        << SourceRange(D.getIdentifierLoc());
2305    D.setInvalidType();
2306    SC = FunctionDecl::None;
2307  }
2308
2309  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2310  if (FTI.TypeQuals != 0) {
2311    if (FTI.TypeQuals & Qualifiers::Const)
2312      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2313        << "const" << SourceRange(D.getIdentifierLoc());
2314    if (FTI.TypeQuals & Qualifiers::Volatile)
2315      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2316        << "volatile" << SourceRange(D.getIdentifierLoc());
2317    if (FTI.TypeQuals & Qualifiers::Restrict)
2318      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2319        << "restrict" << SourceRange(D.getIdentifierLoc());
2320  }
2321
2322  // Rebuild the function type "R" without any type qualifiers (in
2323  // case any of the errors above fired) and with "void" as the
2324  // return type, since constructors don't have return types. We
2325  // *always* have to do this, because GetTypeForDeclarator will
2326  // put in a result type of "int" when none was specified.
2327  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
2328  return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2329                                 Proto->getNumArgs(),
2330                                 Proto->isVariadic(), 0);
2331}
2332
2333/// CheckConstructor - Checks a fully-formed constructor for
2334/// well-formedness, issuing any diagnostics required. Returns true if
2335/// the constructor declarator is invalid.
2336void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
2337  CXXRecordDecl *ClassDecl
2338    = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2339  if (!ClassDecl)
2340    return Constructor->setInvalidDecl();
2341
2342  // C++ [class.copy]p3:
2343  //   A declaration of a constructor for a class X is ill-formed if
2344  //   its first parameter is of type (optionally cv-qualified) X and
2345  //   either there are no other parameters or else all other
2346  //   parameters have default arguments.
2347  if (!Constructor->isInvalidDecl() &&
2348      ((Constructor->getNumParams() == 1) ||
2349       (Constructor->getNumParams() > 1 &&
2350        Constructor->getParamDecl(1)->hasDefaultArg())) &&
2351      Constructor->getTemplateSpecializationKind()
2352                                              != TSK_ImplicitInstantiation) {
2353    QualType ParamType = Constructor->getParamDecl(0)->getType();
2354    QualType ClassTy = Context.getTagDeclType(ClassDecl);
2355    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
2356      SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2357      Diag(ParamLoc, diag::err_constructor_byvalue_arg)
2358        << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
2359
2360      // FIXME: Rather that making the constructor invalid, we should endeavor
2361      // to fix the type.
2362      Constructor->setInvalidDecl();
2363    }
2364  }
2365
2366  // Notify the class that we've added a constructor.
2367  ClassDecl->addedConstructor(Context, Constructor);
2368}
2369
2370/// CheckDestructor - Checks a fully-formed destructor for
2371/// well-formedness, issuing any diagnostics required.
2372void Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
2373  CXXRecordDecl *RD = Destructor->getParent();
2374
2375  if (Destructor->isVirtual()) {
2376    SourceLocation Loc;
2377
2378    if (!Destructor->isImplicit())
2379      Loc = Destructor->getLocation();
2380    else
2381      Loc = RD->getLocation();
2382
2383    // If we have a virtual destructor, look up the deallocation function
2384    FunctionDecl *OperatorDelete = 0;
2385    DeclarationName Name =
2386    Context.DeclarationNames.getCXXOperatorName(OO_Delete);
2387    if (!FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2388      Destructor->setOperatorDelete(OperatorDelete);
2389  }
2390}
2391
2392static inline bool
2393FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2394  return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2395          FTI.ArgInfo[0].Param &&
2396          FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2397}
2398
2399/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2400/// the well-formednes of the destructor declarator @p D with type @p
2401/// R. If there are any errors in the declarator, this routine will
2402/// emit diagnostics and set the declarator to invalid.  Even if this happens,
2403/// will be updated to reflect a well-formed type for the destructor and
2404/// returned.
2405QualType Sema::CheckDestructorDeclarator(Declarator &D,
2406                                         FunctionDecl::StorageClass& SC) {
2407  // C++ [class.dtor]p1:
2408  //   [...] A typedef-name that names a class is a class-name
2409  //   (7.1.3); however, a typedef-name that names a class shall not
2410  //   be used as the identifier in the declarator for a destructor
2411  //   declaration.
2412  QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
2413  if (isa<TypedefType>(DeclaratorType)) {
2414    Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
2415      << DeclaratorType;
2416    D.setInvalidType();
2417  }
2418
2419  // C++ [class.dtor]p2:
2420  //   A destructor is used to destroy objects of its class type. A
2421  //   destructor takes no parameters, and no return type can be
2422  //   specified for it (not even void). The address of a destructor
2423  //   shall not be taken. A destructor shall not be static. A
2424  //   destructor can be invoked for a const, volatile or const
2425  //   volatile object. A destructor shall not be declared const,
2426  //   volatile or const volatile (9.3.2).
2427  if (SC == FunctionDecl::Static) {
2428    if (!D.isInvalidType())
2429      Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2430        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2431        << SourceRange(D.getIdentifierLoc());
2432    SC = FunctionDecl::None;
2433    D.setInvalidType();
2434  }
2435  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
2436    // Destructors don't have return types, but the parser will
2437    // happily parse something like:
2438    //
2439    //   class X {
2440    //     float ~X();
2441    //   };
2442    //
2443    // The return type will be eliminated later.
2444    Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2445      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2446      << SourceRange(D.getIdentifierLoc());
2447  }
2448
2449  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2450  if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
2451    if (FTI.TypeQuals & Qualifiers::Const)
2452      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2453        << "const" << SourceRange(D.getIdentifierLoc());
2454    if (FTI.TypeQuals & Qualifiers::Volatile)
2455      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2456        << "volatile" << SourceRange(D.getIdentifierLoc());
2457    if (FTI.TypeQuals & Qualifiers::Restrict)
2458      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2459        << "restrict" << SourceRange(D.getIdentifierLoc());
2460    D.setInvalidType();
2461  }
2462
2463  // Make sure we don't have any parameters.
2464  if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
2465    Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2466
2467    // Delete the parameters.
2468    FTI.freeArgs();
2469    D.setInvalidType();
2470  }
2471
2472  // Make sure the destructor isn't variadic.
2473  if (FTI.isVariadic) {
2474    Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
2475    D.setInvalidType();
2476  }
2477
2478  // Rebuild the function type "R" without any type qualifiers or
2479  // parameters (in case any of the errors above fired) and with
2480  // "void" as the return type, since destructors don't have return
2481  // types. We *always* have to do this, because GetTypeForDeclarator
2482  // will put in a result type of "int" when none was specified.
2483  return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
2484}
2485
2486/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2487/// well-formednes of the conversion function declarator @p D with
2488/// type @p R. If there are any errors in the declarator, this routine
2489/// will emit diagnostics and return true. Otherwise, it will return
2490/// false. Either way, the type @p R will be updated to reflect a
2491/// well-formed type for the conversion operator.
2492void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
2493                                     FunctionDecl::StorageClass& SC) {
2494  // C++ [class.conv.fct]p1:
2495  //   Neither parameter types nor return type can be specified. The
2496  //   type of a conversion function (8.3.5) is "function taking no
2497  //   parameter returning conversion-type-id."
2498  if (SC == FunctionDecl::Static) {
2499    if (!D.isInvalidType())
2500      Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2501        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2502        << SourceRange(D.getIdentifierLoc());
2503    D.setInvalidType();
2504    SC = FunctionDecl::None;
2505  }
2506  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
2507    // Conversion functions don't have return types, but the parser will
2508    // happily parse something like:
2509    //
2510    //   class X {
2511    //     float operator bool();
2512    //   };
2513    //
2514    // The return type will be changed later anyway.
2515    Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2516      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2517      << SourceRange(D.getIdentifierLoc());
2518  }
2519
2520  // Make sure we don't have any parameters.
2521  if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
2522    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2523
2524    // Delete the parameters.
2525    D.getTypeObject(0).Fun.freeArgs();
2526    D.setInvalidType();
2527  }
2528
2529  // Make sure the conversion function isn't variadic.
2530  if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
2531    Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
2532    D.setInvalidType();
2533  }
2534
2535  // C++ [class.conv.fct]p4:
2536  //   The conversion-type-id shall not represent a function type nor
2537  //   an array type.
2538  QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
2539  if (ConvType->isArrayType()) {
2540    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2541    ConvType = Context.getPointerType(ConvType);
2542    D.setInvalidType();
2543  } else if (ConvType->isFunctionType()) {
2544    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2545    ConvType = Context.getPointerType(ConvType);
2546    D.setInvalidType();
2547  }
2548
2549  // Rebuild the function type "R" without any parameters (in case any
2550  // of the errors above fired) and with the conversion type as the
2551  // return type.
2552  R = Context.getFunctionType(ConvType, 0, 0, false,
2553                              R->getAs<FunctionProtoType>()->getTypeQuals());
2554
2555  // C++0x explicit conversion operators.
2556  if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
2557    Diag(D.getDeclSpec().getExplicitSpecLoc(),
2558         diag::warn_explicit_conversion_functions)
2559      << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
2560}
2561
2562/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2563/// the declaration of the given C++ conversion function. This routine
2564/// is responsible for recording the conversion function in the C++
2565/// class, if possible.
2566Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
2567  assert(Conversion && "Expected to receive a conversion function declaration");
2568
2569  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
2570
2571  // Make sure we aren't redeclaring the conversion function.
2572  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
2573
2574  // C++ [class.conv.fct]p1:
2575  //   [...] A conversion function is never used to convert a
2576  //   (possibly cv-qualified) object to the (possibly cv-qualified)
2577  //   same object type (or a reference to it), to a (possibly
2578  //   cv-qualified) base class of that type (or a reference to it),
2579  //   or to (possibly cv-qualified) void.
2580  // FIXME: Suppress this warning if the conversion function ends up being a
2581  // virtual function that overrides a virtual function in a base class.
2582  QualType ClassType
2583    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
2584  if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
2585    ConvType = ConvTypeRef->getPointeeType();
2586  if (ConvType->isRecordType()) {
2587    ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2588    if (ConvType == ClassType)
2589      Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
2590        << ClassType;
2591    else if (IsDerivedFrom(ClassType, ConvType))
2592      Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
2593        <<  ClassType << ConvType;
2594  } else if (ConvType->isVoidType()) {
2595    Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
2596      << ClassType << ConvType;
2597  }
2598
2599  if (Conversion->getPreviousDeclaration()) {
2600    const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration();
2601    if (FunctionTemplateDecl *ConversionTemplate
2602          = Conversion->getDescribedFunctionTemplate())
2603      ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration();
2604    OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
2605    for (OverloadedFunctionDecl::function_iterator
2606           Conv = Conversions->function_begin(),
2607           ConvEnd = Conversions->function_end();
2608         Conv != ConvEnd; ++Conv) {
2609      if (*Conv == ExpectedPrevDecl) {
2610        *Conv = Conversion;
2611        return DeclPtrTy::make(Conversion);
2612      }
2613    }
2614    assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
2615  } else if (FunctionTemplateDecl *ConversionTemplate
2616               = Conversion->getDescribedFunctionTemplate())
2617    ClassDecl->addConversionFunction(ConversionTemplate);
2618  else if (!Conversion->getPrimaryTemplate()) // ignore specializations
2619    ClassDecl->addConversionFunction(Conversion);
2620
2621  return DeclPtrTy::make(Conversion);
2622}
2623
2624//===----------------------------------------------------------------------===//
2625// Namespace Handling
2626//===----------------------------------------------------------------------===//
2627
2628/// ActOnStartNamespaceDef - This is called at the start of a namespace
2629/// definition.
2630Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2631                                             SourceLocation IdentLoc,
2632                                             IdentifierInfo *II,
2633                                             SourceLocation LBrace) {
2634  NamespaceDecl *Namespc =
2635      NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2636  Namespc->setLBracLoc(LBrace);
2637
2638  Scope *DeclRegionScope = NamespcScope->getParent();
2639
2640  if (II) {
2641    // C++ [namespace.def]p2:
2642    // The identifier in an original-namespace-definition shall not have been
2643    // previously defined in the declarative region in which the
2644    // original-namespace-definition appears. The identifier in an
2645    // original-namespace-definition is the name of the namespace. Subsequently
2646    // in that declarative region, it is treated as an original-namespace-name.
2647
2648    NamedDecl *PrevDecl
2649      = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName, true);
2650
2651    if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2652      // This is an extended namespace definition.
2653      // Attach this namespace decl to the chain of extended namespace
2654      // definitions.
2655      OrigNS->setNextNamespace(Namespc);
2656      Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
2657
2658      // Remove the previous declaration from the scope.
2659      if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
2660        IdResolver.RemoveDecl(OrigNS);
2661        DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
2662      }
2663    } else if (PrevDecl) {
2664      // This is an invalid name redefinition.
2665      Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2666       << Namespc->getDeclName();
2667      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2668      Namespc->setInvalidDecl();
2669      // Continue on to push Namespc as current DeclContext and return it.
2670    } else if (II->isStr("std") &&
2671               CurContext->getLookupContext()->isTranslationUnit()) {
2672      // This is the first "real" definition of the namespace "std", so update
2673      // our cache of the "std" namespace to point at this definition.
2674      if (StdNamespace) {
2675        // We had already defined a dummy namespace "std". Link this new
2676        // namespace definition to the dummy namespace "std".
2677        StdNamespace->setNextNamespace(Namespc);
2678        StdNamespace->setLocation(IdentLoc);
2679        Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2680      }
2681
2682      // Make our StdNamespace cache point at the first real definition of the
2683      // "std" namespace.
2684      StdNamespace = Namespc;
2685    }
2686
2687    PushOnScopeChains(Namespc, DeclRegionScope);
2688  } else {
2689    // Anonymous namespaces.
2690
2691    // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
2692    //   behaves as if it were replaced by
2693    //     namespace unique { /* empty body */ }
2694    //     using namespace unique;
2695    //     namespace unique { namespace-body }
2696    //   where all occurrences of 'unique' in a translation unit are
2697    //   replaced by the same identifier and this identifier differs
2698    //   from all other identifiers in the entire program.
2699
2700    // We just create the namespace with an empty name and then add an
2701    // implicit using declaration, just like the standard suggests.
2702    //
2703    // CodeGen enforces the "universally unique" aspect by giving all
2704    // declarations semantically contained within an anonymous
2705    // namespace internal linkage.
2706
2707    assert(Namespc->isAnonymousNamespace());
2708    CurContext->addDecl(Namespc);
2709
2710    UsingDirectiveDecl* UD
2711      = UsingDirectiveDecl::Create(Context, CurContext,
2712                                   /* 'using' */ LBrace,
2713                                   /* 'namespace' */ SourceLocation(),
2714                                   /* qualifier */ SourceRange(),
2715                                   /* NNS */ NULL,
2716                                   /* identifier */ SourceLocation(),
2717                                   Namespc,
2718                                   /* Ancestor */ CurContext);
2719    UD->setImplicit();
2720    CurContext->addDecl(UD);
2721  }
2722
2723  // Although we could have an invalid decl (i.e. the namespace name is a
2724  // redefinition), push it as current DeclContext and try to continue parsing.
2725  // FIXME: We should be able to push Namespc here, so that the each DeclContext
2726  // for the namespace has the declarations that showed up in that particular
2727  // namespace definition.
2728  PushDeclContext(NamespcScope, Namespc);
2729  return DeclPtrTy::make(Namespc);
2730}
2731
2732/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2733/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
2734void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2735  Decl *Dcl = D.getAs<Decl>();
2736  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2737  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2738  Namespc->setRBracLoc(RBrace);
2739  PopDeclContext();
2740}
2741
2742Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2743                                          SourceLocation UsingLoc,
2744                                          SourceLocation NamespcLoc,
2745                                          const CXXScopeSpec &SS,
2746                                          SourceLocation IdentLoc,
2747                                          IdentifierInfo *NamespcName,
2748                                          AttributeList *AttrList) {
2749  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2750  assert(NamespcName && "Invalid NamespcName.");
2751  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
2752  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
2753
2754  UsingDirectiveDecl *UDir = 0;
2755
2756  // Lookup namespace name.
2757  LookupResult R;
2758  LookupParsedName(R, S, &SS, NamespcName, LookupNamespaceName, false);
2759  if (R.isAmbiguous()) {
2760    DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
2761    return DeclPtrTy();
2762  }
2763  if (!R.empty()) {
2764    NamedDecl *NS = R.getFoundDecl();
2765    // FIXME: Namespace aliases!
2766    assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
2767    // C++ [namespace.udir]p1:
2768    //   A using-directive specifies that the names in the nominated
2769    //   namespace can be used in the scope in which the
2770    //   using-directive appears after the using-directive. During
2771    //   unqualified name lookup (3.4.1), the names appear as if they
2772    //   were declared in the nearest enclosing namespace which
2773    //   contains both the using-directive and the nominated
2774    //   namespace. [Note: in this context, "contains" means "contains
2775    //   directly or indirectly". ]
2776
2777    // Find enclosing context containing both using-directive and
2778    // nominated namespace.
2779    DeclContext *CommonAncestor = cast<DeclContext>(NS);
2780    while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2781      CommonAncestor = CommonAncestor->getParent();
2782
2783    UDir = UsingDirectiveDecl::Create(Context,
2784                                      CurContext, UsingLoc,
2785                                      NamespcLoc,
2786                                      SS.getRange(),
2787                                      (NestedNameSpecifier *)SS.getScopeRep(),
2788                                      IdentLoc,
2789                                      cast<NamespaceDecl>(NS),
2790                                      CommonAncestor);
2791    PushUsingDirective(S, UDir);
2792  } else {
2793    Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
2794  }
2795
2796  // FIXME: We ignore attributes for now.
2797  delete AttrList;
2798  return DeclPtrTy::make(UDir);
2799}
2800
2801void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
2802  // If scope has associated entity, then using directive is at namespace
2803  // or translation unit scope. We add UsingDirectiveDecls, into
2804  // it's lookup structure.
2805  if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
2806    Ctx->addDecl(UDir);
2807  else
2808    // Otherwise it is block-sope. using-directives will affect lookup
2809    // only to the end of scope.
2810    S->PushUsingDirective(DeclPtrTy::make(UDir));
2811}
2812
2813
2814Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
2815                                            AccessSpecifier AS,
2816                                            SourceLocation UsingLoc,
2817                                            const CXXScopeSpec &SS,
2818                                            UnqualifiedId &Name,
2819                                            AttributeList *AttrList,
2820                                            bool IsTypeName) {
2821  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
2822
2823  switch (Name.getKind()) {
2824  case UnqualifiedId::IK_Identifier:
2825  case UnqualifiedId::IK_OperatorFunctionId:
2826  case UnqualifiedId::IK_ConversionFunctionId:
2827    break;
2828
2829  case UnqualifiedId::IK_ConstructorName:
2830    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
2831      << SS.getRange();
2832    return DeclPtrTy();
2833
2834  case UnqualifiedId::IK_DestructorName:
2835    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
2836      << SS.getRange();
2837    return DeclPtrTy();
2838
2839  case UnqualifiedId::IK_TemplateId:
2840    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
2841      << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
2842    return DeclPtrTy();
2843  }
2844
2845  DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
2846  NamedDecl *UD = BuildUsingDeclaration(UsingLoc, SS,
2847                                        Name.getSourceRange().getBegin(),
2848                                        TargetName, AttrList, IsTypeName);
2849  if (UD) {
2850    PushOnScopeChains(UD, S);
2851    UD->setAccess(AS);
2852  }
2853
2854  return DeclPtrTy::make(UD);
2855}
2856
2857NamedDecl *Sema::BuildUsingDeclaration(SourceLocation UsingLoc,
2858                                       const CXXScopeSpec &SS,
2859                                       SourceLocation IdentLoc,
2860                                       DeclarationName Name,
2861                                       AttributeList *AttrList,
2862                                       bool IsTypeName) {
2863  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2864  assert(IdentLoc.isValid() && "Invalid TargetName location.");
2865
2866  // FIXME: We ignore attributes for now.
2867  delete AttrList;
2868
2869  if (SS.isEmpty()) {
2870    Diag(IdentLoc, diag::err_using_requires_qualname);
2871    return 0;
2872  }
2873
2874  NestedNameSpecifier *NNS =
2875    static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2876
2877  DeclContext *LookupContext = computeDeclContext(SS);
2878  if (!LookupContext) {
2879    return UnresolvedUsingDecl::Create(Context, CurContext, UsingLoc,
2880                                       SS.getRange(), NNS,
2881                                       IdentLoc, Name, IsTypeName);
2882  }
2883
2884  if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
2885    // C++0x N2914 [namespace.udecl]p3:
2886    // A using-declaration used as a member-declaration shall refer to a member
2887    // of a base class of the class being defined, shall refer to a member of an
2888    // anonymous union that is a member of a base class of the class being
2889    // defined, or shall refer to an enumerator for an enumeration type that is
2890    // a member of a base class of the class being defined.
2891
2892    CXXRecordDecl *LookupRD = dyn_cast<CXXRecordDecl>(LookupContext);
2893    if (!LookupRD || !RD->isDerivedFrom(LookupRD)) {
2894      Diag(SS.getRange().getBegin(),
2895           diag::err_using_decl_nested_name_specifier_is_not_a_base_class)
2896        << NNS << RD->getDeclName();
2897      return 0;
2898    }
2899  } else {
2900    // C++0x N2914 [namespace.udecl]p8:
2901    // A using-declaration for a class member shall be a member-declaration.
2902    if (isa<CXXRecordDecl>(LookupContext)) {
2903      Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_class_member)
2904        << SS.getRange();
2905      return 0;
2906    }
2907  }
2908
2909  // Lookup target name.
2910  LookupResult R;
2911  LookupQualifiedName(R, LookupContext, Name, LookupOrdinaryName);
2912
2913  if (R.empty()) {
2914    Diag(IdentLoc, diag::err_no_member)
2915      << Name << LookupContext << SS.getRange();
2916    return 0;
2917  }
2918
2919  // FIXME: handle ambiguity?
2920  NamedDecl *ND = R.getAsSingleDecl(Context);
2921
2922  if (IsTypeName && !isa<TypeDecl>(ND)) {
2923    Diag(IdentLoc, diag::err_using_typename_non_type);
2924    return 0;
2925  }
2926
2927  // C++0x N2914 [namespace.udecl]p6:
2928  // A using-declaration shall not name a namespace.
2929  if (isa<NamespaceDecl>(ND)) {
2930    Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
2931      << SS.getRange();
2932    return 0;
2933  }
2934
2935  return UsingDecl::Create(Context, CurContext, IdentLoc, SS.getRange(),
2936                           ND->getLocation(), UsingLoc, ND, NNS, IsTypeName);
2937}
2938
2939/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2940/// is a namespace alias, returns the namespace it points to.
2941static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2942  if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2943    return AD->getNamespace();
2944  return dyn_cast_or_null<NamespaceDecl>(D);
2945}
2946
2947Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
2948                                             SourceLocation NamespaceLoc,
2949                                             SourceLocation AliasLoc,
2950                                             IdentifierInfo *Alias,
2951                                             const CXXScopeSpec &SS,
2952                                             SourceLocation IdentLoc,
2953                                             IdentifierInfo *Ident) {
2954
2955  // Lookup the namespace name.
2956  LookupResult R;
2957  LookupParsedName(R, S, &SS, Ident, LookupNamespaceName, false);
2958
2959  // Check if we have a previous declaration with the same name.
2960  if (NamedDecl *PrevDecl
2961        = LookupSingleName(S, Alias, LookupOrdinaryName, true)) {
2962    if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
2963      // We already have an alias with the same name that points to the same
2964      // namespace, so don't create a new one.
2965      if (!R.isAmbiguous() && !R.empty() &&
2966          AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
2967        return DeclPtrTy();
2968    }
2969
2970    unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
2971      diag::err_redefinition_different_kind;
2972    Diag(AliasLoc, DiagID) << Alias;
2973    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2974    return DeclPtrTy();
2975  }
2976
2977  if (R.isAmbiguous()) {
2978    DiagnoseAmbiguousLookup(R, Ident, IdentLoc);
2979    return DeclPtrTy();
2980  }
2981
2982  if (R.empty()) {
2983    Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
2984    return DeclPtrTy();
2985  }
2986
2987  NamespaceAliasDecl *AliasDecl =
2988    NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
2989                               Alias, SS.getRange(),
2990                               (NestedNameSpecifier *)SS.getScopeRep(),
2991                               IdentLoc, R.getFoundDecl());
2992
2993  CurContext->addDecl(AliasDecl);
2994  return DeclPtrTy::make(AliasDecl);
2995}
2996
2997void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
2998                                            CXXConstructorDecl *Constructor) {
2999  assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3000          !Constructor->isUsed()) &&
3001    "DefineImplicitDefaultConstructor - call it for implicit default ctor");
3002
3003  CXXRecordDecl *ClassDecl
3004    = cast<CXXRecordDecl>(Constructor->getDeclContext());
3005  assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
3006
3007  if (SetBaseOrMemberInitializers(Constructor, 0, 0, true)) {
3008    Diag(CurrentLocation, diag::note_ctor_synthesized_at)
3009      << Context.getTagDeclType(ClassDecl);
3010    Constructor->setInvalidDecl();
3011  } else {
3012    Constructor->setUsed();
3013  }
3014  return;
3015}
3016
3017void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
3018                                    CXXDestructorDecl *Destructor) {
3019  assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
3020         "DefineImplicitDestructor - call it for implicit default dtor");
3021  CXXRecordDecl *ClassDecl = Destructor->getParent();
3022  assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
3023  // C++ [class.dtor] p5
3024  // Before the implicitly-declared default destructor for a class is
3025  // implicitly defined, all the implicitly-declared default destructors
3026  // for its base class and its non-static data members shall have been
3027  // implicitly defined.
3028  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3029       E = ClassDecl->bases_end(); Base != E; ++Base) {
3030    CXXRecordDecl *BaseClassDecl
3031      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3032    if (!BaseClassDecl->hasTrivialDestructor()) {
3033      if (CXXDestructorDecl *BaseDtor =
3034          const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3035        MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3036      else
3037        assert(false &&
3038               "DefineImplicitDestructor - missing dtor in a base class");
3039    }
3040  }
3041
3042  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3043       E = ClassDecl->field_end(); Field != E; ++Field) {
3044    QualType FieldType = Context.getCanonicalType((*Field)->getType());
3045    if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3046      FieldType = Array->getElementType();
3047    if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
3048      CXXRecordDecl *FieldClassDecl
3049        = cast<CXXRecordDecl>(FieldClassType->getDecl());
3050      if (!FieldClassDecl->hasTrivialDestructor()) {
3051        if (CXXDestructorDecl *FieldDtor =
3052            const_cast<CXXDestructorDecl*>(
3053                                        FieldClassDecl->getDestructor(Context)))
3054          MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3055        else
3056          assert(false &&
3057          "DefineImplicitDestructor - missing dtor in class of a data member");
3058      }
3059    }
3060  }
3061  Destructor->setUsed();
3062}
3063
3064void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3065                                          CXXMethodDecl *MethodDecl) {
3066  assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3067          MethodDecl->getOverloadedOperator() == OO_Equal &&
3068          !MethodDecl->isUsed()) &&
3069         "DefineImplicitOverloadedAssign - call it for implicit assignment op");
3070
3071  CXXRecordDecl *ClassDecl
3072    = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
3073
3074  // C++[class.copy] p12
3075  // Before the implicitly-declared copy assignment operator for a class is
3076  // implicitly defined, all implicitly-declared copy assignment operators
3077  // for its direct base classes and its nonstatic data members shall have
3078  // been implicitly defined.
3079  bool err = false;
3080  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3081       E = ClassDecl->bases_end(); Base != E; ++Base) {
3082    CXXRecordDecl *BaseClassDecl
3083      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3084    if (CXXMethodDecl *BaseAssignOpMethod =
3085          getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl))
3086      MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3087  }
3088  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3089       E = ClassDecl->field_end(); Field != E; ++Field) {
3090    QualType FieldType = Context.getCanonicalType((*Field)->getType());
3091    if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3092      FieldType = Array->getElementType();
3093    if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
3094      CXXRecordDecl *FieldClassDecl
3095        = cast<CXXRecordDecl>(FieldClassType->getDecl());
3096      if (CXXMethodDecl *FieldAssignOpMethod =
3097          getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl))
3098        MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
3099    } else if (FieldType->isReferenceType()) {
3100      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
3101      << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3102      Diag(Field->getLocation(), diag::note_declared_at);
3103      Diag(CurrentLocation, diag::note_first_required_here);
3104      err = true;
3105    } else if (FieldType.isConstQualified()) {
3106      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
3107      << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3108      Diag(Field->getLocation(), diag::note_declared_at);
3109      Diag(CurrentLocation, diag::note_first_required_here);
3110      err = true;
3111    }
3112  }
3113  if (!err)
3114    MethodDecl->setUsed();
3115}
3116
3117CXXMethodDecl *
3118Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl,
3119                              CXXRecordDecl *ClassDecl) {
3120  QualType LHSType = Context.getTypeDeclType(ClassDecl);
3121  QualType RHSType(LHSType);
3122  // If class's assignment operator argument is const/volatile qualified,
3123  // look for operator = (const/volatile B&). Otherwise, look for
3124  // operator = (B&).
3125  RHSType = Context.getCVRQualifiedType(RHSType,
3126                                     ParmDecl->getType().getCVRQualifiers());
3127  ExprOwningPtr<Expr> LHS(this,  new (Context) DeclRefExpr(ParmDecl,
3128                                                          LHSType,
3129                                                          SourceLocation()));
3130  ExprOwningPtr<Expr> RHS(this,  new (Context) DeclRefExpr(ParmDecl,
3131                                                          RHSType,
3132                                                          SourceLocation()));
3133  Expr *Args[2] = { &*LHS, &*RHS };
3134  OverloadCandidateSet CandidateSet;
3135  AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
3136                              CandidateSet);
3137  OverloadCandidateSet::iterator Best;
3138  if (BestViableFunction(CandidateSet,
3139                         ClassDecl->getLocation(), Best) == OR_Success)
3140    return cast<CXXMethodDecl>(Best->Function);
3141  assert(false &&
3142         "getAssignOperatorMethod - copy assignment operator method not found");
3143  return 0;
3144}
3145
3146void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3147                                   CXXConstructorDecl *CopyConstructor,
3148                                   unsigned TypeQuals) {
3149  assert((CopyConstructor->isImplicit() &&
3150          CopyConstructor->isCopyConstructor(Context, TypeQuals) &&
3151          !CopyConstructor->isUsed()) &&
3152         "DefineImplicitCopyConstructor - call it for implicit copy ctor");
3153
3154  CXXRecordDecl *ClassDecl
3155    = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3156  assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
3157  // C++ [class.copy] p209
3158  // Before the implicitly-declared copy constructor for a class is
3159  // implicitly defined, all the implicitly-declared copy constructors
3160  // for its base class and its non-static data members shall have been
3161  // implicitly defined.
3162  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3163       Base != ClassDecl->bases_end(); ++Base) {
3164    CXXRecordDecl *BaseClassDecl
3165      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3166    if (CXXConstructorDecl *BaseCopyCtor =
3167        BaseClassDecl->getCopyConstructor(Context, TypeQuals))
3168      MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
3169  }
3170  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3171                                  FieldEnd = ClassDecl->field_end();
3172       Field != FieldEnd; ++Field) {
3173    QualType FieldType = Context.getCanonicalType((*Field)->getType());
3174    if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3175      FieldType = Array->getElementType();
3176    if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
3177      CXXRecordDecl *FieldClassDecl
3178        = cast<CXXRecordDecl>(FieldClassType->getDecl());
3179      if (CXXConstructorDecl *FieldCopyCtor =
3180          FieldClassDecl->getCopyConstructor(Context, TypeQuals))
3181        MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
3182    }
3183  }
3184  CopyConstructor->setUsed();
3185}
3186
3187Sema::OwningExprResult
3188Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3189                            CXXConstructorDecl *Constructor,
3190                            MultiExprArg ExprArgs) {
3191  bool Elidable = false;
3192
3193  // C++ [class.copy]p15:
3194  //   Whenever a temporary class object is copied using a copy constructor, and
3195  //   this object and the copy have the same cv-unqualified type, an
3196  //   implementation is permitted to treat the original and the copy as two
3197  //   different ways of referring to the same object and not perform a copy at
3198  //   all, even if the class copy constructor or destructor have side effects.
3199
3200  // FIXME: Is this enough?
3201  if (Constructor->isCopyConstructor(Context)) {
3202    Expr *E = ((Expr **)ExprArgs.get())[0];
3203    while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3204      E = BE->getSubExpr();
3205    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3206      if (ICE->getCastKind() == CastExpr::CK_NoOp)
3207        E = ICE->getSubExpr();
3208
3209    if (isa<CallExpr>(E) || isa<CXXTemporaryObjectExpr>(E))
3210      Elidable = true;
3211  }
3212
3213  return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
3214                               Elidable, move(ExprArgs));
3215}
3216
3217/// BuildCXXConstructExpr - Creates a complete call to a constructor,
3218/// including handling of its default argument expressions.
3219Sema::OwningExprResult
3220Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3221                            CXXConstructorDecl *Constructor, bool Elidable,
3222                            MultiExprArg ExprArgs) {
3223  unsigned NumExprs = ExprArgs.size();
3224  Expr **Exprs = (Expr **)ExprArgs.release();
3225
3226  return Owned(CXXConstructExpr::Create(Context, DeclInitType, Constructor,
3227                                        Elidable, Exprs, NumExprs));
3228}
3229
3230Sema::OwningExprResult
3231Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor,
3232                                  QualType Ty,
3233                                  SourceLocation TyBeginLoc,
3234                                  MultiExprArg Args,
3235                                  SourceLocation RParenLoc) {
3236  unsigned NumExprs = Args.size();
3237  Expr **Exprs = (Expr **)Args.release();
3238
3239  return Owned(new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty,
3240                                                    TyBeginLoc, Exprs,
3241                                                    NumExprs, RParenLoc));
3242}
3243
3244
3245bool Sema::InitializeVarWithConstructor(VarDecl *VD,
3246                                        CXXConstructorDecl *Constructor,
3247                                        MultiExprArg Exprs) {
3248  OwningExprResult TempResult =
3249    BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
3250                          move(Exprs));
3251  if (TempResult.isInvalid())
3252    return true;
3253
3254  Expr *Temp = TempResult.takeAs<Expr>();
3255  MarkDeclarationReferenced(VD->getLocation(), Constructor);
3256  Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true);
3257  VD->setInit(Context, Temp);
3258
3259  return false;
3260}
3261
3262void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) {
3263  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
3264                                  DeclInitType->getAs<RecordType>()->getDecl());
3265  if (!ClassDecl->hasTrivialDestructor())
3266    if (CXXDestructorDecl *Destructor =
3267        const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
3268      MarkDeclarationReferenced(VD->getLocation(), Destructor);
3269}
3270
3271/// AddCXXDirectInitializerToDecl - This action is called immediately after
3272/// ActOnDeclarator, when a C++ direct initializer is present.
3273/// e.g: "int x(1);"
3274void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
3275                                         SourceLocation LParenLoc,
3276                                         MultiExprArg Exprs,
3277                                         SourceLocation *CommaLocs,
3278                                         SourceLocation RParenLoc) {
3279  unsigned NumExprs = Exprs.size();
3280  assert(NumExprs != 0 && Exprs.get() && "missing expressions");
3281  Decl *RealDecl = Dcl.getAs<Decl>();
3282
3283  // If there is no declaration, there was an error parsing it.  Just ignore
3284  // the initializer.
3285  if (RealDecl == 0)
3286    return;
3287
3288  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3289  if (!VDecl) {
3290    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3291    RealDecl->setInvalidDecl();
3292    return;
3293  }
3294
3295  // We will represent direct-initialization similarly to copy-initialization:
3296  //    int x(1);  -as-> int x = 1;
3297  //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
3298  //
3299  // Clients that want to distinguish between the two forms, can check for
3300  // direct initializer using VarDecl::hasCXXDirectInitializer().
3301  // A major benefit is that clients that don't particularly care about which
3302  // exactly form was it (like the CodeGen) can handle both cases without
3303  // special case code.
3304
3305  // If either the declaration has a dependent type or if any of the expressions
3306  // is type-dependent, we represent the initialization via a ParenListExpr for
3307  // later use during template instantiation.
3308  if (VDecl->getType()->isDependentType() ||
3309      Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
3310    // Let clients know that initialization was done with a direct initializer.
3311    VDecl->setCXXDirectInitializer(true);
3312
3313    // Store the initialization expressions as a ParenListExpr.
3314    unsigned NumExprs = Exprs.size();
3315    VDecl->setInit(Context,
3316                   new (Context) ParenListExpr(Context, LParenLoc,
3317                                               (Expr **)Exprs.release(),
3318                                               NumExprs, RParenLoc));
3319    return;
3320  }
3321
3322
3323  // C++ 8.5p11:
3324  // The form of initialization (using parentheses or '=') is generally
3325  // insignificant, but does matter when the entity being initialized has a
3326  // class type.
3327  QualType DeclInitType = VDecl->getType();
3328  if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
3329    DeclInitType = Context.getBaseElementType(Array);
3330
3331  // FIXME: This isn't the right place to complete the type.
3332  if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
3333                          diag::err_typecheck_decl_incomplete_type)) {
3334    VDecl->setInvalidDecl();
3335    return;
3336  }
3337
3338  if (VDecl->getType()->isRecordType()) {
3339    ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
3340
3341    CXXConstructorDecl *Constructor
3342      = PerformInitializationByConstructor(DeclInitType,
3343                                           move(Exprs),
3344                                           VDecl->getLocation(),
3345                                           SourceRange(VDecl->getLocation(),
3346                                                       RParenLoc),
3347                                           VDecl->getDeclName(),
3348                                           IK_Direct,
3349                                           ConstructorArgs);
3350    if (!Constructor)
3351      RealDecl->setInvalidDecl();
3352    else {
3353      VDecl->setCXXDirectInitializer(true);
3354      if (InitializeVarWithConstructor(VDecl, Constructor,
3355                                       move_arg(ConstructorArgs)))
3356        RealDecl->setInvalidDecl();
3357      FinalizeVarWithDestructor(VDecl, DeclInitType);
3358    }
3359    return;
3360  }
3361
3362  if (NumExprs > 1) {
3363    Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
3364      << SourceRange(VDecl->getLocation(), RParenLoc);
3365    RealDecl->setInvalidDecl();
3366    return;
3367  }
3368
3369  // Let clients know that initialization was done with a direct initializer.
3370  VDecl->setCXXDirectInitializer(true);
3371
3372  assert(NumExprs == 1 && "Expected 1 expression");
3373  // Set the init expression, handles conversions.
3374  AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
3375                       /*DirectInit=*/true);
3376}
3377
3378/// \brief Add the applicable constructor candidates for an initialization
3379/// by constructor.
3380static void AddConstructorInitializationCandidates(Sema &SemaRef,
3381                                                   QualType ClassType,
3382                                                   Expr **Args,
3383                                                   unsigned NumArgs,
3384                                                  Sema::InitializationKind Kind,
3385                                           OverloadCandidateSet &CandidateSet) {
3386  // C++ [dcl.init]p14:
3387  //   If the initialization is direct-initialization, or if it is
3388  //   copy-initialization where the cv-unqualified version of the
3389  //   source type is the same class as, or a derived class of, the
3390  //   class of the destination, constructors are considered. The
3391  //   applicable constructors are enumerated (13.3.1.3), and the
3392  //   best one is chosen through overload resolution (13.3). The
3393  //   constructor so selected is called to initialize the object,
3394  //   with the initializer expression(s) as its argument(s). If no
3395  //   constructor applies, or the overload resolution is ambiguous,
3396  //   the initialization is ill-formed.
3397  const RecordType *ClassRec = ClassType->getAs<RecordType>();
3398  assert(ClassRec && "Can only initialize a class type here");
3399
3400  // FIXME: When we decide not to synthesize the implicitly-declared
3401  // constructors, we'll need to make them appear here.
3402
3403  const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
3404  DeclarationName ConstructorName
3405    = SemaRef.Context.DeclarationNames.getCXXConstructorName(
3406              SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType());
3407  DeclContext::lookup_const_iterator Con, ConEnd;
3408  for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
3409       Con != ConEnd; ++Con) {
3410    // Find the constructor (which may be a template).
3411    CXXConstructorDecl *Constructor = 0;
3412    FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
3413    if (ConstructorTmpl)
3414      Constructor
3415      = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3416    else
3417      Constructor = cast<CXXConstructorDecl>(*Con);
3418
3419    if ((Kind == Sema::IK_Direct) ||
3420        (Kind == Sema::IK_Copy &&
3421         Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
3422        (Kind == Sema::IK_Default && Constructor->isDefaultConstructor())) {
3423      if (ConstructorTmpl)
3424        SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0,
3425                                             Args, NumArgs, CandidateSet);
3426      else
3427        SemaRef.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
3428    }
3429  }
3430}
3431
3432/// \brief Attempt to perform initialization by constructor
3433/// (C++ [dcl.init]p14), which may occur as part of direct-initialization or
3434/// copy-initialization.
3435///
3436/// This routine determines whether initialization by constructor is possible,
3437/// but it does not emit any diagnostics in the case where the initialization
3438/// is ill-formed.
3439///
3440/// \param ClassType the type of the object being initialized, which must have
3441/// class type.
3442///
3443/// \param Args the arguments provided to initialize the object
3444///
3445/// \param NumArgs the number of arguments provided to initialize the object
3446///
3447/// \param Kind the type of initialization being performed
3448///
3449/// \returns the constructor used to initialize the object, if successful.
3450/// Otherwise, emits a diagnostic and returns NULL.
3451CXXConstructorDecl *
3452Sema::TryInitializationByConstructor(QualType ClassType,
3453                                     Expr **Args, unsigned NumArgs,
3454                                     SourceLocation Loc,
3455                                     InitializationKind Kind) {
3456  // Build the overload candidate set
3457  OverloadCandidateSet CandidateSet;
3458  AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
3459                                         CandidateSet);
3460
3461  // Determine whether we found a constructor we can use.
3462  OverloadCandidateSet::iterator Best;
3463  switch (BestViableFunction(CandidateSet, Loc, Best)) {
3464    case OR_Success:
3465    case OR_Deleted:
3466      // We found a constructor. Return it.
3467      return cast<CXXConstructorDecl>(Best->Function);
3468
3469    case OR_No_Viable_Function:
3470    case OR_Ambiguous:
3471      // Overload resolution failed. Return nothing.
3472      return 0;
3473  }
3474
3475  // Silence GCC warning
3476  return 0;
3477}
3478
3479/// \brief Perform initialization by constructor (C++ [dcl.init]p14), which
3480/// may occur as part of direct-initialization or copy-initialization.
3481///
3482/// \param ClassType the type of the object being initialized, which must have
3483/// class type.
3484///
3485/// \param ArgsPtr the arguments provided to initialize the object
3486///
3487/// \param Loc the source location where the initialization occurs
3488///
3489/// \param Range the source range that covers the entire initialization
3490///
3491/// \param InitEntity the name of the entity being initialized, if known
3492///
3493/// \param Kind the type of initialization being performed
3494///
3495/// \param ConvertedArgs a vector that will be filled in with the
3496/// appropriately-converted arguments to the constructor (if initialization
3497/// succeeded).
3498///
3499/// \returns the constructor used to initialize the object, if successful.
3500/// Otherwise, emits a diagnostic and returns NULL.
3501CXXConstructorDecl *
3502Sema::PerformInitializationByConstructor(QualType ClassType,
3503                                         MultiExprArg ArgsPtr,
3504                                         SourceLocation Loc, SourceRange Range,
3505                                         DeclarationName InitEntity,
3506                                         InitializationKind Kind,
3507                      ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
3508
3509  // Build the overload candidate set
3510  Expr **Args = (Expr **)ArgsPtr.get();
3511  unsigned NumArgs = ArgsPtr.size();
3512  OverloadCandidateSet CandidateSet;
3513  AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
3514                                         CandidateSet);
3515
3516  OverloadCandidateSet::iterator Best;
3517  switch (BestViableFunction(CandidateSet, Loc, Best)) {
3518  case OR_Success:
3519    // We found a constructor. Break out so that we can convert the arguments
3520    // appropriately.
3521    break;
3522
3523  case OR_No_Viable_Function:
3524    if (InitEntity)
3525      Diag(Loc, diag::err_ovl_no_viable_function_in_init)
3526        << InitEntity << Range;
3527    else
3528      Diag(Loc, diag::err_ovl_no_viable_function_in_init)
3529        << ClassType << Range;
3530    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3531    return 0;
3532
3533  case OR_Ambiguous:
3534    if (InitEntity)
3535      Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
3536    else
3537      Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
3538    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3539    return 0;
3540
3541  case OR_Deleted:
3542    if (InitEntity)
3543      Diag(Loc, diag::err_ovl_deleted_init)
3544        << Best->Function->isDeleted()
3545        << InitEntity << Range;
3546    else
3547      Diag(Loc, diag::err_ovl_deleted_init)
3548        << Best->Function->isDeleted()
3549        << InitEntity << Range;
3550    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3551    return 0;
3552  }
3553
3554  // Convert the arguments, fill in default arguments, etc.
3555  CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3556  if (CompleteConstructorCall(Constructor, move(ArgsPtr), Loc, ConvertedArgs))
3557    return 0;
3558
3559  return Constructor;
3560}
3561
3562/// \brief Given a constructor and the set of arguments provided for the
3563/// constructor, convert the arguments and add any required default arguments
3564/// to form a proper call to this constructor.
3565///
3566/// \returns true if an error occurred, false otherwise.
3567bool
3568Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
3569                              MultiExprArg ArgsPtr,
3570                              SourceLocation Loc,
3571                     ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
3572  // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
3573  unsigned NumArgs = ArgsPtr.size();
3574  Expr **Args = (Expr **)ArgsPtr.get();
3575
3576  const FunctionProtoType *Proto
3577    = Constructor->getType()->getAs<FunctionProtoType>();
3578  assert(Proto && "Constructor without a prototype?");
3579  unsigned NumArgsInProto = Proto->getNumArgs();
3580  unsigned NumArgsToCheck = NumArgs;
3581
3582  // If too few arguments are available, we'll fill in the rest with defaults.
3583  if (NumArgs < NumArgsInProto) {
3584    NumArgsToCheck = NumArgsInProto;
3585    ConvertedArgs.reserve(NumArgsInProto);
3586  } else {
3587    ConvertedArgs.reserve(NumArgs);
3588    if (NumArgs > NumArgsInProto)
3589      NumArgsToCheck = NumArgsInProto;
3590  }
3591
3592  // Convert arguments
3593  for (unsigned i = 0; i != NumArgsToCheck; i++) {
3594    QualType ProtoArgType = Proto->getArgType(i);
3595
3596    Expr *Arg;
3597    if (i < NumArgs) {
3598      Arg = Args[i];
3599
3600      // Pass the argument.
3601      if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3602        return true;
3603
3604      Args[i] = 0;
3605    } else {
3606      ParmVarDecl *Param = Constructor->getParamDecl(i);
3607
3608      OwningExprResult DefArg = BuildCXXDefaultArgExpr(Loc, Constructor, Param);
3609      if (DefArg.isInvalid())
3610        return true;
3611
3612      Arg = DefArg.takeAs<Expr>();
3613    }
3614
3615    ConvertedArgs.push_back(Arg);
3616  }
3617
3618  // If this is a variadic call, handle args passed through "...".
3619  if (Proto->isVariadic()) {
3620    // Promote the arguments (C99 6.5.2.2p7).
3621    for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
3622      Expr *Arg = Args[i];
3623      if (DefaultVariadicArgumentPromotion(Arg, VariadicConstructor))
3624        return true;
3625
3626      ConvertedArgs.push_back(Arg);
3627      Args[i] = 0;
3628    }
3629  }
3630
3631  return false;
3632}
3633
3634/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3635/// determine whether they are reference-related,
3636/// reference-compatible, reference-compatible with added
3637/// qualification, or incompatible, for use in C++ initialization by
3638/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3639/// type, and the first type (T1) is the pointee type of the reference
3640/// type being initialized.
3641Sema::ReferenceCompareResult
3642Sema::CompareReferenceRelationship(SourceLocation Loc,
3643                                   QualType OrigT1, QualType OrigT2,
3644                                   bool& DerivedToBase) {
3645  assert(!OrigT1->isReferenceType() &&
3646    "T1 must be the pointee type of the reference type");
3647  assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3648
3649  QualType T1 = Context.getCanonicalType(OrigT1);
3650  QualType T2 = Context.getCanonicalType(OrigT2);
3651  QualType UnqualT1 = T1.getLocalUnqualifiedType();
3652  QualType UnqualT2 = T2.getLocalUnqualifiedType();
3653
3654  // C++ [dcl.init.ref]p4:
3655  //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3656  //   reference-related to "cv2 T2" if T1 is the same type as T2, or
3657  //   T1 is a base class of T2.
3658  if (UnqualT1 == UnqualT2)
3659    DerivedToBase = false;
3660  else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
3661           !RequireCompleteType(Loc, OrigT2, PDiag()) &&
3662           IsDerivedFrom(UnqualT2, UnqualT1))
3663    DerivedToBase = true;
3664  else
3665    return Ref_Incompatible;
3666
3667  // At this point, we know that T1 and T2 are reference-related (at
3668  // least).
3669
3670  // C++ [dcl.init.ref]p4:
3671  //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3672  //   reference-related to T2 and cv1 is the same cv-qualification
3673  //   as, or greater cv-qualification than, cv2. For purposes of
3674  //   overload resolution, cases for which cv1 is greater
3675  //   cv-qualification than cv2 are identified as
3676  //   reference-compatible with added qualification (see 13.3.3.2).
3677  if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3678    return Ref_Compatible;
3679  else if (T1.isMoreQualifiedThan(T2))
3680    return Ref_Compatible_With_Added_Qualification;
3681  else
3682    return Ref_Related;
3683}
3684
3685/// CheckReferenceInit - Check the initialization of a reference
3686/// variable with the given initializer (C++ [dcl.init.ref]). Init is
3687/// the initializer (either a simple initializer or an initializer
3688/// list), and DeclType is the type of the declaration. When ICS is
3689/// non-null, this routine will compute the implicit conversion
3690/// sequence according to C++ [over.ics.ref] and will not produce any
3691/// diagnostics; when ICS is null, it will emit diagnostics when any
3692/// errors are found. Either way, a return value of true indicates
3693/// that there was a failure, a return value of false indicates that
3694/// the reference initialization succeeded.
3695///
3696/// When @p SuppressUserConversions, user-defined conversions are
3697/// suppressed.
3698/// When @p AllowExplicit, we also permit explicit user-defined
3699/// conversion functions.
3700/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
3701/// When @p IgnoreBaseAccess, we don't do access control on to-base conversion.
3702/// This is used when this is called from a C-style cast.
3703bool
3704Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
3705                         SourceLocation DeclLoc,
3706                         bool SuppressUserConversions,
3707                         bool AllowExplicit, bool ForceRValue,
3708                         ImplicitConversionSequence *ICS,
3709                         bool IgnoreBaseAccess) {
3710  assert(DeclType->isReferenceType() && "Reference init needs a reference");
3711
3712  QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3713  QualType T2 = Init->getType();
3714
3715  // If the initializer is the address of an overloaded function, try
3716  // to resolve the overloaded function. If all goes well, T2 is the
3717  // type of the resulting function.
3718  if (Context.getCanonicalType(T2) == Context.OverloadTy) {
3719    FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
3720                                                          ICS != 0);
3721    if (Fn) {
3722      // Since we're performing this reference-initialization for
3723      // real, update the initializer with the resulting function.
3724      if (!ICS) {
3725        if (DiagnoseUseOfDecl(Fn, DeclLoc))
3726          return true;
3727
3728        Init = FixOverloadedFunctionReference(Init, Fn);
3729      }
3730
3731      T2 = Fn->getType();
3732    }
3733  }
3734
3735  // Compute some basic properties of the types and the initializer.
3736  bool isRValRef = DeclType->isRValueReferenceType();
3737  bool DerivedToBase = false;
3738  Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
3739                                                  Init->isLvalue(Context);
3740  ReferenceCompareResult RefRelationship
3741    = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
3742
3743  // Most paths end in a failed conversion.
3744  if (ICS)
3745    ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
3746
3747  // C++ [dcl.init.ref]p5:
3748  //   A reference to type "cv1 T1" is initialized by an expression
3749  //   of type "cv2 T2" as follows:
3750
3751  //     -- If the initializer expression
3752
3753  // Rvalue references cannot bind to lvalues (N2812).
3754  // There is absolutely no situation where they can. In particular, note that
3755  // this is ill-formed, even if B has a user-defined conversion to A&&:
3756  //   B b;
3757  //   A&& r = b;
3758  if (isRValRef && InitLvalue == Expr::LV_Valid) {
3759    if (!ICS)
3760      Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
3761        << Init->getSourceRange();
3762    return true;
3763  }
3764
3765  bool BindsDirectly = false;
3766  //       -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3767  //          reference-compatible with "cv2 T2," or
3768  //
3769  // Note that the bit-field check is skipped if we are just computing
3770  // the implicit conversion sequence (C++ [over.best.ics]p2).
3771  if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
3772      RefRelationship >= Ref_Compatible_With_Added_Qualification) {
3773    BindsDirectly = true;
3774
3775    if (ICS) {
3776      // C++ [over.ics.ref]p1:
3777      //   When a parameter of reference type binds directly (8.5.3)
3778      //   to an argument expression, the implicit conversion sequence
3779      //   is the identity conversion, unless the argument expression
3780      //   has a type that is a derived class of the parameter type,
3781      //   in which case the implicit conversion sequence is a
3782      //   derived-to-base Conversion (13.3.3.1).
3783      ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3784      ICS->Standard.First = ICK_Identity;
3785      ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3786      ICS->Standard.Third = ICK_Identity;
3787      ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3788      ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
3789      ICS->Standard.ReferenceBinding = true;
3790      ICS->Standard.DirectBinding = true;
3791      ICS->Standard.RRefBinding = false;
3792      ICS->Standard.CopyConstructor = 0;
3793
3794      // Nothing more to do: the inaccessibility/ambiguity check for
3795      // derived-to-base conversions is suppressed when we're
3796      // computing the implicit conversion sequence (C++
3797      // [over.best.ics]p2).
3798      return false;
3799    } else {
3800      // Perform the conversion.
3801      CastExpr::CastKind CK = CastExpr::CK_NoOp;
3802      if (DerivedToBase)
3803        CK = CastExpr::CK_DerivedToBase;
3804      else if(CheckExceptionSpecCompatibility(Init, T1))
3805        return true;
3806      ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
3807    }
3808  }
3809
3810  //       -- has a class type (i.e., T2 is a class type) and can be
3811  //          implicitly converted to an lvalue of type "cv3 T3,"
3812  //          where "cv1 T1" is reference-compatible with "cv3 T3"
3813  //          92) (this conversion is selected by enumerating the
3814  //          applicable conversion functions (13.3.1.6) and choosing
3815  //          the best one through overload resolution (13.3)),
3816  if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
3817      !RequireCompleteType(DeclLoc, T2, 0)) {
3818    CXXRecordDecl *T2RecordDecl
3819      = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3820
3821    OverloadCandidateSet CandidateSet;
3822    OverloadedFunctionDecl *Conversions
3823      = T2RecordDecl->getVisibleConversionFunctions();
3824    for (OverloadedFunctionDecl::function_iterator Func
3825           = Conversions->function_begin();
3826         Func != Conversions->function_end(); ++Func) {
3827      FunctionTemplateDecl *ConvTemplate
3828        = dyn_cast<FunctionTemplateDecl>(*Func);
3829      CXXConversionDecl *Conv;
3830      if (ConvTemplate)
3831        Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3832      else
3833        Conv = cast<CXXConversionDecl>(*Func);
3834
3835      // If the conversion function doesn't return a reference type,
3836      // it can't be considered for this conversion.
3837      if (Conv->getConversionType()->isLValueReferenceType() &&
3838          (AllowExplicit || !Conv->isExplicit())) {
3839        if (ConvTemplate)
3840          AddTemplateConversionCandidate(ConvTemplate, Init, DeclType,
3841                                         CandidateSet);
3842        else
3843          AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
3844      }
3845    }
3846
3847    OverloadCandidateSet::iterator Best;
3848    switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
3849    case OR_Success:
3850      // This is a direct binding.
3851      BindsDirectly = true;
3852
3853      if (ICS) {
3854        // C++ [over.ics.ref]p1:
3855        //
3856        //   [...] If the parameter binds directly to the result of
3857        //   applying a conversion function to the argument
3858        //   expression, the implicit conversion sequence is a
3859        //   user-defined conversion sequence (13.3.3.1.2), with the
3860        //   second standard conversion sequence either an identity
3861        //   conversion or, if the conversion function returns an
3862        //   entity of a type that is a derived class of the parameter
3863        //   type, a derived-to-base Conversion.
3864        ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
3865        ICS->UserDefined.Before = Best->Conversions[0].Standard;
3866        ICS->UserDefined.After = Best->FinalConversion;
3867        ICS->UserDefined.ConversionFunction = Best->Function;
3868        ICS->UserDefined.EllipsisConversion = false;
3869        assert(ICS->UserDefined.After.ReferenceBinding &&
3870               ICS->UserDefined.After.DirectBinding &&
3871               "Expected a direct reference binding!");
3872        return false;
3873      } else {
3874        OwningExprResult InitConversion =
3875          BuildCXXCastArgument(DeclLoc, QualType(),
3876                               CastExpr::CK_UserDefinedConversion,
3877                               cast<CXXMethodDecl>(Best->Function),
3878                               Owned(Init));
3879        Init = InitConversion.takeAs<Expr>();
3880
3881        if (CheckExceptionSpecCompatibility(Init, T1))
3882          return true;
3883        ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
3884                          /*isLvalue=*/true);
3885      }
3886      break;
3887
3888    case OR_Ambiguous:
3889      if (ICS) {
3890        for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3891             Cand != CandidateSet.end(); ++Cand)
3892          if (Cand->Viable)
3893            ICS->ConversionFunctionSet.push_back(Cand->Function);
3894        break;
3895      }
3896      Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
3897            << Init->getSourceRange();
3898      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3899      return true;
3900
3901    case OR_No_Viable_Function:
3902    case OR_Deleted:
3903      // There was no suitable conversion, or we found a deleted
3904      // conversion; continue with other checks.
3905      break;
3906    }
3907  }
3908
3909  if (BindsDirectly) {
3910    // C++ [dcl.init.ref]p4:
3911    //   [...] In all cases where the reference-related or
3912    //   reference-compatible relationship of two types is used to
3913    //   establish the validity of a reference binding, and T1 is a
3914    //   base class of T2, a program that necessitates such a binding
3915    //   is ill-formed if T1 is an inaccessible (clause 11) or
3916    //   ambiguous (10.2) base class of T2.
3917    //
3918    // Note that we only check this condition when we're allowed to
3919    // complain about errors, because we should not be checking for
3920    // ambiguity (or inaccessibility) unless the reference binding
3921    // actually happens.
3922    if (DerivedToBase)
3923      return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
3924                                          Init->getSourceRange(),
3925                                          IgnoreBaseAccess);
3926    else
3927      return false;
3928  }
3929
3930  //     -- Otherwise, the reference shall be to a non-volatile const
3931  //        type (i.e., cv1 shall be const), or the reference shall be an
3932  //        rvalue reference and the initializer expression shall be an rvalue.
3933  if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
3934    if (!ICS)
3935      Diag(DeclLoc, diag::err_not_reference_to_const_init)
3936        << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3937        << T2 << Init->getSourceRange();
3938    return true;
3939  }
3940
3941  //       -- If the initializer expression is an rvalue, with T2 a
3942  //          class type, and "cv1 T1" is reference-compatible with
3943  //          "cv2 T2," the reference is bound in one of the
3944  //          following ways (the choice is implementation-defined):
3945  //
3946  //          -- The reference is bound to the object represented by
3947  //             the rvalue (see 3.10) or to a sub-object within that
3948  //             object.
3949  //
3950  //          -- A temporary of type "cv1 T2" [sic] is created, and
3951  //             a constructor is called to copy the entire rvalue
3952  //             object into the temporary. The reference is bound to
3953  //             the temporary or to a sub-object within the
3954  //             temporary.
3955  //
3956  //          The constructor that would be used to make the copy
3957  //          shall be callable whether or not the copy is actually
3958  //          done.
3959  //
3960  // Note that C++0x [dcl.init.ref]p5 takes away this implementation
3961  // freedom, so we will always take the first option and never build
3962  // a temporary in this case. FIXME: We will, however, have to check
3963  // for the presence of a copy constructor in C++98/03 mode.
3964  if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
3965      RefRelationship >= Ref_Compatible_With_Added_Qualification) {
3966    if (ICS) {
3967      ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3968      ICS->Standard.First = ICK_Identity;
3969      ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3970      ICS->Standard.Third = ICK_Identity;
3971      ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3972      ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
3973      ICS->Standard.ReferenceBinding = true;
3974      ICS->Standard.DirectBinding = false;
3975      ICS->Standard.RRefBinding = isRValRef;
3976      ICS->Standard.CopyConstructor = 0;
3977    } else {
3978      CastExpr::CastKind CK = CastExpr::CK_NoOp;
3979      if (DerivedToBase)
3980        CK = CastExpr::CK_DerivedToBase;
3981      else if(CheckExceptionSpecCompatibility(Init, T1))
3982        return true;
3983      ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
3984    }
3985    return false;
3986  }
3987
3988  //       -- Otherwise, a temporary of type "cv1 T1" is created and
3989  //          initialized from the initializer expression using the
3990  //          rules for a non-reference copy initialization (8.5). The
3991  //          reference is then bound to the temporary. If T1 is
3992  //          reference-related to T2, cv1 must be the same
3993  //          cv-qualification as, or greater cv-qualification than,
3994  //          cv2; otherwise, the program is ill-formed.
3995  if (RefRelationship == Ref_Related) {
3996    // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3997    // we would be reference-compatible or reference-compatible with
3998    // added qualification. But that wasn't the case, so the reference
3999    // initialization fails.
4000    if (!ICS)
4001      Diag(DeclLoc, diag::err_reference_init_drops_quals)
4002        << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
4003        << T2 << Init->getSourceRange();
4004    return true;
4005  }
4006
4007  // If at least one of the types is a class type, the types are not
4008  // related, and we aren't allowed any user conversions, the
4009  // reference binding fails. This case is important for breaking
4010  // recursion, since TryImplicitConversion below will attempt to
4011  // create a temporary through the use of a copy constructor.
4012  if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
4013      (T1->isRecordType() || T2->isRecordType())) {
4014    if (!ICS)
4015      Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
4016        << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
4017    return true;
4018  }
4019
4020  // Actually try to convert the initializer to T1.
4021  if (ICS) {
4022    // C++ [over.ics.ref]p2:
4023    //
4024    //   When a parameter of reference type is not bound directly to
4025    //   an argument expression, the conversion sequence is the one
4026    //   required to convert the argument expression to the
4027    //   underlying type of the reference according to
4028    //   13.3.3.1. Conceptually, this conversion sequence corresponds
4029    //   to copy-initializing a temporary of the underlying type with
4030    //   the argument expression. Any difference in top-level
4031    //   cv-qualification is subsumed by the initialization itself
4032    //   and does not constitute a conversion.
4033    *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
4034                                 /*AllowExplicit=*/false,
4035                                 /*ForceRValue=*/false,
4036                                 /*InOverloadResolution=*/false);
4037
4038    // Of course, that's still a reference binding.
4039    if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
4040      ICS->Standard.ReferenceBinding = true;
4041      ICS->Standard.RRefBinding = isRValRef;
4042    } else if (ICS->ConversionKind ==
4043              ImplicitConversionSequence::UserDefinedConversion) {
4044      ICS->UserDefined.After.ReferenceBinding = true;
4045      ICS->UserDefined.After.RRefBinding = isRValRef;
4046    }
4047    return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
4048  } else {
4049    ImplicitConversionSequence Conversions;
4050    bool badConversion = PerformImplicitConversion(Init, T1, "initializing",
4051                                                   false, false,
4052                                                   Conversions);
4053    if (badConversion) {
4054      if ((Conversions.ConversionKind  ==
4055            ImplicitConversionSequence::BadConversion)
4056          && !Conversions.ConversionFunctionSet.empty()) {
4057        Diag(DeclLoc,
4058             diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
4059        for (int j = Conversions.ConversionFunctionSet.size()-1;
4060             j >= 0; j--) {
4061          FunctionDecl *Func = Conversions.ConversionFunctionSet[j];
4062          Diag(Func->getLocation(), diag::err_ovl_candidate);
4063        }
4064      }
4065      else {
4066        if (isRValRef)
4067          Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4068            << Init->getSourceRange();
4069        else
4070          Diag(DeclLoc, diag::err_invalid_initialization)
4071            << DeclType << Init->getType() << Init->getSourceRange();
4072      }
4073    }
4074    return badConversion;
4075  }
4076}
4077
4078/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4079/// of this overloaded operator is well-formed. If so, returns false;
4080/// otherwise, emits appropriate diagnostics and returns true.
4081bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
4082  assert(FnDecl && FnDecl->isOverloadedOperator() &&
4083         "Expected an overloaded operator declaration");
4084
4085  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4086
4087  // C++ [over.oper]p5:
4088  //   The allocation and deallocation functions, operator new,
4089  //   operator new[], operator delete and operator delete[], are
4090  //   described completely in 3.7.3. The attributes and restrictions
4091  //   found in the rest of this subclause do not apply to them unless
4092  //   explicitly stated in 3.7.3.
4093  // FIXME: Write a separate routine for checking this. For now, just allow it.
4094  if (Op == OO_Delete || Op == OO_Array_Delete)
4095    return false;
4096
4097  if (Op == OO_New || Op == OO_Array_New) {
4098    bool ret = false;
4099    if (FunctionDecl::param_iterator Param = FnDecl->param_begin()) {
4100      QualType SizeTy = Context.getCanonicalType(Context.getSizeType());
4101      QualType T = Context.getCanonicalType((*Param)->getType());
4102      if (!T->isDependentType() && SizeTy != T) {
4103        Diag(FnDecl->getLocation(),
4104             diag::err_operator_new_param_type) << FnDecl->getDeclName()
4105              << SizeTy;
4106        ret = true;
4107      }
4108    }
4109    QualType ResultTy = Context.getCanonicalType(FnDecl->getResultType());
4110    if (!ResultTy->isDependentType() && ResultTy != Context.VoidPtrTy)
4111      return Diag(FnDecl->getLocation(),
4112                  diag::err_operator_new_result_type) << FnDecl->getDeclName()
4113                  << static_cast<QualType>(Context.VoidPtrTy);
4114    return ret;
4115  }
4116
4117  // C++ [over.oper]p6:
4118  //   An operator function shall either be a non-static member
4119  //   function or be a non-member function and have at least one
4120  //   parameter whose type is a class, a reference to a class, an
4121  //   enumeration, or a reference to an enumeration.
4122  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4123    if (MethodDecl->isStatic())
4124      return Diag(FnDecl->getLocation(),
4125                  diag::err_operator_overload_static) << FnDecl->getDeclName();
4126  } else {
4127    bool ClassOrEnumParam = false;
4128    for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4129                                   ParamEnd = FnDecl->param_end();
4130         Param != ParamEnd; ++Param) {
4131      QualType ParamType = (*Param)->getType().getNonReferenceType();
4132      if (ParamType->isDependentType() || ParamType->isRecordType() ||
4133          ParamType->isEnumeralType()) {
4134        ClassOrEnumParam = true;
4135        break;
4136      }
4137    }
4138
4139    if (!ClassOrEnumParam)
4140      return Diag(FnDecl->getLocation(),
4141                  diag::err_operator_overload_needs_class_or_enum)
4142        << FnDecl->getDeclName();
4143  }
4144
4145  // C++ [over.oper]p8:
4146  //   An operator function cannot have default arguments (8.3.6),
4147  //   except where explicitly stated below.
4148  //
4149  // Only the function-call operator allows default arguments
4150  // (C++ [over.call]p1).
4151  if (Op != OO_Call) {
4152    for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4153         Param != FnDecl->param_end(); ++Param) {
4154      if ((*Param)->hasUnparsedDefaultArg())
4155        return Diag((*Param)->getLocation(),
4156                    diag::err_operator_overload_default_arg)
4157          << FnDecl->getDeclName();
4158      else if (Expr *DefArg = (*Param)->getDefaultArg())
4159        return Diag((*Param)->getLocation(),
4160                    diag::err_operator_overload_default_arg)
4161          << FnDecl->getDeclName() << DefArg->getSourceRange();
4162    }
4163  }
4164
4165  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4166    { false, false, false }
4167#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4168    , { Unary, Binary, MemberOnly }
4169#include "clang/Basic/OperatorKinds.def"
4170  };
4171
4172  bool CanBeUnaryOperator = OperatorUses[Op][0];
4173  bool CanBeBinaryOperator = OperatorUses[Op][1];
4174  bool MustBeMemberOperator = OperatorUses[Op][2];
4175
4176  // C++ [over.oper]p8:
4177  //   [...] Operator functions cannot have more or fewer parameters
4178  //   than the number required for the corresponding operator, as
4179  //   described in the rest of this subclause.
4180  unsigned NumParams = FnDecl->getNumParams()
4181                     + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
4182  if (Op != OO_Call &&
4183      ((NumParams == 1 && !CanBeUnaryOperator) ||
4184       (NumParams == 2 && !CanBeBinaryOperator) ||
4185       (NumParams < 1) || (NumParams > 2))) {
4186    // We have the wrong number of parameters.
4187    unsigned ErrorKind;
4188    if (CanBeUnaryOperator && CanBeBinaryOperator) {
4189      ErrorKind = 2;  // 2 -> unary or binary.
4190    } else if (CanBeUnaryOperator) {
4191      ErrorKind = 0;  // 0 -> unary
4192    } else {
4193      assert(CanBeBinaryOperator &&
4194             "All non-call overloaded operators are unary or binary!");
4195      ErrorKind = 1;  // 1 -> binary
4196    }
4197
4198    return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
4199      << FnDecl->getDeclName() << NumParams << ErrorKind;
4200  }
4201
4202  // Overloaded operators other than operator() cannot be variadic.
4203  if (Op != OO_Call &&
4204      FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
4205    return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
4206      << FnDecl->getDeclName();
4207  }
4208
4209  // Some operators must be non-static member functions.
4210  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4211    return Diag(FnDecl->getLocation(),
4212                diag::err_operator_overload_must_be_member)
4213      << FnDecl->getDeclName();
4214  }
4215
4216  // C++ [over.inc]p1:
4217  //   The user-defined function called operator++ implements the
4218  //   prefix and postfix ++ operator. If this function is a member
4219  //   function with no parameters, or a non-member function with one
4220  //   parameter of class or enumeration type, it defines the prefix
4221  //   increment operator ++ for objects of that type. If the function
4222  //   is a member function with one parameter (which shall be of type
4223  //   int) or a non-member function with two parameters (the second
4224  //   of which shall be of type int), it defines the postfix
4225  //   increment operator ++ for objects of that type.
4226  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
4227    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
4228    bool ParamIsInt = false;
4229    if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
4230      ParamIsInt = BT->getKind() == BuiltinType::Int;
4231
4232    if (!ParamIsInt)
4233      return Diag(LastParam->getLocation(),
4234                  diag::err_operator_overload_post_incdec_must_be_int)
4235        << LastParam->getType() << (Op == OO_MinusMinus);
4236  }
4237
4238  // Notify the class if it got an assignment operator.
4239  if (Op == OO_Equal) {
4240    // Would have returned earlier otherwise.
4241    assert(isa<CXXMethodDecl>(FnDecl) &&
4242      "Overloaded = not member, but not filtered.");
4243    CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
4244    Method->getParent()->addedAssignmentOperator(Context, Method);
4245  }
4246
4247  return false;
4248}
4249
4250/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
4251/// linkage specification, including the language and (if present)
4252/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
4253/// the location of the language string literal, which is provided
4254/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
4255/// the '{' brace. Otherwise, this linkage specification does not
4256/// have any braces.
4257Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
4258                                                     SourceLocation ExternLoc,
4259                                                     SourceLocation LangLoc,
4260                                                     const char *Lang,
4261                                                     unsigned StrSize,
4262                                                     SourceLocation LBraceLoc) {
4263  LinkageSpecDecl::LanguageIDs Language;
4264  if (strncmp(Lang, "\"C\"", StrSize) == 0)
4265    Language = LinkageSpecDecl::lang_c;
4266  else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
4267    Language = LinkageSpecDecl::lang_cxx;
4268  else {
4269    Diag(LangLoc, diag::err_bad_language);
4270    return DeclPtrTy();
4271  }
4272
4273  // FIXME: Add all the various semantics of linkage specifications
4274
4275  LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
4276                                               LangLoc, Language,
4277                                               LBraceLoc.isValid());
4278  CurContext->addDecl(D);
4279  PushDeclContext(S, D);
4280  return DeclPtrTy::make(D);
4281}
4282
4283/// ActOnFinishLinkageSpecification - Completely the definition of
4284/// the C++ linkage specification LinkageSpec. If RBraceLoc is
4285/// valid, it's the position of the closing '}' brace in a linkage
4286/// specification that uses braces.
4287Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
4288                                                      DeclPtrTy LinkageSpec,
4289                                                      SourceLocation RBraceLoc) {
4290  if (LinkageSpec)
4291    PopDeclContext();
4292  return LinkageSpec;
4293}
4294
4295/// \brief Perform semantic analysis for the variable declaration that
4296/// occurs within a C++ catch clause, returning the newly-created
4297/// variable.
4298VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
4299                                         DeclaratorInfo *DInfo,
4300                                         IdentifierInfo *Name,
4301                                         SourceLocation Loc,
4302                                         SourceRange Range) {
4303  bool Invalid = false;
4304
4305  // Arrays and functions decay.
4306  if (ExDeclType->isArrayType())
4307    ExDeclType = Context.getArrayDecayedType(ExDeclType);
4308  else if (ExDeclType->isFunctionType())
4309    ExDeclType = Context.getPointerType(ExDeclType);
4310
4311  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
4312  // The exception-declaration shall not denote a pointer or reference to an
4313  // incomplete type, other than [cv] void*.
4314  // N2844 forbids rvalue references.
4315  if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
4316    Diag(Loc, diag::err_catch_rvalue_ref) << Range;
4317    Invalid = true;
4318  }
4319
4320  QualType BaseType = ExDeclType;
4321  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
4322  unsigned DK = diag::err_catch_incomplete;
4323  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
4324    BaseType = Ptr->getPointeeType();
4325    Mode = 1;
4326    DK = diag::err_catch_incomplete_ptr;
4327  } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
4328    // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
4329    BaseType = Ref->getPointeeType();
4330    Mode = 2;
4331    DK = diag::err_catch_incomplete_ref;
4332  }
4333  if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
4334      !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
4335    Invalid = true;
4336
4337  if (!Invalid && !ExDeclType->isDependentType() &&
4338      RequireNonAbstractType(Loc, ExDeclType,
4339                             diag::err_abstract_type_in_decl,
4340                             AbstractVariableType))
4341    Invalid = true;
4342
4343  // FIXME: Need to test for ability to copy-construct and destroy the
4344  // exception variable.
4345
4346  // FIXME: Need to check for abstract classes.
4347
4348  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
4349                                    Name, ExDeclType, DInfo, VarDecl::None);
4350
4351  if (Invalid)
4352    ExDecl->setInvalidDecl();
4353
4354  return ExDecl;
4355}
4356
4357/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
4358/// handler.
4359Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
4360  DeclaratorInfo *DInfo = 0;
4361  QualType ExDeclType = GetTypeForDeclarator(D, S, &DInfo);
4362
4363  bool Invalid = D.isInvalidType();
4364  IdentifierInfo *II = D.getIdentifier();
4365  if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
4366    // The scope should be freshly made just for us. There is just no way
4367    // it contains any previous declaration.
4368    assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
4369    if (PrevDecl->isTemplateParameter()) {
4370      // Maybe we will complain about the shadowed template parameter.
4371      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
4372    }
4373  }
4374
4375  if (D.getCXXScopeSpec().isSet() && !Invalid) {
4376    Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
4377      << D.getCXXScopeSpec().getRange();
4378    Invalid = true;
4379  }
4380
4381  VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, DInfo,
4382                                              D.getIdentifier(),
4383                                              D.getIdentifierLoc(),
4384                                            D.getDeclSpec().getSourceRange());
4385
4386  if (Invalid)
4387    ExDecl->setInvalidDecl();
4388
4389  // Add the exception declaration into this scope.
4390  if (II)
4391    PushOnScopeChains(ExDecl, S);
4392  else
4393    CurContext->addDecl(ExDecl);
4394
4395  ProcessDeclAttributes(S, ExDecl, D);
4396  return DeclPtrTy::make(ExDecl);
4397}
4398
4399Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
4400                                                   ExprArg assertexpr,
4401                                                   ExprArg assertmessageexpr) {
4402  Expr *AssertExpr = (Expr *)assertexpr.get();
4403  StringLiteral *AssertMessage =
4404    cast<StringLiteral>((Expr *)assertmessageexpr.get());
4405
4406  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
4407    llvm::APSInt Value(32);
4408    if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
4409      Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
4410        AssertExpr->getSourceRange();
4411      return DeclPtrTy();
4412    }
4413
4414    if (Value == 0) {
4415      std::string str(AssertMessage->getStrData(),
4416                      AssertMessage->getByteLength());
4417      Diag(AssertLoc, diag::err_static_assert_failed)
4418        << str << AssertExpr->getSourceRange();
4419    }
4420  }
4421
4422  assertexpr.release();
4423  assertmessageexpr.release();
4424  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
4425                                        AssertExpr, AssertMessage);
4426
4427  CurContext->addDecl(Decl);
4428  return DeclPtrTy::make(Decl);
4429}
4430
4431/// Handle a friend type declaration.  This works in tandem with
4432/// ActOnTag.
4433///
4434/// Notes on friend class templates:
4435///
4436/// We generally treat friend class declarations as if they were
4437/// declaring a class.  So, for example, the elaborated type specifier
4438/// in a friend declaration is required to obey the restrictions of a
4439/// class-head (i.e. no typedefs in the scope chain), template
4440/// parameters are required to match up with simple template-ids, &c.
4441/// However, unlike when declaring a template specialization, it's
4442/// okay to refer to a template specialization without an empty
4443/// template parameter declaration, e.g.
4444///   friend class A<T>::B<unsigned>;
4445/// We permit this as a special case; if there are any template
4446/// parameters present at all, require proper matching, i.e.
4447///   template <> template <class T> friend class A<int>::B;
4448Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
4449                                          MultiTemplateParamsArg TempParams) {
4450  SourceLocation Loc = DS.getSourceRange().getBegin();
4451
4452  assert(DS.isFriendSpecified());
4453  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4454
4455  // Try to convert the decl specifier to a type.  This works for
4456  // friend templates because ActOnTag never produces a ClassTemplateDecl
4457  // for a TUK_Friend.
4458  Declarator TheDeclarator(DS, Declarator::MemberContext);
4459  QualType T = GetTypeForDeclarator(TheDeclarator, S);
4460  if (TheDeclarator.isInvalidType())
4461    return DeclPtrTy();
4462
4463  // This is definitely an error in C++98.  It's probably meant to
4464  // be forbidden in C++0x, too, but the specification is just
4465  // poorly written.
4466  //
4467  // The problem is with declarations like the following:
4468  //   template <T> friend A<T>::foo;
4469  // where deciding whether a class C is a friend or not now hinges
4470  // on whether there exists an instantiation of A that causes
4471  // 'foo' to equal C.  There are restrictions on class-heads
4472  // (which we declare (by fiat) elaborated friend declarations to
4473  // be) that makes this tractable.
4474  //
4475  // FIXME: handle "template <> friend class A<T>;", which
4476  // is possibly well-formed?  Who even knows?
4477  if (TempParams.size() && !isa<ElaboratedType>(T)) {
4478    Diag(Loc, diag::err_tagless_friend_type_template)
4479      << DS.getSourceRange();
4480    return DeclPtrTy();
4481  }
4482
4483  // C++ [class.friend]p2:
4484  //   An elaborated-type-specifier shall be used in a friend declaration
4485  //   for a class.*
4486  //   * The class-key of the elaborated-type-specifier is required.
4487  // This is one of the rare places in Clang where it's legitimate to
4488  // ask about the "spelling" of the type.
4489  if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
4490    // If we evaluated the type to a record type, suggest putting
4491    // a tag in front.
4492    if (const RecordType *RT = T->getAs<RecordType>()) {
4493      RecordDecl *RD = RT->getDecl();
4494
4495      std::string InsertionText = std::string(" ") + RD->getKindName();
4496
4497      Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
4498        << (unsigned) RD->getTagKind()
4499        << T
4500        << SourceRange(DS.getFriendSpecLoc())
4501        << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
4502                                                 InsertionText);
4503      return DeclPtrTy();
4504    }else {
4505      Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
4506          << DS.getSourceRange();
4507      return DeclPtrTy();
4508    }
4509  }
4510
4511  // Enum types cannot be friends.
4512  if (T->getAs<EnumType>()) {
4513    Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
4514      << SourceRange(DS.getFriendSpecLoc());
4515    return DeclPtrTy();
4516  }
4517
4518  // C++98 [class.friend]p1: A friend of a class is a function
4519  //   or class that is not a member of the class . . .
4520  // But that's a silly restriction which nobody implements for
4521  // inner classes, and C++0x removes it anyway, so we only report
4522  // this (as a warning) if we're being pedantic.
4523  if (!getLangOptions().CPlusPlus0x)
4524    if (const RecordType *RT = T->getAs<RecordType>())
4525      if (RT->getDecl()->getDeclContext() == CurContext)
4526        Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class);
4527
4528  Decl *D;
4529  if (TempParams.size())
4530    D = FriendTemplateDecl::Create(Context, CurContext, Loc,
4531                                   TempParams.size(),
4532                                 (TemplateParameterList**) TempParams.release(),
4533                                   T.getTypePtr(),
4534                                   DS.getFriendSpecLoc());
4535  else
4536    D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
4537                           DS.getFriendSpecLoc());
4538  D->setAccess(AS_public);
4539  CurContext->addDecl(D);
4540
4541  return DeclPtrTy::make(D);
4542}
4543
4544Sema::DeclPtrTy
4545Sema::ActOnFriendFunctionDecl(Scope *S,
4546                              Declarator &D,
4547                              bool IsDefinition,
4548                              MultiTemplateParamsArg TemplateParams) {
4549  const DeclSpec &DS = D.getDeclSpec();
4550
4551  assert(DS.isFriendSpecified());
4552  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4553
4554  SourceLocation Loc = D.getIdentifierLoc();
4555  DeclaratorInfo *DInfo = 0;
4556  QualType T = GetTypeForDeclarator(D, S, &DInfo);
4557
4558  // C++ [class.friend]p1
4559  //   A friend of a class is a function or class....
4560  // Note that this sees through typedefs, which is intended.
4561  // It *doesn't* see through dependent types, which is correct
4562  // according to [temp.arg.type]p3:
4563  //   If a declaration acquires a function type through a
4564  //   type dependent on a template-parameter and this causes
4565  //   a declaration that does not use the syntactic form of a
4566  //   function declarator to have a function type, the program
4567  //   is ill-formed.
4568  if (!T->isFunctionType()) {
4569    Diag(Loc, diag::err_unexpected_friend);
4570
4571    // It might be worthwhile to try to recover by creating an
4572    // appropriate declaration.
4573    return DeclPtrTy();
4574  }
4575
4576  // C++ [namespace.memdef]p3
4577  //  - If a friend declaration in a non-local class first declares a
4578  //    class or function, the friend class or function is a member
4579  //    of the innermost enclosing namespace.
4580  //  - The name of the friend is not found by simple name lookup
4581  //    until a matching declaration is provided in that namespace
4582  //    scope (either before or after the class declaration granting
4583  //    friendship).
4584  //  - If a friend function is called, its name may be found by the
4585  //    name lookup that considers functions from namespaces and
4586  //    classes associated with the types of the function arguments.
4587  //  - When looking for a prior declaration of a class or a function
4588  //    declared as a friend, scopes outside the innermost enclosing
4589  //    namespace scope are not considered.
4590
4591  CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
4592  DeclarationName Name = GetNameForDeclarator(D);
4593  assert(Name);
4594
4595  // The context we found the declaration in, or in which we should
4596  // create the declaration.
4597  DeclContext *DC;
4598
4599  // FIXME: handle local classes
4600
4601  // Recover from invalid scope qualifiers as if they just weren't there.
4602  NamedDecl *PrevDecl = 0;
4603  if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
4604    // FIXME: RequireCompleteDeclContext
4605    DC = computeDeclContext(ScopeQual);
4606
4607    // FIXME: handle dependent contexts
4608    if (!DC) return DeclPtrTy();
4609
4610    LookupResult R;
4611    LookupQualifiedName(R, DC, Name, LookupOrdinaryName, true);
4612    PrevDecl = R.getAsSingleDecl(Context);
4613
4614    // If searching in that context implicitly found a declaration in
4615    // a different context, treat it like it wasn't found at all.
4616    // TODO: better diagnostics for this case.  Suggesting the right
4617    // qualified scope would be nice...
4618    if (!PrevDecl || !PrevDecl->getDeclContext()->Equals(DC)) {
4619      D.setInvalidType();
4620      Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
4621      return DeclPtrTy();
4622    }
4623
4624    // C++ [class.friend]p1: A friend of a class is a function or
4625    //   class that is not a member of the class . . .
4626    if (DC->Equals(CurContext))
4627      Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4628
4629  // Otherwise walk out to the nearest namespace scope looking for matches.
4630  } else {
4631    // TODO: handle local class contexts.
4632
4633    DC = CurContext;
4634    while (true) {
4635      // Skip class contexts.  If someone can cite chapter and verse
4636      // for this behavior, that would be nice --- it's what GCC and
4637      // EDG do, and it seems like a reasonable intent, but the spec
4638      // really only says that checks for unqualified existing
4639      // declarations should stop at the nearest enclosing namespace,
4640      // not that they should only consider the nearest enclosing
4641      // namespace.
4642      while (DC->isRecord())
4643        DC = DC->getParent();
4644
4645      LookupResult R;
4646      LookupQualifiedName(R, DC, Name, LookupOrdinaryName, true);
4647      PrevDecl = R.getAsSingleDecl(Context);
4648
4649      // TODO: decide what we think about using declarations.
4650      if (PrevDecl)
4651        break;
4652
4653      if (DC->isFileContext()) break;
4654      DC = DC->getParent();
4655    }
4656
4657    // C++ [class.friend]p1: A friend of a class is a function or
4658    //   class that is not a member of the class . . .
4659    // C++0x changes this for both friend types and functions.
4660    // Most C++ 98 compilers do seem to give an error here, so
4661    // we do, too.
4662    if (PrevDecl && DC->Equals(CurContext) && !getLangOptions().CPlusPlus0x)
4663      Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4664  }
4665
4666  if (DC->isFileContext()) {
4667    // This implies that it has to be an operator or function.
4668    if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
4669        D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
4670        D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
4671      Diag(Loc, diag::err_introducing_special_friend) <<
4672        (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
4673         D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
4674      return DeclPtrTy();
4675    }
4676  }
4677
4678  bool Redeclaration = false;
4679  NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, DInfo, PrevDecl,
4680                                          move(TemplateParams),
4681                                          IsDefinition,
4682                                          Redeclaration);
4683  if (!ND) return DeclPtrTy();
4684
4685  assert(ND->getDeclContext() == DC);
4686  assert(ND->getLexicalDeclContext() == CurContext);
4687
4688  // Add the function declaration to the appropriate lookup tables,
4689  // adjusting the redeclarations list as necessary.  We don't
4690  // want to do this yet if the friending class is dependent.
4691  //
4692  // Also update the scope-based lookup if the target context's
4693  // lookup context is in lexical scope.
4694  if (!CurContext->isDependentContext()) {
4695    DC = DC->getLookupContext();
4696    DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
4697    if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
4698      PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
4699  }
4700
4701  FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
4702                                       D.getIdentifierLoc(), ND,
4703                                       DS.getFriendSpecLoc());
4704  FrD->setAccess(AS_public);
4705  CurContext->addDecl(FrD);
4706
4707  return DeclPtrTy::make(ND);
4708}
4709
4710void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
4711  AdjustDeclIfTemplate(dcl);
4712
4713  Decl *Dcl = dcl.getAs<Decl>();
4714  FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
4715  if (!Fn) {
4716    Diag(DelLoc, diag::err_deleted_non_function);
4717    return;
4718  }
4719  if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
4720    Diag(DelLoc, diag::err_deleted_decl_not_first);
4721    Diag(Prev->getLocation(), diag::note_previous_declaration);
4722    // If the declaration wasn't the first, we delete the function anyway for
4723    // recovery.
4724  }
4725  Fn->setDeleted();
4726}
4727
4728static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
4729  for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
4730       ++CI) {
4731    Stmt *SubStmt = *CI;
4732    if (!SubStmt)
4733      continue;
4734    if (isa<ReturnStmt>(SubStmt))
4735      Self.Diag(SubStmt->getSourceRange().getBegin(),
4736           diag::err_return_in_constructor_handler);
4737    if (!isa<Expr>(SubStmt))
4738      SearchForReturnInStmt(Self, SubStmt);
4739  }
4740}
4741
4742void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
4743  for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
4744    CXXCatchStmt *Handler = TryBlock->getHandler(I);
4745    SearchForReturnInStmt(*this, Handler);
4746  }
4747}
4748
4749bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
4750                                             const CXXMethodDecl *Old) {
4751  QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
4752  QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
4753
4754  QualType CNewTy = Context.getCanonicalType(NewTy);
4755  QualType COldTy = Context.getCanonicalType(OldTy);
4756
4757  if (CNewTy == COldTy &&
4758      CNewTy.getLocalCVRQualifiers() == COldTy.getLocalCVRQualifiers())
4759    return false;
4760
4761  // Check if the return types are covariant
4762  QualType NewClassTy, OldClassTy;
4763
4764  /// Both types must be pointers or references to classes.
4765  if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
4766    if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
4767      NewClassTy = NewPT->getPointeeType();
4768      OldClassTy = OldPT->getPointeeType();
4769    }
4770  } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
4771    if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
4772      NewClassTy = NewRT->getPointeeType();
4773      OldClassTy = OldRT->getPointeeType();
4774    }
4775  }
4776
4777  // The return types aren't either both pointers or references to a class type.
4778  if (NewClassTy.isNull()) {
4779    Diag(New->getLocation(),
4780         diag::err_different_return_type_for_overriding_virtual_function)
4781      << New->getDeclName() << NewTy << OldTy;
4782    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4783
4784    return true;
4785  }
4786
4787  if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
4788    // Check if the new class derives from the old class.
4789    if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
4790      Diag(New->getLocation(),
4791           diag::err_covariant_return_not_derived)
4792      << New->getDeclName() << NewTy << OldTy;
4793      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4794      return true;
4795    }
4796
4797    // Check if we the conversion from derived to base is valid.
4798    if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
4799                      diag::err_covariant_return_inaccessible_base,
4800                      diag::err_covariant_return_ambiguous_derived_to_base_conv,
4801                      // FIXME: Should this point to the return type?
4802                      New->getLocation(), SourceRange(), New->getDeclName())) {
4803      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4804      return true;
4805    }
4806  }
4807
4808  // The qualifiers of the return types must be the same.
4809  if (CNewTy.getLocalCVRQualifiers() != COldTy.getLocalCVRQualifiers()) {
4810    Diag(New->getLocation(),
4811         diag::err_covariant_return_type_different_qualifications)
4812    << New->getDeclName() << NewTy << OldTy;
4813    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4814    return true;
4815  };
4816
4817
4818  // The new class type must have the same or less qualifiers as the old type.
4819  if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
4820    Diag(New->getLocation(),
4821         diag::err_covariant_return_type_class_type_more_qualified)
4822    << New->getDeclName() << NewTy << OldTy;
4823    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4824    return true;
4825  };
4826
4827  return false;
4828}
4829
4830/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4831/// initializer for the declaration 'Dcl'.
4832/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4833/// static data member of class X, names should be looked up in the scope of
4834/// class X.
4835void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
4836  AdjustDeclIfTemplate(Dcl);
4837
4838  Decl *D = Dcl.getAs<Decl>();
4839  // If there is no declaration, there was an error parsing it.
4840  if (D == 0)
4841    return;
4842
4843  // Check whether it is a declaration with a nested name specifier like
4844  // int foo::bar;
4845  if (!D->isOutOfLine())
4846    return;
4847
4848  // C++ [basic.lookup.unqual]p13
4849  //
4850  // A name used in the definition of a static data member of class X
4851  // (after the qualified-id of the static member) is looked up as if the name
4852  // was used in a member function of X.
4853
4854  // Change current context into the context of the initializing declaration.
4855  EnterDeclaratorContext(S, D->getDeclContext());
4856}
4857
4858/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4859/// initializer for the declaration 'Dcl'.
4860void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
4861  AdjustDeclIfTemplate(Dcl);
4862
4863  Decl *D = Dcl.getAs<Decl>();
4864  // If there is no declaration, there was an error parsing it.
4865  if (D == 0)
4866    return;
4867
4868  // Check whether it is a declaration with a nested name specifier like
4869  // int foo::bar;
4870  if (!D->isOutOfLine())
4871    return;
4872
4873  assert(S->getEntity() == D->getDeclContext() && "Context imbalance!");
4874  ExitDeclaratorContext(S);
4875}
4876