SemaDeclCXX.cpp revision 194179
1130803Smarcel//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2130803Smarcel//
3130803Smarcel//                     The LLVM Compiler Infrastructure
4130803Smarcel//
5130803Smarcel// This file is distributed under the University of Illinois Open Source
6130803Smarcel// License. See LICENSE.TXT for details.
7130803Smarcel//
8130803Smarcel//===----------------------------------------------------------------------===//
9130803Smarcel//
10130803Smarcel//  This file implements semantic analysis for C++ declarations.
11130803Smarcel//
12130803Smarcel//===----------------------------------------------------------------------===//
13130803Smarcel
14130803Smarcel#include "Sema.h"
15130803Smarcel#include "SemaInherit.h"
16130803Smarcel#include "clang/AST/ASTConsumer.h"
17130803Smarcel#include "clang/AST/ASTContext.h"
18130803Smarcel#include "clang/AST/DeclVisitor.h"
19130803Smarcel#include "clang/AST/TypeOrdering.h"
20130803Smarcel#include "clang/AST/StmtVisitor.h"
21130803Smarcel#include "clang/Lex/Preprocessor.h"
22130803Smarcel#include "clang/Parse/DeclSpec.h"
23130803Smarcel#include "llvm/ADT/STLExtras.h"
24130803Smarcel#include "llvm/Support/Compiler.h"
25130803Smarcel#include <algorithm> // for std::equal
26130803Smarcel#include <map>
27130803Smarcel
28130803Smarcelusing namespace clang;
29130803Smarcel
30130803Smarcel//===----------------------------------------------------------------------===//
31130803Smarcel// CheckDefaultArgumentVisitor
32130803Smarcel//===----------------------------------------------------------------------===//
33130803Smarcel
34130803Smarcelnamespace {
35130803Smarcel  /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
36130803Smarcel  /// the default argument of a parameter to determine whether it
37130803Smarcel  /// contains any ill-formed subexpressions. For example, this will
38130803Smarcel  /// diagnose the use of local variables or parameters within the
39130803Smarcel  /// default argument expression.
40130803Smarcel  class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
41130803Smarcel    : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
42130803Smarcel    Expr *DefaultArg;
43130803Smarcel    Sema *S;
44130803Smarcel
45130803Smarcel  public:
46130803Smarcel    CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
47130803Smarcel      : DefaultArg(defarg), S(s) {}
48130803Smarcel
49130803Smarcel    bool VisitExpr(Expr *Node);
50130803Smarcel    bool VisitDeclRefExpr(DeclRefExpr *DRE);
51130803Smarcel    bool VisitCXXThisExpr(CXXThisExpr *ThisE);
52130803Smarcel  };
53130803Smarcel
54130803Smarcel  /// VisitExpr - Visit all of the children of this expression.
55130803Smarcel  bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
56130803Smarcel    bool IsInvalid = false;
57130803Smarcel    for (Stmt::child_iterator I = Node->child_begin(),
58130803Smarcel         E = Node->child_end(); I != E; ++I)
59130803Smarcel      IsInvalid |= Visit(*I);
60130803Smarcel    return IsInvalid;
61130803Smarcel  }
62130803Smarcel
63130803Smarcel  /// VisitDeclRefExpr - Visit a reference to a declaration, to
64130803Smarcel  /// determine whether this declaration can be used in the default
65130803Smarcel  /// argument expression.
66130803Smarcel  bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
67130803Smarcel    NamedDecl *Decl = DRE->getDecl();
68130803Smarcel    if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
69130803Smarcel      // C++ [dcl.fct.default]p9
70130803Smarcel      //   Default arguments are evaluated each time the function is
71130803Smarcel      //   called. The order of evaluation of function arguments is
72130803Smarcel      //   unspecified. Consequently, parameters of a function shall not
73130803Smarcel      //   be used in default argument expressions, even if they are not
74130803Smarcel      //   evaluated. Parameters of a function declared before a default
75130803Smarcel      //   argument expression are in scope and can hide namespace and
76130803Smarcel      //   class member names.
77130803Smarcel      return S->Diag(DRE->getSourceRange().getBegin(),
78130803Smarcel                     diag::err_param_default_argument_references_param)
79130803Smarcel         << Param->getDeclName() << DefaultArg->getSourceRange();
80130803Smarcel    } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
81130803Smarcel      // C++ [dcl.fct.default]p7
82130803Smarcel      //   Local variables shall not be used in default argument
83130803Smarcel      //   expressions.
84130803Smarcel      if (VDecl->isBlockVarDecl())
85130803Smarcel        return S->Diag(DRE->getSourceRange().getBegin(),
86130803Smarcel                       diag::err_param_default_argument_references_local)
87130803Smarcel          << VDecl->getDeclName() << DefaultArg->getSourceRange();
88130803Smarcel    }
89130803Smarcel
90130803Smarcel    return false;
91130803Smarcel  }
92130803Smarcel
93130803Smarcel  /// VisitCXXThisExpr - Visit a C++ "this" expression.
94130803Smarcel  bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
95130803Smarcel    // C++ [dcl.fct.default]p8:
96130803Smarcel    //   The keyword this shall not be used in a default argument of a
97130803Smarcel    //   member function.
98130803Smarcel    return S->Diag(ThisE->getSourceRange().getBegin(),
99130803Smarcel                   diag::err_param_default_argument_references_this)
100130803Smarcel               << ThisE->getSourceRange();
101130803Smarcel  }
102130803Smarcel}
103130803Smarcel
104130803Smarcel/// ActOnParamDefaultArgument - Check whether the default argument
105130803Smarcel/// provided for a function parameter is well-formed. If so, attach it
106130803Smarcel/// to the parameter declaration.
107130803Smarcelvoid
108130803SmarcelSema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
109130803Smarcel                                ExprArg defarg) {
110130803Smarcel  ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
111130803Smarcel  UnparsedDefaultArgLocs.erase(Param);
112130803Smarcel
113130803Smarcel  ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
114130803Smarcel  QualType ParamType = Param->getType();
115130803Smarcel
116130803Smarcel  // Default arguments are only permitted in C++
117130803Smarcel  if (!getLangOptions().CPlusPlus) {
118130803Smarcel    Diag(EqualLoc, diag::err_param_default_argument)
119130803Smarcel      << DefaultArg->getSourceRange();
120130803Smarcel    Param->setInvalidDecl();
121130803Smarcel    return;
122130803Smarcel  }
123130803Smarcel
124130803Smarcel  // C++ [dcl.fct.default]p5
125130803Smarcel  //   A default argument expression is implicitly converted (clause
126130803Smarcel  //   4) to the parameter type. The default argument expression has
127130803Smarcel  //   the same semantic constraints as the initializer expression in
128130803Smarcel  //   a declaration of a variable of the parameter type, using the
129130803Smarcel  //   copy-initialization semantics (8.5).
130130803Smarcel  Expr *DefaultArgPtr = DefaultArg.get();
131130803Smarcel  bool DefaultInitFailed = CheckInitializerTypes(DefaultArgPtr, ParamType,
132130803Smarcel                                                 EqualLoc,
133130803Smarcel                                                 Param->getDeclName(),
134130803Smarcel                                                 /*DirectInit=*/false);
135130803Smarcel  if (DefaultArgPtr != DefaultArg.get()) {
136130803Smarcel    DefaultArg.take();
137130803Smarcel    DefaultArg.reset(DefaultArgPtr);
138130803Smarcel  }
139130803Smarcel  if (DefaultInitFailed) {
140130803Smarcel    return;
141130803Smarcel  }
142130803Smarcel
143130803Smarcel  // Check that the default argument is well-formed
144130803Smarcel  CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
145130803Smarcel  if (DefaultArgChecker.Visit(DefaultArg.get())) {
146130803Smarcel    Param->setInvalidDecl();
147130803Smarcel    return;
148130803Smarcel  }
149130803Smarcel
150130803Smarcel  // Okay: add the default argument to the parameter
151130803Smarcel  Param->setDefaultArg(DefaultArg.take());
152130803Smarcel}
153130803Smarcel
154130803Smarcel/// ActOnParamUnparsedDefaultArgument - We've seen a default
155130803Smarcel/// argument for a function parameter, but we can't parse it yet
156130803Smarcel/// because we're inside a class definition. Note that this default
157130803Smarcel/// argument will be parsed later.
158130803Smarcelvoid Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
159130803Smarcel                                             SourceLocation EqualLoc,
160130803Smarcel                                             SourceLocation ArgLoc) {
161130803Smarcel  ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
162130803Smarcel  if (Param)
163130803Smarcel    Param->setUnparsedDefaultArg();
164130803Smarcel
165130803Smarcel  UnparsedDefaultArgLocs[Param] = ArgLoc;
166130803Smarcel}
167130803Smarcel
168130803Smarcel/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
169130803Smarcel/// the default argument for the parameter param failed.
170130803Smarcelvoid Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
171130803Smarcel  ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
172130803Smarcel
173130803Smarcel  Param->setInvalidDecl();
174130803Smarcel
175130803Smarcel  UnparsedDefaultArgLocs.erase(Param);
176130803Smarcel}
177130803Smarcel
178130803Smarcel/// CheckExtraCXXDefaultArguments - Check for any extra default
179130803Smarcel/// arguments in the declarator, which is not a function declaration
180130803Smarcel/// or definition and therefore is not permitted to have default
181130803Smarcel/// arguments. This routine should be invoked for every declarator
182130803Smarcel/// that is not a function declaration or definition.
183130803Smarcelvoid Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
184130803Smarcel  // C++ [dcl.fct.default]p3
185130803Smarcel  //   A default argument expression shall be specified only in the
186130803Smarcel  //   parameter-declaration-clause of a function declaration or in a
187130803Smarcel  //   template-parameter (14.1). It shall not be specified for a
188130803Smarcel  //   parameter pack. If it is specified in a
189130803Smarcel  //   parameter-declaration-clause, it shall not occur within a
190130803Smarcel  //   declarator or abstract-declarator of a parameter-declaration.
191130803Smarcel  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
192130803Smarcel    DeclaratorChunk &chunk = D.getTypeObject(i);
193130803Smarcel    if (chunk.Kind == DeclaratorChunk::Function) {
194130803Smarcel      for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
195130803Smarcel        ParmVarDecl *Param =
196130803Smarcel          cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
197130803Smarcel        if (Param->hasUnparsedDefaultArg()) {
198130803Smarcel          CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
199130803Smarcel          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
200130803Smarcel            << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
201130803Smarcel          delete Toks;
202130803Smarcel          chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
203130803Smarcel        } else if (Param->getDefaultArg()) {
204130803Smarcel          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
205130803Smarcel            << Param->getDefaultArg()->getSourceRange();
206130803Smarcel          Param->setDefaultArg(0);
207130803Smarcel        }
208130803Smarcel      }
209130803Smarcel    }
210130803Smarcel  }
211130803Smarcel}
212130803Smarcel
213130803Smarcel// MergeCXXFunctionDecl - Merge two declarations of the same C++
214130803Smarcel// function, once we already know that they have the same
215130803Smarcel// type. Subroutine of MergeFunctionDecl. Returns true if there was an
216130803Smarcel// error, false otherwise.
217130803Smarcelbool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
218130803Smarcel  bool Invalid = false;
219130803Smarcel
220130803Smarcel  // C++ [dcl.fct.default]p4:
221130803Smarcel  //
222130803Smarcel  //   For non-template functions, default arguments can be added in
223130803Smarcel  //   later declarations of a function in the same
224130803Smarcel  //   scope. Declarations in different scopes have completely
225130803Smarcel  //   distinct sets of default arguments. That is, declarations in
226130803Smarcel  //   inner scopes do not acquire default arguments from
227130803Smarcel  //   declarations in outer scopes, and vice versa. In a given
228130803Smarcel  //   function declaration, all parameters subsequent to a
229130803Smarcel  //   parameter with a default argument shall have default
230130803Smarcel  //   arguments supplied in this or previous declarations. A
231130803Smarcel  //   default argument shall not be redefined by a later
232130803Smarcel  //   declaration (not even to the same value).
233130803Smarcel  for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
234130803Smarcel    ParmVarDecl *OldParam = Old->getParamDecl(p);
235130803Smarcel    ParmVarDecl *NewParam = New->getParamDecl(p);
236130803Smarcel
237130803Smarcel    if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
238130803Smarcel      Diag(NewParam->getLocation(),
239130803Smarcel           diag::err_param_default_argument_redefinition)
240130803Smarcel        << NewParam->getDefaultArg()->getSourceRange();
241130803Smarcel      Diag(OldParam->getLocation(), diag::note_previous_definition);
242130803Smarcel      Invalid = true;
243130803Smarcel    } else if (OldParam->getDefaultArg()) {
244130803Smarcel      // Merge the old default argument into the new parameter
245130803Smarcel      NewParam->setDefaultArg(OldParam->getDefaultArg());
246130803Smarcel    }
247130803Smarcel  }
248130803Smarcel
249130803Smarcel  return Invalid;
250130803Smarcel}
251130803Smarcel
252130803Smarcel/// CheckCXXDefaultArguments - Verify that the default arguments for a
253130803Smarcel/// function declaration are well-formed according to C++
254130803Smarcel/// [dcl.fct.default].
255130803Smarcelvoid Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
256130803Smarcel  unsigned NumParams = FD->getNumParams();
257130803Smarcel  unsigned p;
258130803Smarcel
259130803Smarcel  // Find first parameter with a default argument
260130803Smarcel  for (p = 0; p < NumParams; ++p) {
261130803Smarcel    ParmVarDecl *Param = FD->getParamDecl(p);
262130803Smarcel    if (Param->getDefaultArg())
263130803Smarcel      break;
264130803Smarcel  }
265130803Smarcel
266130803Smarcel  // C++ [dcl.fct.default]p4:
267130803Smarcel  //   In a given function declaration, all parameters
268130803Smarcel  //   subsequent to a parameter with a default argument shall
269130803Smarcel  //   have default arguments supplied in this or previous
270130803Smarcel  //   declarations. A default argument shall not be redefined
271130803Smarcel  //   by a later declaration (not even to the same value).
272130803Smarcel  unsigned LastMissingDefaultArg = 0;
273130803Smarcel  for(; p < NumParams; ++p) {
274130803Smarcel    ParmVarDecl *Param = FD->getParamDecl(p);
275130803Smarcel    if (!Param->getDefaultArg()) {
276130803Smarcel      if (Param->isInvalidDecl())
277130803Smarcel        /* We already complained about this parameter. */;
278130803Smarcel      else if (Param->getIdentifier())
279130803Smarcel        Diag(Param->getLocation(),
280130803Smarcel             diag::err_param_default_argument_missing_name)
281130803Smarcel          << Param->getIdentifier();
282130803Smarcel      else
283130803Smarcel        Diag(Param->getLocation(),
284130803Smarcel             diag::err_param_default_argument_missing);
285130803Smarcel
286130803Smarcel      LastMissingDefaultArg = p;
287130803Smarcel    }
288130803Smarcel  }
289130803Smarcel
290130803Smarcel  if (LastMissingDefaultArg > 0) {
291130803Smarcel    // Some default arguments were missing. Clear out all of the
292130803Smarcel    // default arguments up to (and including) the last missing
293130803Smarcel    // default argument, so that we leave the function parameters
294130803Smarcel    // in a semantically valid state.
295130803Smarcel    for (p = 0; p <= LastMissingDefaultArg; ++p) {
296130803Smarcel      ParmVarDecl *Param = FD->getParamDecl(p);
297130803Smarcel      if (Param->hasDefaultArg()) {
298130803Smarcel        if (!Param->hasUnparsedDefaultArg())
299130803Smarcel          Param->getDefaultArg()->Destroy(Context);
300130803Smarcel        Param->setDefaultArg(0);
301130803Smarcel      }
302130803Smarcel    }
303130803Smarcel  }
304130803Smarcel}
305130803Smarcel
306130803Smarcel/// isCurrentClassName - Determine whether the identifier II is the
307130803Smarcel/// name of the class type currently being defined. In the case of
308130803Smarcel/// nested classes, this will only return true if II is the name of
309130803Smarcel/// the innermost class.
310130803Smarcelbool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
311130803Smarcel                              const CXXScopeSpec *SS) {
312130803Smarcel  CXXRecordDecl *CurDecl;
313130803Smarcel  if (SS && SS->isSet() && !SS->isInvalid()) {
314130803Smarcel    DeclContext *DC = computeDeclContext(*SS);
315130803Smarcel    CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
316130803Smarcel  } else
317130803Smarcel    CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
318130803Smarcel
319130803Smarcel  if (CurDecl)
320130803Smarcel    return &II == CurDecl->getIdentifier();
321130803Smarcel  else
322130803Smarcel    return false;
323130803Smarcel}
324130803Smarcel
325130803Smarcel/// \brief Check the validity of a C++ base class specifier.
326130803Smarcel///
327130803Smarcel/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
328130803Smarcel/// and returns NULL otherwise.
329130803SmarcelCXXBaseSpecifier *
330130803SmarcelSema::CheckBaseSpecifier(CXXRecordDecl *Class,
331130803Smarcel                         SourceRange SpecifierRange,
332130803Smarcel                         bool Virtual, AccessSpecifier Access,
333130803Smarcel                         QualType BaseType,
334130803Smarcel                         SourceLocation BaseLoc) {
335130803Smarcel  // C++ [class.union]p1:
336130803Smarcel  //   A union shall not have base classes.
337130803Smarcel  if (Class->isUnion()) {
338130803Smarcel    Diag(Class->getLocation(), diag::err_base_clause_on_union)
339130803Smarcel      << SpecifierRange;
340130803Smarcel    return 0;
341130803Smarcel  }
342130803Smarcel
343130803Smarcel  if (BaseType->isDependentType())
344130803Smarcel    return new CXXBaseSpecifier(SpecifierRange, Virtual,
345130803Smarcel                                Class->getTagKind() == RecordDecl::TK_class,
346130803Smarcel                                Access, BaseType);
347130803Smarcel
348130803Smarcel  // Base specifiers must be record types.
349130803Smarcel  if (!BaseType->isRecordType()) {
350130803Smarcel    Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
351130803Smarcel    return 0;
352  }
353
354  // C++ [class.union]p1:
355  //   A union shall not be used as a base class.
356  if (BaseType->isUnionType()) {
357    Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
358    return 0;
359  }
360
361  // C++ [class.derived]p2:
362  //   The class-name in a base-specifier shall not be an incompletely
363  //   defined class.
364  if (RequireCompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,
365                          SpecifierRange))
366    return 0;
367
368  // If the base class is polymorphic, the new one is, too.
369  RecordDecl *BaseDecl = BaseType->getAsRecordType()->getDecl();
370  assert(BaseDecl && "Record type has no declaration");
371  BaseDecl = BaseDecl->getDefinition(Context);
372  assert(BaseDecl && "Base type is not incomplete, but has no definition");
373  if (cast<CXXRecordDecl>(BaseDecl)->isPolymorphic())
374    Class->setPolymorphic(true);
375
376  // C++ [dcl.init.aggr]p1:
377  //   An aggregate is [...] a class with [...] no base classes [...].
378  Class->setAggregate(false);
379  Class->setPOD(false);
380
381  if (Virtual) {
382    // C++ [class.ctor]p5:
383    //   A constructor is trivial if its class has no virtual base classes.
384    Class->setHasTrivialConstructor(false);
385  } else {
386    // C++ [class.ctor]p5:
387    //   A constructor is trivial if all the direct base classes of its
388    //   class have trivial constructors.
389    Class->setHasTrivialConstructor(cast<CXXRecordDecl>(BaseDecl)->
390                                    hasTrivialConstructor());
391  }
392
393  // C++ [class.ctor]p3:
394  //   A destructor is trivial if all the direct base classes of its class
395  //   have trivial destructors.
396  Class->setHasTrivialDestructor(cast<CXXRecordDecl>(BaseDecl)->
397                                 hasTrivialDestructor());
398
399  // Create the base specifier.
400  // FIXME: Allocate via ASTContext?
401  return new CXXBaseSpecifier(SpecifierRange, Virtual,
402                              Class->getTagKind() == RecordDecl::TK_class,
403                              Access, BaseType);
404}
405
406/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
407/// one entry in the base class list of a class specifier, for
408/// example:
409///    class foo : public bar, virtual private baz {
410/// 'public bar' and 'virtual private baz' are each base-specifiers.
411Sema::BaseResult
412Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
413                         bool Virtual, AccessSpecifier Access,
414                         TypeTy *basetype, SourceLocation BaseLoc) {
415  AdjustDeclIfTemplate(classdecl);
416  CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
417  QualType BaseType = QualType::getFromOpaquePtr(basetype);
418  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
419                                                      Virtual, Access,
420                                                      BaseType, BaseLoc))
421    return BaseSpec;
422
423  return true;
424}
425
426/// \brief Performs the actual work of attaching the given base class
427/// specifiers to a C++ class.
428bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
429                                unsigned NumBases) {
430 if (NumBases == 0)
431    return false;
432
433  // Used to keep track of which base types we have already seen, so
434  // that we can properly diagnose redundant direct base types. Note
435  // that the key is always the unqualified canonical type of the base
436  // class.
437  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
438
439  // Copy non-redundant base specifiers into permanent storage.
440  unsigned NumGoodBases = 0;
441  bool Invalid = false;
442  for (unsigned idx = 0; idx < NumBases; ++idx) {
443    QualType NewBaseType
444      = Context.getCanonicalType(Bases[idx]->getType());
445    NewBaseType = NewBaseType.getUnqualifiedType();
446
447    if (KnownBaseTypes[NewBaseType]) {
448      // C++ [class.mi]p3:
449      //   A class shall not be specified as a direct base class of a
450      //   derived class more than once.
451      Diag(Bases[idx]->getSourceRange().getBegin(),
452           diag::err_duplicate_base_class)
453        << KnownBaseTypes[NewBaseType]->getType()
454        << Bases[idx]->getSourceRange();
455
456      // Delete the duplicate base class specifier; we're going to
457      // overwrite its pointer later.
458      delete Bases[idx];
459
460      Invalid = true;
461    } else {
462      // Okay, add this new base class.
463      KnownBaseTypes[NewBaseType] = Bases[idx];
464      Bases[NumGoodBases++] = Bases[idx];
465    }
466  }
467
468  // Attach the remaining base class specifiers to the derived class.
469  Class->setBases(Bases, NumGoodBases);
470
471  // Delete the remaining (good) base class specifiers, since their
472  // data has been copied into the CXXRecordDecl.
473  for (unsigned idx = 0; idx < NumGoodBases; ++idx)
474    delete Bases[idx];
475
476  return Invalid;
477}
478
479/// ActOnBaseSpecifiers - Attach the given base specifiers to the
480/// class, after checking whether there are any duplicate base
481/// classes.
482void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
483                               unsigned NumBases) {
484  if (!ClassDecl || !Bases || !NumBases)
485    return;
486
487  AdjustDeclIfTemplate(ClassDecl);
488  AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
489                       (CXXBaseSpecifier**)(Bases), NumBases);
490}
491
492//===----------------------------------------------------------------------===//
493// C++ class member Handling
494//===----------------------------------------------------------------------===//
495
496/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
497/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
498/// bitfield width if there is one and 'InitExpr' specifies the initializer if
499/// any.
500Sema::DeclPtrTy
501Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
502                               ExprTy *BW, ExprTy *InitExpr, bool Deleted) {
503  const DeclSpec &DS = D.getDeclSpec();
504  DeclarationName Name = GetNameForDeclarator(D);
505  Expr *BitWidth = static_cast<Expr*>(BW);
506  Expr *Init = static_cast<Expr*>(InitExpr);
507  SourceLocation Loc = D.getIdentifierLoc();
508
509  bool isFunc = D.isFunctionDeclarator();
510
511  // C++ 9.2p6: A member shall not be declared to have automatic storage
512  // duration (auto, register) or with the extern storage-class-specifier.
513  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
514  // data members and cannot be applied to names declared const or static,
515  // and cannot be applied to reference members.
516  switch (DS.getStorageClassSpec()) {
517    case DeclSpec::SCS_unspecified:
518    case DeclSpec::SCS_typedef:
519    case DeclSpec::SCS_static:
520      // FALL THROUGH.
521      break;
522    case DeclSpec::SCS_mutable:
523      if (isFunc) {
524        if (DS.getStorageClassSpecLoc().isValid())
525          Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
526        else
527          Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
528
529        // FIXME: It would be nicer if the keyword was ignored only for this
530        // declarator. Otherwise we could get follow-up errors.
531        D.getMutableDeclSpec().ClearStorageClassSpecs();
532      } else {
533        QualType T = GetTypeForDeclarator(D, S);
534        diag::kind err = static_cast<diag::kind>(0);
535        if (T->isReferenceType())
536          err = diag::err_mutable_reference;
537        else if (T.isConstQualified())
538          err = diag::err_mutable_const;
539        if (err != 0) {
540          if (DS.getStorageClassSpecLoc().isValid())
541            Diag(DS.getStorageClassSpecLoc(), err);
542          else
543            Diag(DS.getThreadSpecLoc(), err);
544          // FIXME: It would be nicer if the keyword was ignored only for this
545          // declarator. Otherwise we could get follow-up errors.
546          D.getMutableDeclSpec().ClearStorageClassSpecs();
547        }
548      }
549      break;
550    default:
551      if (DS.getStorageClassSpecLoc().isValid())
552        Diag(DS.getStorageClassSpecLoc(),
553             diag::err_storageclass_invalid_for_member);
554      else
555        Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
556      D.getMutableDeclSpec().ClearStorageClassSpecs();
557  }
558
559  if (!isFunc &&
560      D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
561      D.getNumTypeObjects() == 0) {
562    // Check also for this case:
563    //
564    // typedef int f();
565    // f a;
566    //
567    QualType TDType = QualType::getFromOpaquePtr(DS.getTypeRep());
568    isFunc = TDType->isFunctionType();
569  }
570
571  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
572                       DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
573                      !isFunc);
574
575  Decl *Member;
576  if (isInstField) {
577    Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
578                         AS);
579    assert(Member && "HandleField never returns null");
580  } else {
581    Member = ActOnDeclarator(S, D).getAs<Decl>();
582    if (!Member) {
583      if (BitWidth) DeleteExpr(BitWidth);
584      return DeclPtrTy();
585    }
586
587    // Non-instance-fields can't have a bitfield.
588    if (BitWidth) {
589      if (Member->isInvalidDecl()) {
590        // don't emit another diagnostic.
591      } else if (isa<VarDecl>(Member)) {
592        // C++ 9.6p3: A bit-field shall not be a static member.
593        // "static member 'A' cannot be a bit-field"
594        Diag(Loc, diag::err_static_not_bitfield)
595          << Name << BitWidth->getSourceRange();
596      } else if (isa<TypedefDecl>(Member)) {
597        // "typedef member 'x' cannot be a bit-field"
598        Diag(Loc, diag::err_typedef_not_bitfield)
599          << Name << BitWidth->getSourceRange();
600      } else {
601        // A function typedef ("typedef int f(); f a;").
602        // C++ 9.6p3: A bit-field shall have integral or enumeration type.
603        Diag(Loc, diag::err_not_integral_type_bitfield)
604          << Name << cast<ValueDecl>(Member)->getType()
605          << BitWidth->getSourceRange();
606      }
607
608      DeleteExpr(BitWidth);
609      BitWidth = 0;
610      Member->setInvalidDecl();
611    }
612
613    Member->setAccess(AS);
614  }
615
616  assert((Name || isInstField) && "No identifier for non-field ?");
617
618  if (Init)
619    AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
620  if (Deleted) // FIXME: Source location is not very good.
621    SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
622
623  if (isInstField) {
624    FieldCollector->Add(cast<FieldDecl>(Member));
625    return DeclPtrTy();
626  }
627  return DeclPtrTy::make(Member);
628}
629
630/// ActOnMemInitializer - Handle a C++ member initializer.
631Sema::MemInitResult
632Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
633                          Scope *S,
634                          IdentifierInfo *MemberOrBase,
635                          SourceLocation IdLoc,
636                          SourceLocation LParenLoc,
637                          ExprTy **Args, unsigned NumArgs,
638                          SourceLocation *CommaLocs,
639                          SourceLocation RParenLoc) {
640  CXXConstructorDecl *Constructor
641    = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
642  if (!Constructor) {
643    // The user wrote a constructor initializer on a function that is
644    // not a C++ constructor. Ignore the error for now, because we may
645    // have more member initializers coming; we'll diagnose it just
646    // once in ActOnMemInitializers.
647    return true;
648  }
649
650  CXXRecordDecl *ClassDecl = Constructor->getParent();
651
652  // C++ [class.base.init]p2:
653  //   Names in a mem-initializer-id are looked up in the scope of the
654  //   constructor���s class and, if not found in that scope, are looked
655  //   up in the scope containing the constructor���s
656  //   definition. [Note: if the constructor���s class contains a member
657  //   with the same name as a direct or virtual base class of the
658  //   class, a mem-initializer-id naming the member or base class and
659  //   composed of a single identifier refers to the class member. A
660  //   mem-initializer-id for the hidden base class may be specified
661  //   using a qualified name. ]
662  // Look for a member, first.
663  FieldDecl *Member = 0;
664  DeclContext::lookup_result Result
665    = ClassDecl->lookup(Context, MemberOrBase);
666  if (Result.first != Result.second)
667    Member = dyn_cast<FieldDecl>(*Result.first);
668
669  // FIXME: Handle members of an anonymous union.
670
671  if (Member) {
672    // FIXME: Perform direct initialization of the member.
673    return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs);
674  }
675
676  // It didn't name a member, so see if it names a class.
677  TypeTy *BaseTy = getTypeName(*MemberOrBase, IdLoc, S, 0/*SS*/);
678  if (!BaseTy)
679    return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
680      << MemberOrBase << SourceRange(IdLoc, RParenLoc);
681
682  QualType BaseType = QualType::getFromOpaquePtr(BaseTy);
683  if (!BaseType->isRecordType())
684    return Diag(IdLoc, diag::err_base_init_does_not_name_class)
685      << BaseType << SourceRange(IdLoc, RParenLoc);
686
687  // C++ [class.base.init]p2:
688  //   [...] Unless the mem-initializer-id names a nonstatic data
689  //   member of the constructor���s class or a direct or virtual base
690  //   of that class, the mem-initializer is ill-formed. A
691  //   mem-initializer-list can initialize a base class using any
692  //   name that denotes that base class type.
693
694  // First, check for a direct base class.
695  const CXXBaseSpecifier *DirectBaseSpec = 0;
696  for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
697       Base != ClassDecl->bases_end(); ++Base) {
698    if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
699        Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
700      // We found a direct base of this type. That's what we're
701      // initializing.
702      DirectBaseSpec = &*Base;
703      break;
704    }
705  }
706
707  // Check for a virtual base class.
708  // FIXME: We might be able to short-circuit this if we know in advance that
709  // there are no virtual bases.
710  const CXXBaseSpecifier *VirtualBaseSpec = 0;
711  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
712    // We haven't found a base yet; search the class hierarchy for a
713    // virtual base class.
714    BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
715                    /*DetectVirtual=*/false);
716    if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
717      for (BasePaths::paths_iterator Path = Paths.begin();
718           Path != Paths.end(); ++Path) {
719        if (Path->back().Base->isVirtual()) {
720          VirtualBaseSpec = Path->back().Base;
721          break;
722        }
723      }
724    }
725  }
726
727  // C++ [base.class.init]p2:
728  //   If a mem-initializer-id is ambiguous because it designates both
729  //   a direct non-virtual base class and an inherited virtual base
730  //   class, the mem-initializer is ill-formed.
731  if (DirectBaseSpec && VirtualBaseSpec)
732    return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
733      << MemberOrBase << SourceRange(IdLoc, RParenLoc);
734
735  return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs);
736}
737
738void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
739                                SourceLocation ColonLoc,
740                                MemInitTy **MemInits, unsigned NumMemInits) {
741  CXXConstructorDecl *Constructor =
742  dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
743
744  if (!Constructor) {
745    Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
746    return;
747  }
748}
749
750namespace {
751  /// PureVirtualMethodCollector - traverses a class and its superclasses
752  /// and determines if it has any pure virtual methods.
753  class VISIBILITY_HIDDEN PureVirtualMethodCollector {
754    ASTContext &Context;
755
756  public:
757    typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
758
759  private:
760    MethodList Methods;
761
762    void Collect(const CXXRecordDecl* RD, MethodList& Methods);
763
764  public:
765    PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
766      : Context(Ctx) {
767
768      MethodList List;
769      Collect(RD, List);
770
771      // Copy the temporary list to methods, and make sure to ignore any
772      // null entries.
773      for (size_t i = 0, e = List.size(); i != e; ++i) {
774        if (List[i])
775          Methods.push_back(List[i]);
776      }
777    }
778
779    bool empty() const { return Methods.empty(); }
780
781    MethodList::const_iterator methods_begin() { return Methods.begin(); }
782    MethodList::const_iterator methods_end() { return Methods.end(); }
783  };
784
785  void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
786                                           MethodList& Methods) {
787    // First, collect the pure virtual methods for the base classes.
788    for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
789         BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
790      if (const RecordType *RT = Base->getType()->getAsRecordType()) {
791        const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
792        if (BaseDecl && BaseDecl->isAbstract())
793          Collect(BaseDecl, Methods);
794      }
795    }
796
797    // Next, zero out any pure virtual methods that this class overrides.
798    typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
799
800    MethodSetTy OverriddenMethods;
801    size_t MethodsSize = Methods.size();
802
803    for (RecordDecl::decl_iterator i = RD->decls_begin(Context),
804         e = RD->decls_end(Context);
805         i != e; ++i) {
806      // Traverse the record, looking for methods.
807      if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
808        // If the method is pre virtual, add it to the methods vector.
809        if (MD->isPure()) {
810          Methods.push_back(MD);
811          continue;
812        }
813
814        // Otherwise, record all the overridden methods in our set.
815        for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
816             E = MD->end_overridden_methods(); I != E; ++I) {
817          // Keep track of the overridden methods.
818          OverriddenMethods.insert(*I);
819        }
820      }
821    }
822
823    // Now go through the methods and zero out all the ones we know are
824    // overridden.
825    for (size_t i = 0, e = MethodsSize; i != e; ++i) {
826      if (OverriddenMethods.count(Methods[i]))
827        Methods[i] = 0;
828    }
829
830  }
831}
832
833bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
834                                  unsigned DiagID, AbstractDiagSelID SelID,
835                                  const CXXRecordDecl *CurrentRD) {
836
837  if (!getLangOptions().CPlusPlus)
838    return false;
839
840  if (const ArrayType *AT = Context.getAsArrayType(T))
841    return RequireNonAbstractType(Loc, AT->getElementType(), DiagID, SelID,
842                                  CurrentRD);
843
844  if (const PointerType *PT = T->getAsPointerType()) {
845    // Find the innermost pointer type.
846    while (const PointerType *T = PT->getPointeeType()->getAsPointerType())
847      PT = T;
848
849    if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
850      return RequireNonAbstractType(Loc, AT->getElementType(), DiagID, SelID,
851                                    CurrentRD);
852  }
853
854  const RecordType *RT = T->getAsRecordType();
855  if (!RT)
856    return false;
857
858  const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
859  if (!RD)
860    return false;
861
862  if (CurrentRD && CurrentRD != RD)
863    return false;
864
865  if (!RD->isAbstract())
866    return false;
867
868  Diag(Loc, DiagID) << RD->getDeclName() << SelID;
869
870  // Check if we've already emitted the list of pure virtual functions for this
871  // class.
872  if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
873    return true;
874
875  PureVirtualMethodCollector Collector(Context, RD);
876
877  for (PureVirtualMethodCollector::MethodList::const_iterator I =
878       Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
879    const CXXMethodDecl *MD = *I;
880
881    Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
882      MD->getDeclName();
883  }
884
885  if (!PureVirtualClassDiagSet)
886    PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
887  PureVirtualClassDiagSet->insert(RD);
888
889  return true;
890}
891
892namespace {
893  class VISIBILITY_HIDDEN AbstractClassUsageDiagnoser
894    : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
895    Sema &SemaRef;
896    CXXRecordDecl *AbstractClass;
897
898    bool VisitDeclContext(const DeclContext *DC) {
899      bool Invalid = false;
900
901      for (CXXRecordDecl::decl_iterator I = DC->decls_begin(SemaRef.Context),
902           E = DC->decls_end(SemaRef.Context); I != E; ++I)
903        Invalid |= Visit(*I);
904
905      return Invalid;
906    }
907
908  public:
909    AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
910      : SemaRef(SemaRef), AbstractClass(ac) {
911        Visit(SemaRef.Context.getTranslationUnitDecl());
912    }
913
914    bool VisitFunctionDecl(const FunctionDecl *FD) {
915      if (FD->isThisDeclarationADefinition()) {
916        // No need to do the check if we're in a definition, because it requires
917        // that the return/param types are complete.
918        // because that requires
919        return VisitDeclContext(FD);
920      }
921
922      // Check the return type.
923      QualType RTy = FD->getType()->getAsFunctionType()->getResultType();
924      bool Invalid =
925        SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
926                                       diag::err_abstract_type_in_decl,
927                                       Sema::AbstractReturnType,
928                                       AbstractClass);
929
930      for (FunctionDecl::param_const_iterator I = FD->param_begin(),
931           E = FD->param_end(); I != E; ++I) {
932        const ParmVarDecl *VD = *I;
933        Invalid |=
934          SemaRef.RequireNonAbstractType(VD->getLocation(),
935                                         VD->getOriginalType(),
936                                         diag::err_abstract_type_in_decl,
937                                         Sema::AbstractParamType,
938                                         AbstractClass);
939      }
940
941      return Invalid;
942    }
943
944    bool VisitDecl(const Decl* D) {
945      if (const DeclContext *DC = dyn_cast<DeclContext>(D))
946        return VisitDeclContext(DC);
947
948      return false;
949    }
950  };
951}
952
953void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
954                                             DeclPtrTy TagDecl,
955                                             SourceLocation LBrac,
956                                             SourceLocation RBrac) {
957  AdjustDeclIfTemplate(TagDecl);
958  ActOnFields(S, RLoc, TagDecl,
959              (DeclPtrTy*)FieldCollector->getCurFields(),
960              FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
961
962  CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>());
963  if (!RD->isAbstract()) {
964    // Collect all the pure virtual methods and see if this is an abstract
965    // class after all.
966    PureVirtualMethodCollector Collector(Context, RD);
967    if (!Collector.empty())
968      RD->setAbstract(true);
969  }
970
971  if (RD->isAbstract())
972    AbstractClassUsageDiagnoser(*this, RD);
973
974  if (RD->hasTrivialConstructor() || RD->hasTrivialDestructor()) {
975    for (RecordDecl::field_iterator i = RD->field_begin(Context),
976         e = RD->field_end(Context); i != e; ++i) {
977      // All the nonstatic data members must have trivial constructors.
978      QualType FTy = i->getType();
979      while (const ArrayType *AT = Context.getAsArrayType(FTy))
980        FTy = AT->getElementType();
981
982      if (const RecordType *RT = FTy->getAsRecordType()) {
983        CXXRecordDecl *FieldRD = cast<CXXRecordDecl>(RT->getDecl());
984
985        if (!FieldRD->hasTrivialConstructor())
986          RD->setHasTrivialConstructor(false);
987        if (!FieldRD->hasTrivialDestructor())
988          RD->setHasTrivialDestructor(false);
989
990        // If RD has neither a trivial constructor nor a trivial destructor
991        // we don't need to continue checking.
992        if (!RD->hasTrivialConstructor() && !RD->hasTrivialDestructor())
993          break;
994      }
995    }
996  }
997
998  if (!RD->isDependentType())
999    AddImplicitlyDeclaredMembersToClass(RD);
1000}
1001
1002/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
1003/// special functions, such as the default constructor, copy
1004/// constructor, or destructor, to the given C++ class (C++
1005/// [special]p1).  This routine can only be executed just before the
1006/// definition of the class is complete.
1007void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
1008  QualType ClassType = Context.getTypeDeclType(ClassDecl);
1009  ClassType = Context.getCanonicalType(ClassType);
1010
1011  // FIXME: Implicit declarations have exception specifications, which are
1012  // the union of the specifications of the implicitly called functions.
1013
1014  if (!ClassDecl->hasUserDeclaredConstructor()) {
1015    // C++ [class.ctor]p5:
1016    //   A default constructor for a class X is a constructor of class X
1017    //   that can be called without an argument. If there is no
1018    //   user-declared constructor for class X, a default constructor is
1019    //   implicitly declared. An implicitly-declared default constructor
1020    //   is an inline public member of its class.
1021    DeclarationName Name
1022      = Context.DeclarationNames.getCXXConstructorName(ClassType);
1023    CXXConstructorDecl *DefaultCon =
1024      CXXConstructorDecl::Create(Context, ClassDecl,
1025                                 ClassDecl->getLocation(), Name,
1026                                 Context.getFunctionType(Context.VoidTy,
1027                                                         0, 0, false, 0),
1028                                 /*isExplicit=*/false,
1029                                 /*isInline=*/true,
1030                                 /*isImplicitlyDeclared=*/true);
1031    DefaultCon->setAccess(AS_public);
1032    DefaultCon->setImplicit();
1033    ClassDecl->addDecl(Context, DefaultCon);
1034
1035    // Notify the class that we've added a constructor.
1036    ClassDecl->addedConstructor(Context, DefaultCon);
1037  }
1038
1039  if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
1040    // C++ [class.copy]p4:
1041    //   If the class definition does not explicitly declare a copy
1042    //   constructor, one is declared implicitly.
1043
1044    // C++ [class.copy]p5:
1045    //   The implicitly-declared copy constructor for a class X will
1046    //   have the form
1047    //
1048    //       X::X(const X&)
1049    //
1050    //   if
1051    bool HasConstCopyConstructor = true;
1052
1053    //     -- each direct or virtual base class B of X has a copy
1054    //        constructor whose first parameter is of type const B& or
1055    //        const volatile B&, and
1056    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1057         HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
1058      const CXXRecordDecl *BaseClassDecl
1059        = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
1060      HasConstCopyConstructor
1061        = BaseClassDecl->hasConstCopyConstructor(Context);
1062    }
1063
1064    //     -- for all the nonstatic data members of X that are of a
1065    //        class type M (or array thereof), each such class type
1066    //        has a copy constructor whose first parameter is of type
1067    //        const M& or const volatile M&.
1068    for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(Context);
1069         HasConstCopyConstructor && Field != ClassDecl->field_end(Context);
1070         ++Field) {
1071      QualType FieldType = (*Field)->getType();
1072      if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1073        FieldType = Array->getElementType();
1074      if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
1075        const CXXRecordDecl *FieldClassDecl
1076          = cast<CXXRecordDecl>(FieldClassType->getDecl());
1077        HasConstCopyConstructor
1078          = FieldClassDecl->hasConstCopyConstructor(Context);
1079      }
1080    }
1081
1082    //   Otherwise, the implicitly declared copy constructor will have
1083    //   the form
1084    //
1085    //       X::X(X&)
1086    QualType ArgType = ClassType;
1087    if (HasConstCopyConstructor)
1088      ArgType = ArgType.withConst();
1089    ArgType = Context.getLValueReferenceType(ArgType);
1090
1091    //   An implicitly-declared copy constructor is an inline public
1092    //   member of its class.
1093    DeclarationName Name
1094      = Context.DeclarationNames.getCXXConstructorName(ClassType);
1095    CXXConstructorDecl *CopyConstructor
1096      = CXXConstructorDecl::Create(Context, ClassDecl,
1097                                   ClassDecl->getLocation(), Name,
1098                                   Context.getFunctionType(Context.VoidTy,
1099                                                           &ArgType, 1,
1100                                                           false, 0),
1101                                   /*isExplicit=*/false,
1102                                   /*isInline=*/true,
1103                                   /*isImplicitlyDeclared=*/true);
1104    CopyConstructor->setAccess(AS_public);
1105    CopyConstructor->setImplicit();
1106
1107    // Add the parameter to the constructor.
1108    ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
1109                                                 ClassDecl->getLocation(),
1110                                                 /*IdentifierInfo=*/0,
1111                                                 ArgType, VarDecl::None, 0);
1112    CopyConstructor->setParams(Context, &FromParam, 1);
1113
1114    ClassDecl->addedConstructor(Context, CopyConstructor);
1115    ClassDecl->addDecl(Context, CopyConstructor);
1116  }
1117
1118  if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
1119    // Note: The following rules are largely analoguous to the copy
1120    // constructor rules. Note that virtual bases are not taken into account
1121    // for determining the argument type of the operator. Note also that
1122    // operators taking an object instead of a reference are allowed.
1123    //
1124    // C++ [class.copy]p10:
1125    //   If the class definition does not explicitly declare a copy
1126    //   assignment operator, one is declared implicitly.
1127    //   The implicitly-defined copy assignment operator for a class X
1128    //   will have the form
1129    //
1130    //       X& X::operator=(const X&)
1131    //
1132    //   if
1133    bool HasConstCopyAssignment = true;
1134
1135    //       -- each direct base class B of X has a copy assignment operator
1136    //          whose parameter is of type const B&, const volatile B& or B,
1137    //          and
1138    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1139         HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
1140      const CXXRecordDecl *BaseClassDecl
1141        = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
1142      HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context);
1143    }
1144
1145    //       -- for all the nonstatic data members of X that are of a class
1146    //          type M (or array thereof), each such class type has a copy
1147    //          assignment operator whose parameter is of type const M&,
1148    //          const volatile M& or M.
1149    for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(Context);
1150         HasConstCopyAssignment && Field != ClassDecl->field_end(Context);
1151         ++Field) {
1152      QualType FieldType = (*Field)->getType();
1153      if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1154        FieldType = Array->getElementType();
1155      if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
1156        const CXXRecordDecl *FieldClassDecl
1157          = cast<CXXRecordDecl>(FieldClassType->getDecl());
1158        HasConstCopyAssignment
1159          = FieldClassDecl->hasConstCopyAssignment(Context);
1160      }
1161    }
1162
1163    //   Otherwise, the implicitly declared copy assignment operator will
1164    //   have the form
1165    //
1166    //       X& X::operator=(X&)
1167    QualType ArgType = ClassType;
1168    QualType RetType = Context.getLValueReferenceType(ArgType);
1169    if (HasConstCopyAssignment)
1170      ArgType = ArgType.withConst();
1171    ArgType = Context.getLValueReferenceType(ArgType);
1172
1173    //   An implicitly-declared copy assignment operator is an inline public
1174    //   member of its class.
1175    DeclarationName Name =
1176      Context.DeclarationNames.getCXXOperatorName(OO_Equal);
1177    CXXMethodDecl *CopyAssignment =
1178      CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
1179                            Context.getFunctionType(RetType, &ArgType, 1,
1180                                                    false, 0),
1181                            /*isStatic=*/false, /*isInline=*/true);
1182    CopyAssignment->setAccess(AS_public);
1183    CopyAssignment->setImplicit();
1184
1185    // Add the parameter to the operator.
1186    ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
1187                                                 ClassDecl->getLocation(),
1188                                                 /*IdentifierInfo=*/0,
1189                                                 ArgType, VarDecl::None, 0);
1190    CopyAssignment->setParams(Context, &FromParam, 1);
1191
1192    // Don't call addedAssignmentOperator. There is no way to distinguish an
1193    // implicit from an explicit assignment operator.
1194    ClassDecl->addDecl(Context, CopyAssignment);
1195  }
1196
1197  if (!ClassDecl->hasUserDeclaredDestructor()) {
1198    // C++ [class.dtor]p2:
1199    //   If a class has no user-declared destructor, a destructor is
1200    //   declared implicitly. An implicitly-declared destructor is an
1201    //   inline public member of its class.
1202    DeclarationName Name
1203      = Context.DeclarationNames.getCXXDestructorName(ClassType);
1204    CXXDestructorDecl *Destructor
1205      = CXXDestructorDecl::Create(Context, ClassDecl,
1206                                  ClassDecl->getLocation(), Name,
1207                                  Context.getFunctionType(Context.VoidTy,
1208                                                          0, 0, false, 0),
1209                                  /*isInline=*/true,
1210                                  /*isImplicitlyDeclared=*/true);
1211    Destructor->setAccess(AS_public);
1212    Destructor->setImplicit();
1213    ClassDecl->addDecl(Context, Destructor);
1214  }
1215}
1216
1217void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
1218  TemplateDecl *Template = TemplateD.getAs<TemplateDecl>();
1219  if (!Template)
1220    return;
1221
1222  TemplateParameterList *Params = Template->getTemplateParameters();
1223  for (TemplateParameterList::iterator Param = Params->begin(),
1224                                    ParamEnd = Params->end();
1225       Param != ParamEnd; ++Param) {
1226    NamedDecl *Named = cast<NamedDecl>(*Param);
1227    if (Named->getDeclName()) {
1228      S->AddDecl(DeclPtrTy::make(Named));
1229      IdResolver.AddDecl(Named);
1230    }
1231  }
1232}
1233
1234/// ActOnStartDelayedCXXMethodDeclaration - We have completed
1235/// parsing a top-level (non-nested) C++ class, and we are now
1236/// parsing those parts of the given Method declaration that could
1237/// not be parsed earlier (C++ [class.mem]p2), such as default
1238/// arguments. This action should enter the scope of the given
1239/// Method declaration as if we had just parsed the qualified method
1240/// name. However, it should not bring the parameters into scope;
1241/// that will be performed by ActOnDelayedCXXMethodParameter.
1242void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
1243  CXXScopeSpec SS;
1244  FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
1245  QualType ClassTy
1246    = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
1247  SS.setScopeRep(
1248    NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
1249  ActOnCXXEnterDeclaratorScope(S, SS);
1250}
1251
1252/// ActOnDelayedCXXMethodParameter - We've already started a delayed
1253/// C++ method declaration. We're (re-)introducing the given
1254/// function parameter into scope for use in parsing later parts of
1255/// the method declaration. For example, we could see an
1256/// ActOnParamDefaultArgument event for this parameter.
1257void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
1258  ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
1259
1260  // If this parameter has an unparsed default argument, clear it out
1261  // to make way for the parsed default argument.
1262  if (Param->hasUnparsedDefaultArg())
1263    Param->setDefaultArg(0);
1264
1265  S->AddDecl(DeclPtrTy::make(Param));
1266  if (Param->getDeclName())
1267    IdResolver.AddDecl(Param);
1268}
1269
1270/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
1271/// processing the delayed method declaration for Method. The method
1272/// declaration is now considered finished. There may be a separate
1273/// ActOnStartOfFunctionDef action later (not necessarily
1274/// immediately!) for this method, if it was also defined inside the
1275/// class body.
1276void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
1277  FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
1278  CXXScopeSpec SS;
1279  QualType ClassTy
1280    = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
1281  SS.setScopeRep(
1282    NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
1283  ActOnCXXExitDeclaratorScope(S, SS);
1284
1285  // Now that we have our default arguments, check the constructor
1286  // again. It could produce additional diagnostics or affect whether
1287  // the class has implicitly-declared destructors, among other
1288  // things.
1289  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
1290    CheckConstructor(Constructor);
1291
1292  // Check the default arguments, which we may have added.
1293  if (!Method->isInvalidDecl())
1294    CheckCXXDefaultArguments(Method);
1295}
1296
1297/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
1298/// the well-formedness of the constructor declarator @p D with type @p
1299/// R. If there are any errors in the declarator, this routine will
1300/// emit diagnostics and set the invalid bit to true.  In any case, the type
1301/// will be updated to reflect a well-formed type for the constructor and
1302/// returned.
1303QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
1304                                          FunctionDecl::StorageClass &SC) {
1305  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
1306
1307  // C++ [class.ctor]p3:
1308  //   A constructor shall not be virtual (10.3) or static (9.4). A
1309  //   constructor can be invoked for a const, volatile or const
1310  //   volatile object. A constructor shall not be declared const,
1311  //   volatile, or const volatile (9.3.2).
1312  if (isVirtual) {
1313    if (!D.isInvalidType())
1314      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1315        << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
1316        << SourceRange(D.getIdentifierLoc());
1317    D.setInvalidType();
1318  }
1319  if (SC == FunctionDecl::Static) {
1320    if (!D.isInvalidType())
1321      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1322        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1323        << SourceRange(D.getIdentifierLoc());
1324    D.setInvalidType();
1325    SC = FunctionDecl::None;
1326  }
1327
1328  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1329  if (FTI.TypeQuals != 0) {
1330    if (FTI.TypeQuals & QualType::Const)
1331      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1332        << "const" << SourceRange(D.getIdentifierLoc());
1333    if (FTI.TypeQuals & QualType::Volatile)
1334      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1335        << "volatile" << SourceRange(D.getIdentifierLoc());
1336    if (FTI.TypeQuals & QualType::Restrict)
1337      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1338        << "restrict" << SourceRange(D.getIdentifierLoc());
1339  }
1340
1341  // Rebuild the function type "R" without any type qualifiers (in
1342  // case any of the errors above fired) and with "void" as the
1343  // return type, since constructors don't have return types. We
1344  // *always* have to do this, because GetTypeForDeclarator will
1345  // put in a result type of "int" when none was specified.
1346  const FunctionProtoType *Proto = R->getAsFunctionProtoType();
1347  return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
1348                                 Proto->getNumArgs(),
1349                                 Proto->isVariadic(), 0);
1350}
1351
1352/// CheckConstructor - Checks a fully-formed constructor for
1353/// well-formedness, issuing any diagnostics required. Returns true if
1354/// the constructor declarator is invalid.
1355void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
1356  CXXRecordDecl *ClassDecl
1357    = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
1358  if (!ClassDecl)
1359    return Constructor->setInvalidDecl();
1360
1361  // C++ [class.copy]p3:
1362  //   A declaration of a constructor for a class X is ill-formed if
1363  //   its first parameter is of type (optionally cv-qualified) X and
1364  //   either there are no other parameters or else all other
1365  //   parameters have default arguments.
1366  if (!Constructor->isInvalidDecl() &&
1367      ((Constructor->getNumParams() == 1) ||
1368       (Constructor->getNumParams() > 1 &&
1369        Constructor->getParamDecl(1)->hasDefaultArg()))) {
1370    QualType ParamType = Constructor->getParamDecl(0)->getType();
1371    QualType ClassTy = Context.getTagDeclType(ClassDecl);
1372    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
1373      SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
1374      Diag(ParamLoc, diag::err_constructor_byvalue_arg)
1375        << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
1376      Constructor->setInvalidDecl();
1377    }
1378  }
1379
1380  // Notify the class that we've added a constructor.
1381  ClassDecl->addedConstructor(Context, Constructor);
1382}
1383
1384static inline bool
1385FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
1386  return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1387          FTI.ArgInfo[0].Param &&
1388          FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
1389}
1390
1391/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
1392/// the well-formednes of the destructor declarator @p D with type @p
1393/// R. If there are any errors in the declarator, this routine will
1394/// emit diagnostics and set the declarator to invalid.  Even if this happens,
1395/// will be updated to reflect a well-formed type for the destructor and
1396/// returned.
1397QualType Sema::CheckDestructorDeclarator(Declarator &D,
1398                                         FunctionDecl::StorageClass& SC) {
1399  // C++ [class.dtor]p1:
1400  //   [...] A typedef-name that names a class is a class-name
1401  //   (7.1.3); however, a typedef-name that names a class shall not
1402  //   be used as the identifier in the declarator for a destructor
1403  //   declaration.
1404  QualType DeclaratorType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1405  if (isa<TypedefType>(DeclaratorType)) {
1406    Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
1407      << DeclaratorType;
1408    D.setInvalidType();
1409  }
1410
1411  // C++ [class.dtor]p2:
1412  //   A destructor is used to destroy objects of its class type. A
1413  //   destructor takes no parameters, and no return type can be
1414  //   specified for it (not even void). The address of a destructor
1415  //   shall not be taken. A destructor shall not be static. A
1416  //   destructor can be invoked for a const, volatile or const
1417  //   volatile object. A destructor shall not be declared const,
1418  //   volatile or const volatile (9.3.2).
1419  if (SC == FunctionDecl::Static) {
1420    if (!D.isInvalidType())
1421      Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
1422        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1423        << SourceRange(D.getIdentifierLoc());
1424    SC = FunctionDecl::None;
1425    D.setInvalidType();
1426  }
1427  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
1428    // Destructors don't have return types, but the parser will
1429    // happily parse something like:
1430    //
1431    //   class X {
1432    //     float ~X();
1433    //   };
1434    //
1435    // The return type will be eliminated later.
1436    Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
1437      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1438      << SourceRange(D.getIdentifierLoc());
1439  }
1440
1441  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1442  if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
1443    if (FTI.TypeQuals & QualType::Const)
1444      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1445        << "const" << SourceRange(D.getIdentifierLoc());
1446    if (FTI.TypeQuals & QualType::Volatile)
1447      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1448        << "volatile" << SourceRange(D.getIdentifierLoc());
1449    if (FTI.TypeQuals & QualType::Restrict)
1450      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1451        << "restrict" << SourceRange(D.getIdentifierLoc());
1452    D.setInvalidType();
1453  }
1454
1455  // Make sure we don't have any parameters.
1456  if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
1457    Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
1458
1459    // Delete the parameters.
1460    FTI.freeArgs();
1461    D.setInvalidType();
1462  }
1463
1464  // Make sure the destructor isn't variadic.
1465  if (FTI.isVariadic) {
1466    Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
1467    D.setInvalidType();
1468  }
1469
1470  // Rebuild the function type "R" without any type qualifiers or
1471  // parameters (in case any of the errors above fired) and with
1472  // "void" as the return type, since destructors don't have return
1473  // types. We *always* have to do this, because GetTypeForDeclarator
1474  // will put in a result type of "int" when none was specified.
1475  return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
1476}
1477
1478/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
1479/// well-formednes of the conversion function declarator @p D with
1480/// type @p R. If there are any errors in the declarator, this routine
1481/// will emit diagnostics and return true. Otherwise, it will return
1482/// false. Either way, the type @p R will be updated to reflect a
1483/// well-formed type for the conversion operator.
1484void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
1485                                     FunctionDecl::StorageClass& SC) {
1486  // C++ [class.conv.fct]p1:
1487  //   Neither parameter types nor return type can be specified. The
1488  //   type of a conversion function (8.3.5) is ���function taking no
1489  //   parameter returning conversion-type-id.���
1490  if (SC == FunctionDecl::Static) {
1491    if (!D.isInvalidType())
1492      Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
1493        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1494        << SourceRange(D.getIdentifierLoc());
1495    D.setInvalidType();
1496    SC = FunctionDecl::None;
1497  }
1498  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
1499    // Conversion functions don't have return types, but the parser will
1500    // happily parse something like:
1501    //
1502    //   class X {
1503    //     float operator bool();
1504    //   };
1505    //
1506    // The return type will be changed later anyway.
1507    Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
1508      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1509      << SourceRange(D.getIdentifierLoc());
1510  }
1511
1512  // Make sure we don't have any parameters.
1513  if (R->getAsFunctionProtoType()->getNumArgs() > 0) {
1514    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
1515
1516    // Delete the parameters.
1517    D.getTypeObject(0).Fun.freeArgs();
1518    D.setInvalidType();
1519  }
1520
1521  // Make sure the conversion function isn't variadic.
1522  if (R->getAsFunctionProtoType()->isVariadic() && !D.isInvalidType()) {
1523    Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
1524    D.setInvalidType();
1525  }
1526
1527  // C++ [class.conv.fct]p4:
1528  //   The conversion-type-id shall not represent a function type nor
1529  //   an array type.
1530  QualType ConvType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1531  if (ConvType->isArrayType()) {
1532    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
1533    ConvType = Context.getPointerType(ConvType);
1534    D.setInvalidType();
1535  } else if (ConvType->isFunctionType()) {
1536    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
1537    ConvType = Context.getPointerType(ConvType);
1538    D.setInvalidType();
1539  }
1540
1541  // Rebuild the function type "R" without any parameters (in case any
1542  // of the errors above fired) and with the conversion type as the
1543  // return type.
1544  R = Context.getFunctionType(ConvType, 0, 0, false,
1545                              R->getAsFunctionProtoType()->getTypeQuals());
1546
1547  // C++0x explicit conversion operators.
1548  if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
1549    Diag(D.getDeclSpec().getExplicitSpecLoc(),
1550         diag::warn_explicit_conversion_functions)
1551      << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
1552}
1553
1554/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
1555/// the declaration of the given C++ conversion function. This routine
1556/// is responsible for recording the conversion function in the C++
1557/// class, if possible.
1558Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
1559  assert(Conversion && "Expected to receive a conversion function declaration");
1560
1561  // Set the lexical context of this conversion function
1562  Conversion->setLexicalDeclContext(CurContext);
1563
1564  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
1565
1566  // Make sure we aren't redeclaring the conversion function.
1567  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
1568
1569  // C++ [class.conv.fct]p1:
1570  //   [...] A conversion function is never used to convert a
1571  //   (possibly cv-qualified) object to the (possibly cv-qualified)
1572  //   same object type (or a reference to it), to a (possibly
1573  //   cv-qualified) base class of that type (or a reference to it),
1574  //   or to (possibly cv-qualified) void.
1575  // FIXME: Suppress this warning if the conversion function ends up being a
1576  // virtual function that overrides a virtual function in a base class.
1577  QualType ClassType
1578    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
1579  if (const ReferenceType *ConvTypeRef = ConvType->getAsReferenceType())
1580    ConvType = ConvTypeRef->getPointeeType();
1581  if (ConvType->isRecordType()) {
1582    ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
1583    if (ConvType == ClassType)
1584      Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
1585        << ClassType;
1586    else if (IsDerivedFrom(ClassType, ConvType))
1587      Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
1588        <<  ClassType << ConvType;
1589  } else if (ConvType->isVoidType()) {
1590    Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
1591      << ClassType << ConvType;
1592  }
1593
1594  if (Conversion->getPreviousDeclaration()) {
1595    OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
1596    for (OverloadedFunctionDecl::function_iterator
1597           Conv = Conversions->function_begin(),
1598           ConvEnd = Conversions->function_end();
1599         Conv != ConvEnd; ++Conv) {
1600      if (*Conv == Conversion->getPreviousDeclaration()) {
1601        *Conv = Conversion;
1602        return DeclPtrTy::make(Conversion);
1603      }
1604    }
1605    assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
1606  } else
1607    ClassDecl->addConversionFunction(Context, Conversion);
1608
1609  return DeclPtrTy::make(Conversion);
1610}
1611
1612//===----------------------------------------------------------------------===//
1613// Namespace Handling
1614//===----------------------------------------------------------------------===//
1615
1616/// ActOnStartNamespaceDef - This is called at the start of a namespace
1617/// definition.
1618Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
1619                                             SourceLocation IdentLoc,
1620                                             IdentifierInfo *II,
1621                                             SourceLocation LBrace) {
1622  NamespaceDecl *Namespc =
1623      NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
1624  Namespc->setLBracLoc(LBrace);
1625
1626  Scope *DeclRegionScope = NamespcScope->getParent();
1627
1628  if (II) {
1629    // C++ [namespace.def]p2:
1630    // The identifier in an original-namespace-definition shall not have been
1631    // previously defined in the declarative region in which the
1632    // original-namespace-definition appears. The identifier in an
1633    // original-namespace-definition is the name of the namespace. Subsequently
1634    // in that declarative region, it is treated as an original-namespace-name.
1635
1636    NamedDecl *PrevDecl = LookupName(DeclRegionScope, II, LookupOrdinaryName,
1637                                     true);
1638
1639    if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
1640      // This is an extended namespace definition.
1641      // Attach this namespace decl to the chain of extended namespace
1642      // definitions.
1643      OrigNS->setNextNamespace(Namespc);
1644      Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
1645
1646      // Remove the previous declaration from the scope.
1647      if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
1648        IdResolver.RemoveDecl(OrigNS);
1649        DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
1650      }
1651    } else if (PrevDecl) {
1652      // This is an invalid name redefinition.
1653      Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
1654       << Namespc->getDeclName();
1655      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1656      Namespc->setInvalidDecl();
1657      // Continue on to push Namespc as current DeclContext and return it.
1658    }
1659
1660    PushOnScopeChains(Namespc, DeclRegionScope);
1661  } else {
1662    // FIXME: Handle anonymous namespaces
1663  }
1664
1665  // Although we could have an invalid decl (i.e. the namespace name is a
1666  // redefinition), push it as current DeclContext and try to continue parsing.
1667  // FIXME: We should be able to push Namespc here, so that the each DeclContext
1668  // for the namespace has the declarations that showed up in that particular
1669  // namespace definition.
1670  PushDeclContext(NamespcScope, Namespc);
1671  return DeclPtrTy::make(Namespc);
1672}
1673
1674/// ActOnFinishNamespaceDef - This callback is called after a namespace is
1675/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
1676void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
1677  Decl *Dcl = D.getAs<Decl>();
1678  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
1679  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
1680  Namespc->setRBracLoc(RBrace);
1681  PopDeclContext();
1682}
1683
1684Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
1685                                          SourceLocation UsingLoc,
1686                                          SourceLocation NamespcLoc,
1687                                          const CXXScopeSpec &SS,
1688                                          SourceLocation IdentLoc,
1689                                          IdentifierInfo *NamespcName,
1690                                          AttributeList *AttrList) {
1691  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
1692  assert(NamespcName && "Invalid NamespcName.");
1693  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
1694  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
1695
1696  UsingDirectiveDecl *UDir = 0;
1697
1698  // Lookup namespace name.
1699  LookupResult R = LookupParsedName(S, &SS, NamespcName,
1700                                    LookupNamespaceName, false);
1701  if (R.isAmbiguous()) {
1702    DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
1703    return DeclPtrTy();
1704  }
1705  if (NamedDecl *NS = R) {
1706    assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
1707    // C++ [namespace.udir]p1:
1708    //   A using-directive specifies that the names in the nominated
1709    //   namespace can be used in the scope in which the
1710    //   using-directive appears after the using-directive. During
1711    //   unqualified name lookup (3.4.1), the names appear as if they
1712    //   were declared in the nearest enclosing namespace which
1713    //   contains both the using-directive and the nominated
1714    //   namespace. [Note: in this context, ���contains��� means ���contains
1715    //   directly or indirectly���. ]
1716
1717    // Find enclosing context containing both using-directive and
1718    // nominated namespace.
1719    DeclContext *CommonAncestor = cast<DeclContext>(NS);
1720    while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
1721      CommonAncestor = CommonAncestor->getParent();
1722
1723    UDir = UsingDirectiveDecl::Create(Context,
1724                                      CurContext, UsingLoc,
1725                                      NamespcLoc,
1726                                      SS.getRange(),
1727                                      (NestedNameSpecifier *)SS.getScopeRep(),
1728                                      IdentLoc,
1729                                      cast<NamespaceDecl>(NS),
1730                                      CommonAncestor);
1731    PushUsingDirective(S, UDir);
1732  } else {
1733    Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
1734  }
1735
1736  // FIXME: We ignore attributes for now.
1737  delete AttrList;
1738  return DeclPtrTy::make(UDir);
1739}
1740
1741void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
1742  // If scope has associated entity, then using directive is at namespace
1743  // or translation unit scope. We add UsingDirectiveDecls, into
1744  // it's lookup structure.
1745  if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
1746    Ctx->addDecl(Context, UDir);
1747  else
1748    // Otherwise it is block-sope. using-directives will affect lookup
1749    // only to the end of scope.
1750    S->PushUsingDirective(DeclPtrTy::make(UDir));
1751}
1752
1753/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
1754/// is a namespace alias, returns the namespace it points to.
1755static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
1756  if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
1757    return AD->getNamespace();
1758  return dyn_cast_or_null<NamespaceDecl>(D);
1759}
1760
1761Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
1762                                             SourceLocation NamespaceLoc,
1763                                             SourceLocation AliasLoc,
1764                                             IdentifierInfo *Alias,
1765                                             const CXXScopeSpec &SS,
1766                                             SourceLocation IdentLoc,
1767                                             IdentifierInfo *Ident) {
1768
1769  // Lookup the namespace name.
1770  LookupResult R = LookupParsedName(S, &SS, Ident, LookupNamespaceName, false);
1771
1772  // Check if we have a previous declaration with the same name.
1773  if (NamedDecl *PrevDecl = LookupName(S, Alias, LookupOrdinaryName, true)) {
1774    if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
1775      // We already have an alias with the same name that points to the same
1776      // namespace, so don't create a new one.
1777      if (!R.isAmbiguous() && AD->getNamespace() == getNamespaceDecl(R))
1778        return DeclPtrTy();
1779    }
1780
1781    unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
1782      diag::err_redefinition_different_kind;
1783    Diag(AliasLoc, DiagID) << Alias;
1784    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1785    return DeclPtrTy();
1786  }
1787
1788  if (R.isAmbiguous()) {
1789    DiagnoseAmbiguousLookup(R, Ident, IdentLoc);
1790    return DeclPtrTy();
1791  }
1792
1793  if (!R) {
1794    Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
1795    return DeclPtrTy();
1796  }
1797
1798  NamespaceAliasDecl *AliasDecl =
1799    NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
1800                               Alias, SS.getRange(),
1801                               (NestedNameSpecifier *)SS.getScopeRep(),
1802                               IdentLoc, R);
1803
1804  CurContext->addDecl(Context, AliasDecl);
1805  return DeclPtrTy::make(AliasDecl);
1806}
1807
1808void Sema::InitializeVarWithConstructor(VarDecl *VD,
1809                                        CXXConstructorDecl *Constructor,
1810                                        QualType DeclInitType,
1811                                        Expr **Exprs, unsigned NumExprs) {
1812  Expr *Temp = CXXConstructExpr::Create(Context, DeclInitType, Constructor,
1813                                        false, Exprs, NumExprs);
1814  VD->setInit(Context, Temp);
1815}
1816
1817/// AddCXXDirectInitializerToDecl - This action is called immediately after
1818/// ActOnDeclarator, when a C++ direct initializer is present.
1819/// e.g: "int x(1);"
1820void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
1821                                         SourceLocation LParenLoc,
1822                                         MultiExprArg Exprs,
1823                                         SourceLocation *CommaLocs,
1824                                         SourceLocation RParenLoc) {
1825  unsigned NumExprs = Exprs.size();
1826  assert(NumExprs != 0 && Exprs.get() && "missing expressions");
1827  Decl *RealDecl = Dcl.getAs<Decl>();
1828
1829  // If there is no declaration, there was an error parsing it.  Just ignore
1830  // the initializer.
1831  if (RealDecl == 0)
1832    return;
1833
1834  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1835  if (!VDecl) {
1836    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
1837    RealDecl->setInvalidDecl();
1838    return;
1839  }
1840
1841  // FIXME: Need to handle dependent types and expressions here.
1842
1843  // We will treat direct-initialization as a copy-initialization:
1844  //    int x(1);  -as-> int x = 1;
1845  //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
1846  //
1847  // Clients that want to distinguish between the two forms, can check for
1848  // direct initializer using VarDecl::hasCXXDirectInitializer().
1849  // A major benefit is that clients that don't particularly care about which
1850  // exactly form was it (like the CodeGen) can handle both cases without
1851  // special case code.
1852
1853  // C++ 8.5p11:
1854  // The form of initialization (using parentheses or '=') is generally
1855  // insignificant, but does matter when the entity being initialized has a
1856  // class type.
1857  QualType DeclInitType = VDecl->getType();
1858  if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
1859    DeclInitType = Array->getElementType();
1860
1861  // FIXME: This isn't the right place to complete the type.
1862  if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
1863                          diag::err_typecheck_decl_incomplete_type)) {
1864    VDecl->setInvalidDecl();
1865    return;
1866  }
1867
1868  if (VDecl->getType()->isRecordType()) {
1869    CXXConstructorDecl *Constructor
1870      = PerformInitializationByConstructor(DeclInitType,
1871                                           (Expr **)Exprs.get(), NumExprs,
1872                                           VDecl->getLocation(),
1873                                           SourceRange(VDecl->getLocation(),
1874                                                       RParenLoc),
1875                                           VDecl->getDeclName(),
1876                                           IK_Direct);
1877    if (!Constructor)
1878      RealDecl->setInvalidDecl();
1879    else {
1880      VDecl->setCXXDirectInitializer(true);
1881      InitializeVarWithConstructor(VDecl, Constructor, DeclInitType,
1882                                   (Expr**)Exprs.release(), NumExprs);
1883    }
1884    return;
1885  }
1886
1887  if (NumExprs > 1) {
1888    Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
1889      << SourceRange(VDecl->getLocation(), RParenLoc);
1890    RealDecl->setInvalidDecl();
1891    return;
1892  }
1893
1894  // Let clients know that initialization was done with a direct initializer.
1895  VDecl->setCXXDirectInitializer(true);
1896
1897  assert(NumExprs == 1 && "Expected 1 expression");
1898  // Set the init expression, handles conversions.
1899  AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
1900                       /*DirectInit=*/true);
1901}
1902
1903/// PerformInitializationByConstructor - Perform initialization by
1904/// constructor (C++ [dcl.init]p14), which may occur as part of
1905/// direct-initialization or copy-initialization. We are initializing
1906/// an object of type @p ClassType with the given arguments @p
1907/// Args. @p Loc is the location in the source code where the
1908/// initializer occurs (e.g., a declaration, member initializer,
1909/// functional cast, etc.) while @p Range covers the whole
1910/// initialization. @p InitEntity is the entity being initialized,
1911/// which may by the name of a declaration or a type. @p Kind is the
1912/// kind of initialization we're performing, which affects whether
1913/// explicit constructors will be considered. When successful, returns
1914/// the constructor that will be used to perform the initialization;
1915/// when the initialization fails, emits a diagnostic and returns
1916/// null.
1917CXXConstructorDecl *
1918Sema::PerformInitializationByConstructor(QualType ClassType,
1919                                         Expr **Args, unsigned NumArgs,
1920                                         SourceLocation Loc, SourceRange Range,
1921                                         DeclarationName InitEntity,
1922                                         InitializationKind Kind) {
1923  const RecordType *ClassRec = ClassType->getAsRecordType();
1924  assert(ClassRec && "Can only initialize a class type here");
1925
1926  // C++ [dcl.init]p14:
1927  //
1928  //   If the initialization is direct-initialization, or if it is
1929  //   copy-initialization where the cv-unqualified version of the
1930  //   source type is the same class as, or a derived class of, the
1931  //   class of the destination, constructors are considered. The
1932  //   applicable constructors are enumerated (13.3.1.3), and the
1933  //   best one is chosen through overload resolution (13.3). The
1934  //   constructor so selected is called to initialize the object,
1935  //   with the initializer expression(s) as its argument(s). If no
1936  //   constructor applies, or the overload resolution is ambiguous,
1937  //   the initialization is ill-formed.
1938  const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1939  OverloadCandidateSet CandidateSet;
1940
1941  // Add constructors to the overload set.
1942  DeclarationName ConstructorName
1943    = Context.DeclarationNames.getCXXConstructorName(
1944                       Context.getCanonicalType(ClassType.getUnqualifiedType()));
1945  DeclContext::lookup_const_iterator Con, ConEnd;
1946  for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(Context, ConstructorName);
1947       Con != ConEnd; ++Con) {
1948    CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
1949    if ((Kind == IK_Direct) ||
1950        (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
1951        (Kind == IK_Default && Constructor->isDefaultConstructor()))
1952      AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
1953  }
1954
1955  // FIXME: When we decide not to synthesize the implicitly-declared
1956  // constructors, we'll need to make them appear here.
1957
1958  OverloadCandidateSet::iterator Best;
1959  switch (BestViableFunction(CandidateSet, Best)) {
1960  case OR_Success:
1961    // We found a constructor. Return it.
1962    return cast<CXXConstructorDecl>(Best->Function);
1963
1964  case OR_No_Viable_Function:
1965    if (InitEntity)
1966      Diag(Loc, diag::err_ovl_no_viable_function_in_init)
1967        << InitEntity << Range;
1968    else
1969      Diag(Loc, diag::err_ovl_no_viable_function_in_init)
1970        << ClassType << Range;
1971    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1972    return 0;
1973
1974  case OR_Ambiguous:
1975    if (InitEntity)
1976      Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
1977    else
1978      Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
1979    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1980    return 0;
1981
1982  case OR_Deleted:
1983    if (InitEntity)
1984      Diag(Loc, diag::err_ovl_deleted_init)
1985        << Best->Function->isDeleted()
1986        << InitEntity << Range;
1987    else
1988      Diag(Loc, diag::err_ovl_deleted_init)
1989        << Best->Function->isDeleted()
1990        << InitEntity << Range;
1991    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1992    return 0;
1993  }
1994
1995  return 0;
1996}
1997
1998/// CompareReferenceRelationship - Compare the two types T1 and T2 to
1999/// determine whether they are reference-related,
2000/// reference-compatible, reference-compatible with added
2001/// qualification, or incompatible, for use in C++ initialization by
2002/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2003/// type, and the first type (T1) is the pointee type of the reference
2004/// type being initialized.
2005Sema::ReferenceCompareResult
2006Sema::CompareReferenceRelationship(QualType T1, QualType T2,
2007                                   bool& DerivedToBase) {
2008  assert(!T1->isReferenceType() &&
2009    "T1 must be the pointee type of the reference type");
2010  assert(!T2->isReferenceType() && "T2 cannot be a reference type");
2011
2012  T1 = Context.getCanonicalType(T1);
2013  T2 = Context.getCanonicalType(T2);
2014  QualType UnqualT1 = T1.getUnqualifiedType();
2015  QualType UnqualT2 = T2.getUnqualifiedType();
2016
2017  // C++ [dcl.init.ref]p4:
2018  //   Given types ���cv1 T1��� and ���cv2 T2,��� ���cv1 T1��� is
2019  //   reference-related to ���cv2 T2��� if T1 is the same type as T2, or
2020  //   T1 is a base class of T2.
2021  if (UnqualT1 == UnqualT2)
2022    DerivedToBase = false;
2023  else if (IsDerivedFrom(UnqualT2, UnqualT1))
2024    DerivedToBase = true;
2025  else
2026    return Ref_Incompatible;
2027
2028  // At this point, we know that T1 and T2 are reference-related (at
2029  // least).
2030
2031  // C++ [dcl.init.ref]p4:
2032  //   "cv1 T1��� is reference-compatible with ���cv2 T2��� if T1 is
2033  //   reference-related to T2 and cv1 is the same cv-qualification
2034  //   as, or greater cv-qualification than, cv2. For purposes of
2035  //   overload resolution, cases for which cv1 is greater
2036  //   cv-qualification than cv2 are identified as
2037  //   reference-compatible with added qualification (see 13.3.3.2).
2038  if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2039    return Ref_Compatible;
2040  else if (T1.isMoreQualifiedThan(T2))
2041    return Ref_Compatible_With_Added_Qualification;
2042  else
2043    return Ref_Related;
2044}
2045
2046/// CheckReferenceInit - Check the initialization of a reference
2047/// variable with the given initializer (C++ [dcl.init.ref]). Init is
2048/// the initializer (either a simple initializer or an initializer
2049/// list), and DeclType is the type of the declaration. When ICS is
2050/// non-null, this routine will compute the implicit conversion
2051/// sequence according to C++ [over.ics.ref] and will not produce any
2052/// diagnostics; when ICS is null, it will emit diagnostics when any
2053/// errors are found. Either way, a return value of true indicates
2054/// that there was a failure, a return value of false indicates that
2055/// the reference initialization succeeded.
2056///
2057/// When @p SuppressUserConversions, user-defined conversions are
2058/// suppressed.
2059/// When @p AllowExplicit, we also permit explicit user-defined
2060/// conversion functions.
2061/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
2062bool
2063Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
2064                         ImplicitConversionSequence *ICS,
2065                         bool SuppressUserConversions,
2066                         bool AllowExplicit, bool ForceRValue) {
2067  assert(DeclType->isReferenceType() && "Reference init needs a reference");
2068
2069  QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
2070  QualType T2 = Init->getType();
2071
2072  // If the initializer is the address of an overloaded function, try
2073  // to resolve the overloaded function. If all goes well, T2 is the
2074  // type of the resulting function.
2075  if (Context.getCanonicalType(T2) == Context.OverloadTy) {
2076    FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
2077                                                          ICS != 0);
2078    if (Fn) {
2079      // Since we're performing this reference-initialization for
2080      // real, update the initializer with the resulting function.
2081      if (!ICS) {
2082        if (DiagnoseUseOfDecl(Fn, Init->getSourceRange().getBegin()))
2083          return true;
2084
2085        FixOverloadedFunctionReference(Init, Fn);
2086      }
2087
2088      T2 = Fn->getType();
2089    }
2090  }
2091
2092  // Compute some basic properties of the types and the initializer.
2093  bool isRValRef = DeclType->isRValueReferenceType();
2094  bool DerivedToBase = false;
2095  Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2096                                                  Init->isLvalue(Context);
2097  ReferenceCompareResult RefRelationship
2098    = CompareReferenceRelationship(T1, T2, DerivedToBase);
2099
2100  // Most paths end in a failed conversion.
2101  if (ICS)
2102    ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
2103
2104  // C++ [dcl.init.ref]p5:
2105  //   A reference to type ���cv1 T1��� is initialized by an expression
2106  //   of type ���cv2 T2��� as follows:
2107
2108  //     -- If the initializer expression
2109
2110  // Rvalue references cannot bind to lvalues (N2812).
2111  // There is absolutely no situation where they can. In particular, note that
2112  // this is ill-formed, even if B has a user-defined conversion to A&&:
2113  //   B b;
2114  //   A&& r = b;
2115  if (isRValRef && InitLvalue == Expr::LV_Valid) {
2116    if (!ICS)
2117      Diag(Init->getSourceRange().getBegin(), diag::err_lvalue_to_rvalue_ref)
2118        << Init->getSourceRange();
2119    return true;
2120  }
2121
2122  bool BindsDirectly = false;
2123  //       -- is an lvalue (but is not a bit-field), and ���cv1 T1��� is
2124  //          reference-compatible with ���cv2 T2,��� or
2125  //
2126  // Note that the bit-field check is skipped if we are just computing
2127  // the implicit conversion sequence (C++ [over.best.ics]p2).
2128  if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
2129      RefRelationship >= Ref_Compatible_With_Added_Qualification) {
2130    BindsDirectly = true;
2131
2132    if (ICS) {
2133      // C++ [over.ics.ref]p1:
2134      //   When a parameter of reference type binds directly (8.5.3)
2135      //   to an argument expression, the implicit conversion sequence
2136      //   is the identity conversion, unless the argument expression
2137      //   has a type that is a derived class of the parameter type,
2138      //   in which case the implicit conversion sequence is a
2139      //   derived-to-base Conversion (13.3.3.1).
2140      ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
2141      ICS->Standard.First = ICK_Identity;
2142      ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2143      ICS->Standard.Third = ICK_Identity;
2144      ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
2145      ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
2146      ICS->Standard.ReferenceBinding = true;
2147      ICS->Standard.DirectBinding = true;
2148      ICS->Standard.RRefBinding = false;
2149      ICS->Standard.CopyConstructor = 0;
2150
2151      // Nothing more to do: the inaccessibility/ambiguity check for
2152      // derived-to-base conversions is suppressed when we're
2153      // computing the implicit conversion sequence (C++
2154      // [over.best.ics]p2).
2155      return false;
2156    } else {
2157      // Perform the conversion.
2158      // FIXME: Binding to a subobject of the lvalue is going to require more
2159      // AST annotation than this.
2160      ImpCastExprToType(Init, T1, /*isLvalue=*/true);
2161    }
2162  }
2163
2164  //       -- has a class type (i.e., T2 is a class type) and can be
2165  //          implicitly converted to an lvalue of type ���cv3 T3,���
2166  //          where ���cv1 T1��� is reference-compatible with ���cv3 T3���
2167  //          92) (this conversion is selected by enumerating the
2168  //          applicable conversion functions (13.3.1.6) and choosing
2169  //          the best one through overload resolution (13.3)),
2170  if (!isRValRef && !SuppressUserConversions && T2->isRecordType()) {
2171    // FIXME: Look for conversions in base classes!
2172    CXXRecordDecl *T2RecordDecl
2173      = dyn_cast<CXXRecordDecl>(T2->getAsRecordType()->getDecl());
2174
2175    OverloadCandidateSet CandidateSet;
2176    OverloadedFunctionDecl *Conversions
2177      = T2RecordDecl->getConversionFunctions();
2178    for (OverloadedFunctionDecl::function_iterator Func
2179           = Conversions->function_begin();
2180         Func != Conversions->function_end(); ++Func) {
2181      CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
2182
2183      // If the conversion function doesn't return a reference type,
2184      // it can't be considered for this conversion.
2185      if (Conv->getConversionType()->isLValueReferenceType() &&
2186          (AllowExplicit || !Conv->isExplicit()))
2187        AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
2188    }
2189
2190    OverloadCandidateSet::iterator Best;
2191    switch (BestViableFunction(CandidateSet, Best)) {
2192    case OR_Success:
2193      // This is a direct binding.
2194      BindsDirectly = true;
2195
2196      if (ICS) {
2197        // C++ [over.ics.ref]p1:
2198        //
2199        //   [...] If the parameter binds directly to the result of
2200        //   applying a conversion function to the argument
2201        //   expression, the implicit conversion sequence is a
2202        //   user-defined conversion sequence (13.3.3.1.2), with the
2203        //   second standard conversion sequence either an identity
2204        //   conversion or, if the conversion function returns an
2205        //   entity of a type that is a derived class of the parameter
2206        //   type, a derived-to-base Conversion.
2207        ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
2208        ICS->UserDefined.Before = Best->Conversions[0].Standard;
2209        ICS->UserDefined.After = Best->FinalConversion;
2210        ICS->UserDefined.ConversionFunction = Best->Function;
2211        assert(ICS->UserDefined.After.ReferenceBinding &&
2212               ICS->UserDefined.After.DirectBinding &&
2213               "Expected a direct reference binding!");
2214        return false;
2215      } else {
2216        // Perform the conversion.
2217        // FIXME: Binding to a subobject of the lvalue is going to require more
2218        // AST annotation than this.
2219        ImpCastExprToType(Init, T1, /*isLvalue=*/true);
2220      }
2221      break;
2222
2223    case OR_Ambiguous:
2224      assert(false && "Ambiguous reference binding conversions not implemented.");
2225      return true;
2226
2227    case OR_No_Viable_Function:
2228    case OR_Deleted:
2229      // There was no suitable conversion, or we found a deleted
2230      // conversion; continue with other checks.
2231      break;
2232    }
2233  }
2234
2235  if (BindsDirectly) {
2236    // C++ [dcl.init.ref]p4:
2237    //   [...] In all cases where the reference-related or
2238    //   reference-compatible relationship of two types is used to
2239    //   establish the validity of a reference binding, and T1 is a
2240    //   base class of T2, a program that necessitates such a binding
2241    //   is ill-formed if T1 is an inaccessible (clause 11) or
2242    //   ambiguous (10.2) base class of T2.
2243    //
2244    // Note that we only check this condition when we're allowed to
2245    // complain about errors, because we should not be checking for
2246    // ambiguity (or inaccessibility) unless the reference binding
2247    // actually happens.
2248    if (DerivedToBase)
2249      return CheckDerivedToBaseConversion(T2, T1,
2250                                          Init->getSourceRange().getBegin(),
2251                                          Init->getSourceRange());
2252    else
2253      return false;
2254  }
2255
2256  //     -- Otherwise, the reference shall be to a non-volatile const
2257  //        type (i.e., cv1 shall be const), or the reference shall be an
2258  //        rvalue reference and the initializer expression shall be an rvalue.
2259  if (!isRValRef && T1.getCVRQualifiers() != QualType::Const) {
2260    if (!ICS)
2261      Diag(Init->getSourceRange().getBegin(),
2262           diag::err_not_reference_to_const_init)
2263        << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
2264        << T2 << Init->getSourceRange();
2265    return true;
2266  }
2267
2268  //       -- If the initializer expression is an rvalue, with T2 a
2269  //          class type, and ���cv1 T1��� is reference-compatible with
2270  //          ���cv2 T2,��� the reference is bound in one of the
2271  //          following ways (the choice is implementation-defined):
2272  //
2273  //          -- The reference is bound to the object represented by
2274  //             the rvalue (see 3.10) or to a sub-object within that
2275  //             object.
2276  //
2277  //          -- A temporary of type ���cv1 T2��� [sic] is created, and
2278  //             a constructor is called to copy the entire rvalue
2279  //             object into the temporary. The reference is bound to
2280  //             the temporary or to a sub-object within the
2281  //             temporary.
2282  //
2283  //          The constructor that would be used to make the copy
2284  //          shall be callable whether or not the copy is actually
2285  //          done.
2286  //
2287  // Note that C++0x [dcl.init.ref]p5 takes away this implementation
2288  // freedom, so we will always take the first option and never build
2289  // a temporary in this case. FIXME: We will, however, have to check
2290  // for the presence of a copy constructor in C++98/03 mode.
2291  if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
2292      RefRelationship >= Ref_Compatible_With_Added_Qualification) {
2293    if (ICS) {
2294      ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
2295      ICS->Standard.First = ICK_Identity;
2296      ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2297      ICS->Standard.Third = ICK_Identity;
2298      ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
2299      ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
2300      ICS->Standard.ReferenceBinding = true;
2301      ICS->Standard.DirectBinding = false;
2302      ICS->Standard.RRefBinding = isRValRef;
2303      ICS->Standard.CopyConstructor = 0;
2304    } else {
2305      // FIXME: Binding to a subobject of the rvalue is going to require more
2306      // AST annotation than this.
2307      ImpCastExprToType(Init, T1, /*isLvalue=*/false);
2308    }
2309    return false;
2310  }
2311
2312  //       -- Otherwise, a temporary of type ���cv1 T1��� is created and
2313  //          initialized from the initializer expression using the
2314  //          rules for a non-reference copy initialization (8.5). The
2315  //          reference is then bound to the temporary. If T1 is
2316  //          reference-related to T2, cv1 must be the same
2317  //          cv-qualification as, or greater cv-qualification than,
2318  //          cv2; otherwise, the program is ill-formed.
2319  if (RefRelationship == Ref_Related) {
2320    // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2321    // we would be reference-compatible or reference-compatible with
2322    // added qualification. But that wasn't the case, so the reference
2323    // initialization fails.
2324    if (!ICS)
2325      Diag(Init->getSourceRange().getBegin(),
2326           diag::err_reference_init_drops_quals)
2327        << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
2328        << T2 << Init->getSourceRange();
2329    return true;
2330  }
2331
2332  // If at least one of the types is a class type, the types are not
2333  // related, and we aren't allowed any user conversions, the
2334  // reference binding fails. This case is important for breaking
2335  // recursion, since TryImplicitConversion below will attempt to
2336  // create a temporary through the use of a copy constructor.
2337  if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
2338      (T1->isRecordType() || T2->isRecordType())) {
2339    if (!ICS)
2340      Diag(Init->getSourceRange().getBegin(),
2341           diag::err_typecheck_convert_incompatible)
2342        << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
2343    return true;
2344  }
2345
2346  // Actually try to convert the initializer to T1.
2347  if (ICS) {
2348    // C++ [over.ics.ref]p2:
2349    //
2350    //   When a parameter of reference type is not bound directly to
2351    //   an argument expression, the conversion sequence is the one
2352    //   required to convert the argument expression to the
2353    //   underlying type of the reference according to
2354    //   13.3.3.1. Conceptually, this conversion sequence corresponds
2355    //   to copy-initializing a temporary of the underlying type with
2356    //   the argument expression. Any difference in top-level
2357    //   cv-qualification is subsumed by the initialization itself
2358    //   and does not constitute a conversion.
2359    *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
2360    // Of course, that's still a reference binding.
2361    if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
2362      ICS->Standard.ReferenceBinding = true;
2363      ICS->Standard.RRefBinding = isRValRef;
2364    } else if(ICS->ConversionKind ==
2365              ImplicitConversionSequence::UserDefinedConversion) {
2366      ICS->UserDefined.After.ReferenceBinding = true;
2367      ICS->UserDefined.After.RRefBinding = isRValRef;
2368    }
2369    return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
2370  } else {
2371    return PerformImplicitConversion(Init, T1, "initializing");
2372  }
2373}
2374
2375/// CheckOverloadedOperatorDeclaration - Check whether the declaration
2376/// of this overloaded operator is well-formed. If so, returns false;
2377/// otherwise, emits appropriate diagnostics and returns true.
2378bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
2379  assert(FnDecl && FnDecl->isOverloadedOperator() &&
2380         "Expected an overloaded operator declaration");
2381
2382  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
2383
2384  // C++ [over.oper]p5:
2385  //   The allocation and deallocation functions, operator new,
2386  //   operator new[], operator delete and operator delete[], are
2387  //   described completely in 3.7.3. The attributes and restrictions
2388  //   found in the rest of this subclause do not apply to them unless
2389  //   explicitly stated in 3.7.3.
2390  // FIXME: Write a separate routine for checking this. For now, just allow it.
2391  if (Op == OO_New || Op == OO_Array_New ||
2392      Op == OO_Delete || Op == OO_Array_Delete)
2393    return false;
2394
2395  // C++ [over.oper]p6:
2396  //   An operator function shall either be a non-static member
2397  //   function or be a non-member function and have at least one
2398  //   parameter whose type is a class, a reference to a class, an
2399  //   enumeration, or a reference to an enumeration.
2400  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
2401    if (MethodDecl->isStatic())
2402      return Diag(FnDecl->getLocation(),
2403                  diag::err_operator_overload_static) << FnDecl->getDeclName();
2404  } else {
2405    bool ClassOrEnumParam = false;
2406    for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
2407                                   ParamEnd = FnDecl->param_end();
2408         Param != ParamEnd; ++Param) {
2409      QualType ParamType = (*Param)->getType().getNonReferenceType();
2410      if (ParamType->isRecordType() || ParamType->isEnumeralType()) {
2411        ClassOrEnumParam = true;
2412        break;
2413      }
2414    }
2415
2416    if (!ClassOrEnumParam)
2417      return Diag(FnDecl->getLocation(),
2418                  diag::err_operator_overload_needs_class_or_enum)
2419        << FnDecl->getDeclName();
2420  }
2421
2422  // C++ [over.oper]p8:
2423  //   An operator function cannot have default arguments (8.3.6),
2424  //   except where explicitly stated below.
2425  //
2426  // Only the function-call operator allows default arguments
2427  // (C++ [over.call]p1).
2428  if (Op != OO_Call) {
2429    for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
2430         Param != FnDecl->param_end(); ++Param) {
2431      if ((*Param)->hasUnparsedDefaultArg())
2432        return Diag((*Param)->getLocation(),
2433                    diag::err_operator_overload_default_arg)
2434          << FnDecl->getDeclName();
2435      else if (Expr *DefArg = (*Param)->getDefaultArg())
2436        return Diag((*Param)->getLocation(),
2437                    diag::err_operator_overload_default_arg)
2438          << FnDecl->getDeclName() << DefArg->getSourceRange();
2439    }
2440  }
2441
2442  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
2443    { false, false, false }
2444#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2445    , { Unary, Binary, MemberOnly }
2446#include "clang/Basic/OperatorKinds.def"
2447  };
2448
2449  bool CanBeUnaryOperator = OperatorUses[Op][0];
2450  bool CanBeBinaryOperator = OperatorUses[Op][1];
2451  bool MustBeMemberOperator = OperatorUses[Op][2];
2452
2453  // C++ [over.oper]p8:
2454  //   [...] Operator functions cannot have more or fewer parameters
2455  //   than the number required for the corresponding operator, as
2456  //   described in the rest of this subclause.
2457  unsigned NumParams = FnDecl->getNumParams()
2458                     + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
2459  if (Op != OO_Call &&
2460      ((NumParams == 1 && !CanBeUnaryOperator) ||
2461       (NumParams == 2 && !CanBeBinaryOperator) ||
2462       (NumParams < 1) || (NumParams > 2))) {
2463    // We have the wrong number of parameters.
2464    unsigned ErrorKind;
2465    if (CanBeUnaryOperator && CanBeBinaryOperator) {
2466      ErrorKind = 2;  // 2 -> unary or binary.
2467    } else if (CanBeUnaryOperator) {
2468      ErrorKind = 0;  // 0 -> unary
2469    } else {
2470      assert(CanBeBinaryOperator &&
2471             "All non-call overloaded operators are unary or binary!");
2472      ErrorKind = 1;  // 1 -> binary
2473    }
2474
2475    return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
2476      << FnDecl->getDeclName() << NumParams << ErrorKind;
2477  }
2478
2479  // Overloaded operators other than operator() cannot be variadic.
2480  if (Op != OO_Call &&
2481      FnDecl->getType()->getAsFunctionProtoType()->isVariadic()) {
2482    return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
2483      << FnDecl->getDeclName();
2484  }
2485
2486  // Some operators must be non-static member functions.
2487  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
2488    return Diag(FnDecl->getLocation(),
2489                diag::err_operator_overload_must_be_member)
2490      << FnDecl->getDeclName();
2491  }
2492
2493  // C++ [over.inc]p1:
2494  //   The user-defined function called operator++ implements the
2495  //   prefix and postfix ++ operator. If this function is a member
2496  //   function with no parameters, or a non-member function with one
2497  //   parameter of class or enumeration type, it defines the prefix
2498  //   increment operator ++ for objects of that type. If the function
2499  //   is a member function with one parameter (which shall be of type
2500  //   int) or a non-member function with two parameters (the second
2501  //   of which shall be of type int), it defines the postfix
2502  //   increment operator ++ for objects of that type.
2503  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
2504    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
2505    bool ParamIsInt = false;
2506    if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
2507      ParamIsInt = BT->getKind() == BuiltinType::Int;
2508
2509    if (!ParamIsInt)
2510      return Diag(LastParam->getLocation(),
2511                  diag::err_operator_overload_post_incdec_must_be_int)
2512        << LastParam->getType() << (Op == OO_MinusMinus);
2513  }
2514
2515  // Notify the class if it got an assignment operator.
2516  if (Op == OO_Equal) {
2517    // Would have returned earlier otherwise.
2518    assert(isa<CXXMethodDecl>(FnDecl) &&
2519      "Overloaded = not member, but not filtered.");
2520    CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
2521    Method->getParent()->addedAssignmentOperator(Context, Method);
2522  }
2523
2524  return false;
2525}
2526
2527/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
2528/// linkage specification, including the language and (if present)
2529/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
2530/// the location of the language string literal, which is provided
2531/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
2532/// the '{' brace. Otherwise, this linkage specification does not
2533/// have any braces.
2534Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
2535                                                     SourceLocation ExternLoc,
2536                                                     SourceLocation LangLoc,
2537                                                     const char *Lang,
2538                                                     unsigned StrSize,
2539                                                     SourceLocation LBraceLoc) {
2540  LinkageSpecDecl::LanguageIDs Language;
2541  if (strncmp(Lang, "\"C\"", StrSize) == 0)
2542    Language = LinkageSpecDecl::lang_c;
2543  else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2544    Language = LinkageSpecDecl::lang_cxx;
2545  else {
2546    Diag(LangLoc, diag::err_bad_language);
2547    return DeclPtrTy();
2548  }
2549
2550  // FIXME: Add all the various semantics of linkage specifications
2551
2552  LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
2553                                               LangLoc, Language,
2554                                               LBraceLoc.isValid());
2555  CurContext->addDecl(Context, D);
2556  PushDeclContext(S, D);
2557  return DeclPtrTy::make(D);
2558}
2559
2560/// ActOnFinishLinkageSpecification - Completely the definition of
2561/// the C++ linkage specification LinkageSpec. If RBraceLoc is
2562/// valid, it's the position of the closing '}' brace in a linkage
2563/// specification that uses braces.
2564Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
2565                                                      DeclPtrTy LinkageSpec,
2566                                                      SourceLocation RBraceLoc) {
2567  if (LinkageSpec)
2568    PopDeclContext();
2569  return LinkageSpec;
2570}
2571
2572/// \brief Perform semantic analysis for the variable declaration that
2573/// occurs within a C++ catch clause, returning the newly-created
2574/// variable.
2575VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
2576                                         IdentifierInfo *Name,
2577                                         SourceLocation Loc,
2578                                         SourceRange Range) {
2579  bool Invalid = false;
2580
2581  // Arrays and functions decay.
2582  if (ExDeclType->isArrayType())
2583    ExDeclType = Context.getArrayDecayedType(ExDeclType);
2584  else if (ExDeclType->isFunctionType())
2585    ExDeclType = Context.getPointerType(ExDeclType);
2586
2587  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
2588  // The exception-declaration shall not denote a pointer or reference to an
2589  // incomplete type, other than [cv] void*.
2590  // N2844 forbids rvalue references.
2591  if(!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
2592    Diag(Loc, diag::err_catch_rvalue_ref) << Range;
2593    Invalid = true;
2594  }
2595
2596  QualType BaseType = ExDeclType;
2597  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
2598  unsigned DK = diag::err_catch_incomplete;
2599  if (const PointerType *Ptr = BaseType->getAsPointerType()) {
2600    BaseType = Ptr->getPointeeType();
2601    Mode = 1;
2602    DK = diag::err_catch_incomplete_ptr;
2603  } else if(const ReferenceType *Ref = BaseType->getAsReferenceType()) {
2604    // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
2605    BaseType = Ref->getPointeeType();
2606    Mode = 2;
2607    DK = diag::err_catch_incomplete_ref;
2608  }
2609  if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
2610      !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
2611    Invalid = true;
2612
2613  if (!Invalid && !ExDeclType->isDependentType() &&
2614      RequireNonAbstractType(Loc, ExDeclType,
2615                             diag::err_abstract_type_in_decl,
2616                             AbstractVariableType))
2617    Invalid = true;
2618
2619  // FIXME: Need to test for ability to copy-construct and destroy the
2620  // exception variable.
2621
2622  // FIXME: Need to check for abstract classes.
2623
2624  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
2625                                    Name, ExDeclType, VarDecl::None,
2626                                    Range.getBegin());
2627
2628  if (Invalid)
2629    ExDecl->setInvalidDecl();
2630
2631  return ExDecl;
2632}
2633
2634/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
2635/// handler.
2636Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
2637  QualType ExDeclType = GetTypeForDeclarator(D, S);
2638
2639  bool Invalid = D.isInvalidType();
2640  IdentifierInfo *II = D.getIdentifier();
2641  if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
2642    // The scope should be freshly made just for us. There is just no way
2643    // it contains any previous declaration.
2644    assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
2645    if (PrevDecl->isTemplateParameter()) {
2646      // Maybe we will complain about the shadowed template parameter.
2647      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2648    }
2649  }
2650
2651  if (D.getCXXScopeSpec().isSet() && !Invalid) {
2652    Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
2653      << D.getCXXScopeSpec().getRange();
2654    Invalid = true;
2655  }
2656
2657  VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType,
2658                                              D.getIdentifier(),
2659                                              D.getIdentifierLoc(),
2660                                            D.getDeclSpec().getSourceRange());
2661
2662  if (Invalid)
2663    ExDecl->setInvalidDecl();
2664
2665  // Add the exception declaration into this scope.
2666  if (II)
2667    PushOnScopeChains(ExDecl, S);
2668  else
2669    CurContext->addDecl(Context, ExDecl);
2670
2671  ProcessDeclAttributes(ExDecl, D);
2672  return DeclPtrTy::make(ExDecl);
2673}
2674
2675Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
2676                                                   ExprArg assertexpr,
2677                                                   ExprArg assertmessageexpr) {
2678  Expr *AssertExpr = (Expr *)assertexpr.get();
2679  StringLiteral *AssertMessage =
2680    cast<StringLiteral>((Expr *)assertmessageexpr.get());
2681
2682  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
2683    llvm::APSInt Value(32);
2684    if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
2685      Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
2686        AssertExpr->getSourceRange();
2687      return DeclPtrTy();
2688    }
2689
2690    if (Value == 0) {
2691      std::string str(AssertMessage->getStrData(),
2692                      AssertMessage->getByteLength());
2693      Diag(AssertLoc, diag::err_static_assert_failed)
2694        << str << AssertExpr->getSourceRange();
2695    }
2696  }
2697
2698  assertexpr.release();
2699  assertmessageexpr.release();
2700  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
2701                                        AssertExpr, AssertMessage);
2702
2703  CurContext->addDecl(Context, Decl);
2704  return DeclPtrTy::make(Decl);
2705}
2706
2707bool Sema::ActOnFriendDecl(Scope *S, SourceLocation FriendLoc, DeclPtrTy Dcl) {
2708  if (!(S->getFlags() & Scope::ClassScope)) {
2709    Diag(FriendLoc, diag::err_friend_decl_outside_class);
2710    return true;
2711  }
2712
2713  return false;
2714}
2715
2716void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
2717  Decl *Dcl = dcl.getAs<Decl>();
2718  FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
2719  if (!Fn) {
2720    Diag(DelLoc, diag::err_deleted_non_function);
2721    return;
2722  }
2723  if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
2724    Diag(DelLoc, diag::err_deleted_decl_not_first);
2725    Diag(Prev->getLocation(), diag::note_previous_declaration);
2726    // If the declaration wasn't the first, we delete the function anyway for
2727    // recovery.
2728  }
2729  Fn->setDeleted();
2730}
2731
2732static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
2733  for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
2734       ++CI) {
2735    Stmt *SubStmt = *CI;
2736    if (!SubStmt)
2737      continue;
2738    if (isa<ReturnStmt>(SubStmt))
2739      Self.Diag(SubStmt->getSourceRange().getBegin(),
2740           diag::err_return_in_constructor_handler);
2741    if (!isa<Expr>(SubStmt))
2742      SearchForReturnInStmt(Self, SubStmt);
2743  }
2744}
2745
2746void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
2747  for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
2748    CXXCatchStmt *Handler = TryBlock->getHandler(I);
2749    SearchForReturnInStmt(*this, Handler);
2750  }
2751}
2752
2753bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
2754                                             const CXXMethodDecl *Old) {
2755  QualType NewTy = New->getType()->getAsFunctionType()->getResultType();
2756  QualType OldTy = Old->getType()->getAsFunctionType()->getResultType();
2757
2758  QualType CNewTy = Context.getCanonicalType(NewTy);
2759  QualType COldTy = Context.getCanonicalType(OldTy);
2760
2761  if (CNewTy == COldTy &&
2762      CNewTy.getCVRQualifiers() == COldTy.getCVRQualifiers())
2763    return false;
2764
2765  // Check if the return types are covariant
2766  QualType NewClassTy, OldClassTy;
2767
2768  /// Both types must be pointers or references to classes.
2769  if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
2770    if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
2771      NewClassTy = NewPT->getPointeeType();
2772      OldClassTy = OldPT->getPointeeType();
2773    }
2774  } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
2775    if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
2776      NewClassTy = NewRT->getPointeeType();
2777      OldClassTy = OldRT->getPointeeType();
2778    }
2779  }
2780
2781  // The return types aren't either both pointers or references to a class type.
2782  if (NewClassTy.isNull()) {
2783    Diag(New->getLocation(),
2784         diag::err_different_return_type_for_overriding_virtual_function)
2785      << New->getDeclName() << NewTy << OldTy;
2786    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2787
2788    return true;
2789  }
2790
2791  if (NewClassTy.getUnqualifiedType() != OldClassTy.getUnqualifiedType()) {
2792    // Check if the new class derives from the old class.
2793    if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
2794      Diag(New->getLocation(),
2795           diag::err_covariant_return_not_derived)
2796      << New->getDeclName() << NewTy << OldTy;
2797      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2798      return true;
2799    }
2800
2801    // Check if we the conversion from derived to base is valid.
2802    if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
2803                      diag::err_covariant_return_inaccessible_base,
2804                      diag::err_covariant_return_ambiguous_derived_to_base_conv,
2805                      // FIXME: Should this point to the return type?
2806                      New->getLocation(), SourceRange(), New->getDeclName())) {
2807      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2808      return true;
2809    }
2810  }
2811
2812  // The qualifiers of the return types must be the same.
2813  if (CNewTy.getCVRQualifiers() != COldTy.getCVRQualifiers()) {
2814    Diag(New->getLocation(),
2815         diag::err_covariant_return_type_different_qualifications)
2816    << New->getDeclName() << NewTy << OldTy;
2817    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2818    return true;
2819  };
2820
2821
2822  // The new class type must have the same or less qualifiers as the old type.
2823  if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
2824    Diag(New->getLocation(),
2825         diag::err_covariant_return_type_class_type_more_qualified)
2826    << New->getDeclName() << NewTy << OldTy;
2827    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2828    return true;
2829  };
2830
2831  return false;
2832}
2833