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